text:
using System;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using Gorgon.Core;
using Gorgon.Diagnostics;
using Gorgon.IO;
using Gorgon.Native;
using Gorgon.Timing;
using Gorgon.Windows.Properties;

namespace Gorgon.UI
{
    ///
    /// An application class for windows <see cref="Form"/> applications.
    ///
    /// <remarks>
    /// <para>
    /// This class is meant as a replacement for the standard windows forms <see cref="Application"/> class. It expands the functionality of the application class by exposing useful functionality for
    /// working with the main application <see cref="Form"/>.
    /// </para>
    /// <para>
    /// One of the key components to this class is the introduction of a proper Idle loop. This allows an application to perform operations while the windows message pump is in an idle state. This is useful
    /// for things like games, or applications that require constant interaction with other systems. To set an idle loop you may pass a method to execute in one of the <see cref="Run(Form, Func{bool})"/>
    /// method overloads. Or, if you choose, you may assign an idle method to execute at any point in the application life cycle by assigning a method to the <see cref="IdleMethod"/>.
    /// </para>
    /// <para>
    /// Like the <see cref="Application"/> class, this class also provides the ability to pass a windows <see cref="Form"/>, or <see cref="ApplicationContext"/> to one of the <see cref="Run(Form, Func{bool})"/>
    /// overloads.
    /// </para>
    /// <para>
    /// <note type="tip">
    /// <para>
    /// When passing a form to the <see cref="Run(Form,Func{bool})"/> method, that form automatically becomes the main application window. The application will exit when this form is closed.
    /// The main form of an application may be retrieved from the <see cref="MainForm"/> property.
    /// </para>
    /// <para>
    /// If this is not suitable, one of the other <see cref="Run(Func{bool})"/> overloads will allow you to finely control the life cycle of your application.
    /// </para>
    /// </note>
    /// </para>
    /// </remarks>
    /// <example>
    /// An application that wishes to use this class instead of the <see cref="Application"/> class should follow this pattern:
    ///
    /// <![CDATA[
    /// // In program.cs:
    /// [STAThread]
    ///	static void Main()
    ///	{
    ///		try
    ///		{
    ///			Application.EnableVisualStyles();
    ///			Application.SetCompatibleTextRenderingDefault(false);
    ///
    ///			// Perhaps you could run initialization stuff here.
    ///
    ///			// This replaces:
    ///			// Application.Run(new YourMainForm());
    ///
    ///			// This will run with a form and an idle method named "Idle"
    ///			GorgonApplication.Run(new YourMainForm(), Idle);
    ///		}
    ///		catch (Exception ex)
    ///		{
    ///			// You should always catch any unhandled exceptions and either log them, or display them, or something.
    ///			// It can get real ugly for your users otherwise.
    ///			ex.Catch(_ => GorgonDialogs.ErrorBox(null, _), GorgonApplication.Log);
    ///		}
    ///		finally
    ///		{
    ///			// Do your clean up here.
    ///		}
    ///	}
    /// ]]>
    ///
    /// </example>
    public static class GorgonApplication
    {
        #region Constants.
        // Log file application name.
        private const string LogFile = "GorgonLibrary";
        // Peek message NoRemove flag.
        private const uint PeekMessageNoRemove = 0;
        #endregion

        #region Events.
        // Event fired when the application is about to exit.
        private static event EventHandler ExitEvent;

        // Event fired when a message pump thread is about to exit.
        private static event EventHandler ThreadExitEvent;

        ///
        /// Event fired when the application is about to exit.
        ///
        public static event EventHandler Exit
        {
            add
            {
                if (value is null)
                {
                    ExitEvent = null;
                    return;
                }

                ExitEvent += value;
            }
            remove
            {
                if (value is null)
                {
                    return;
                }

                ExitEvent -= value;
            }
        }

        ///
        /// Event fired when a message pump thread is about to exit.
        ///
        public static event EventHandler ThreadExit
        {
            add
            {
                if (value is null)
                {
                    ThreadExitEvent = null;
                    return;
                }

                ThreadExitEvent += value;
            }
            remove
            {
                if (value is null)
                {
                    return;
                }

                ThreadExitEvent -= value;
            }
        }
        #endregion

        #region Variables.
        // Main application form.
        private static Form _mainForm;
        // Flag to indicate that the application needs to close.
        private static bool _quitSignalled;
        // Application loop method.
        private static Func<bool> _loop;
        // The log interface to use.
        private static IGorgonLog _log;
        // The dummy log interface.
        private static readonly IGorgonLog _dummyLog = GorgonLog.NullLog;
        // A synchronization object for threads.
        private static readonly object _syncLock = new();
        // The number of milliseconds to sleep while the application is unfocused but running in the background.
        private static int _unfocusedSleepTime = 16;
        // An atomic to ensure that run is only called by 1 thread at a time.
        private static int _runAtomic;
        // Event used to put the application to sleep.
        private static readonly ManualResetEventSlim _unfocusedTimeout = new(false, 20);
        #endregion

        #region Properties.
        ///
        /// Property to return information about the computer.
        ///
        public static IGorgonComputerInfo ComputerInfo
        {
            get;
        }

        ///
        /// Property to set or return the current <see cref="CultureInfo"/> for the application.
        ///
        /// <remarks>
        /// This is a pass through for the <see cref="Application.CurrentCulture"/> property.
        /// </remarks>
        /// <seealso cref="Application.CurrentCulture"/>
        public static CultureInfo CurrentCulture
        {
            get => Application.CurrentCulture;
            set => Application.CurrentCulture = value;
        }

        ///
        /// Property to return the current <see cref="InputLanguage"/> for the application.
        ///
        /// <remarks>
        /// This is a pass through for the <see cref="Application.CurrentInputLanguage"/> property.
        /// </remarks>
        /// <seealso cref="Application.CurrentInputLanguage"/>
        public static InputLanguage CurrentInputLanguage => Application.CurrentInputLanguage;

        ///
        /// Property to return a read-only list of all the forms that are open in the application.
        ///
        /// <remarks>
        /// This is a pass through for the <see cref="Application.OpenForms"/> property.
        /// </remarks>
        /// <seealso cref="Application.OpenForms"/>
        public static FormCollection OpenForms => Application.OpenForms;

        ///
        /// Property to return if the application is running in the foreground or background.
        ///
        /// <remarks>
        /// <para>
        /// This determines whether the <see cref="MainForm"/> is focused (i.e. a top level, active window). It does this by ensuring the <see cref="Form.WindowState"/> is not set to
        /// <see cref="FormWindowState.Minimized"/>, and the window, or one of its child controls, currently has input focus.
        /// </para>
        /// <para>
        /// This only applies to the <see cref="MainForm"/>. If Gorgon is required to keep processing unfettered, then set the <see cref="AllowBackground"/> property to true.
        /// </para>
        /// <para>
        /// If <see cref="AllowBackground"/> is true, and the main form is not active, but another form belonging to the executing application is active, then processing will continue at full speed.
        /// But, if the entire application does not have focus, then Gorgon will limit the processing time to cycle every 16 milliseconds so as to not hog all the CPU.
        /// </para>
        /// <para>
        /// If no <see cref="MainForm"/> is assigned, then this property will always return false.
        /// </para>
        /// </remarks>
        public static bool IsForeground => ((MainForm is not null) && (MainForm.WindowState != FormWindowState.Minimized) && (MainForm.ContainsFocus));

        ///
        /// Property to return the ID of the application UI thread.
        ///
        public static int ThreadID
        {
            get;
        }

        ///
        /// Property to set or return the amount of time in milliseconds to sleep when the application window is not focused or minimized.
        ///
        /// <remarks>
        /// <para>
        /// Settings this property to a value other than zero will tell the <see cref="GorgonApplication"/> to put the message pump to sleep for the requested number of milliseconds while the application is not
        /// focused. A value of zero, will tell the application to continuously process messages regardless of focus state.
        /// </para>
        /// <para>
        /// This has value for systems that run on batteries, like a laptop, where unnecessary processing can be detrimental to battery life.
        /// </para>
        /// <para>
        /// <note type="tip">
        /// <para>
        /// This value has no effect if the <see cref="AllowBackground"/> property is set to false.
        /// </para>
        /// </note>
        /// </para>
        /// <para>
        /// <note type="warning">
        /// <para>
        /// Do not set this value to a large number, doing so will stall the message pump and cause issues for the application. A value of 10 milliseconds (the default) is small enough to keep the application
        /// responsive.
        /// </para>
        /// </note>
        /// </para>
        /// </remarks>
        public static int UnfocusedSleepTime
        {
            get => _unfocusedSleepTime;
            set
            {
                if (value < 0)
                {
                    value = 0;
                }

                _unfocusedSleepTime = value;
            }
        }

        ///
        /// Property to set or return whether to allow the application message pump to continue running while the window is not focused or minimized.
        ///
        /// <remarks>
        /// <para>
        /// When set to true, this will allow an application to process messages and execute the <see cref="IdleMethod"/> while the application is unfocused or minimized. If it
        /// is set to false, the application will pause until it regains focus again.
        /// </para>
        /// <para>
        /// It is recommended that this property be left at the default setting of false unless it's absolutely necessary to run the application in the background. On systems that use batteries, like
        /// laptops, setting this value to true could be detrimental to the battery life.
        /// </para>
        /// <para>
        /// <note type="tip">
        /// <para>
        /// If this property is set to true, there will be a delay corresponding to the value set on the <see cref="UnfocusedSleepTime"/> property. If that property is set to zero, then the
        /// application will process messages as though it were focused.
        /// </para>
        /// </note>
        /// </para>
        /// </remarks>
        public static bool AllowBackground
        {
            get;
            set;
        }

        ///
        /// Property to set or return the method to execute user code while the application is in an idle state.
        ///
        /// <remarks>
        /// <para>
        /// This property can be set at any time during the lifetime of the application. As soon as the application stops processing messages, it will execute the <see cref="Func{TResult}"/> assigned to it.
        /// </para>
        /// <para>
        /// The property expects a function that returns a <see cref="bool"/> value. When this return value is true, then the application will continue processing messages. If it returns false,
        /// then the application will exit its message loop and shut down.
        /// </para>
        /// <para>
        /// Setting this value to null when no <see cref="MainForm"/> or <see cref="ApplicationContext"/> is assigned will lead to an exception being thrown. This is
        /// because this method is the only thing the application has to do, and without it, there'd be no application processing.
        /// </para>
        /// <para>
        /// <note type="warning">
        /// <para>
        /// Do not set this to a non-null value when shutting down the application. Doing this will lead to undefined behaviour.
        /// </para>
        /// </note>
        /// </para>
        /// </remarks>
        /// <exception cref="InvalidOperationException">
        /// Thrown when an attempt to set this property to null is made and there is no <see cref="MainForm"/> or <see cref="ApplicationContext"/>
        /// attached to the application.
        /// </exception>
        public static Func<bool> IdleMethod
        {
            get => _loop;
            set
            {
                // If we have no application form, or context and we try disable the loop, leave.
                // We do this because if there's no context or form, then there's nothing to run and that's an invalid state.
                if ((value is null)
                    && (MainForm is null)
                    && (ApplicationContext is null))
                {
                    throw new InvalidOperationException(Resources.GOR_ERR_APPLICATION_CANNOT_REMOVE_IDLE_LOOP);
                }

                // Remove the previous event.
                if (IsRunning)
                {
                    Application.Idle -= Application_Idle;
                    Log.Print("Application loop stopped.", LoggingLevel.Simple);
                }

                _loop = value;

                if ((value is null) || (!IsRunning))
                {
                    return;
                }

                Log.Print("Application loop starting...", LoggingLevel.Simple);
                Application.Idle += Application_Idle;
            }
        }

        ///
        /// Property to return the directory for the currently running application.
        ///
        public static DirectoryInfo StartupPath
        {
            get;
        }

        ///
        /// Property to return the path for the currently running application.
        ///
        /// <remarks>
        /// This includes the file name of the assembly that is executing as well as the directory that the application was executed from.
        /// </remarks>
        public static string ExecutablePath => Application.ExecutablePath;

        ///
        /// Property to return if the <see cref="GorgonApplication"/> is in a running state or not.
        ///
        /// <remarks>
        /// When this value is true, the application message pump is running and processing messages.
        /// </remarks>
        public static bool IsRunning
        {
            get;
            private set;
        }

        ///
        /// Property to return the main windows <see cref="Form"/> for the application.
        ///
        /// <remarks>
        /// <para>
        /// This property can be used to retrieve the <see cref="Form"/> that is the primary form for the application. When this form closes, the application will shut down.
        /// </para>
        /// <para>
        /// This value is set when the <see cref="Run(Form,Func{bool})"/> is used to run the application, or a form has been assigned to the <see cref="ApplicationContext.MainForm"/>
        /// property.
        /// </para>
        /// </remarks>
        public static Form MainForm => ApplicationContext is not null ? ApplicationContext.MainForm : _mainForm;

        ///
        /// Property to set or return the current application context.
        ///
        /// <remarks>
        /// This value will return null if this application wasn't started with the <see cref="Run(System.Windows.Forms.ApplicationContext,Func{bool})"/> method.
        /// </remarks>
        public static ApplicationContext ApplicationContext
        {
            get;
            private set;
        }

        ///
        /// Property to set return the application log file interface.
        ///
        /// <remarks>
        /// <para>
        /// Setting this value to null will turn off logging for the application, but will not set the value to null. A dummy version of the log, that does no actual logging, will be used
        /// instead.
        /// </para>
        /// <para>
        /// Ensure that the log being assigned to this property was created on the same thread as the application, otherwise an exception may be thrown.
        /// </para>
        /// </remarks>
        public static IGorgonLog Log
        {
            get => _log;
            set
            {
                lock (_syncLock)
                {
                    try
                    {
                        _log?.LogEnd();

                        if (value is null)
                        {
                            _log = _dummyLog;
                            return;
                        }

                        _log = value;

                        InitializeLogger();
                    }
                    catch
                    {
                        // We couldn't set up the logging, so fall back to the null log.
                        _log = GorgonLog.NullLog;
                    }
                }
            }
        }
        #endregion

        #region Methods.
        ///
        /// Handles the Idle event of the Application control.
        ///
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private static void Application_Idle(object sender, EventArgs e)
        {
            // Windows message to retrieve.

            // We have nothing to execute, so just leave.
            if ((IdleMethod is null) || (!IsRunning))
            {
                return;
            }

            // Check for application focus. If we didn't assign a main form, or one was not assigned to the application context, then
            // run regardless since we have an idle method to execute.
            bool appShouldProcess = MainForm is null || AllowBackground || IsForeground;

            if (!GorgonTiming.TimingStarted)
            {
                if (GorgonTimerQpc.SupportsQpc())
                {
                    GorgonTiming.StartTiming<GorgonTimerQpc>();
                }
                else
                {
                    GorgonTimerMultimedia.BeginTiming();
                    GorgonTiming.StartTiming<GorgonTimerMultimedia>();
                }
            }

            while ((appShouldProcess) && (!UserApi.PeekMessage(out MSG _, IntPtr.Zero, 0, 0, PeekMessageNoRemove)))
            {
                // Only update the time when we have focus, otherwise reset the time so we don't get super weird values
                // spiking in the background.
                if ((IsForeground) || (AllowBackground))
                {
                    GorgonTiming.Update();
                }
                else
                {
                    GorgonTiming.Reset();
                    continue;
                }

                if (!IdleMethod())
                {
                    // Force an exit from the thread.
                    Quit();
                    return;
                }

                // Give up CPU time if we're not focused.
                if ((MainForm is null) || (MainForm.ContainsFocus) || (_unfocusedSleepTime <= 0) || (Form.ActiveForm is not null))
                {
                    continue;
                }

                // Put the application to bed until the elapsed timeout is triggered.
                _unfocusedTimeout.Wait(_unfocusedSleepTime);

                if (_quitSignalled)
                {
                    break;
                }
            }
        }

        ///
        /// Function to perform initialization of the logger interface.
        ///
        private static void InitializeLogger()
        {
            if (Log is null)
            {
                return;
            }

            Log.LogStart();

            // Display information
            Log.Print("Logging interface assigned. Initializing...", LoggingLevel.All);
            Log.Print($"Architecture: {ComputerInfo.PlatformArchitecture}", LoggingLevel.Verbose);
            Log.Print($"Processor count: {ComputerInfo.ProcessorCount}", LoggingLevel.Verbose);
            Log.Print($"Installed Memory: {ComputerInfo.TotalPhysicalRAM.FormatMemory()}", LoggingLevel.Verbose);
            Log.Print($"Available Memory: {ComputerInfo.AvailablePhysicalRAM.FormatMemory()}", LoggingLevel.Verbose);
            Log.Print($"Operating System: {ComputerInfo.OperatingSystemVersionText} ({ComputerInfo.OperatingSystemArchitecture})", LoggingLevel.Verbose);
            Log.Print(string.Empty, LoggingLevel.Verbose);
        }

        ///
        /// Function to initialize the main form and idle loop..
        ///
        private static void Initialize()
        {
            // Initialize the timing data.
            // This will start the application uptime counter.  But since there's no actual timer set on this yet,
            // no statistical timing will be collected until the application begins its run in Application_Idle.
            GorgonTiming.Reset();

            // Notify that we're in a running state.
            IsRunning = true;

            // Display the form.
            if ((MainForm is not null) && (!MainForm.IsDisposed))
            {
                MainForm.Show();
            }

            if ((IdleMethod is not null) && (!_quitSignalled))
            {
                Log.Print("Application loop starting...", LoggingLevel.Simple);
                Application.Idle += Application_Idle;
            }

            // Register quit handlers.
            Application.ApplicationExit += Application_ApplicationExit;
            Application.ThreadExit += Application_ThreadExit;

            // If anything kills the application early, then capture the quit state.
            IsRunning = !_quitSignalled;
        }

        ///
        /// Handles the ThreadExit event of the Application control.
        ///
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private static void Application_ThreadExit(object sender, EventArgs e)
        {
            Application.ThreadExit -= Application_ThreadExit;

            // This will only allow one thread to actually call this.
            // It also has the added benefit of unassigning the exit handler when the application shuts down.
            EventHandler exitHandler = Interlocked.Exchange(ref ThreadExitEvent, null);
            exitHandler?.Invoke(sender, e);
        }

        ///
        /// Handles the ApplicationExit event of the Application control.
        ///
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private static void Application_ApplicationExit(object sender, EventArgs e)
        {
            Application.ApplicationExit -= Application_ApplicationExit;

            // This will only allow one thread to actually call this.
            // It also has the added benefit of unassigning the exit handler when the application shuts down.
            EventHandler exitHandler = Interlocked.Exchange(ref ExitEvent, null);
            exitHandler?.Invoke(sender, e);
        }

        ///
        /// Function to clean up events and other objects after an application exits.
        ///
        private static void CleanUp()
        {
            IsRunning = false;

            _unfocusedTimeout.Dispose();

            // Remove quit handlers.
            Application.ApplicationExit -= Application_ApplicationExit;
            Application.ThreadExit -= Application_ThreadExit;
            ExitEvent = null;
            ThreadExitEvent = null;

            if (IdleMethod is not null)
            {
                Application.Idle -= Application_Idle;
                _loop = null;
                Log.Print("Application loop stopped.", LoggingLevel.Simple);
            }

            // Reset the low resolution timer period on application end.
            if (!GorgonTimerQpc.SupportsQpc())
            {
                GorgonTimerMultimedia.EndTiming();
            }

            Log.Print("Shutting down.", LoggingLevel.All);

            // Destroy log.
            _log?.LogEnd();
        }

        ///
        /// Function to add a message filter to intercept application messages.
        ///
        /// <param name="filter">A <see cref="IMessageFilter"/> used to intercept an application message.</param>
        /// <remarks>
        /// <para>
        /// This is a pass through for the <see cref="Application.AddMessageFilter"/> method.
        /// </para>
        /// </remarks>
        /// <seealso cref="Application.AddMessageFilter"/>
        public static void AddMessageFilter(IMessageFilter filter) => Application.AddMessageFilter(filter);

        ///
        /// Function to remove a message filter added with the <see cref="AddMessageFilter"/> method.
        ///
        /// <param name="filter">A <see cref="IMessageFilter"/> used to intercept an application message.</param>
        /// <remarks>
        /// <para>
        /// This is a pass through for the <see cref="Application.RemoveMessageFilter"/> method.
        /// </para>
        /// </remarks>
        /// <seealso cref="Application.RemoveMessageFilter"/>
        public static void RemoveMessageFilter(IMessageFilter filter) => Application.RemoveMessageFilter(filter);

        ///
        /// Function that will signal the application to begin shutdown.
        ///
        /// <remarks>
        /// This will signal the application to tell it that it is time to shut down. This shut down will not happen immediately as the application needs to finish up whatever processing it is doing
        /// before exiting.
        /// </remarks>
        public static void Quit()
        {
            _quitSignalled = true;
            _unfocusedTimeout.Set();

            if (IsRunning)
            {
                Application.Exit();
            }
        }

        ///
        /// Function to begin execution of a <see cref="GorgonApplication"/>.
        ///
        /// <param name="context">The <see cref="System.Windows.Forms.ApplicationContext"/> to use for this application.</param>
        /// <param name="idleMethod">[Optional] A method to execute while the application is idle.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="context"/> parameter is null.</exception>
        /// <exception cref="InvalidOperationException">Thrown when the application is already executing. Check the <see cref="IsRunning"/> property before calling this method.</exception>
        /// <remarks>
        /// <para>
        /// This method begins execution of the application by starting its messaging pump and processing application messages.
        /// </para>
        /// <para>
        /// This particular overload takes a <see cref="System.Windows.Forms.ApplicationContext"/> which allows for more fine grained control over the lifetime
        /// of the application.
        /// </para>
        /// <para>
        /// The <paramref name="idleMethod"/> is called while the application is idle (i.e. not processing messages). User code may execute within this method
        /// to allow for processing while the application is not doing anything.
        /// </para>
        /// <para>
        /// <note type="tip">
        /// <para>
        /// The <paramref name="idleMethod"/> takes a <see cref="Func{TResult}"/> that returns a <see cref="bool"/> value. When this value is true, the application will continue processing as normal,
        /// but when it returns false, the application will exit.
        /// </para>
        /// </note>
        /// </para>
        /// <para>
        /// <note type="important">
        /// <para>
        /// Only one thread may call this method at any given time. If this method is executed by a thread, and another attempts to execute it, an exception will be thrown.
        /// </para>
        /// </note>
        /// </para>
        /// </remarks>
        /// <seealso cref="System.Windows.Forms.ApplicationContext"/>
        /// <seealso cref="IsRunning"/>
        /// <seealso cref="IdleMethod"/>
        public static void Run(ApplicationContext context, Func<bool> idleMethod = null)
        {
            if (IsRunning)
            {
                throw new InvalidOperationException(Resources.GOR_ERR_APPLICATION_ALREADY_RUNNING);
            }

            if (Interlocked.Increment(ref _runAtomic) > 1)
            {
                throw new InvalidOperationException(Resources.GOR_ERR_APPLICATION_RUN_ONLY_FROM_ONE_THREAD);
            }

            if (idleMethod is not null)
            {
                IdleMethod = idleMethod;
            }

            ApplicationContext = context ?? throw new InvalidOperationException(Resources.GOR_ERR_APPLICATION_NOCONTEXT);

            try
            {
                Initialize();

                if (!IsRunning)
                {
                    return;
                }

                Application.Run(context);
            }
            catch (Exception ex)
            {
                _unfocusedTimeout.Set();
                Log.LogException(ex);
                throw;
            }
            finally
            {
                CleanUp();
                Interlocked.Decrement(ref _runAtomic);
            }
        }

        ///
        /// Function to begin execution of a <see cref="GorgonApplication"/>.
        ///
        /// <param name="mainForm">The main application <see cref="Form"/> to use for this application.</param>
        /// <param name="idleMethod">[Optional] A method to execute while the application is idle.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="mainForm"/> parameter is null.</exception>
        /// <exception cref="InvalidOperationException">Thrown when the application is already executing. Check the <see cref="IsRunning"/> property before calling this method.</exception>
        /// <remarks>
        /// <para>
        /// This method begins execution of the application by starting its messaging pump and processing application messages.
        /// </para>
        /// <para>
        /// This overload uses the <paramref name="mainForm"/> passed to it as the main application form. When this window closes, the application will shut down.
        /// </para>
        /// <para>
        /// The <paramref name="idleMethod"/> is called while the application is idle (i.e. not processing messages). User code may execute within this method to allow for processing while the application
        /// is not doing anything.
        /// </para>
        /// <para>
        /// <note type="tip">
        /// <para>
        /// The <paramref name="idleMethod"/> takes a <see cref="Func{TResult}"/> that returns a <see cref="bool"/> value. When this value is true, the application will continue processing as normal,
        /// but when it returns false, the application will exit.
        /// </para>
        /// </note>
        /// </para>
        /// <para>
        /// <note type="important">
        /// <para>
        /// Only one thread may call this method at any given time. If this method is executed by a thread, and another attempts to execute it, an exception will be thrown.
        /// </para>
        /// </note>
        /// </para>
        /// </remarks>
        /// <seealso cref="System.Windows.Forms.ApplicationContext"/>
        /// <seealso cref="IsRunning"/>
        /// <seealso cref="IdleMethod"/>
        /// <seealso cref="MainForm"/>
        public static void Run(Form mainForm, Func<bool> idleMethod = null)
        {
            if (IsRunning)
            {
                throw new InvalidOperationException(Resources.GOR_ERR_APPLICATION_ALREADY_RUNNING);
            }

            if (Interlocked.Increment(ref _runAtomic) > 1)
            {
                throw new InvalidOperationException(Resources.GOR_ERR_APPLICATION_RUN_ONLY_FROM_ONE_THREAD);
            }

            if (idleMethod is not null)
            {
                IdleMethod = idleMethod;
            }

            _mainForm = mainForm ?? throw new ArgumentNullException(nameof(mainForm));

            try
            {
                Initialize();

                if (!IsRunning)
                {
                    return;
                }

                Application.Run(MainForm);
            }
            catch (Exception ex)
            {
                _unfocusedTimeout.Set();
                Log.LogException(ex);
                throw;
            }
            finally
            {
                CleanUp();
                Interlocked.Decrement(ref _runAtomic);
            }
        }

        ///
        /// Function to begin execution of a <see cref="GorgonApplication"/>.
        ///
        /// <param name="idleMethod">A method to execute while the application is idle.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="idleMethod"/> parameter is null.</exception>
        /// <exception cref="InvalidOperationException">Thrown when the application is already executing. Check the <see cref="IsRunning"/> property before calling this method.</exception>
        /// <remarks>
        /// <para>
        /// This method begins execution of the application by starting its messaging pump and processing application messages.
        /// </para>
        /// <para>
        /// This overload only uses the <see cref="IdleMethod"/> for its execution. This is called when the application has no messages to process in its message pump. Because of this, there is no indication
        /// of whether the application is in the foreground or background as it is really always running in the background. When this method is chosen, the <see cref="IsForeground"/> property will always return
        /// false. Applications that use this should take care to balance the CPU usage of the <paramref name="idleMethod"/>.
        /// </para>
        /// <para>
        /// The <paramref name="idleMethod"/> takes a <see cref="Func{TResult}"/> that returns a <see cref="bool"/> value. When this value is true, the application will continue processing as normal,
        /// but when it returns false, the application will exit.
        /// </para>
        /// <para>
        /// <note type="important">
        /// <para>
        /// Only one thread may call this method at any given time. If this method is executed by a thread, and another attempts to execute it, an exception will be thrown.
        /// </para>
        /// </note>
        /// </para>
        /// </remarks>
        /// <seealso cref="IsForeground"/>
        /// <seealso cref="System.Windows.Forms.ApplicationContext"/>
        /// <seealso cref="IsRunning"/>
        /// <seealso cref="IdleMethod"/>
        public static void Run(Func<bool> idleMethod)
        {
            if (IsRunning)
            {
                throw new InvalidOperationException(Resources.GOR_ERR_APPLICATION_ALREADY_RUNNING);
            }

            if (Interlocked.Increment(ref _runAtomic) > 1)
            {
                throw new InvalidOperationException(Resources.GOR_ERR_APPLICATION_RUN_ONLY_FROM_ONE_THREAD);
            }

            IdleMethod = idleMethod ?? throw new ArgumentNullException(nameof(idleMethod));

            try
            {
                Initialize();

                if (!IsRunning)
                {
                    return;
                }

                Application.Run();
            }
            catch (Exception ex)
            {
                _unfocusedTimeout.Set();
                Log.LogException(ex);
                throw;
            }
            finally
            {
                CleanUp();
                Interlocked.Decrement(ref _runAtomic);
            }
        }
        #endregion

        #region Constructor.
        ///
        /// Initializes the <see cref="GorgonApplication"/> class.
        ///
        static GorgonApplication()
        {
            ComputerInfo = new GorgonComputerInfo();
            ThreadID = Thread.CurrentThread.ManagedThreadId;

            try
            {
                Log = new GorgonTextFileLog(LogFile, "Tape_Worm", typeof(GorgonApplication).Assembly.GetName().Version);
            }
            catch
            {
                Log = GorgonLog.NullLog;
            }

            StartupPath = new DirectoryInfo(Application.StartupPath.FormatDirectory(Path.DirectorySeparatorChar));
        }
        #endregion
    }
}


text:
package com.java110.api.listener.org;

import com.alibaba.fastjson.JSONObject;
import com.java110.api.bmo.org.IOrgBMO;
import com.java110.api.listener.AbstractServiceApiPlusListener;
import com.java110.core.annotation.Java110Listener;
import com.java110.core.context.DataFlowContext;
import com.java110.intf.user.IOrgInnerServiceSMO;
import com.java110.core.event.service.api.ServiceDataFlowEvent;
import com.java110.utils.constant.ServiceCodeOrgConstant;
import com.java110.utils.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;

/**
 * 保存组织管理侦听
 * add by wuxw 2019-06-30
 */
@Java110Listener("updateOrgListener")
public class UpdateOrgListener extends AbstractServiceApiPlusListener {

    @Autowired
    private IOrgInnerServiceSMO orgInnerServiceSMOImpl;
    @Autowired
    private IOrgBMO orgBMOImpl;

    @Override
    protected void validate(ServiceDataFlowEvent event, JSONObject reqJson) {

        Assert.hasKeyAndValue(reqJson, "orgId", "组织ID不能为空");
        Assert.hasKeyAndValue(reqJson, "orgName", "必填,请填写组织名称");
        Assert.hasKeyAndValue(reqJson, "orgLevel", "必填,请填写报修人名称");
        Assert.hasKeyAndValue(reqJson, "parentOrgId", "必填,请选择上级ID");
        //Assert.hasKeyAndValue(reqJson, "description", "必填,请填写描述");
        Assert.hasKeyAndValue(reqJson, "storeId", "必填,请填写商户ID");

    }

    @Override
    protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) {

        orgBMOImpl.updateOrg(reqJson, context);
    }

    @Override
    public String getServiceCode() {
        return ServiceCodeOrgConstant.UPDATE_ORG;
    }

    @Override
    public HttpMethod getHttpMethod() {
        return HttpMethod.POST;
    }

    @Override
    public int getOrder() {
        return DEFAULT_ORDER;
    }

    public IOrgInnerServiceSMO getOrgInnerServiceSMOImpl() {
        return orgInnerServiceSMOImpl;
    }

    public void setOrgInnerServiceSMOImpl(IOrgInnerServiceSMO orgInnerServiceSMOImpl) {
        this.orgInnerServiceSMOImpl = orgInnerServiceSMOImpl;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package jadx.gui.device.debugger.smali;

import jadx.api.plugins.input.data.ILocalVar;

public abstract class RegisterInfo implements ILocalVar {

	public boolean isInitialized(long codeOffset) {
		return codeOffset >= getStartOffset() && codeOffset < getEndOffset();
	}

	public boolean isUnInitialized(long codeOffset) {
		return codeOffset < getStartOffset() || codeOffset >= getEndOffset();
	}
}


text:
- Regenerate the `ReceiptModule` with `:asn1` 5.0.16.
- Update minimal requirement to OTP 21 & Elixir 1.10.

## v0.4.0

- Fixes the date fields in receipt should be parsed as a `DateTime` in UTC.
- Drop Support for Elixir 1.4 and 1.5.

## v0.3.0

- Added `ReceiptDecoder.Verifier` to verify the the receipt,
  this would let a invalid receipt failed to decode.
- Added new `is_in_intro_offer_period` field to IAP receipt.
- Drop support for Elixir 1.3.
- Returns `{:error, msg}` for invalid receipt.

## v0.2.0

- Parse result as `ReceiptDecoder.AppReceipt` & `ReceiptDecoder.IAPReceipt`.

## v0.1.0

- Initial release


text:
'use strict';

import type {DocumentNode} from 'graphql';

const GraphQL = require('graphql');

/**
 * Given a babel AST path to a tagged template literal, return an AST if it is
 * a graphql literal being used in a valid way.
 * If it is some other type of template literal then return nothing.
 */
function getValidGraphQLTag(path: any): ?DocumentNode {
  const tag = path.get('tag');

  if (!tag.isIdentifier({name: 'graphql'})) {
    return null;
  }

  const quasis = path.node.quasi.quasis;

  if (quasis.length !== 1) {
    throw new Error(
      'BabelPluginRelay: Substitutions are not allowed in graphql fragments. ' +
        'Included fragments should be referenced as `...MyModule_propName`.',
    );
  }

  const text = quasis[0].value.raw;

  const ast = GraphQL.parse(text);

  if (ast.definitions.length === 0) {
    throw new Error('BabelPluginRelay: Unexpected empty graphql tag.');
  }

  return ast;
}

module.exports = getValidGraphQLTag;


text:
package org.cipres.treebase.domain.search;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.cipres.treebase.domain.matrix.CharacterMatrix;
import org.cipres.treebase.domain.matrix.Matrix;
import org.cipres.treebase.domain.study.Study;
import org.cipres.treebase.domain.study.AnalysisStep;
import org.cipres.treebase.domain.study.AnalyzedData;
import org.cipres.treebase.domain.taxon.Taxon;
import org.cipres.treebase.domain.taxon.TaxonLabel;
import org.cipres.treebase.domain.tree.PhyloTree;
import org.cipres.treebase.service.AbstractService;

public class MatrixSearchResults extends SearchResults<Matrix> {

	public MatrixSearchResults() { super(); }

	public MatrixSearchResults(Boolean b) { super(b); }

	public MatrixSearchResults(Collection<Matrix> results) {
		super(results);
	}

	public SearchResultsType resultType() { return SearchResultsType.MATRIX; }

	public StudySearchResults convertToStudies() {
		if (this.isAll()) return new StudySearchResults();

		Collection<Study> studies = new HashSet<Study> ();
		for (Matrix m : this.getResults()) {
			studies.add(m.getStudy());
		}
		return new StudySearchResults(studies);
	}

	public MatrixSearchResults convertToMatrices() { return this; }

	// Bill says this can return the trees that were derived from these matrices.
	// That is, it returns all phylotree t such that exists analysis step a such that t was the output of a
	// and some matrix in this searchresults was the input of a.  20081205 mjd
	// The implementation below should meet that requirement. 20092602 rav
	public TreeSearchResults convertToTrees() {
		Collection<PhyloTree> pResults = new ArrayList<PhyloTree>();

		Set<Matrix> matrixSet = getResults();
		if ( matrixSet != null ) {

			// for each matrix in the result set we need to traverse the associated study
			for ( Matrix matrix : matrixSet ) {
				Study study = matrix.getStudy();

				// need to resurrect the study, otherwise we get a LazyInitializationException
				Study resurrectedStudy = getStudyService().resurrect(study);
				Collection<AnalysisStep> analysisStepCollection = resurrectedStudy.getAnalysisSteps();

				// for that study we need to iterate over all analysis steps
				for ( AnalysisStep analysisStep : analysisStepCollection ) {
					Collection<AnalyzedData> analyzedDataCollection = analysisStep.getDataSetReadOnly();
					boolean matrixIsInput = false;

					// then we need to see if the focal matrix is an input matrix
					for ( AnalyzedData analyzedData : analyzedDataCollection ) {
						Matrix analyzedMatrix = analyzedData.getMatrixData();
						String inputOutput = analyzedData.getInputOutput();

						// if the focal datum is an input, and it's a matrix, and it's THIS matrix...
						if ( inputOutput.equals("input") && analyzedMatrix != null && analyzedMatrix.getId() == matrix.getId() ) {
							matrixIsInput = true;
						}
					}
					// ...then collect all output trees
					if ( matrixIsInput ) {
						for ( AnalyzedData analyzedData : analyzedDataCollection ) {
							PhyloTree analyzedTree = analyzedData.getTreeData();
							String inputOutput = analyzedData.getInputOutput();

							// here we store all output data that are trees
							if ( inputOutput.equals("output") && analyzedTree != null ) {
								pResults.add(analyzedTree);
							}
						}
					}
				}
			}
		}
		if ( pResults.size() > 0 ) {
			return new TreeSearchResults(pResults);
		}
		else {
			return new TreeSearchResults();
		}
	}

	@Override
	public TaxonSearchResults convertToTaxa() {
		if (this.isAll()) return new TaxonSearchResults();

		Collection<Taxon> taxa = new HashSet<Taxon> ();
		for (Matrix m : getResults()) {
			if (! m.isCharacterMatrix()) continue;
			CharacterMatrix cm = (CharacterMatrix) m;
			for (TaxonLabel tl : cm.getAllTaxonLabels())
				if (tl.getTaxonVariant() != null && tl.getTaxonVariant().getTaxon() != null)
					taxa.add(tl.getTaxonVariant().getTaxon());
		}
		return new TaxonSearchResults(taxa);
	}

	@Override
	public Class getResultClass() {
		return Matrix.class;
	}

	@Override
	public AbstractService getService() {
		return getMatrixService();
	}
}


text:
package org.apache.log4j.chainsaw;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JPopupMenu;

/**
 *
 * Ensures that a specific popupMenu is displayed when the relevant
 * mouse events are trapped.
 *
 * @author Scott Deboy <sdeboy@apache.org>
 * @author Paul Smith <psmith@apache.org>
 *
 */
public class PopupListener extends MouseAdapter {
  final JPopupMenu popupMenu;

  public PopupListener(JPopupMenu popupMenu) {
    this.popupMenu = popupMenu;
  }

  public void mousePressed(MouseEvent e) {
    checkPopup(e);
  }

  public void mouseReleased(MouseEvent e) {
    checkPopup(e);
  }

  public void mouseClicked(MouseEvent e)
  {
      checkPopup(e);
  }

  private void checkPopup(MouseEvent e) {
    if (e.isPopupTrigger()) {
      popupMenu.show(e.getComponent(), e.getX(), e.getY());
    }
  }
}


text:
class AdminSession < Authlogic::Session::Base
end


text:
package org.optaplanner.core.impl.heuristic.selector.move.generic;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.optaplanner.core.api.domain.solution.Solution;
import org.optaplanner.core.api.domain.valuerange.ValueRange;
import org.optaplanner.core.impl.domain.valuerange.descriptor.ValueRangeDescriptor;
import org.optaplanner.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import org.optaplanner.core.impl.heuristic.move.AbstractMove;
import org.optaplanner.core.impl.heuristic.move.Move;
import org.optaplanner.core.impl.score.director.ScoreDirector;

/**
 * Non-cacheable.
 */
public class PillarChangeMove extends AbstractMove {

    protected final GenuineVariableDescriptor variableDescriptor;

    protected final List<Object> pillar;
    protected final Object toPlanningValue;

    public PillarChangeMove(List<Object> pillar, GenuineVariableDescriptor variableDescriptor, Object toPlanningValue) {
        this.pillar = pillar;
        this.variableDescriptor = variableDescriptor;
        this.toPlanningValue = toPlanningValue;
    }

    public List<Object> getPillar() {
        return pillar;
    }

    public Object getToPlanningValue() {
        return toPlanningValue;
    }

    // ************************************************************************
    // Worker methods
    // ************************************************************************

    public boolean isMoveDoable(ScoreDirector scoreDirector) {
        Object oldValue = variableDescriptor.getValue(pillar.get(0));
        if (ObjectUtils.equals(oldValue, toPlanningValue)) {
            return false;
        }
        if (!variableDescriptor.isValueRangeEntityIndependent()) {
            ValueRangeDescriptor valueRangeDescriptor = variableDescriptor.getValueRangeDescriptor();
            Solution workingSolution = scoreDirector.getWorkingSolution();
            for (Object entity : pillar) {
                ValueRange rightValueRange = valueRangeDescriptor.extractValueRange(workingSolution, entity);
                if (!rightValueRange.contains(toPlanningValue)) {
                    return false;
                }
            }
        }
        return true;
    }

    public Move createUndoMove(ScoreDirector scoreDirector) {
        Object oldValue = variableDescriptor.getValue(pillar.get(0));
        return new PillarChangeMove(pillar, variableDescriptor, oldValue);
    }

    @Override
    protected void doMoveOnGenuineVariables(ScoreDirector scoreDirector) {
        for (Object entity : pillar) {
            scoreDirector.beforeVariableChanged(variableDescriptor, entity);
            variableDescriptor.setValue(entity, toPlanningValue);
            scoreDirector.afterVariableChanged(variableDescriptor, entity);
        }
    }

    // ************************************************************************
    // Introspection methods
    // ************************************************************************

    @Override
    public String getSimpleMoveTypeDescription() {
        return getClass().getSimpleName() + "(" + variableDescriptor.getSimpleEntityAndVariableName() + ")";
    }

    public Collection<? extends Object> getPlanningEntities() {
        return pillar;
    }

    public Collection<? extends Object> getPlanningValues() {
        return Collections.singletonList(toPlanningValue);
    }

    public boolean equals(Object o) {
        if (this == o) {
            return true;
        } else if (o instanceof PillarChangeMove) {
            PillarChangeMove other = (PillarChangeMove) o;
            return new EqualsBuilder()
                    .append(variableDescriptor, other.variableDescriptor)
                    .append(pillar, other.pillar)
                    .append(toPlanningValue, other.toPlanningValue)
                    .isEquals();
        } else {
            return false;
        }
    }

    public int hashCode() {
        return new HashCodeBuilder()
                .append(variableDescriptor)
                .append(pillar)
                .append(toPlanningValue)
                .toHashCode();
    }

    public String toString() {
        Object oldValue = variableDescriptor.getValue(pillar.get(0));
        return pillar.toString() + " {" + oldValue + " -> " + toPlanningValue + "}";
    }

}


text:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Invio.Xunit;
using Xunit;

namespace Invio.Validation {

    [UnitTest]
    public class ValidationIssueTests {

        [Fact]
        public void Warning_NullMessage() {

            // Act

            var exception = Record.Exception(
                () => ValidationIssue.Warning(null)
            );

            // Assert

            Assert.IsType<ArgumentNullException>(exception);
        }

        [Fact]
        public void Warning_WhiteSpaceMessage() {

            // Act

            var exception = Record.Exception(
                () => ValidationIssue.Warning(" \t")
            );

            // Assert

            Assert.IsType<ArgumentException>(exception);
        }

        [Fact]
        public void Warning_WithJustCode() {

            // Arrange

            var message = "FooBar";
            var code = "some-code";

            // Act

            var warning = ValidationIssue.Warning(message, code);

            // Assert

            Assert.Equal(message, warning.Message);
            Assert.Equal(ValidationIssueLevel.Warning, warning.Level);
            Assert.Equal(code, warning.Code);
            Assert.Null(warning.MemberNames);
        }

        [Fact]
        public void Warning_WithJustMemberNames() {

            // Arrange

            var message = "FooBar";
            var memberNames = ImmutableHashSet.Create("foo", "bar");

            // Act

            var warning = ValidationIssue.Warning(message, memberNames);

            // Assert

            Assert.Equal(message, warning.Message);
            Assert.Equal(ValidationIssueLevel.Warning, warning.Level);
            Assert.Null(warning.Code);
            Assert.Equal(memberNames, warning.MemberNames);
        }

        [Fact]
        public void Warning_Valid() {

            // Arrange

            var message = "FooBar";
            var code = "some-code";
            var names = ImmutableHashSet.Create("Foo", "Bar");

            // Act

            var warning = ValidationIssue.Warning(
                message,
                code,
                names
            );

            // Assert

            Assert.Equal(message, warning.Message);
            Assert.Equal(ValidationIssueLevel.Warning, warning.Level);
            Assert.Equal(code, warning.Code);
            Assert.Equal(names, warning.MemberNames);
        }

        [Fact]
        public void Error_NullMessage() {

            // Act

            var exception = Record.Exception(
                () => ValidationIssue.Error(null)
            );

            // Assert

            Assert.IsType<ArgumentNullException>(exception);
        }

        [Fact]
        public void Error_WhiteSpaceMessage() {

            // Act

            var exception = Record.Exception(
                () => ValidationIssue.Error(" \t")
            );

            // Assert

            Assert.IsType<ArgumentException>(exception);
        }

        [Fact]
        public void Error_WithJustCode() {

            // Arrange

            var message = "FooBar";
            var code = "some-code";

            // Act

            var warning = ValidationIssue.Error(message, code);

            // Assert

            Assert.Equal(message, warning.Message);
            Assert.Equal(ValidationIssueLevel.Error, warning.Level);
            Assert.Equal(code, warning.Code);
            Assert.Null(warning.MemberNames);
        }

        [Fact]
        public void Error_WithJustMemberNames() {

            // Arrange

            var message = "FooBar";
            var memberNames = ImmutableHashSet.Create("foo", "bar");

            // Act

            var warning = ValidationIssue.Error(message, memberNames);

            // Assert

            Assert.Equal(message, warning.Message);
            Assert.Equal(ValidationIssueLevel.Error, warning.Level);
            Assert.Null(warning.Code);
            Assert.Equal(memberNames, warning.MemberNames);
        }

        [Fact]
        public void Error_Valid() {

            // Arrange

            var message = "FooBar";
            var code = "bizz buzz barr";
            var names = ImmutableHashSet.Create("Foo", "Bar");

            // Act

            var warning = ValidationIssue.Error(
                message,
                code,
                names
            );

            // Assert

            Assert.Equal(message, warning.Message);
            Assert.Equal(ValidationIssueLevel.Error, warning.Level);
            Assert.Equal(code, warning.Code);
            Assert.Equal(names, warning.MemberNames);
        }

        [Fact]
        public void Constructor_NullMessage() {

            // Act

            var exception = Record.Exception(
                () => new ValidationIssue(null, ValidationIssueLevel.Warning)
            );

            // Assert

            Assert.IsType<ArgumentNullException>(exception);
        }

        [Fact]
        public void Constructor_WhiteSpaceMessage() {

            // Act

            var exception = Record.Exception(
                () => new ValidationIssue(" \n", ValidationIssueLevel.Warning)
            );

            // Assert

            Assert.IsType<ArgumentException>(exception);
        }

        [Fact]
        public void Constructor_Valid() {

            // Arrange

            var message = "FooBar";
            var code = "some-error-code";
            var level = ValidationIssueLevel.Error;
            var names = ImmutableHashSet.Create("Foo", "Bar");

            // Act

            var issue = new ValidationIssue(
                message: message,
                code: code,
                level: level,
                memberNames: names
            );

            // Assert

            Assert.Equal(message, issue.Message);
            Assert.Equal(code, issue.Code);
            Assert.Equal(level, issue.Level);
            Assert.Equal(names, issue.MemberNames);
        }

        [Fact]
        public void SetMessage_NullMessage() {

            // Arrange

            var issue = ValidationIssue.Error("FooBar");

            // Act

            var exception = Record.Exception(
                () => issue.SetMessage(null)
            );

            // Assert

            Assert.IsType<ArgumentNullException>(exception);
        }

        [Fact]
        public void SetMessage_WhiteSpaceMessage() {

            // Arrange

            var issue = ValidationIssue.Error("FooBar");

            // Act

            var exception = Record.Exception(
                () => issue.SetMessage(" \n")
            );

            // Assert

            Assert.IsType<ArgumentException>(exception);
        }

        [Fact]
        public void SetMessage_Valid() {

            // Arrange

            var initial = ValidationIssue.Error("Foo");

            // Act

            var updated = initial.SetMessage("FooBar");

            // Assert

            Assert.Equal("Foo", initial.Message);
            Assert.Equal("FooBar", updated.Message);
        }

        [Theory]
        [InlineData(null)]
        [InlineData("")]
        [InlineData(" ")]
        [InlineData("SomeCode")]
        public void SetCode_AllStringsAreValid(string newCode) {

            // Arrange

            var initial = ValidationIssue.Warning("Bar", "Code?");

            // Act

            var updated = initial.SetCode(newCode);

            // Assert

            Assert.Equal(newCode, updated.Code);
        }

        [Fact]
        public void SetLevel_Valid() {

            // Arrange

            var initial = ValidationIssue.Error("Foo");

            // Act

            var updated = initial.SetLevel(ValidationIssueLevel.Warning);

            // Assert

            Assert.Equal(ValidationIssueLevel.Error, initial.Level);
            Assert.Equal(ValidationIssueLevel.Warning, updated.Level);
        }

        [Fact]
        public void SetMemberNames_Valid() {

            // Arrange

            var names = ImmutableHashSet.Create("Foo", "Bar");
            var initial = ValidationIssue.Error("Foo", memberNames: names);

            // Act

            var nextNames = names.Add("Name");
            var updated = initial.SetMemberNames(nextNames);

            // Assert

            Assert.DoesNotContain("Name", initial.MemberNames);
            Assert.Contains("Name", updated.MemberNames);
        }

    }

}


text:
def sendingRequest(msg, initiator, helper):
	#print 'sendingRequest called for url=' + msg.getRequestHeader().getURI().toString()
	pass

def regparser(logoutIndicators, msg):
	import re

	for indicatorDict in logoutIndicators:
		matches = []
		if "STATUS" in indicatorDict:
			regex = re.compile(indicatorDict["STATUS"])
			matches.append(re.search(regex, str(msg.getResponseHeader().getStatusCode())))
		if "HEADER" in indicatorDict:
			regex = re.compile(indicatorDict["HEADER"])
			matches.append(re.search(regex, msg.getResponseHeader().toString()))
		if "BODY" in indicatorDict:
			regex = re.compile(indicatorDict["BODY"])
			matches.append(re.search(regex, msg.getResponseBody().toString()))
		if "HEADER/i" in indicatorDict:
			regex = re.compile(indicatorDict["HEADER/i"],re.IGNORECASE)
			matches.append(re.search(regex, msg.getResponseHeader().toString()))
		if "BODY/i" in indicatorDict:
			regex = re.compile(indicatorDict["BODY/i"],re.IGNORECASE)
			matches.append(re.search(regex, msg.getResponseBody().toString()))
		if all(None != s for s in matches):
			return True
	return False

def responseReceived(msg, initiator, helper):
	#print 'responseReceived called for url=' + msg.getRequestHeader().getURI().toString()

	if msg.isInScope():

		if initiator == 2 or initiator == 3 or initiator == 4 or initiator == 6:
			logoutIndicators = []

			#########################################################################

			import os
			import org.parosproxy.paros.model.Model as sess
			sfil = sess.getSingleton().getSession().getFileName()
			if sfil != "":

				divider = '/'
				import platform
				if 'Windows' in platform.platform():
					divider  = '\\'

				patth = sfil.rpartition(divider)[0]
				basename = sfil.split(divider)[-1].split(".session")[0]

				import re
				if not os.path.isfile(patth + divider + basename + ".json"):
					print "SAVE AUTHENTICATION SETTINGS! OR DISABLE AUTH SCCRIPT"
					return
				f = open(patth + divider + basename + ".json", 'r')
				text = f.read()
				results = re.findall('{.*?}', text)

				for result in results:
					try:
						eval("logoutIndicators.append(" + result + ")")
					except SyntaxError:
						print "The JSON is invalid! Please check your input!"

				loginTestcase = patth + divider + basename + ".html"
				loginVerificationRequest = patth + divider + basename + ".raw"
			else:
				print "Save session first!"
				return

			#########################################################################

			errorScreens = divider.join(loginTestcase.split(divider)[0:-1]) + divider + "errorScreens"

			if  regparser(logoutIndicators, msg) is True:
				print "Current request appears to be logged out"
				verifyMsg = sendVerificationMessage(loginVerificationRequest, helper, msg)

				if  verifyMsg is None or regparser(logoutIndicators, verifyMsg) is True:

					if os.path.isfile(loginTestcase):
						authenticate(msg, initiator, helper, loginTestcase, errorScreens)
					else:
						print "Login Testcase is invalid"
				else:
					pass
					print "Session is still valid!"
			else:
				pass
				#print "rcv-ignore authenticated"
		else:
			pass
			#print "via-proxy " + str(msg.getResponseHeader().getStatusCode())
	else:
		pass
		#print "msg out of scope"

def sendVerificationMessage(verifyMsgPath, helper, msg):
	import org.parosproxy.paros.network.HttpMessage
	import org.parosproxy.paros.network.HttpRequestHeader
	import os.path

	verifyMsg = org.parosproxy.paros.network.HttpMessage()

	f = open(verifyMsgPath, 'r')
	verifyMsg.setRequestHeader(org.parosproxy.paros.network.HttpRequestHeader(str(f.read())))
	if resendMessageWithSession(verifyMsg, helper, getZAPsessionSite(msg).getActiveSession()) is False:
		print "Auth required"
		return None

	return verifyMsg

def authenticate(msg, initiator, helper, loginTestcase, errorScreens):
	print "AUTHENTICATION REQUIRED! Your initiator is: " + str(initiator) + " URL: " + msg.getRequestHeader().getURI().toString()

	sessionSite = getZAPsessionSite(msg)
	seleniumSession = "Auth-Selenium"

	import org.zaproxy.zap.extension.script.ScriptVars as vars
	if vars.getGlobalVar("auth_running") == "True":
		print "Another authentication is running... waiting..."
		import time
		mustend = time.time() + 30
		while time.time() < mustend:
			try:
				time.sleep(1)
			except:
				print "Script was interruped, stop processing current message"
				return
			if vars.getGlobalVar("auth_running") != "True":
				resendMessageWithSession(msg, helper, sessionSite.getHttpSession(seleniumSession))
				return
		print "Authentication timeout exceeded, discard message"
	else:
		#do auth
		vars.setGlobalVar("auth_running", "True")

		if sessionSite.getHttpSession(seleniumSession) is not None:
			seleniumSession = "Re-Auth-Selenium " + str(sessionSite.getNextSessionId())
		sessionSite.createEmptySession(seleniumSession)

		firefoxBinary = 'FirefoxPortableDeveloper/linux/firefox'
		import platform
		if 'Windows' in platform.platform():
			firefoxBinary  = 'FirefoxPortable\FirefoxPortable.exe'

		import subprocess as sub
		#selenese = sub.Popen("java -jar selenese-runner-2.5.0.jar --strict-exit-code --proxy "+ str(getZAPproxy()) +" --no-proxy *.mozilla.com --screenshot-on-fail \"" + errorScreens + "\" --set-speed 100 --cli-args /private-window --cli-args about:blank \"" + loginTestcase + "\" --firefox " + firefoxBinary, stdout=sub.PIPE)
		selenese = sub.Popen(["java", "-jar", "selenese-runner-2.5.0.jar", "--strict-exit-code", "--proxy", str(getZAPproxy()), "--no-proxy", "*.mozilla.com", "--screenshot-on-fail", errorScreens, "--set-speed", "100", "--cli-args", "-private-window", "--cli-args", "about:blank", loginTestcase, "--firefox", firefoxBinary], stdout=sub.PIPE)

		output = selenese.communicate()[0]
		returns = selenese.returncode

		vars.setGlobalVar("auth_running", "False")

		if returns != 0:
			print "AUTHENTICATION FAILURE!"
			print output
		else:
			print "Auth-SUCCESS"
			resendMessageWithSession(msg, helper, sessionSite.getHttpSession(seleniumSession))

def resendMessageWithSession(msg, helper, httpSession):
	if (httpSession is not None and httpSession.getTokenValuesCount() > 0):
		import org.zaproxy.zap.session.CookieBasedSessionManagementHelper as sessionmgmt
		sessionmgmt.processMessageToMatchSession(msg, httpSession)
		helper.getHttpSender().sendAndReceive(msg, True);
		#print 'Re-Send-Authenticated=' + str(msg.getResponseHeader().getStatusCode())
	else:
		print "There is no active session or the token is empty"
		return False

def getZAPsessionSite(msg):
	import org.parosproxy.paros.control.Control
	import org.zaproxy.zap.extension.httpsessions.ExtensionHttpSessions
	import org.zaproxy.zap.extension.httpsessions.HttpSessionsSite

	zapsessions = org.parosproxy.paros.control.Control.getSingleton().getExtensionLoader().getExtension(org.zaproxy.zap.extension.httpsessions.ExtensionHttpSessions.NAME)
	return zapsessions.getHttpSessionsSite(msg.getRequestHeader().getURI().getHost() + ":" + str(msg.getRequestHeader().getHostPort()), False)

def getZAPproxy():
	import org.parosproxy.paros.model.Model
	proxyConfig = org.parosproxy.paros.model.Model.getSingleton().getOptionsParam().getProxyParam();
	return str(proxyConfig.getProxyIp()) + ":" + str(proxyConfig.getProxyPort())


text:
class WXDLLIMPEXP_XRC wxComboBoxXmlHandler : public wxXmlResourceHandler
{
    wxDECLARE_DYNAMIC_CLASS(wxComboBoxXmlHandler);

public:
    wxComboBoxXmlHandler();
    virtual wxObject *DoCreateResource();
    virtual bool CanHandle(wxXmlNode *node);

private:
    bool m_insideBox;
    wxArrayString strList;
};

#endif // wxUSE_XRC && wxUSE_COMBOBOX

#endif // _WX_XH_COMBO_H_


text:
.class Lcom/samsung/bluetoothle/IBluetoothLEClientCharUpdationCallBack$Stub$Proxy;
.super Ljava/lang/Object;
.source "IBluetoothLEClientCharUpdationCallBack.java"

# interfaces
.implements Lcom/samsung/bluetoothle/IBluetoothLEClientCharUpdationCallBack;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/samsung/bluetoothle/IBluetoothLEClientCharUpdationCallBack$Stub;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "Proxy"
.end annotation

# instance fields
.field private mRemote:Landroid/os/IBinder;

# direct methods
.method constructor <init>(Landroid/os/IBinder;)V
    .locals 0
    .parameter "remote"

    .prologue
    .line 119
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 120
    iput-object p1, p0, Lcom/samsung/bluetoothle/IBluetoothLEClientCharUpdationCallBack$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    .line 121
    return-void
.end method

# virtual methods
.method public asBinder()Landroid/os/IBinder;
    .locals 1

    .prologue
    .line 124
    iget-object v0, p0, Lcom/samsung/bluetoothle/IBluetoothLEClientCharUpdationCallBack$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    return-object v0
.end method

.method public getInterfaceDescriptor()Ljava/lang/String;
    .locals 1

    .prologue
    .line 128
    const-string v0, "com.samsung.bluetoothle.IBluetoothLEClientCharUpdationCallBack"

    return-object v0
.end method

.method public onDiscoverCharacteristics(Ljava/lang/String;[Ljava/lang/String;)V
    .locals 5
    .parameter "address"
    .parameter "charPaths"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 179
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    .line 180
    .local v0, _data:Landroid/os/Parcel;
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    .line 182
    .local v1, _reply:Landroid/os/Parcel;
    :try_start_0
    const-string v2, "com.samsung.bluetoothle.IBluetoothLEClientCharUpdationCallBack"

    invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    .line 183
    invoke-virtual {v0, p1}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V

    .line 184
    invoke-virtual {v0, p2}, Landroid/os/Parcel;->writeStringArray([Ljava/lang/String;)V

    .line 185
    iget-object v2, p0, Lcom/samsung/bluetoothle/IBluetoothLEClientCharUpdationCallBack$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v3, 0x4

    const/4 v4, 0x0

    invoke-interface {v2, v3, v0, v1, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    .line 186
    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 189
    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 190
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 192
    return-void

    .line 189
    :catchall_0
    move-exception v2

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 190
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    throw v2
.end method

.method public onDiscoverCharacteristicsFailed(Ljava/lang/String;)V
    .locals 5
    .parameter "address"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 195
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    .line 196
    .local v0, _data:Landroid/os/Parcel;
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    .line 198
    .local v1, _reply:Landroid/os/Parcel;
    :try_start_0
    const-string v2, "com.samsung.bluetoothle.IBluetoothLEClientCharUpdationCallBack"

    invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    .line 199
    invoke-virtual {v0, p1}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V

    .line 200
    iget-object v2, p0, Lcom/samsung/bluetoothle/IBluetoothLEClientCharUpdationCallBack$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v3, 0x5

    const/4 v4, 0x0

    invoke-interface {v2, v3, v0, v1, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    .line 201
    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 204
    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 205
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 207
    return-void

    .line 204
    :catchall_0
    move-exception v2

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 205
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    throw v2
.end method

.method public onReadCharValue(Ljava/lang/String;)V
    .locals 5
    .parameter "charPath"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 132
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    .line 133
    .local v0, _data:Landroid/os/Parcel;
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    .line 135
    .local v1, _reply:Landroid/os/Parcel;
    :try_start_0
    const-string v2, "com.samsung.bluetoothle.IBluetoothLEClientCharUpdationCallBack"

    invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    .line 136
    invoke-virtual {v0, p1}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V

    .line 137
    iget-object v2, p0, Lcom/samsung/bluetoothle/IBluetoothLEClientCharUpdationCallBack$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v3, 0x1

    const/4 v4, 0x0

    invoke-interface {v2, v3, v0, v1, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    .line 138
    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 141
    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 142
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 144
    return-void

    .line 141
    :catchall_0
    move-exception v2

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 142
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    throw v2
.end method

.method public onWatcherValueChanged(Ljava/lang/String;Ljava/lang/String;)V
    .locals 5
    .parameter "charPath"
    .parameter "value"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 212
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    .line 213
    .local v0, _data:Landroid/os/Parcel;
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    .line 215
    .local v1, _reply:Landroid/os/Parcel;
    :try_start_0
    const-string v2, "com.samsung.bluetoothle.IBluetoothLEClientCharUpdationCallBack"

    invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    .line 216
    invoke-virtual {v0, p1}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V

    .line 217
    invoke-virtual {v0, p2}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V

    .line 218
    iget-object v2, p0, Lcom/samsung/bluetoothle/IBluetoothLEClientCharUpdationCallBack$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v3, 0x6

    const/4 v4, 0x0

    invoke-interface {v2, v3, v0, v1, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    .line 219
    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 222
    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 223
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 225
    return-void

    .line 222
    :catchall_0
    move-exception v2

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 223
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    throw v2
.end method

.method public onWriteCharValue(Ljava/lang/String;Ljava/lang/String;)V
    .locals 5
    .parameter "charPath"
    .parameter "status"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 147
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    .line 148
    .local v0, _data:Landroid/os/Parcel;
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    .line 150
    .local v1, _reply:Landroid/os/Parcel;
    :try_start_0
    const-string v2, "com.samsung.bluetoothle.IBluetoothLEClientCharUpdationCallBack"

    invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    .line 151
    invoke-virtual {v0, p1}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V

    .line 152
    invoke-virtual {v0, p2}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V

    .line 153
    iget-object v2, p0, Lcom/samsung/bluetoothle/IBluetoothLEClientCharUpdationCallBack$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v3, 0x2

    const/4 v4, 0x0

    invoke-interface {v2, v3, v0, v1, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    .line 154
    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 157
    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 158
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 160
    return-void

    .line 157
    :catchall_0
    move-exception v2

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 158
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    throw v2
.end method

.method public onWriteClientConfigDesc(Ljava/lang/String;Ljava/lang/String;)V
    .locals 5
    .parameter "charPath"
    .parameter "status"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 163
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    .line 164
    .local v0, _data:Landroid/os/Parcel;
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    .line 166
    .local v1, _reply:Landroid/os/Parcel;
    :try_start_0
    const-string v2, "com.samsung.bluetoothle.IBluetoothLEClientCharUpdationCallBack"

    invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    .line 167
    invoke-virtual {v0, p1}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V

    .line 168
    invoke-virtual {v0, p2}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V

    .line 169
    iget-object v2, p0, Lcom/samsung/bluetoothle/IBluetoothLEClientCharUpdationCallBack$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v3, 0x3

    const/4 v4, 0x0

    invoke-interface {v2, v3, v0, v1, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    .line 170
    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 173
    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 174
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 176
    return-void

    .line 173
    :catchall_0
    move-exception v2

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    .line 174
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    throw v2
.end method


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="generator" content="ApiGen 2.8.0" />

	<title>Class Peg\Lib\Definitions\Element\Constant | PEG Api</title>

	<link rel="stylesheet" type="text/css" media="all" href="resources/style.css?3505392360" />

		Overview

Namespaces

None

Peg

Cli

Commands

Config

Custom

Command

Action

Generate

Parse

CommandLine

Config

Localization

Utilities

Lib

Definitions

Element

Generator

Lexers

Plugins

Signals

Data

Definitions

Lexers

Type

PHP

Classes

ClassElement

ClassVariable

Constant

Enumeration

FunctionElement

GlobalVariable

Header

NamespaceElement

Overload

Parameter

ReturnType

TypeComponents

TypeDef

VariableType

	<form id="search">
		<input type="hidden" name="cx" value="" />
		<input type="hidden" name="ie" value="UTF-8" />
		<input type="text" name="q" class="text" />
		<input type="submit" value="Search" />
	</form>

				Overview

				Namespace

Class

				Tree

				Todo

Class Constant

Represents a constant/#define defined on some include file.

		Namespace: Peg\Lib\Definitions\Element

		Located at src/Definitions/Element/Constant.php

Methods summary

			 public

		#
		__construct( string <var>$name</var>, string <var>$value</var>, string <var>$description</var> = "" )

Create a constant element.

Create a constant element.

Parameters

<var>$name</var>

string
$name

<var>$value</var>

string
$value

<var>$description</var>

string
$description

Properties summary

			public
			string

				<var>$name</var>

			#

Holds the name of the constant

Holds the name of the constant

			public
			string

				<var>$value</var>

			#

Value of the constant

Value of the constant

			public
			string

				<var>$description</var>

			#

Description of the element.

Description of the element.

			public
			Peg\Lib\Definitions\Element\Header

				<var>$header</var>

			#

Reference to the header containing this element.

Reference to the header containing this element.

			public
			Peg\Lib\Definitions\Element\NamespaceElement

				<var>$namespace</var>

			#

Reference to the header containing this element.

Reference to the header containing this element.

		PEG Api API documentation generated by ApiGen 2.8.0


text:
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using AspNetCoreAngular2Starter.Backend.Data;

namespace AspNetCoreAngular2Starter
{
    using AspNetCoreAngular2Starter.Backend.Models;

    public class Startup
    {
        public IConfigurationRoot Configuration { get; }

        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            // Add framework services.
            services.AddMvc()
                .AddMvcOptions(options =>
                {
                    options.CacheProfiles.Add("NoCache", new Microsoft.AspNetCore.Mvc.CacheProfile
                    {
                        NoStore = true,
                        Duration = 0
                    });
                });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext dbContext)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            // support the Routing of Angular2. If the Browser calls a URL which doesn't exists on the server, it could be a Angular route. Especially if the URL doesn't contain a file extension.
            app.Use(async (context, next) =>
            {
                await next();

                if (context.Response.StatusCode == 404
                    && !Path.HasExtension(context.Request.Path.Value)
                    && !context.Request.Path.Value.StartsWith("/api/")
                    && !context.Request.Path.Value.StartsWith("/libs/"))
                {
                    context.Request.Path = "/index.html";
                    await next();
                }
            });

            app.UseDefaultFiles();
            app.UseStaticFiles();

            app.UseMvc();
            //app.UseMvc(routes =>
            //{
            //    routes.MapRoute(
            //        name: "default",
            //        template: "{controller=Home}/{action=Index}/{id?}");
            //});

            DbInitializer.Initialize(dbContext);
        }
    }
}


text:
class PagesController < ApplicationController
  include Seo::Redirects

  # GET /pages
  # GET /pages.json
  def index
    @pages = Page.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @pages }
    end
  end

  # GET /pages/1
  # GET /pages/1.json
  def show
    @page = Page.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @page }
    end
  end

  # GET /pages/new
  # GET /pages/new.json
  def new
    @page = Page.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @page }
    end
  end

  # GET /pages/1/edit
  def edit
    @page = Page.find(params[:id])
  end

  # POST /pages
  # POST /pages.json
  def create
    @page = Page.new(params[:page])

    respond_to do |format|
      if @page.save
        format.html { redirect_to @page, notice: 'Page was successfully created.' }
        format.json { render json: @page, status: :created, location: @page }
      else
        format.html { render action: "new" }
        format.json { render json: @page.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /pages/1
  # PUT /pages/1.json
  def update
    @page = Page.find(params[:id])

    respond_to do |format|
      if @page.update_attributes(params[:page])
        format.html { redirect_to @page, notice: 'Page was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @page.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /pages/1
  # DELETE /pages/1.json
  def destroy
    @page = Page.find(params[:id])
    @page.destroy

    respond_to do |format|
      format.html { redirect_to pages_url }
      format.json { head :no_content }
    end
  end
end


text:
package io.scalajs.nodejs.repl

import io.scalajs.RawOptions
import io.scalajs.nodejs.events.IEventEmitter
import io.scalajs.nodejs.net.Socket

import scala.scalajs.js
import scala.scalajs.js.annotation.JSImport
import scala.scalajs.js.|

/**
  * The repl module provides a Read-Eval-Print-Loop (REPL) implementation that is available
  * both as a standalone program or includable in other applications.
  * @see https://nodejs.org/api/repl.html#repl_repl
  * @author lawrence.daniels@gmail.com
  */
@js.native
trait REPL extends IEventEmitter {
  var REPL_MODE_SLOPPY: String = js.native
  var REPL_MODE_STRICT: String = js.native
  var REPL_MODE_MAGIC: String = js.native

  /**
    * @example repl.start([options])
    */
  def start(options: REPLOptions | RawOptions): REPLServer = js.native

  /**
    * @example repl.start([options])
    */
  def start(prompt: String, socket: Socket): REPLServer = js.native

  /**
    * @example repl.start([options])
    */
  def start(prompt: String): REPLServer = js.native

  /**
    * @example repl.start([options])
    */
  def start(): REPLServer = js.native

}

/**
  * REPL Singleton
  * @author lawrence.daniels@gmail.com
  */
@js.native
@JSImport("repl", JSImport.Namespace)
object REPL extends REPL


text:
<?xml version="1.0" encoding="utf-8"?>

<merge
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
  <TextView
      android:id="@+id/fps_text"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_margin="3dp"
      android:background="#a4141823"
      android:gravity="right"
      android:layout_gravity="top|right"
      android:padding="3dp"
      android:textColor="@android:color/white"
      android:textSize="11sp"
      />
</merge>
<!-- From: file:/Users/mkonicek/code/react-native/ReactAndroid/src/main/res/devsupport/layout/fps_view.xml --><!-- From: file:/Users/northfoxz/Documents/TIL/reactnative/whatsthis/node_modules/react-native-camera/android/build/intermediates/exploded-aar/com.facebook.react/react-native/0.12.0/res/layout/fps_view.xml -->


text:
<!--
  Copyright The Ohio State University Research Foundation, The University of Chicago -
Argonne National Laboratory, Emory University, SemanticBits LLC, and Ekagra Software Technologies Ltd.

  Distributed under the OSI-approved BSD 3-Clause License.
  See http://ncip.github.com/cagrid-core/LICENSE.txt for details.
-->
<?xml version="1.0"?>

<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="http://incubator.apache.org/ivy/schemas/ivy.xsd">

	<info organisation="springframework" module="spring" revision="2.5.5">
		<license name="Apache" url="http://www.apache.org/licenses/LICENSE-2.0.txt"/>
		<description homepage="http://www.springframework.org/">Spring is a layered Java/J2EE
			application framework </description>
	</info>

	<configurations>
		<!-- Public Configurations-->
		<conf name="full" visibility="public"/>
		<conf name="webmvc" visibility="public"/>
		<conf name="context" visibility="public"/>
	</configurations>

	<publications>
		<artifact name="spring" conf="full" type="jar"/>
		<artifact name="spring-webmvc" conf="webmvc" type="jar"/>
		<artifact name="spring-context" conf="context" type="jar"/>
		<artifact name="spring-test" type="jar"/>
	</publications>
</ivy-module>