text:
using System;
using System.Collections.Generic;
using GameAnalyticsSDK.Net.Device;
using GameAnalyticsSDK.Net.Logging;
using GameAnalyticsSDK.Net.Store;
using GameAnalyticsSDK.Net.Events;
using GameAnalyticsSDK.Net.Utilities;
using GameAnalyticsSDK.Net.Http;
using GameAnalyticsSDK.Net.Validators;
using GameAnalyticsSDK.Net.Threading;

namespace GameAnalyticsSDK.Net.State
{
    internal class GAState
    {
        #region Fields and properties

        private const String CategorySdkError = "sdk_error";
        private const int MaxCustomFieldsCount = 50;
        private const int MaxCustomFieldsKeyLength = 64;
        private const int MaxCustomFieldsValueStringLength = 256;

        private const int MaxErrorCount = 10;
        private static Dictionary<string, int> countMap = new Dictionary<string, int>();
        private static Dictionary<string, DateTime> timestampMap = new Dictionary<string, DateTime>();

        private static readonly GAState _instance = new GAState();
        private static GAState Instance
        {
            get
            {
                return _instance;
            }
        }

        private string _userId;
        public static string UserId
        {
            private get { return Instance._userId; }
            set
            {
                Instance._userId = value == null ? "" : value;
                CacheIdentifier();
            }
        }

        private string _identifier;
        public static string Identifier
        {
            get { return Instance._identifier; }
            private set { Instance._identifier = value; }
        }

        private bool _initialized;
        public static bool Initialized
        {
            get { return Instance._initialized; }
            private set { Instance._initialized = value; }
        }

        private long _sessionStart;
        public static long SessionStart
        {
            get { return Instance._sessionStart; }
            private set { Instance._sessionStart = value; }
        }

        private int _sessionNum;
        public static int SessionNum
        {
            get { return Instance._sessionNum; }
            private set { Instance._sessionNum = value; }
        }

        private int _transactionNum;
        public static int TransactionNum
        {
            get { return Instance._transactionNum; }
            private set { Instance._transactionNum = value; }
        }

        private string _sessionId;
        public static string SessionId
        {
            get { return Instance._sessionId; }
            private set { Instance._sessionId = value; }
        }

        private string _currentCustomDimension01;
        public static string CurrentCustomDimension01
        {
            get { return Instance._currentCustomDimension01; }
            private set { Instance._currentCustomDimension01 = value; }
        }

        private string _currentCustomDimension02;
        public static string CurrentCustomDimension02
        {
            get { return Instance._currentCustomDimension02; }
            private set { Instance._currentCustomDimension02 = value; }
        }

        private string _currentCustomDimension03;
        public static string CurrentCustomDimension03
        {
            get { return Instance._currentCustomDimension03; }
            private set { Instance._currentCustomDimension03 = value; }
        }

        private IDictionary<string, object> _currentGlobalCustomEventFields = new Dictionary<string, object>();
        public static IDictionary<string, object> CurrentGlobalCustomEventFields
        {
            get { return Instance._currentGlobalCustomEventFields; }
        }

        private string _gameKey;
        public static string GameKey
        {
            get { return Instance._gameKey; }
            private set { Instance._gameKey = value; }
        }

        private string _gameSecret;
        public static string GameSecret
        {
            get { return Instance._gameSecret; }
            private set { Instance._gameSecret = value; }
        }

        private string[] _availableCustomDimensions01 = new string[0];
        public static string[] AvailableCustomDimensions01
        {
            get { return Instance._availableCustomDimensions01; }
            set
            {
                // Validate
                if (!GAValidator.ValidateCustomDimensions(value))
                {
                    return;
                }
                Instance._availableCustomDimensions01 = value;

                // validate current dimension values
                ValidateAndFixCurrentDimensions();

                GALogger.I("Set available custom01 dimension values: (" + GAUtilities.JoinStringArray(value, ", ") + ")");
            }
        }

        private string[] _availableCustomDimensions02 = new string[0];
        public static string[] AvailableCustomDimensions02
        {
            get { return Instance._availableCustomDimensions02; }
            set
            {
                // Validate
                if (!GAValidator.ValidateCustomDimensions(value))
                {
                    return;
                }
                Instance._availableCustomDimensions02 = value;

                // validate current dimension values
                ValidateAndFixCurrentDimensions();

                GALogger.I("Set available custom02 dimension values: (" + GAUtilities.JoinStringArray(value, ", ") + ")");
            }
        }

        private string[] _availableCustomDimensions03 = new string[0];
        public static string[] AvailableCustomDimensions03
        {
            get { return Instance._availableCustomDimensions03; }
            set
            {
                // Validate
                if (!GAValidator.ValidateCustomDimensions(value))
                {
                    return;
                }
                Instance._availableCustomDimensions03 = value;

                // validate current dimension values
                ValidateAndFixCurrentDimensions();

                GALogger.I("Set available custom03 dimension values: (" + GAUtilities.JoinStringArray(value, ", ") + ")");
            }
        }

        private string[] _availableResourceCurrencies = new string[0];
        public static string[] AvailableResourceCurrencies
        {
            get { return Instance._availableResourceCurrencies; }
            set
            {
                // Validate
                if (!GAValidator.ValidateResourceCurrencies(value))
                {
                    return;
                }
                Instance._availableResourceCurrencies = value;

                GALogger.I("Set available resource currencies: (" + GAUtilities.JoinStringArray(value, ", ") + ")");
            }
        }

        private string[] _availableResourceItemTypes = new string[0];
        public static string[] AvailableResourceItemTypes
        {
            get { return Instance._availableResourceItemTypes; }
            set
            {
                // Validate
                if (!GAValidator.ValidateResourceItemTypes(value))
                {
                    return;
                }
                Instance._availableResourceItemTypes = value;

                GALogger.I("Set available resource item types: (" + GAUtilities.JoinStringArray(value, ", ") + ")");
            }
        }

        private string _build;
        public static string Build
        {
            get { return Instance._build; }
            set { Instance._build = value; }
        }

        private bool _useManualSessionHandling;
        public static bool UseManualSessionHandling
        {
            get { return Instance._useManualSessionHandling; }
            private set { Instance._useManualSessionHandling = value; }
        }

        private bool _isEventSubmissionEnabled = true;
        public static bool IsEventSubmissionEnabled
        {
            get { return Instance._isEventSubmissionEnabled; }
            private set { Instance._isEventSubmissionEnabled = value; }
        }

        private bool Enabled
        {
            get;
            set;
        }
        private JSONNode SdkConfigCached
        {
            get;
            set;
        }
        private bool InitAuthorized
        {
            get;
            set;
        }
        private long ClientServerTimeOffset
        {
            get;
            set;
        }
        private long SuspendBlockId
        {
            get;
            set;
        }
        public string ConfigsHash
        {
            get;
            set;
        }
        public string AbId
        {
            get;
            set;
        }
        public string AbVariantId
        {
            get;
            set;
        }

        private string _defaultUserId;
        private string DefaultUserId
        {
            get { return Instance._defaultUserId; }
            set
            {
                Instance._defaultUserId = value == null ? "" : value;
                CacheIdentifier();
            }
        }

        private static JSONNode SdkConfig
        {
            get
            {
                if (Instance.sdkConfig.AsObject != null && Instance.sdkConfig.Count != 0)
                {
                    return Instance.sdkConfig;
                }

                if (Instance.sdkConfigCached.AsObject != null && Instance.sdkConfigCached.Count != 0)
                {
                    return Instance.sdkConfigCached;
                }

                return Instance.sdkConfigDefault;
            }
        }

        private Dictionary<string, int> progressionTries = new Dictionary<string, int>();
        private JSONNode sdkConfigDefault = new JSONObject();
        private JSONNode sdkConfig = new JSONObject();
        private JSONNode sdkConfigCached = new JSONObject();
        private JSONNode remoteConfigs = new JSONObject();
        private bool remoteConfigsIsReady;
        private readonly List<IRemoteConfigsListener> remoteConfigsListeners = new List<IRemoteConfigsListener>();
        private readonly object remoteConfigsLock = new object();

        public const string InMemoryPrefix = "in_memory_";
        private const string DefaultUserIdKey = "default_user_id";
        public const string SessionNumKey = "session_num";
        public const string TransactionNumKey = "transaction_num";
        private const string Dimension01Key = "dimension01";
        private const string Dimension02Key = "dimension02";
        private const string Dimension03Key = "dimension03";
        private const string SdkConfigCachedKey = "sdk_config_cached";

        #endregion // Fields and properties

        private GAState()
        {
            Enabled = false;
        }

        ~GAState()
        {
            EndSessionAndStopQueue(false);
        }

        #region Public methods

        public static bool IsEnabled()
        {
            return Instance.Enabled;
        }

        public static void SetCustomDimension01(string dimension)
        {
            CurrentCustomDimension01 = dimension;
            if(GAStore.IsTableReady)
            {
                GAStore.SetState(Dimension01Key, dimension);
            }
            GALogger.I("Set custom01 dimension value: " + dimension);
        }

        public static void SetCustomDimension02(string dimension)
        {
            CurrentCustomDimension02 = dimension;
            if(GAStore.IsTableReady)
            {
                GAStore.SetState(Dimension02Key, dimension);
            }
            GALogger.I("Set custom02 dimension value: " + dimension);
        }

        public static void SetCustomDimension03(string dimension)
        {
            CurrentCustomDimension03 = dimension;
            if(GAStore.IsTableReady)
            {
                GAStore.SetState(Dimension03Key, dimension);
            }
            GALogger.I("Set custom03 dimension value: " + dimension);
        }

        public static void SetGlobalCustomEventFields(IDictionary<string, object> customFields)
        {
            if(customFields == null || customFields.Count == 0)
            {
                CurrentGlobalCustomEventFields.Clear();
                return;
            }

            CurrentGlobalCustomEventFields.Clear();
            foreach(var pair in customFields)
            {
                CurrentGlobalCustomEventFields.Add(pair);
            }
            GALogger.I("Set global custom event fields");
        }

        public static void IncrementSessionNum()
        {
            int sessionNumInt = SessionNum + 1;
            SessionNum = sessionNumInt;
        }

        public static void IncrementTransactionNum()
        {
            int transactionNumInt = TransactionNum + 1;
            TransactionNum = transactionNumInt;
        }

#pragma warning disable 0162
        public static void IncrementProgressionTries(string progression)
        {
            int tries = GetProgressionTries(progression) + 1;
            Instance.progressionTries[progression] = tries;

            if(GAStore.InMemory)
            {
                GALogger.D("Trying to IncrementProgressionTries with InMemory=true - cannot. Skipping.");
            }
            else
            {
                // Persist
                Dictionary<string, object> parms = new Dictionary<string, object>();
                parms.Add("$progression", progression);
                parms.Add("$tries", tries);
                GAStore.ExecuteQuerySync("INSERT OR REPLACE INTO ga_progression (progression, tries) VALUES($progression, $tries);", parms);
            }
        }
#pragma warning restore 0162

        public static int GetProgressionTries(string progression)
        {
            if(Instance.progressionTries.ContainsKey(progression))
            {
                return Instance.progressionTries[progression];
            }
            else
            {
                return 0;
            }
        }

#pragma warning disable 0162
        public static void ClearProgressionTries(string progression)
        {
            Dictionary<string, int> progressionTries = Instance.progressionTries;
            if(progressionTries.ContainsKey(progression))
            {
                progressionTries.Remove(progression);
            }

            if(GAStore.InMemory)
            {
                GALogger.D("Trying to ClearProgressionTries with InMemory=true - cannot. Skipping.");
            }
            else
            {
                // Delete
                Dictionary<string, object> parms = new Dictionary<string, object>();
                parms.Add("$progression", progression);
                GAStore.ExecuteQuerySync("DELETE FROM ga_progression WHERE progression = $progression;", parms);
            }
        }
#pragma warning restore 0162

        public static bool HasAvailableCustomDimensions01(string dimension1)
        {
            return GAUtilities.StringArrayContainsString(AvailableCustomDimensions01, dimension1);
        }

        public static bool HasAvailableCustomDimensions02(string dimension2)
        {
            return GAUtilities.StringArrayContainsString(AvailableCustomDimensions02, dimension2);
        }

        public static bool HasAvailableCustomDimensions03(string dimension3)
        {
            return GAUtilities.StringArrayContainsString(AvailableCustomDimensions03, dimension3);
        }

        public static bool HasAvailableResourceCurrency(string currency)
        {
            return GAUtilities.StringArrayContainsString(AvailableResourceCurrencies, currency);
        }

        public static bool HasAvailableResourceItemType(string itemType)
        {
            return GAUtilities.StringArrayContainsString(AvailableResourceItemTypes, itemType);
        }

        public static void SetKeys(string gameKey, string gameSecret)
        {
            GameKey = gameKey;
            GameSecret = gameSecret;
        }

        public static void SetManualSessionHandling(bool flag)
        {
            UseManualSessionHandling = flag;
            GALogger.I("Use manual session handling: " + flag);
        }

        public static void SetEnabledEventSubmission(bool flag)
        {
            IsEventSubmissionEnabled = flag;
        }

#if WINDOWS_UWP || WINDOWS_WSA
        public async static void InternalInitialize()
#else
        public static void InternalInitialize()
#endif
        {
            // Make sure database is ready
            if (!GAStore.IsTableReady)
            {
                return;
            }

            EnsurePersistedStates();
            GAStore.SetState(DefaultUserIdKey, Instance.DefaultUserId);

            Initialized = true;

#if WINDOWS_UWP || WINDOWS_WSA
            await StartNewSession();
#else
            StartNewSession();
#endif

            if (IsEnabled())
            {
                GAEvents.EnsureEventQueueIsRunning();
            }
        }

        public static void EndSessionAndStopQueue(bool endThread)
        {
            if(Initialized)
            {
                if (IsEnabled() && SessionIsStarted())
                {
                    GALogger.I("Ending session.");
                    GAEvents.StopEventQueue();
                    GAEvents.AddSessionEndEvent();
                    SessionStart = 0;
                }
            }

            if(endThread)
            {
                GAThreading.StopThread();
            }
        }

#if WINDOWS_UWP || WINDOWS_WSA
        public async static void ResumeSessionAndStartQueue()
#else
        public static void ResumeSessionAndStartQueue()
#endif
        {
            if(!Initialized)
            {
                return;
            }
            GALogger.I("Resuming session.");
            if(!SessionIsStarted())
            {
#if WINDOWS_UWP || WINDOWS_WSA
                await StartNewSession();
#else
                StartNewSession();
#endif
            }
        }

        public static JSONObject GetEventAnnotations()
        {
            JSONObject annotations = new JSONObject();

            // ---- REQUIRED ---- //

            // collector event API version
            annotations.Add("v", new JSONNumber(2));
            // Event UUID
            annotations["event_uuid"] = Guid.NewGuid().ToString().ToLowerInvariant();
            // User identifier
            annotations["user_id"] = Identifier;

            // Client Timestamp (the adjusted timestamp)
            annotations.Add("client_ts", new JSONNumber(GetClientTsAdjusted()));
            // SDK version
            annotations["sdk_version"] = GADevice.RelevantSdkVersion;
            // Operation system version
            annotations["os_version"] = GADevice.OSVersion;
            // Device make (hardcoded to apple)
            annotations["manufacturer"] = GADevice.DeviceManufacturer;
            // Device version
            annotations["device"] = GADevice.DeviceModel;
            // Platform (operating system)
            annotations["platform"] = GADevice.BuildPlatform;
            // Session identifier
            annotations["session_id"] = SessionId;
            // Session number
            annotations.Add(SessionNumKey, new JSONNumber(SessionNum));

            // type of connection the user is currently on (add if valid)
            string connection_type = GADevice.ConnectionType;
            if (GAValidator.ValidateConnectionType(connection_type))
            {
                annotations["connection_type"] = connection_type;
            }

            if (!string.IsNullOrEmpty(GADevice.GameEngineVersion))
            {
                annotations["engine_version"] = GADevice.GameEngineVersion;
            }

            // remote configs
            if(Instance.remoteConfigs != null && Instance.remoteConfigs.Count > 0)
            {
                annotations["configurations"] = Instance.remoteConfigs;
            }

            // A/B testing
            if (!string.IsNullOrEmpty(Instance.AbId))
            {
                annotations["ab_id"] = Instance.AbId;
            }
            if (!string.IsNullOrEmpty(Instance.AbVariantId))
            {
                annotations["ab_variant_id"] = Instance.AbVariantId;
            }

#if WINDOWS_UWP
            if (!string.IsNullOrEmpty(GADevice.AdvertisingId))
            {
                annotations["uwp_aid"] = GADevice.AdvertisingId;
            }
            else if (!string.IsNullOrEmpty(GADevice.DeviceId))
            {
                annotations["uwp_id"] = GADevice.DeviceId;
            }
#endif

            // ---- CONDITIONAL ---- //

            // App build version (use if not nil)
            if (!string.IsNullOrEmpty(Build))
            {
                annotations["build"] = Build;
            }

            return annotations;
        }

        public static JSONObject GetSdkErrorEventAnnotations()
        {
            JSONObject annotations = new JSONObject();

            // ---- REQUIRED ---- //

            // collector event API version
            annotations.Add("v", new JSONNumber(2));
            // Event UUID
            annotations["event_uuid"] = Guid.NewGuid().ToString().ToLowerInvariant();

            // Category
            annotations["category"] = CategorySdkError;
            // SDK version
            annotations["sdk_version"] = GADevice.RelevantSdkVersion;
            // Operation system version
            annotations["os_version"] = GADevice.OSVersion;
            // Device make (hardcoded to apple)
            annotations["manufacturer"] = GADevice.DeviceManufacturer;
            // Device version
            annotations["device"] = GADevice.DeviceModel;
            // Platform (operating system)
            annotations["platform"] = GADevice.BuildPlatform;

            // type of connection the user is currently on (add if valid)
            string connection_type = GADevice.ConnectionType;
            if (GAValidator.ValidateConnectionType(connection_type))
            {
                annotations["connection_type"] = connection_type;
            }

            if (!string.IsNullOrEmpty(GADevice.GameEngineVersion))
            {
                annotations["engine_version"] = GADevice.GameEngineVersion;
            }

            return annotations;
        }

        public static JSONObject GetInitAnnotations()
        {
            JSONObject initAnnotations = new JSONObject();

            if(string.IsNullOrEmpty(GAState.Identifier))
            {
                CacheIdentifier();
            }

            GAStore.SetState("last_used_identifier", GAState.Identifier);

            initAnnotations["user_id"] = GAState.Identifier;

            // SDK version
            initAnnotations["sdk_version"] = GADevice.RelevantSdkVersion;
            // Operation system version
            initAnnotations["os_version"] = GADevice.OSVersion;

            // Platform (operating system)
            initAnnotations["platform"] = GADevice.BuildPlatform;

            // Build
            if (!string.IsNullOrEmpty(Build))
            {
                initAnnotations["build"] = Build;
            }
            else
            {
                initAnnotations["build"] = null;
            }

            initAnnotations["session_num"] = GAState.SessionNum;
            initAnnotations["random_salt"] = GAState.SessionNum;

            return initAnnotations;
        }

        public static long GetClientTsAdjusted()
        {
            long clientTs = GAUtilities.TimeIntervalSince1970();
            long clientTsAdjustedInteger = clientTs + Instance.ClientServerTimeOffset;

            if(GAValidator.ValidateClientTs(clientTsAdjustedInteger))
            {
                return clientTsAdjustedInteger;
            }
            else
            {
                return clientTs;
            }
        }

        public static bool SessionIsStarted()
        {
            return SessionStart != 0;
        }

        private static void AddErrorEvent(string baseMessage, EGAErrorSeverity severity, string message)
        {
            if (!GAState.IsEventSubmissionEnabled)
            {
                return;
            }

            DateTime now = DateTime.Now;
            if(!timestampMap.ContainsKey(baseMessage))
            {
                timestampMap.Add(baseMessage, now);
            }
            if (!countMap.ContainsKey(baseMessage))
            {
                countMap.Add(baseMessage, 0);
            }
            TimeSpan diff = now - timestampMap[baseMessage];
            int diffMinutes = (int)diff.TotalMinutes;
            if(diffMinutes >= 60)
            {
                countMap[baseMessage] = 0;
                timestampMap[baseMessage] = now;
            }

            if(countMap[baseMessage] >= MaxErrorCount)
            {
                return;
            }

            GAThreading.PerformTaskOnGAThread("addErrorEvent", () =>
            {
                GAEvents.AddErrorEvent(severity, message, null, false, true);
                countMap[baseMessage] = countMap[baseMessage] + 1;
            });
        }

        public static JSONObject ValidateAndCleanCustomFields(IDictionary<string, object> fields)
        {
            JSONObject result = new JSONObject();

            if(fields != null)
            {
                int count = 0;

                foreach(KeyValuePair<string, object> entry in fields)
                {
                    if(entry.Key == null || entry.Value == null)
                    {
                        string baseMessage = "ValidateAndCleanCustomFields: entry with key={0}, value={1} has been omitted because its key or value is null";
                        string message = String.Format(baseMessage, entry.Key, entry.Value);
                        GALogger.W(message);
                        AddErrorEvent(baseMessage, EGAErrorSeverity.Warning, message);
                    }
                    else if(count < MaxCustomFieldsCount)
                    {
                        if(GAUtilities.StringMatch(entry.Key, "^[a-zA-Z0-9_]{1," + MaxCustomFieldsKeyLength + "}$"))
                        {
                            if(entry.Value is string || entry.Value is char)
                            {
                                string value = Convert.ToString(entry.Value);

                                if(value.Length <= MaxCustomFieldsValueStringLength && value.Length > 0)
                                {
                                    result[entry.Key] = value;
                                    ++count;
                                }
                                else
                                {
                                    string baseMessage = "ValidateAndCleanCustomFields: entry with key={0}, value={1} has been omitted because its value is an empty string or exceeds the max number of characters ({2})";
                                    string message = String.Format(baseMessage, entry.Key, entry.Value, MaxCustomFieldsValueStringLength);
                                    GALogger.W(message);
                                    AddErrorEvent(baseMessage, EGAErrorSeverity.Warning, message);
                                }
                            }
                            else if (entry.Value is double)
                            {
                                result[entry.Key] = new JSONNumber((double)entry.Value);
                                ++count;
                            }
                            else if (entry.Value is float)
                            {
                                result[entry.Key] = new JSONNumber((float)entry.Value);
                                ++count;
                            }
                            else if (entry.Value is long || entry.Value is ulong)
                            {
                                result[entry.Key] = new JSONNumber(Convert.ToInt64(entry.Value));
                                ++count;
                            }
                            else if (entry.Value is int ||
                                entry.Value is byte ||
                                entry.Value is sbyte ||
                                entry.Value is byte ||
                                entry.Value is uint ||
                                entry.Value is short ||
                                entry.Value is ushort)
                            {
                                result[entry.Key] = new JSONNumber(Convert.ToInt32(entry.Value));
                                ++count;
                            }
                            else
                            {
                                string baseMessage = "ValidateAndCleanCustomFields: entry with key={0}, value={1} has been omitted because its value is not a string or number";
                                string message = String.Format(baseMessage, entry.Key, entry.Value);
                                GALogger.W(message);
                                AddErrorEvent(baseMessage, EGAErrorSeverity.Warning, message);
                            }
                        }
                        else
                        {
                            string baseMessage = "ValidateAndCleanCustomFields: entry with key={0}, value={1} has been omitted because its key illegal characters, an empty or exceeds the max number of characters ({2})";
                            string message = String.Format(baseMessage, entry.Key, entry.Value, MaxCustomFieldsKeyLength);
                            GALogger.W(message);
                            AddErrorEvent(baseMessage, EGAErrorSeverity.Warning, message);
                        }
                    }
                    else
                    {
                        string baseMessage = "ValidateAndCleanCustomFields: entry with key={0}, value={1} has been omitted because it exceeds the max number of custom fields ({2})";
                        string message = String.Format(baseMessage, entry.Key, entry.Value, MaxCustomFieldsCount);
                        GALogger.W(message);
                        AddErrorEvent(baseMessage, EGAErrorSeverity.Warning, message);
                    }
                }
            }

            return result;
        }

        public static string GetRemoteConfigsStringValue(string key, string defaultValue)
        {
            lock (Instance.remoteConfigsLock)
            {
                return !Instance.remoteConfigs[key].IsNull ? Instance.remoteConfigs[key].Value : defaultValue;
            }
        }

        public static bool IsRemoteConfigsReady()
        {
            return Instance.remoteConfigsIsReady;
        }

        public static void AddRemoteConfigsListener(IRemoteConfigsListener listener)
        {
            if(!Instance.remoteConfigsListeners.Contains(listener))
            {
                Instance.remoteConfigsListeners.Add(listener);
            }
        }

        public static void RemoveRemoteConfigsListener(IRemoteConfigsListener listener)
        {
            if(Instance.remoteConfigsListeners.Contains(listener))
            {
                Instance.remoteConfigsListeners.Remove(listener);
            }
        }

        public static string GetRemoteConfigsAsString()
        {
            return Instance.remoteConfigs.ToString();
        }

        public static string GetABTestingId()
        {
            return Instance.AbId;
        }

        public static string GetABTestingVariantId()
        {
            return Instance.AbVariantId;
        }

        #endregion // Public methods

        #region Private methods

        private static void CacheIdentifier()
        {
            if(!string.IsNullOrEmpty(GAState.UserId))
            {
                GAState.Identifier = GAState.UserId;
            }
#if WINDOWS_UWP
            else if (!string.IsNullOrEmpty(GADevice.AdvertisingId))
            {
                GAState.Identifier = GADevice.AdvertisingId;
            }
            else if (!string.IsNullOrEmpty(GADevice.DeviceId))
            {
                GAState.Identifier = GADevice.DeviceId;
            }
#endif
            else if(!string.IsNullOrEmpty(Instance.DefaultUserId))
            {
                GAState.Identifier = Instance.DefaultUserId;
            }

            GALogger.D("identifier, {clean:" + GAState.Identifier + "}");
        }

#pragma warning disable 0162
        private static void EnsurePersistedStates()
        {
            if(GAStore.InMemory)
            {
#if UNITY
                GALogger.D("retrieving persisted states from local PlayerPrefs");

                GAState instance = GAState.Instance;

                instance.DefaultUserId = UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + SessionNumKey, Guid.NewGuid().ToString());
                {
                    int tmp;
                    int.TryParse(UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + SessionNumKey, "0"), out tmp);
                    SessionNum = tmp;
                }
                {
                    int tmp;
                    int.TryParse(UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + TransactionNumKey, "0"), out tmp);
                    TransactionNum = tmp;
                }
                if(!string.IsNullOrEmpty(CurrentCustomDimension01))
                {
                    UnityEngine.PlayerPrefs.SetString(InMemoryPrefix + Dimension01Key, CurrentCustomDimension01);
                }
                else
                {
                    CurrentCustomDimension01 = UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + Dimension01Key, "");
                }
                if(!string.IsNullOrEmpty(CurrentCustomDimension02))
                {
                    UnityEngine.PlayerPrefs.SetString(InMemoryPrefix + Dimension02Key, CurrentCustomDimension02);
                }
                else
                {
                    CurrentCustomDimension02 = UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + Dimension02Key, "");
                }
                if(!string.IsNullOrEmpty(CurrentCustomDimension03))
                {
                    UnityEngine.PlayerPrefs.SetString(InMemoryPrefix + Dimension03Key, CurrentCustomDimension03);
                }
                else
                {
                    CurrentCustomDimension03 = UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + Dimension03Key, "");
                }

                string sdkConfigCachedString = UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + SdkConfigCachedKey, "");
                if(!string.IsNullOrEmpty(sdkConfigCachedString))
                {
                    // decode JSON
                    JSONNode sdkConfigCached = null;
                    try
                    {
                        sdkConfigCached = JSONNode.LoadFromBinaryBase64(sdkConfigCachedString);
                    }
                    catch(Exception)
                    {
                        //GALogger.E("EnsurePersistedStates: Error decoding json, " + e);
                    }

                    if(sdkConfigCached != null && sdkConfigCached.Count != 0)
                    {
                        string lastUsedIdentifier = UnityEngine.PlayerPrefs.GetString(InMemoryPrefix + "last_used_identifier", "");
                        if(!string.IsNullOrEmpty(lastUsedIdentifier) && lastUsedIdentifier != GAState.Identifier)
                        {
                            GALogger.W("New identifier spotted compared to last one used, clearing cached configs hash!!");
                            if(sdkConfigCached["configs_hash"] != null)
                            {
                                sdkConfigCached["configs_hash"] = null;
                            }
                        }
                        instance.SdkConfigCached = sdkConfigCached;
                    }
                }
#else
                GALogger.W("EnsurePersistedStates: No implementation yet for InMemory=true");
#endif
            }
            else
            {
                // get and extract stored states
                JSONObject state_dict = new JSONObject();
                JSONArray results_ga_state = GAStore.ExecuteQuerySync("SELECT * FROM ga_state;");

                if (results_ga_state != null && results_ga_state.Count != 0)
                {
                    for (int i = 0; i < results_ga_state.Count; ++i)
                    {
                        JSONNode result = results_ga_state[i];
                        state_dict.Add(result["key"], result["value"]);
                    }
                }

                // insert into GAState instance
                GAState instance = GAState.Instance;

                instance.DefaultUserId = state_dict[DefaultUserIdKey] != null ? state_dict[DefaultUserIdKey].Value : Guid.NewGuid().ToString();

                SessionNum = state_dict[SessionNumKey] != null ? state_dict[SessionNumKey].AsInt : 0;

                TransactionNum = state_dict[TransactionNumKey] != null ? state_dict[TransactionNumKey].AsInt : 0;

                // restore dimension settings
                if(!string.IsNullOrEmpty(CurrentCustomDimension01))
                {
                    GAStore.SetState(Dimension01Key, CurrentCustomDimension01);
                }
                else
                {
                    CurrentCustomDimension01 = state_dict[Dimension01Key] != null ? state_dict[Dimension01Key].Value : "";
                    if(!string.IsNullOrEmpty(CurrentCustomDimension01))
                    {
                        GALogger.D("Dimension01 found in cache: " + CurrentCustomDimension01);
                    }
                }

                if(!string.IsNullOrEmpty(CurrentCustomDimension02))
                {
                    GAStore.SetState(Dimension02Key, CurrentCustomDimension02);
                }
                else
                {
                    CurrentCustomDimension02 = state_dict[Dimension02Key] != null ? state_dict[Dimension02Key].Value : "";
                    if(!string.IsNullOrEmpty(CurrentCustomDimension02))
                    {
                        GALogger.D("Dimension02 found in cache: " + CurrentCustomDimension02);
                    }
                }

                if(!string.IsNullOrEmpty(CurrentCustomDimension03))
                {
                    GAStore.SetState(Dimension03Key, CurrentCustomDimension03);
                }
                else
                {
                    CurrentCustomDimension03 = state_dict[Dimension03Key] != null ? state_dict[Dimension03Key].Value : "";
                    if(!string.IsNullOrEmpty(CurrentCustomDimension03))
                    {
                        GALogger.D("Dimension03 found in cache: " + CurrentCustomDimension03);
                    }
                }

                // get cached init call values
                string sdkConfigCachedString = state_dict[SdkConfigCachedKey] != null ? state_dict[SdkConfigCachedKey].Value : "";
                if (!string.IsNullOrEmpty(sdkConfigCachedString))
                {
                    // decode JSON
                    JSONNode sdkConfigCached = null;

                    try
                    {
                        sdkConfigCached = JSONNode.LoadFromBinaryBase64(sdkConfigCachedString);
                    }
                    catch(Exception)
                    {
                        //GALogger.E("EnsurePersistedStates: Error decoding json, " + e);
                    }

                    if (sdkConfigCached != null && sdkConfigCached.Count != 0)
                    {
                        string lastUsedIdentifier = state_dict["last_used_identifier"] != null ? state_dict["last_used_identifier"].Value : "";
                        if(!string.IsNullOrEmpty(lastUsedIdentifier) && lastUsedIdentifier != GAState.Identifier)
                        {
                            GALogger.W("New identifier spotted compared to last one used, clearing cached configs hash!!");
                            if(sdkConfigCached["configs_hash"] != null)
                            {
                                sdkConfigCached["configs_hash"] = null;
                            }
                        }
                        instance.SdkConfigCached = sdkConfigCached;
                    }
                }

                {
                    JSONNode currentSdkConfig = SdkConfig;
                    instance.ConfigsHash = currentSdkConfig["configs_hash"] != null && currentSdkConfig["configs_hash"].IsString ? currentSdkConfig["configs_hash"].Value : "";
                    instance.AbId = currentSdkConfig["ab_id"] != null && currentSdkConfig["ab_id"].IsString ? currentSdkConfig["ab_id"].Value : "";
                    instance.AbVariantId = currentSdkConfig["ab_variant_id"] != null && currentSdkConfig["ab_variant_id"].IsString ? currentSdkConfig["ab_variant_id"].Value : "";
                }

                JSONArray results_ga_progression = GAStore.ExecuteQuerySync("SELECT * FROM ga_progression;");

                if (results_ga_progression != null && results_ga_progression.Count != 0)
                {
                    for (int i = 0; i < results_ga_progression.Count; ++i)
                    {
                        JSONNode result = results_ga_progression[i];
                        if (result != null && result.Count != 0)
                        {
                            instance.progressionTries[result["progression"].Value] = result["tries"].AsInt;
                        }
                    }
                }
            }
        }
#pragma warning restore 0162

#if WINDOWS_UWP || WINDOWS_WSA
        private async static System.Threading.Tasks.Task StartNewSession()
#else
        private static void StartNewSession()
#endif
        {
            GALogger.I("Starting a new session.");

            // make sure the current custom dimensions are valid
            ValidateAndFixCurrentDimensions();

            // call the init call
#if WINDOWS_UWP || WINDOWS_WSA
            KeyValuePair<EGAHTTPApiResponse, JSONObject> initResponse = await GAHTTPApi.Instance.RequestInitReturningDict(Instance.ConfigsHash);
#else
            KeyValuePair<EGAHTTPApiResponse, JSONObject> initResponse = GAHTTPApi.Instance.RequestInitReturningDict(Instance.ConfigsHash);
#endif

            StartNewSession(initResponse.Key, initResponse.Value);
        }

        public static void StartNewSession(EGAHTTPApiResponse initResponse, JSONObject initResponseDict)
        {
            // init is ok
            if((initResponse == EGAHTTPApiResponse.Ok || initResponse == EGAHTTPApiResponse.Created) && initResponseDict != null)
            {
                // set the time offset - how many seconds the local time is different from servertime
                long timeOffsetSeconds = 0;
                if(initResponseDict["server_ts"] != null)
                {
                    long serverTs = initResponseDict["server_ts"].AsLong;
                    timeOffsetSeconds = CalculateServerTimeOffset(serverTs);
                }
                initResponseDict.Add("time_offset", new JSONNumber(timeOffsetSeconds));

                if(initResponse != EGAHTTPApiResponse.Created)
                {
                    JSONNode currentSdkConfig = GAState.SdkConfig;
                    // use cached if not Created
                    if(currentSdkConfig["configs"] != null && currentSdkConfig["configs"].IsArray)
                    {
                        initResponseDict["configs"] = currentSdkConfig["configs"].AsArray;
                    }
                    if(currentSdkConfig["configs_hash"] != null && currentSdkConfig["configs_hash"].IsString)
                    {
                        initResponseDict["configs_hash"] = currentSdkConfig["configs_hash"].Value;
                    }
                    if(currentSdkConfig["ab_id"] != null && currentSdkConfig["ab_id"].IsString)
                    {
                        initResponseDict["ab_id"] = currentSdkConfig["ab_id"].Value;
                    }
                    if(currentSdkConfig["ab_variant_id"] != null && currentSdkConfig["ab_variant_id"].IsString)
                    {
                        initResponseDict["ab_variant_id"] = currentSdkConfig["ab_variant_id"].Value;
                    }
                }

                Instance.ConfigsHash = initResponseDict["configs_hash"] != null && initResponseDict["configs_hash"].IsString ? initResponseDict["configs_hash"].Value : "";
                Instance.AbId = initResponseDict["ab_id"] != null && initResponseDict["ab_id"].IsString ? initResponseDict["ab_id"].Value : "";
                Instance.AbVariantId = initResponseDict["ab_variant_id"] != null && initResponseDict["ab_variant_id"].IsString ? initResponseDict["ab_variant_id"].Value : "";

                // insert new config in sql lite cross session storage
                GAStore.SetState(SdkConfigCachedKey, initResponseDict.SaveToBinaryBase64());
                GALogger.D("initResponseDict: " + initResponseDict.ToString());

                // set new config and cache in memory
                Instance.sdkConfigCached = initResponseDict;
                Instance.sdkConfig = initResponseDict;

                Instance.InitAuthorized = true;
            }
            else if(initResponse == EGAHTTPApiResponse.Unauthorized)
            {
                GALogger.W("Initialize SDK failed - Unauthorized");
                Instance.InitAuthorized = false;
            }
            else
            {
                // log the status if no connection
                if(initResponse == EGAHTTPApiResponse.NoResponse || initResponse == EGAHTTPApiResponse.RequestTimeout)
                {
                    GALogger.I("Init call (session start) failed - no response. Could be offline or timeout.");
                }
                else if(initResponse == EGAHTTPApiResponse.BadResponse || initResponse == EGAHTTPApiResponse.JsonEncodeFailed || initResponse == EGAHTTPApiResponse.JsonDecodeFailed)
                {
                    GALogger.I("Init call (session start) failed - bad response. Could be bad response from proxy or GA servers.");
                }
                else if(initResponse == EGAHTTPApiResponse.BadRequest || initResponse == EGAHTTPApiResponse.UnknownResponseCode)
                {
                    GALogger.I("Init call (session start) failed - bad request or unknown response.");
                }

                // init call failed (perhaps offline)
                if(Instance.sdkConfig == null)
                {
                    if(Instance.sdkConfigCached != null)
                    {
                        GALogger.I("Init call (session start) failed - using cached init values.");
                        // set last cross session stored config init values
                        Instance.sdkConfig = Instance.sdkConfigCached;
                    }
                    else
                    {
                        GALogger.I("Init call (session start) failed - using default init values.");
                        // set default init values
                        Instance.sdkConfig = Instance.sdkConfigDefault;
                    }
                }
                else
                {
                    GALogger.I("Init call (session start) failed - using cached init values.");
                }
                Instance.InitAuthorized = true;
            }

            {
                JSONNode currentSdkConfig = SdkConfig;

                if (currentSdkConfig["enabled"].IsBoolean && !currentSdkConfig["enabled"].AsBool)
                {
                    Instance.Enabled = false;
                }
                else if (!Instance.InitAuthorized)
                {
                    Instance.Enabled = false;
                }
                else
                {
                    Instance.Enabled = true;
                }
            }

            // set offset in state (memory) from current config (config could be from cache etc.)
            Instance.ClientServerTimeOffset = SdkConfig["time_offset"] != null ? SdkConfig["time_offset"].AsLong : 0;

            // populate remoteConfigs
            PopulateConfigurations(SdkConfig);

            // if SDK is disabled in config
            if(!IsEnabled())
            {
                GALogger.W("Could not start session: SDK is disabled.");
                // stop event queue
                // + make sure it's able to restart if another session detects it's enabled again
                GAEvents.StopEventQueue();
                return;
            }
            else
            {
                GAEvents.EnsureEventQueueIsRunning();
            }

            // generate the new session
            string newSessionId = Guid.NewGuid().ToString();
            string newSessionIdLowercase = newSessionId.ToLowerInvariant();

            // Set session id
            SessionId = newSessionIdLowercase;

            // Set session start
            SessionStart = GetClientTsAdjusted();

            // Add session start event
            GAEvents.AddSessionStartEvent();
        }

        private static void ValidateAndFixCurrentDimensions()
        {
            // validate that there are no current dimension01 not in list
            if (!GAValidator.ValidateDimension01(CurrentCustomDimension01))
            {
                GALogger.D("Invalid dimension01 found in variable. Setting to nil. Invalid dimension: " + CurrentCustomDimension01);
                SetCustomDimension01("");
            }
            // validate that there are no current dimension02 not in list
            if (!GAValidator.ValidateDimension02(CurrentCustomDimension02))
            {
                GALogger.D("Invalid dimension02 found in variable. Setting to nil. Invalid dimension: " + CurrentCustomDimension02);
                SetCustomDimension02("");
            }
            // validate that there are no current dimension03 not in list
            if (!GAValidator.ValidateDimension03(CurrentCustomDimension03))
            {
                GALogger.D("Invalid dimension03 found in variable. Setting to nil. Invalid dimension: " + CurrentCustomDimension03);
                SetCustomDimension03("");
            }
        }

        private static long CalculateServerTimeOffset(long serverTs)
        {
            long clientTs = GAUtilities.TimeIntervalSince1970();
            return serverTs - clientTs;
        }

        private static void PopulateConfigurations(JSONNode sdkConfig)
        {
            lock(Instance.remoteConfigsLock)
            {
                JSONArray remoteConfigs = sdkConfig["configs"].AsArray;

                if(remoteConfigs != null)
                {
                    Instance.remoteConfigs = new JSONObject();
                    for(int i = 0; i < remoteConfigs.Count; ++i)
                    {
                        JSONNode configuration = remoteConfigs[i];

                        if(configuration != null)
                        {
                            string key = configuration["key"].Value;
                            object value = null;
                            if(configuration["value"].IsNumber)
                            {
                                value = configuration["value"].AsDouble;
                            }
                            else
                            {
                                value = configuration["value"].Value;
                            }
                            long start_ts = configuration["start_ts"].IsNumber ? configuration["start_ts"].AsLong : long.MinValue;
                            long end_ts = configuration["end_ts"].IsNumber ? configuration["end_ts"].AsLong : long.MaxValue;

                            long client_ts_adjusted = GetClientTsAdjusted();

                            GALogger.D("PopulateConfigurations: key=" + key + ", value=" + value + ", start_ts=" + start_ts + ", end_ts=" + ", client_ts_adjusted=" + client_ts_adjusted);

                            if(key != null && value != null && client_ts_adjusted > start_ts && client_ts_adjusted < end_ts)
                            {
                                JSONObject json = new JSONObject();
                                if(configuration["value"].IsNumber)
                                {
                                    Instance.remoteConfigs.Add(key, new JSONNumber(configuration["value"].AsDouble));
                                }
                                else
                                {
                                    Instance.remoteConfigs.Add(key, configuration["value"].Value);
                                }

                                GALogger.D("configuration added: " + configuration);
                            }
                        }
                    }
                }
                Instance.remoteConfigsIsReady = true;
                foreach(IRemoteConfigsListener listener in Instance.remoteConfigsListeners)
                {
                    listener.OnRemoteConfigsUpdated();
                }
            }
        }

        #endregion // Private methods
    }
}


text:
#ifndef __XF_TYPEDEF_H__
#define __XF_TYPEDEF_H__

#define XF_NULL     0

typedef signed char int8;
typedef unsigned char   uint8;
typedef short  int16;
typedef unsigned short  uint16;
typedef int  int32;
typedef unsigned   uint32;
typedef long long  int64;
typedef unsigned long long   uint64;

/* 7.18.1.2  Minimum-width integer types */
typedef signed char int_least8;
typedef unsigned char   uint_least8;
typedef short  int_least16;
typedef unsigned short  uint_least16;
typedef int  int_least32;
typedef unsigned   uint_least32;
typedef long long  int_least64;
typedef unsigned long long   uint_least64;

/*  7.18.1.3  Fastest minimum-width integer types
 *  Not actually guaranteed to be fastest for all purposes
 *  Here we use the exact-width types for 8 and 16-bit ints.
 */
typedef signed char int_fast8;
typedef unsigned char uint_fast8;
typedef short  int_fast16;
typedef unsigned short  uint_fast16;
typedef int  int_fast32;
typedef unsigned  int  uint_fast32;
typedef long long  int_fast64;
typedef unsigned long long   uint_fast64;

/* 7.18.1.5  Greatest-width integer types */
typedef long long  intmax;
typedef unsigned long long   uintmax;

//typedef enum {
//    false = (char)0,
//    true,
//} bool;

typedef uint8 *XF_Memory;

#endif

redpajama_set_name: RedPajamaGithub


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddColumnsUsersFacebook extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::table('users', function(Blueprint $table)
        {
            $table->string('fotoperfil')->nullable();
            $table->string('fotoportada')->nullable();
            $table->string('facebook')->nullable();
        });
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
        Schema::table('users', function(Blueprint $table)
        {
            $table->dropColumn(array('fotoperfil','fotoportada','facebook'));
        });
	}

}


text:
package org.george.minesweeper;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder.AudioSource;
import android.os.Bundle;
import android.view.MotionEvent;

import com.google.android.glass.touchpad.Gesture;
import com.google.android.glass.touchpad.GestureDetector;

public class MineSweeperActivity extends Activity implements SensorEventListener {

	private static final int SAMPLING_RATE = 44100;

	private MineSweeperView mMineSweeperView;

	private SensorManager mSensorManager;
	private GestureDetector mGestureDetector;

	private RecordingThread mRecordingThread;
	private int mBufferSize;
	private short[] mAudioBuffer;

	private final float[] mRotationMatrix = new float[16];
	private final float[] mOrientation = new float[9];

	float previousHeading = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_minesweeper);

		mMineSweeperView = (MineSweeperView) findViewById(R.id.minesweeper_view);

		// Compute the minimum required audio buffer size and allocate the buffer.
		mBufferSize = AudioRecord.getMinBufferSize(SAMPLING_RATE, AudioFormat.CHANNEL_IN_MONO,
				AudioFormat.ENCODING_PCM_16BIT);
		mAudioBuffer = new short[mBufferSize / 2];

		mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		mGestureDetector = createGestureDetector(this);

	}

	@Override
	protected void onResume() {
		super.onResume();

		mRecordingThread = new RecordingThread();
		mRecordingThread.start();

		registerListeners();
	}

	@Override
	protected void onPause() {
		super.onPause();

		if (mRecordingThread != null) {
			mRecordingThread.stopRunning();
			mRecordingThread = null;
		}
		unregisterListeners();
	}

	@Override
	protected void onDestroy() {
		super.onPause();

		if (mRecordingThread != null) {
			mRecordingThread.stopRunning();
			mRecordingThread = null;
		}
		unregisterListeners();
	}

	private class RecordingThread extends Thread {

		private boolean mShouldContinue = true;

		@Override
		public void run() {
			android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO);

			AudioRecord record = new AudioRecord(AudioSource.MIC, SAMPLING_RATE,
					AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, mBufferSize);
			record.startRecording();

			while (shouldContinue()) {
				record.read(mAudioBuffer, 0, mBufferSize / 2);
				mMineSweeperView.updateData();
				reveal();
			}

			record.stop();
			record.release();
		}

		private synchronized boolean shouldContinue() {
			return mShouldContinue;
		}

		public synchronized void stopRunning() {
			mShouldContinue = false;
		}

		private void reveal() {
			double sum = 0;

			for (short rawSample : mAudioBuffer) {
				double sample = rawSample / 32768.0;
				sum += sample * sample;
			}

			double rms = Math.sqrt(sum / mAudioBuffer.length);
			final double db = 20 * Math.log10(rms);

			if (db > -30) {
				mMineSweeperView.reveal();
			}
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		return;
	}

	private static float GetHeadingDiff(float start, float end)
    {
		float diff = end - start;
		float absDiff = Math.abs(diff);

        if (absDiff <= 180f)
        {
            return absDiff == 180f ? absDiff : diff;
        } else if (end > start) {
            return absDiff - 360f;
        } else {
            return 360f - absDiff;
        }
    }

	@Override
	public void onSensorChanged(SensorEvent event) {
		if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
			SensorManager.getRotationMatrixFromVector(mRotationMatrix, event.values);
			SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_X,
					SensorManager.AXIS_Z, mRotationMatrix);
			SensorManager.getOrientation(mRotationMatrix, mOrientation);

			float pitch = (float) Math.toDegrees(mOrientation[1]);

			pitch = (pitch > 20) ? 20 : pitch;
			pitch = (pitch < -20) ? -20 : pitch;
			int y = 180 + (int)(9 * pitch);

			float currentHeading = (float) Math.toDegrees(mOrientation[0]);

			int x;
			if (previousHeading == -1) {
				previousHeading = currentHeading;
				x = (int)((640 * .75) / 2);
			} else {
				x = mMineSweeperView.getTarget().getX();
			}
			x += (int) (20 * GetHeadingDiff(previousHeading, currentHeading));
			x = (x > 640) ? 640 : x;
			x = (x < 0) ? 0 : x;
			previousHeading = currentHeading;

			mMineSweeperView.getTarget().setX(x);
			mMineSweeperView.getTarget().setY(y);

		}
	}

	private void registerListeners() {
		mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR),
				SensorManager.SENSOR_DELAY_NORMAL);
	}

	private void unregisterListeners() {
		mSensorManager.unregisterListener(this);
	}

    private GestureDetector createGestureDetector(Context context) {
    GestureDetector gestureDetector = new GestureDetector(context);
        //Create a base listener for generic gestures
        gestureDetector.setBaseListener( new GestureDetector.BaseListener() {
            @Override
            public boolean onGesture(Gesture gesture) {
                if (gesture == Gesture.TAP) {
                    // do something on tap
                    return false;
                } else if (gesture == Gesture.TWO_TAP) {
                    // do something on two finger tap
                    return false;
                } else if (gesture == Gesture.SWIPE_RIGHT) {
                	mMineSweeperView.reveal();
                    return true;
                } else if (gesture == Gesture.SWIPE_LEFT) {
                    // do something on left (backwards) swipe
                	mMineSweeperView.flag();
                    return true;
                }
                return false;
            }
        });

        return gestureDetector;
    }

    /*
     * Send generic motion events to the gesture detector
     */
    @Override
    public boolean onGenericMotionEvent(MotionEvent event) {
        if (mGestureDetector != null) {
            return mGestureDetector.onMotionEvent(event);
        }
        return false;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true" android:drawable="@mipmap/icon_add_story_p"/>
    <item android:state_pressed="false" android:drawable="@mipmap/icon_add_story_n"/>

</selector>


text:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
using System.Xml.Linq;

namespace Marimo.LinqToDejizo.DejizoEntity
{
    [DataContract(Namespace = "http://btonic.est.co.jp/NetDic/NetDicV09")]
    public class GetDicItemResult
    {
        [DataMember(Order =0)]
        public XElement Head { get; set; }

        [DataMember(Order =1)]
        public XElement Body { get; set; }
    }
}


text:
{% assign array = site.course | sort:include.param1 %}

  {% for item in array offset:include.param2 limit:include.param3 %}

{{ item.title }}

          {{ item.price }}
          €

          {% for date in item.termin %}
          {{ date  }}

          {% endfor %}

        {{ item.summary | markdownify }}

  {% endfor %}


text:
package com.leandronunes85.lfe.maven_plugin.it.java;

import com.leandronunes85.lfe.maven_plugin.it.java.LogFormatEnforcer;
import org.junit.Test;

import java.util.ArrayList;

public class LogFormatEnforcerTest {

    private final LogFormatEnforcer victim = LogFormatEnforcer.loggerFor(LogFormatEnforcerTest.class);

    @Test
    public void basicSyntaxTest() {
        victim.info(messageBuilder -> messageBuilder.mandatory1("valueMandatory1").mandatory2(100)
                .optional1(new ArrayList()).optional2("value")
                .and("other", "otherValue").exception(new RuntimeException()));
    }

    private String costlyOperation() {
        throw new RuntimeException("This method should not have been called!");
    }

    public void logValuesAreNotComputedIfTheLogIsNotPerformed() {
        victim.trace(messageBuilder -> messageBuilder
                .mandatory1("valueMandatory1").mandatory2(costlyOperation())
        );
    }
}


text:
import gevent
from gevent import monkey
monkey.patch_all()

import os
import sys
import optparse
import textwrap
import StringIO
import logging.config

import configobj
import pkg_resources

from . import config

from services.common.configuration import mqtt_spec, mqtt_configuration

class Manager(object):
    def __init__(self, mqtt_conf):
        self.mqtt_conf = mqtt_configuration(**mqtt_conf)

    def _run(self):
        msg = "This is start point"
        #msg = 'Manager app launched (mqtt_host : %s, mqtt_port : %s)' %(self.mqtt_host, self.mqtt_port)
        print msg
        logging.getLogger('limfx.manager').info(msg)

    def run(self):
        me = gevent.spawn(self._run)
        me.join()

    # The callback for when the client receives a CONNACK response from the server.
    def on_connect(self, client, userdata, flags, rc):
        print("Connected with result code "+str(rc))

        # Subscribing in on_connect() means that if we lose the connection and
        # reconnect then subscriptions will be renewed.
        client.subscribe("$SYS/#")

    # The callback for when a PUBLISH message is received from the server.
    def on_message(self, client, userdata, msg):
        print(msg.topic+" "+str(msg.payload))

class App(object):
    spec = {
        'root': 'string(default="%s")' % pkg_resources.get_distribution('limfx').location,

        'application': {
            '': 'boolean(default=True)',
        },

        'mqtt': mqtt_spec,

        'logging': {
            'formatters': {'keys': 'string(default="")'},
            'handlers': {'keys': 'string(default="")'},
            'loggers': {'keys': 'string(default="root")'},
            'logger_root': {
                'level': 'string(default="NOTSET")',
                'handlers': 'string(default="")'
            }
        }
    }

    def __init__(self, config_file, error, initial_conf=None):
        conf = configobj.ConfigObj(config_file, configspec=configobj.ConfigObj(self.spec), list_values=False, interpolation='Template')
        conf.merge(initial_conf or {})
        config.validate(config_file, conf, error)

        logging.addLevelName(10000, 'NONE')

        log_conf = ''
        for k, v in conf['logging'].items():
            log_conf += '\n[%s]\n' % k
            log_conf += '\n'.join(map('='.join, v.items()))

        logging.config.fileConfig(StringIO.StringIO(log_conf))

        self.manager = Manager(mqtt_conf=conf['mqtt'])

    def run(self):
        self.manager.run()

def run(*args, **kw):
    if len(sys.argv) == 1:
        print textwrap.dedent('''
        Usage: %s <command>

        with <command>:
          - run           : launch app
        ''' % os.path.basename(sys.argv[0]))
        return 2

    command = sys.argv.pop(1)
    parser = optparse.OptionParser('%%prog start <config_file>')

    if command != 'run':
        parser.error('command not found')

    options, args = parser.parse_args()
    conf = {}

    if len(args) != 1:
        parser.error('<config_file> missing')

    config_file = args[0]
    if not os.path.isfile(config_file):
        parser.error('Configuration file "%s" doesn\'t exist' % config_file)

    # -------------------------------------------------------------------------

    app = App(config_file, parser.error, conf)

    if command == 'run':
        app.run()


text:
//---------------------------------------------------------------------------
//		E L E N A   P r o j e c t:  ELENA Common Library
//
//		This file contains ELENA Engine Path class declarations.
//
//                                             (C)2021-2022, by Aleksey Rakov
//---------------------------------------------------------------------------

#ifndef PATHS_H
#define PATHS_H

namespace elena_lang
{

   // --- path_t ---
#ifdef _MSC_VER

   typedef wstr_t path_t;

#elif __GNUG__

   typedef ustr_t path_t;

#endif

   // --- PathUtil ---
   class PathUtil
   {
   public:
      static bool compare(path_t path1, path_t path);

      static bool removeFile(path_t path);

      static bool recreatePath(/*path_t root, */path_t path);

      static bool isRelative(path_t path, size_t length);

      static bool checkExtension(path_t path, path_t extension);
#ifdef _MSC_VER
      static bool checkExtension(path_t path, ustr_t extension);
#endif
   };

   // --- PathString ---
   class PathString : public String<path_c, FILENAME_MAX>
   {
   public:
      path_t operator*() const { return path_t(_string); }

      void copy(path_t path)
      {
         String::copy(path);
      }
      void copy(path_t path, size_t length)
      {
         String::copy(path, length);
      }
      void copySubPath(path_t path)
      {
         size_t pos = path.findLast(PATH_SEPARATOR);
         if (pos != NOTFOUND_POS) {
            copy(path, pos);
         }
         else clear();
      }

      void combine(path_t path)
      {
         combine(path, path.length());
      }
      void combine(path_t path, size_t length)
      {
         if (length > 0) {
            if (PathUtil::isRelative(path, length)) {
               size_t strLength = getlength(_string);

               if (strLength > 0 && _string[strLength - 1] != PATH_SEPARATOR)
                  append(PATH_SEPARATOR);

               append(path, length);
            }
            else copy(path, length);
         }
      }

      void appendSubName(path_t name, size_t len)
      {
         if (!emptystr(name)) {
            append('.');
            append(name, len);
         }
      }

      void appendExtension(path_t extension)
      {
         append('.');
         append(extension, extension.length());
      }

      void changeExtension(path_t extension)
      {
         path_t p(_string);

         size_t namepos = p.findLast(PATH_SEPARATOR) + 1;
         size_t index = p.findLastSub(namepos, '.', NOTFOUND_POS);
         if (index != NOTFOUND_POS) {
            _string[index] = 0;
         }
         append('.');
         append(extension, extension.length());
      }

      PathString() = default;

      PathString(path_t path)
      {
         copy(path);
      }
      PathString(path_t root, path_t subPath)
      {
         copy(root);
         combine(subPath);
      }
   #ifdef _MSC_VER
      bool append(const path_c* s, size_t length)
      {
         return String::append(s, length);
      }
      bool append(const path_c* s)
      {
         return String::append(s);
      }
      bool append(path_c c)
      {
         return String::append(c);
      }
      void append(ustr_t s)
      {
         PathString tmp(s);

         append(*tmp);
      }

      void changeExtension(ustr_t extension)
      {
         PathString ext(extension);

         changeExtension(*ext);
      }

      void appendExtension(ustr_t extension)
      {
         PathString ext(extension);

         appendExtension(*ext);
      }

      void copy(ustr_t path)
      {
         size_t destLen = FILENAME_MAX;
         StrConvertor::copy(_string, path.str(), path.length(), destLen);

         _string[destLen] = 0;
      }
      void copy(ustr_t path, size_t length)
      {
         size_t destLen = FILENAME_MAX;
         StrConvertor::copy(_string, path.str(), length, destLen);

         _string[destLen] = 0;
      }
      void combine(ustr_t path)
      {
         PathString pathStr(path);
         combine(*pathStr);
      }

      PathString(ustr_t path)
      {
         copy(path);
      }
      PathString(path_t root, ustr_t path)
      {
         copy(root);

         PathString subPath(path);
         combine(*subPath);
      }
#endif
   };

   // --- FileNameString ---
   class FileNameString : public String<path_c, FILENAME_MAX>
   {
   public:
      path_t operator*() const { return path_t(_string); }

      void copyName(path_t path)
      {
         size_t index = path.findLast(PATH_SEPARATOR) + 1;
         size_t dotIndex = path.findLastSub(index, '.', path.length());

         copy(path.str() + index, dotIndex - index);
      }
      void copyExtension(path_t path)
      {
         size_t index = path.findLast(PATH_SEPARATOR) + 1;
         size_t dotIndex = path.findLastSub(index, '.', path.length());

         append('.');
         append(path.str() + dotIndex + 1);
      }

      FileNameString(path_t path, bool withExtension = false)
      {
         copyName(path);
         if (withExtension)
            copyExtension(path);
      }
   };

   inline void freepath(path_t path)
   {
      path.free();
   }

}

#endif


text:
/* Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification\
for details on configuring this project to bundle and minify static web assets. */
* {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}

body {
    background-image: url(../images/background11.jpg);
    background-size:cover;

    background-position: initial;

    box-sizing: border-box;

    padding-top: 60px;
    padding-bottom: 25px;
    display:flex;
    justify-content:center;
    align-items:center;
    min-height: 100vh;

}

/* Wrapping element */
/* Set some basic padding to keep content from hitting the edges */
.body-content {
    padding-left: 15px;
    padding-right: 15px;

}

/* Carousel
.carousel-caption p {
    font-size: 20px;
    line-height: 1.4;
}

/* Make .svg files in the carousel display properly in older browsers */
.carousel-inner .item img[src$=".svg"] {
    width: 100%;
}

/* QR code generator */
#qrCode {
    margin: 15px;
}

/* Hide/rearrange for smaller screens */
@media screen and (max-width: 767px) {
    /* Hide captions */
    .carousel-caption {
        display: none;
    }
}
/*Nav bar style */

mynav_navbar {
    overflow: hidden;
    background-color: #007bff;
    font-family: Arial, Helvetica, sans-serif;

}

.mynav_navbar a {
    float: left;
    font-size: 16px;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

.mynav_dropdown {
    float: left;
    overflow: hidden;
}

    .mynav_dropdown .mynav_dropbtn {
        font-size: 16px;
        border: none;
        outline: none;
        color: white;
        padding: 14px 16px;
        background-color: inherit;
        font-family: inherit;
        margin: 0;
    }

    .mynav_navbar a:hover, .mynav_dropdown:hover .mynav_dropbtn {
        background-color: #0b98de;
    }

.mynav_dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

    .mynav_dropdown-content a {
        float: none;
        color: black;
        padding: 12px 16px;
        text-decoration: none;
        display: block;
        text-align: left;
    }

        .mynav_dropdown-content a:hover {
            background-color: #ddd;
        }

.mynav_dropdown:hover .mynav_dropdown-content {
    display: block;
}

.navbar-inverse {
    background-color: #007bff;
}

/*.navbar-brand {
    background-image: url(../images/codeLogo.jpg);
    background:repeating-linear-gradient();
}*/

/* Style Vehicle Tracker Page */

#logo {
    font-family: 'Hind', sans-serif;
    font-size: 30px;
    letter-spacing: -2px;
    text-shadow: 1px 1px 2px #c4c4c4;
    padding-left: 20px;
    padding-right: 40px;
    margin-right: 10px;
    margin-top: -6px;

}

.container {
    /*margin-left: 15px !important;
    width:auto !important;*/

    position:relative !important;
    width:900px !important;

    display:flex !important;
    justify-content:space-around !important;
}

.container .card
{
    position:relative;
    width:2000px;
    background: linear-gradient(0deg,#1b1b1b,#222,#1b1b1b);
    display:flex;
    justify-content:center;
    /*align-items:centre;*/
    height:1050px;
    border-radius:4px;
    text-align:center;
    overflow:hidden;
    transition:0.5s;
}

.container .card:hover{

    transform:translateY(-10);
    box-shadow:0 15px 35px rgba(0,0,0,5);

}

.container .card:before
{
    content:'';
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height: 100%;
    /*background: rgba(255,255,255,03);*/
    pointer-events:none;
    z-index:1;

}

.percent{

    position:relative;
    width:150px;
    height:150px;
    border-radius:50%;
    box-shadow:inset 0 0 50px #000;
    background:#222;
    z-index:1000;
}

.percent .number{

    position: absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
    display: flex;
    justify-content:center;
    align-items: center;
    border-radius:50%;

}

.percent .number h2{

    color:#777;
    font-weight:700;
    font-size:40px;
    transition:0.5s;

}

.card:hover .percent .number h2{

    color:#fff;
    font-size:60px;

}

.percent .number h2 span {

    font-size:24px;
    color:#777;

}

.card:hover .percent .number h2 span{

    color:#fff;

}

.text{

    margin-top:20px;
    position:relative;
    color:#777;
    font-weight:700;
    font-size: 18px;
    letter-spacing: 1px;
    text-transform:uppercase;
    transition: 0.5s;

}

.card:hover .text{

    color:#fff;

}

    .footer {
    position:fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    background-color: #007bff;
    color: white;
    text-align: center;
}

#myFooter{
    position:center;
    text-align:center;
}
/* style the main context of the page */
p {
    color: white;
    text-align: left;
    font-size: 16px;
    text-decoration: none;
    font-family: 'Myanmar Text';
}

.my_home_div1 {
    padding-left: 16px;
    padding-top: 105px;

}
.my_home_div2 {
    padding-left: 16px;
    padding-top: 314px;
    padding-right: 200px;
}

.img_h_text_wrap{

    float:left;

}

.mydiv_h_rightside {
    width: 200px;

    height: 300px;
    background-color: aliceblue;
    padding-top: 100px;

    margin: 50px;
    float: right;
    top: -40px;
}

.row{

    margin-right:-15px !important;
    margin-left:-45px !important;
}

/*   Meter reading */
 svg{

     position: relative;
     width:150px;
     height:150px;
     z-index:1000;

 }

    svg circle {
        width: 100%;
        height: 100%;
        fill: none;
        stroke: #191919;
        stroke-width: 10;
        stroke-linecap: round;
        /*background-color: wheat;*/
        transform: translate(5px,5px);
    }

 svg circle:nth-child(2){

     stroke-dasharray:450;
     stroke-dashoffset:450;
 }

.card:nth-child(1) svg circle:nth-child(2) {

    stroke-dashoffset: calc( 450 - ( 450 * 90) / 100); /* OpenCV page  */
    stroke: #10e522;
}

.card:nth-child(2) svg circle:nth-child(2) {

    stroke-dashoffset: calc( 450 - ( 450 * 85 ) / 100);
    stroke: #0b98de;
}

.card:nth-child(3) svg circle:nth-child(2) {

    stroke-dashoffset: calc( 450 - ( 450 * 60 ) / 100);
    stroke: #ff6a00;
}

/* career plan */
#ip5 {
    border-radius: 15px 50px;
    background: #609;
    padding: 20px;
    width: 230px;
    height: 15px;
    color:white;
}

#ipArrow{
    font-size:100px;
    color:#609;
    margin-left:396px;
}

/*download button */
.btn {
    background-color: DodgerBlue;
    border: none;
    color: white;
    padding: 12px 30px;
    cursor: pointer;
    font-size: 20px;
}

    /* Darker background on mouse-over */
    .btn:hover {
        background-color: RoyalBlue;
    }

    /*image rotate issue */
.rotateimg180 {
    -webkit-transform: rotate(180deg);
    -moz-transform: rotate(180deg);
    -ms-transform: rotate(180deg);
    -o-transform: rotate(180deg);
    transform: rotate(180deg);
}

.rotateimg90 {
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    transform: rotate(90deg);
}

.PicLeft {

    margin-left:-200px;
}


text:
<?php

namespace Eshopera\Core\Lib\UI\Component;

use Eshopera\Core\Lib\UI\Component;
use Eshopera\Core\Lib\UI\Component\Navigation\Section;
use Eshopera\Core\Lib\UI\Component\Navigation\Item;

/**
 * Navigation UI component
 */
class Navigation extends Component
{

    const DEFAULT_TEMPLATE = 'core/component/navigation';

    /**
     * Creates navigation component
     * @param  array $attributes - default null
     */
    public function __construct(array $attributes = null)
    {
        $this->setAttribute('class', 'nav');
        if ($attributes) {
            $this->setAttributes($attributes);
        }
    }

    /**
     * Adds navigation section
     * @param  string $label
     * @param  string $id - default null
     * @param  array $attributes - default null
     * @return \Eshopera\Core\Lib\UI\Component\Navigation\Section
     */
    public function addSection(string $label, string $id = null, array $attributes = null)
    {
        return $this->add(new Section($label, $attributes), $id);
    }

    /**
     * Adds navigation item
     * @param  string $link
     * @param  string $label
     * @param  string $id - default null
     * @param  array $attributes - default null
     * @return \Eshopera\Core\Lib\UI\Component\Navigation\Item
     */
    public function addItem(string $link, string $label, string $id = null, array $attributes = null)
    {
        return $this->add(new Item($link, $label, $attributes), $id);
    }
}


text:
/* ---------------------------------------
/* Fine Uploader Gallery View Styles
/* ---------------------------------------

/* Buttons
------------------------------------------ */
.qq-gallery .qq-btn
{
    float: right;
    border: none;
    padding: 0;
    margin: 0;
    box-shadow: none;
}

/* Upload Button
------------------------------------------ */
.qq-gallery .qq-upload-button {
    display: inline;
    width: 105px;
    padding: 7px 10px;
    float: left;
    text-align: center;
    background: #00ABC7;
    color: #FFFFFF;
    border-radius: 2px;
    border: 1px solid #37B7CC;
    box-shadow: 0 1px 1px rgba(255, 255, 255, 0.37) inset,
    1px 0 1px rgba(255, 255, 255, 0.07) inset,
    0 1px 0 rgba(0, 0, 0, 0.36),
    0 -2px 12px rgba(0, 0, 0, 0.08) inset
}
.qq-gallery .qq-upload-button-hover {
    background: #33B6CC;
}
.qq-gallery .qq-upload-button-focus {
    outline: 1px dotted #000000;
}

/* Drop Zone
------------------------------------------ */
.qq-gallery.qq-uploader {
    position: relative;
    min-height: 200px;
    max-height: 490px;
    overflow-y: hidden;
    width: inherit;
    border-radius: 6px;
    border: 1px dashed #CCCCCC;
    background-color: #FAFAFA;
    padding: 20px;
}
.qq-gallery.qq-uploader:before {
    content: attr(qq-drop-area-text) " ";
    position: absolute;
    font-size: 200%;
    left: 0;
    width: 100%;
    text-align: center;
    top: 45%;
    opacity: 0.25;
    filter: alpha(opacity=25);
}
.qq-gallery .qq-upload-drop-area, .qq-upload-extra-drop-area {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    min-height: 30px;
    z-index: 2;
    background: #F9F9F9;
    border-radius: 4px;
    text-align: center;
}
.qq-gallery .qq-upload-drop-area span {
    display: block;
    position: absolute;
    top: 50%;
    width: 100%;
    margin-top: -8px;
    font-size: 16px;
}
.qq-gallery .qq-upload-extra-drop-area {
    position: relative;
    margin-top: 50px;
    font-size: 16px;
    padding-top: 30px;
    height: 20px;
    min-height: 40px;
}
.qq-gallery .qq-upload-drop-area-active {
    background: #FDFDFD;
    border-radius: 4px;
}
.qq-gallery .qq-upload-list {
    margin: 0;
    padding: 10px 0 0;
    list-style: none;
    max-height: 450px;
    overflow-y: auto;
    clear: both;
    box-shadow: none;
}

/* Uploaded Elements
------------------------------------------ */
.qq-gallery .qq-upload-list li {
    display: inline-block;
    position: relative;
    max-width: 120px;
    margin: 0 25px 25px 0;
    padding: 0;
    line-height: 16px;
    font-size: 13px;
    color: #424242;
    background-color: #FFFFFF;
    border-radius: 2px;
    box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.22);
    vertical-align: top;

    /* to ensure consistent size of tiles - may need to change if qq-max-size attr on preview img changes */
    height: 186px;
}

.qq-gallery .qq-upload-spinner,
.qq-gallery .qq-upload-size,
.qq-gallery .qq-upload-retry,
.qq-gallery .qq-upload-failed-text,
.qq-gallery .qq-upload-delete,
.qq-gallery .qq-upload-pause,
.qq-gallery .qq-upload-continue {
    display: inline;
}
.qq-gallery .qq-upload-retry:hover,
.qq-gallery .qq-upload-delete:hover,
.qq-gallery .qq-upload-pause:hover,
.qq-gallery .qq-upload-continue:hover {
    background-color: transparent;
}
.qq-gallery .qq-upload-delete,
.qq-gallery .qq-upload-pause,
.qq-gallery .qq-upload-continue,
.qq-gallery .qq-upload-cancel {
    cursor: pointer;
}
.qq-gallery .qq-upload-delete,
.qq-gallery .qq-upload-pause,
.qq-gallery .qq-upload-continue {
    border:none;
    background: none;
    color: #00A0BA;
    font-size: 12px;
    padding: 0;
}
/* to ensure consistent size of tiles - only display status text before auto-retry or after failure */
.qq-gallery .qq-upload-status-text {
    color: #333333;
    font-size: 12px;
    padding-left: 3px;
    padding-top: 2px;
    width: inherit;
    display: none;
    width: 108px;
}
.qq-gallery .qq-upload-fail .qq-upload-status-text {
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow-x: hidden;
    display: block;
}
.qq-gallery .qq-upload-retrying .qq-upload-status-text {
    display: inline-block;
}
.qq-gallery .qq-upload-retrying .qq-progress-bar-container {
    display: none;
}

.qq-gallery .qq-upload-cancel {
    background-color: #525252;
    color: #F7F7F7;
    font-weight: bold;
    font-family: Arial, Helvetica, sans-serif;
    border-radius: 12px;
    border: none;
    height: 22px;
    width: 22px;
    padding: 4px;
    position: absolute;
    right: -5px;
    top: -6px;
    margin: 0;
    line-height: 17px;
}
.qq-gallery .qq-upload-cancel:hover {
    background-color: #525252;
}
.qq-gallery .qq-upload-retry {
    cursor: pointer;
    position: absolute;
    top: 30px;
    left: 50%;
    margin-left: -31px;
    box-shadow: 0 1px 1px rgba(255, 255, 255, 0.37) inset,
                1px 0 1px rgba(255, 255, 255, 0.07) inset,
                0 4px 4px rgba(0, 0, 0, 0.5),
                0 -2px 12px rgba(0, 0, 0, 0.08) inset;
    padding: 3px 4px;
    border: 1px solid #d2ddc7;
    border-radius: 2px;
    color: inherit;
    background-color: #EBF6E0;
    z-index: 1;
}
.qq-gallery .qq-upload-retry:hover {
    background-color: #f7ffec;
}

.qq-gallery .qq-file-info {
    padding: 10px 6px 4px;
    margin-top: -3px;
    border-radius: 0 0 2px 2px;
    text-align: left;
    overflow: hidden;
}

.qq-gallery .qq-file-info .qq-file-name {
    position: relative;
}

.qq-gallery .qq-upload-file {
    display: block;
    margin-right: 0;
    margin-bottom: 3px;
    width: auto;

    /* to ensure consistent size of tiles - constrain text to single line */
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow-x: hidden;
}
.qq-gallery .qq-upload-spinner {
    display: inline-block;
    background: url("loading.gif");
    position: absolute;
    left: 50%;
    margin-left: -7px;
    top: 53px;
    width: 15px;
    height: 15px;
    vertical-align: text-bottom;
}
.qq-gallery .qq-drop-processing {
    display: block;
}
.qq-gallery .qq-drop-processing-spinner {
    display: inline-block;
    background: url("processing.gif");
    width: 24px;
    height: 24px;
    vertical-align: text-bottom;
}
.qq-gallery .qq-upload-failed-text {
    display: none;
    font-style: italic;
    font-weight: bold;
}
.qq-gallery .qq-upload-failed-icon {
    display:none;
    width:15px;
    height:15px;
    vertical-align:text-bottom;
}
.qq-gallery .qq-upload-fail .qq-upload-failed-text {
    display: inline;
}
.qq-gallery .qq-upload-retrying .qq-upload-failed-text {
    display: inline;
}
.qq-gallery .qq-upload-list li.qq-upload-success {
    background-color: #F2F7ED;
}
.qq-gallery .qq-upload-list li.qq-upload-fail {
    background-color: #F5EDED;
    box-shadow: 0 0 1px 0 red;
    border: 0;
}
.qq-gallery .qq-progress-bar {
    display: block;
    background: #00abc7;
    width: 0%;
    height: 15px;
    border-radius: 6px;
    margin-bottom: 3px;
}

.qq-gallery .qq-total-progress-bar {
    height: 25px;
    border-radius: 9px;
}

.qq-gallery .qq-total-progress-bar-container {
    margin-left: 9px;
    display: inline;
    float: right;
    width: 500px;
}

.qq-gallery .qq-upload-size {
    float: left;
    font-size: 11px;
    color: #929292;
    margin-bottom: 3px;
    margin-right: 0;
    display: inline-block;
}

.qq-gallery INPUT.qq-edit-filename {
    position: absolute;
    opacity: 0;
    filter: alpha(opacity=0);
    z-index: -1;
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
}

.qq-gallery .qq-upload-file.qq-editable {
    cursor: pointer;
    margin-right: 20px;
}

.qq-gallery .qq-edit-filename-icon.qq-editable {
    display: inline-block;
    cursor: pointer;
    position: absolute;
    right: 0;
    top: 0;
}

.qq-gallery INPUT.qq-edit-filename.qq-editing {
    position: static;
    height: 28px;
    width: 90px;
    width: -moz-available;
    padding: 0 8px;
    margin-bottom: 3px;
    border: 1px solid #ccc;
    border-radius: 2px;
    font-size: 13px;

    opacity: 1;
    filter: alpha(opacity=100);
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
}

.qq-gallery .qq-edit-filename-icon {
    display: none;
    background: url("edit.gif");
    width: 15px;
    height: 15px;
    vertical-align: text-bottom;
}
.qq-gallery .qq-delete-icon {
    background: url("trash.gif");
    width: 15px;
    height: 15px;
    vertical-align: sub;
    display: inline-block;
}
.qq-gallery .qq-retry-icon {
    background: url("retry.gif");
    width: 15px;
    height: 15px;
    vertical-align: sub;
    display: inline-block;
    float: none;
}
.qq-gallery .qq-continue-icon {
    background: url("continue.gif");
    width: 15px;
    height: 15px;
    vertical-align: sub;
    display: inline-block;
}
.qq-gallery .qq-pause-icon {
    background: url("pause.gif");
    width: 15px;
    height: 15px;
    vertical-align: sub;
    display: inline-block;
}

.qq-gallery .qq-hide {
    display: none;
}

/* Thumbnail
------------------------------------------ */
.qq-gallery .qq-in-progress .qq-thumbnail-wrapper {
    /* makes the spinner on top of the thumbnail more visible */
    opacity: 0.5;
    filter: alpha(opacity=50);
}
.qq-gallery .qq-thumbnail-wrapper {
    overflow: hidden;
    position: relative;

    /* to ensure consistent size of tiles - should match qq-max-size attribute value on qq-thumbnail-selector IMG element */
    height: 120px;
    width: 120px;
}
.qq-gallery .qq-thumbnail-selector {
    border-radius: 2px 2px 0 0;
    bottom: 0;

    /* we will override this in the :root thumbnail selector (to help center the preview) for everything other than IE8 */
    top: 0;

    /* center the thumb horizontally in the tile */
    margin:auto;
    display: block;
}

/* hack to ensure we don't try to center preview in IE8, since -ms-filter doesn't mimic translateY as expected in all cases */
:root *> .qq-gallery .qq-thumbnail-selector {
    /* vertically center preview image on tile */
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
}

/* <dialog> element styles */
.qq-gallery.qq-uploader DIALOG {
    display: none;
}

.qq-gallery.qq-uploader DIALOG[open] {
    display: block;
}

.qq-gallery.qq-uploader DIALOG {
    display: none;
}

.qq-gallery.qq-uploader DIALOG[open] {
    display: block;
}

.qq-gallery.qq-uploader DIALOG .qq-dialog-buttons {
    text-align: center;
    padding-top: 10px;
}

.qq-gallery.qq-uploader DIALOG .qq-dialog-buttons BUTTON {
    margin-left: 5px;
    margin-right: 5px;
}

.qq-gallery.qq-uploader DIALOG .qq-dialog-message-selector {
    padding-bottom: 10px;
}

.qq-gallery .qq-uploader DIALOG::backdrop {
    background-color: rgba(0, 0, 0, 0.7);
}
/*! 2015-06-09 */


text:
package org.apache.sysml.test.integration.functions.binary.scalar;

import org.junit.Test;

import org.apache.sysml.test.integration.AutomatedTestBase;
import org.apache.sysml.test.integration.TestConfiguration;

public class AndTest extends AutomatedTestBase
{

	private static final String TEST_DIR = "functions/binary/scalar/";
	private static final String TEST_CLASS_DIR = TEST_DIR + AndTest.class.getSimpleName() + "/";

	@Override
	public void setUp() {
		addTestConfiguration("AndTest", new TestConfiguration(TEST_CLASS_DIR, "AndTest",
				new String[] { "left_1", "left_2", "left_3", "left_4", "right_1", "right_2", "right_3", "right_4" }));
	}

	@Test
	public void testAnd() {
		if(shouldSkipTest())
			return;

		TestConfiguration config = getTestConfiguration("AndTest");
		loadTestConfiguration(config);

		createHelperMatrix();
		writeExpectedHelperMatrix("left_1", 2);
		writeExpectedHelperMatrix("left_2", 1);
		writeExpectedHelperMatrix("left_3", 1);
		writeExpectedHelperMatrix("left_4", 1);
		writeExpectedHelperMatrix("right_1", 2);
		writeExpectedHelperMatrix("right_2", 1);
		writeExpectedHelperMatrix("right_3", 1);
		writeExpectedHelperMatrix("right_4", 1);

		runTest();

		compareResults();
	}

}


text:
/**
 * This example draws the frequency spectrum of a sound by using
 * the p5.FFT object's analyze() method.
 *
 * FFT is a Fast Fourier Transform function that calculates
 * amplitude across the frequency spectrum. The analyze() method returns
 * an array of values. These values represent how much volume exists in a
 * sound at various frequencies (or pitches). The beginning of the
 * array represents the lowest frequencies (bass), and the end of the
 * array represents the highest frequencies (treble).
 *
 * By default, the array length is 1024. We can determine the size of the array by including
 * an optional parameter, but the number must be a power of 2 between
 * 16 and 1024.
 */

var soundFile;
var fft;
var fftBands = 512;

var description = 'loading';
var p;

// This will be an array of amplitude values from lowest to highest frequencies
var frequencySpectrum = [];

function preload() {
  soundFormats('mp3', 'ogg');
  soundFile = loadSound('../files/lucky_dragons_-_power_melody');
}

function setup() {
  createCanvas(fftBands, 256);
  fill(255, 40, 255);

  // loop the sound file
  soundFile.loop();

  fft = new p5.FFT();

  // update description text
  p = createP(description);
  var p2 = createP('Draw the array returned by FFT.analyze( ). This represents the frequency spectrum, from lowest to highest frequencies.');

  // set the master volume;
  masterVolume(.5);
}

function draw() {
  background(30);

  // update the description if the sound is playing
  updateDescription();

  /**
   * Analyze the sound.
   * Return array of frequency volumes, from lowest to highest frequencies.
   */
  frequencySpectrum = fft.analyze();

  // Draw every value in the frequencySpectrum array as a rectangle
  noStroke();
  for (var i = 0; i< fftBands; i++){
    var x = map(i, 0, fftBands, 0, width);
    var h = -height + map(frequencySpectrum[i], 0, 255, height, 0);
    rect(x, height, width/fftBands, h) ;
  }
}

// Change description text if the song is loading, playing or paused
function updateDescription() {
  if (soundFile.isPaused()) {
    description = 'Paused...';
    p.html(description);
  }
  else if (soundFile.isPlaying()){
    description = 'Playing! Press any key to pause';
    p.html(description);
  }
  else {
    for (var i = 0; i < frameCount%3; i++ ) {
      // add periods to loading to create a fun loading bar effect
      if (frameCount%4 == 0){
        description += '.';
      }
      if (frameCount%25 == 0) {
        description = 'loading';
      }
    }
    p.html(description);
  }
}

// pause the song if a key is pressed
function keyPressed() {
  if (soundFile.isPlaying()){
    soundFile.pause();
  } else {
    soundFile.play();
  }
}


text:
@implementation MPNativeAdTableHeaderView

@end