text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// https://github.com/dotnet/wpf

namespace Microsoft.Windows.Themes
{
    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media;
    using System.Windows.Media.Animation;

    /// <summary>
    /// The ButtonChrome element
    /// This element is a theme-specific type that is used as an optimization
    /// for a common complex rendering used in Aero
    /// </summary>
    public sealed class ButtonChrome : Decorator
    {
        static ButtonChrome()
        {
            IsEnabledProperty.OverrideMetadata(typeof(ButtonChrome),
                new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.AffectsRender));
        }

        /// <summary>
        /// DependencyProperty for <see cref="Background" /> property.
        /// </summary>
        public static readonly DependencyProperty BackgroundProperty =
            Control.BackgroundProperty.AddOwner(
                typeof(ButtonChrome),
                new FrameworkPropertyMetadata(
                    null,
                    FrameworkPropertyMetadataOptions.AffectsRender));

        /// <summary>
        /// The Background property defines the brush used to fill the background of the button.
        /// </summary>
        public Brush Background
        {
            get => (Brush)GetValue(BackgroundProperty);
            set => SetValue(BackgroundProperty, value);
        }

        /// <summary>
        /// DependencyProperty for <see cref="BorderBrush" /> property.
        /// </summary>
        public static readonly DependencyProperty BorderBrushProperty =
            Border.BorderBrushProperty.AddOwner(
                typeof(ButtonChrome),
                new FrameworkPropertyMetadata(
                    null,
                    FrameworkPropertyMetadataOptions.AffectsRender));

        /// <summary>
        /// The BorderBrush property defines the brush used to draw the outer border.
        /// </summary>
        public Brush BorderBrush
        {
            get => (Brush)GetValue(BorderBrushProperty);
            set => SetValue(BorderBrushProperty, value);
        }

        /// <summary>
        /// DependencyProperty for <see cref="RenderDefaulted" /> property.
        /// </summary>
        public static readonly DependencyProperty RenderDefaultedProperty =
            DependencyProperty.Register("RenderDefaulted",
                typeof(bool),
                typeof(ButtonChrome),
                new FrameworkPropertyMetadata(
                    false,
                    OnRenderDefaultedChanged));

        /// <summary>
        /// When true the chrome renders with a mouse over look.
        /// </summary>
        public bool RenderDefaulted
        {
            get => (bool)GetValue(RenderDefaultedProperty);
            set => SetValue(RenderDefaultedProperty, value);
        }

        private static void OnRenderDefaultedChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            var chrome = (ButtonChrome)o;

            if (chrome.Animates)
            {
                if ((bool)e.NewValue)
                {
                    if (chrome._localResources == null)
                    {
                        chrome._localResources = new LocalResources();
                        chrome.InvalidateVisual();
                    }

                    var duration = new Duration(TimeSpan.FromSeconds(0.3));

                    var ca = new ColorAnimation(Color.FromArgb(0xF9, 0x00, 0xCC, 0xFF), duration);
                    var gsc = ((LinearGradientBrush)chrome.InnerBorderPen.Brush).GradientStops;
                    gsc[0].BeginAnimation(GradientStop.ColorProperty, ca);
                    gsc[1].BeginAnimation(GradientStop.ColorProperty, ca);

                    if (!chrome.RenderPressed)
                    {
                        // Create a repeating animation like:
                        //  __/ \__/ \__/ \__...
                        var daukf = new DoubleAnimationUsingKeyFrames();
                        daukf.KeyFrames.Add(new LinearDoubleKeyFrame(1.0, TimeSpan.FromSeconds(0.5)));
                        daukf.KeyFrames.Add(new DiscreteDoubleKeyFrame(1.0, TimeSpan.FromSeconds(0.75)));
                        daukf.KeyFrames.Add(new LinearDoubleKeyFrame(0.0, TimeSpan.FromSeconds(2.0)));
                        daukf.RepeatBehavior = RepeatBehavior.Forever;
                        Timeline.SetDesiredFrameRate(daukf, 10);

                        chrome.BackgroundOverlay.BeginAnimation(Brush.OpacityProperty, daukf);
                        chrome.BorderOverlayPen.Brush.BeginAnimation(Brush.OpacityProperty, daukf);
                    }
                }
                else if (chrome._localResources == null)
                {
                    if (!chrome.RenderPressed) chrome.InvalidateVisual();
                }
                else
                {
                    var duration = new Duration(TimeSpan.FromSeconds(0.2));

                    if (!chrome.RenderPressed)
                    {
                        var da = new DoubleAnimation();
                        da.Duration = duration;
                        chrome.BorderOverlayPen.Brush.BeginAnimation(Brush.OpacityProperty, da);
                        chrome.BackgroundOverlay.BeginAnimation(Brush.OpacityProperty, da);
                    }

                    var ca = new ColorAnimation();
                    ca.Duration = duration;
                    var gsc = ((LinearGradientBrush)chrome.InnerBorderPen.Brush).GradientStops;
                    gsc[0].BeginAnimation(GradientStop.ColorProperty, ca);
                    gsc[1].BeginAnimation(GradientStop.ColorProperty, ca);
                }
            }
            else
            {
                chrome._localResources = null;
                chrome.InvalidateVisual();
            }
        }

        /// <summary>
        /// DependencyProperty for <see cref="RenderMouseOver" /> property.
        /// </summary>
        public static readonly DependencyProperty RenderMouseOverProperty =
            DependencyProperty.Register("RenderMouseOver",
                typeof(bool),
                typeof(ButtonChrome),
                new FrameworkPropertyMetadata(
                    false,
                    OnRenderMouseOverChanged));

        /// <summary>
        /// When true the chrome renders with a mouse over look.
        /// </summary>
        public bool RenderMouseOver
        {
            get => (bool)GetValue(RenderMouseOverProperty);
            set => SetValue(RenderMouseOverProperty, value);
        }

        private static void OnRenderMouseOverChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            var chrome = (ButtonChrome)o;

            if (chrome.Animates)
            {
                if (!chrome.RenderPressed)
                {
                    if ((bool)e.NewValue)
                    {
                        if (chrome._localResources == null)
                        {
                            chrome._localResources = new LocalResources();
                            chrome.InvalidateVisual();
                        }

                        var duration = new Duration(TimeSpan.FromSeconds(0.3));

                        var da = new DoubleAnimation(1, duration);

                        chrome.BorderOverlayPen.Brush.BeginAnimation(Brush.OpacityProperty, da);
                        chrome.BackgroundOverlay.BeginAnimation(Brush.OpacityProperty, da);
                    }
                    else if (chrome._localResources == null)
                    {
                        chrome.InvalidateVisual();
                    }
                    else
                    {
                        if (chrome.RenderDefaulted)
                        {
                            // Since the mouse was over the button the opacity should be 1.0
                            // Create a repeating animation like:
                            //  \__/ \__/ \__/ \_...
                            // But if the user quickly mouses over a button, the opacity may not be 1 yet
                            // so the first keyframe brings the opacity to 1
                            var currentOpacity = chrome.BackgroundOverlay.Opacity;

                            // This is the time needed to complete the animation to 1:
                            var to1 = (1.0 - currentOpacity) * 0.5;

                            var daukf = new DoubleAnimationUsingKeyFrames();
                            daukf.KeyFrames.Add(new LinearDoubleKeyFrame(1.0, TimeSpan.FromSeconds(to1)));
                            daukf.KeyFrames.Add(new DiscreteDoubleKeyFrame(1.0, TimeSpan.FromSeconds(to1 + 0.25)));
                            daukf.KeyFrames.Add(new LinearDoubleKeyFrame(0.0, TimeSpan.FromSeconds(to1 + 1.5)));
                            daukf.KeyFrames.Add(new LinearDoubleKeyFrame(currentOpacity, TimeSpan.FromSeconds(2)));
                            daukf.RepeatBehavior = RepeatBehavior.Forever;
                            Timeline.SetDesiredFrameRate(daukf, 10);
                            chrome.BackgroundOverlay.BeginAnimation(Brush.OpacityProperty, daukf);
                            chrome.BorderOverlayPen.Brush.BeginAnimation(Brush.OpacityProperty, daukf);
                        }
                        else
                        {
                            var duration = new Duration(TimeSpan.FromSeconds(0.2));

                            var da = new DoubleAnimation();
                            da.Duration = duration;

                            chrome.BackgroundOverlay.BeginAnimation(Brush.OpacityProperty, da);
                            chrome.BorderOverlayPen.Brush.BeginAnimation(Brush.OpacityProperty, da);
                        }
                    }
                }
            }
            else
            {
                chrome._localResources = null;
                chrome.InvalidateVisual();
            }
        }

        /// <summary>
        /// DependencyProperty for <see cref="RenderPressed" /> property.
        /// </summary>
        public static readonly DependencyProperty RenderPressedProperty =
            DependencyProperty.Register("RenderPressed",
                typeof(bool),
                typeof(ButtonChrome),
                new FrameworkPropertyMetadata(
                    false,
                    OnRenderPressedChanged));

        /// <summary>
        /// When true the chrome renders with a pressed look.
        /// </summary>
        public bool RenderPressed
        {
            get => (bool)GetValue(RenderPressedProperty);
            set => SetValue(RenderPressedProperty, value);
        }

        private static void OnRenderPressedChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            var chrome = (ButtonChrome)o;

            if (chrome.Animates)
            {
                if ((bool)e.NewValue)
                {
                    if (chrome._localResources == null)
                    {
                        chrome._localResources = new LocalResources();
                        chrome.InvalidateVisual();
                    }

                    var duration = new Duration(TimeSpan.FromSeconds(0.1));

                    var da = new DoubleAnimation(1, duration);

                    chrome.BackgroundOverlay.BeginAnimation(Brush.OpacityProperty, da);
                    chrome.BorderOverlayPen.Brush.BeginAnimation(Brush.OpacityProperty, da);
                    chrome.LeftDropShadowBrush.BeginAnimation(Brush.OpacityProperty, da);
                    chrome.TopDropShadowBrush.BeginAnimation(Brush.OpacityProperty, da);

                    da = new DoubleAnimation(0, duration);
                    chrome.InnerBorderPen.Brush.BeginAnimation(Brush.OpacityProperty, da);

                    var ca = new ColorAnimation(Color.FromRgb(0xC2, 0xE4, 0xF6), duration);
                    var gsc = ((LinearGradientBrush)chrome.BackgroundOverlay).GradientStops;
                    gsc[0].BeginAnimation(GradientStop.ColorProperty, ca);
                    gsc[1].BeginAnimation(GradientStop.ColorProperty, ca);

                    ca = new ColorAnimation(Color.FromRgb(0xAB, 0xDA, 0xF3), duration);
                    gsc[2].BeginAnimation(GradientStop.ColorProperty, ca);

                    ca = new ColorAnimation(Color.FromRgb(0x90, 0xCB, 0xEB), duration);
                    gsc[3].BeginAnimation(GradientStop.ColorProperty, ca);

                    ca = new ColorAnimation(Color.FromRgb(0x2C, 0x62, 0x8B), duration);
                    chrome.BorderOverlayPen.Brush.BeginAnimation(SolidColorBrush.ColorProperty, ca);
                }
                else if (chrome._localResources == null)
                {
                    chrome.InvalidateVisual();
                }
                else
                {
                    var renderMouseOver = chrome.RenderMouseOver;
                    var duration = new Duration(TimeSpan.FromSeconds(0.1));

                    var da = new DoubleAnimation();
                    da.Duration = duration;
                    chrome.LeftDropShadowBrush.BeginAnimation(Brush.OpacityProperty, da);
                    chrome.TopDropShadowBrush.BeginAnimation(Brush.OpacityProperty, da);
                    chrome.InnerBorderPen.Brush.BeginAnimation(Brush.OpacityProperty, da);

                    if (!renderMouseOver)
                    {
                        chrome.BorderOverlayPen.Brush.BeginAnimation(Brush.OpacityProperty, da);
                        chrome.BackgroundOverlay.BeginAnimation(Brush.OpacityProperty, da);
                    }

                    var ca = new ColorAnimation();
                    ca.Duration = duration;
                    chrome.BorderOverlayPen.Brush.BeginAnimation(SolidColorBrush.ColorProperty, ca);

                    var gsc = ((LinearGradientBrush)chrome.BackgroundOverlay).GradientStops;
                    gsc[0].BeginAnimation(GradientStop.ColorProperty, ca);
                    gsc[1].BeginAnimation(GradientStop.ColorProperty, ca);
                    gsc[2].BeginAnimation(GradientStop.ColorProperty, ca);
                    gsc[3].BeginAnimation(GradientStop.ColorProperty, ca);
                }
            }
            else
            {
                chrome._localResources = null;
                chrome.InvalidateVisual();
            }
        }

        /// <summary>
        /// DependencyProperty for <see cref="RoundCorners" /> property.
        /// </summary>
        public static readonly DependencyProperty RoundCornersProperty =
            DependencyProperty.Register("RoundCorners",
                typeof(bool),
                typeof(ButtonChrome),
                new FrameworkPropertyMetadata(
                    true,
                    FrameworkPropertyMetadataOptions.AffectsRender));

        /// <summary>
        /// When true, the left border will have round corners, otherwise they will be square.
        /// </summary>
        public bool RoundCorners
        {
            get => (bool)GetValue(RoundCornersProperty);
            set => SetValue(RoundCornersProperty, value);
        }

        /// <summary>
        /// Updates DesiredSize of the ButtonChrome.  Called by parent UIElement.  This is the first pass of layout.
        /// </summary>
        /// <remarks>
        /// ButtonChrome basically inflates the desired size of its one child by 2 on all four sides
        /// </remarks>
        /// <param name="availableSize">Available size is an "upper limit" that the return value should not exceed.</param>
        /// <returns>The ButtonChrome's desired size.</returns>
        protected override Size MeasureOverride(Size availableSize)
        {
            Size desired;
            var child = Child;
            if (child != null)
            {
                var childConstraint = new Size();
                var isWidthTooSmall = availableSize.Width < 4.0;
                var isHeightTooSmall = availableSize.Height < 4.0;

                if (!isWidthTooSmall) childConstraint.Width = availableSize.Width - 4.0;
                if (!isHeightTooSmall) childConstraint.Height = availableSize.Height - 4.0;

                child.Measure(childConstraint);

                desired = child.DesiredSize;

                if (!isWidthTooSmall) desired.Width += 4.0;
                if (!isHeightTooSmall) desired.Height += 4.0;
            }
            else
            {
                desired = new Size(Math.Min(4.0, availableSize.Width), Math.Min(4.0, availableSize.Height));
            }

            return desired;
        }

        /// <summary>
        /// ButtonChrome computes the position of its single child inside child's Margin and calls Arrange
        /// on the child.
        /// </summary>
        /// <remarks>
        /// ButtonChrome basically inflates the desired size of its one child by 2 on all four sides
        /// </remarks>
        /// <param name="finalSize">Size the ContentPresenter will assume.</param>
        protected override Size ArrangeOverride(Size finalSize)
        {
            var childArrangeRect = new Rect();

            childArrangeRect.Width = Math.Max(0d, finalSize.Width - 4.0);
            childArrangeRect.Height = Math.Max(0d, finalSize.Height - 4.0);
            childArrangeRect.X = (finalSize.Width - childArrangeRect.Width) * 0.5;
            childArrangeRect.Y = (finalSize.Height - childArrangeRect.Height) * 0.5;

            var child = Child;
            if (child != null) child.Arrange(childArrangeRect);

            return finalSize;
        }

        /// <summary>
        /// Render callback.
        /// </summary>
        protected override void OnRender(DrawingContext drawingContext)
        {
            var bounds = new Rect(0, 0, ActualWidth, ActualHeight);

            // Draw Background
            DrawBackground(drawingContext, ref bounds);

            // Draw Border dropshadows
            DrawDropShadows(drawingContext, ref bounds);

            // Draw outer border
            DrawBorder(drawingContext, ref bounds);

            // Draw innerborder
            DrawInnerBorder(drawingContext, ref bounds);
        }

        private void DrawBackground(DrawingContext dc, ref Rect bounds)
        {
            if (!IsEnabled && !RoundCorners)
                return;

            var fill = Background;
            if (bounds.Width > 4.0 && bounds.Height > 4.0)
            {
                var backgroundRect = new Rect(bounds.Left + 1.0,
                    bounds.Top + 1.0,
                    bounds.Width - 2.0,
                    bounds.Height - 2.0);

                // Draw Background
                if (fill != null)
                    dc.DrawRectangle(fill, null, backgroundRect);

                // Draw BackgroundOverlay
                fill = BackgroundOverlay;
                if (fill != null)
                    dc.DrawRectangle(fill, null, backgroundRect);
            }
        }

        // Draw the Pressed dropshadows
        private void DrawDropShadows(DrawingContext dc, ref Rect bounds)
        {
            if (bounds.Width > 4.0 && bounds.Height > 4.0)
            {
                Brush leftShadow = LeftDropShadowBrush;

                if (leftShadow != null)
                    dc.DrawRectangle(leftShadow, null, new Rect(1.0, 1.0, 2.0, bounds.Bottom - 2.0));

                Brush topShadow = TopDropShadowBrush;

                if (topShadow != null) dc.DrawRectangle(topShadow, null, new Rect(1.0, 1.0, bounds.Right - 2.0, 2.0));
            }
        }

        // Draw the main border
        private void DrawBorder(DrawingContext dc, ref Rect bounds)
        {
            if (bounds.Width >= 5.0 && bounds.Height >= 5.0)
            {
                var border = BorderBrush;
                Pen pen = null;

                if (border != null)
                {
                    if (_commonBorderPen == null) // Common case, if non-null, avoid the lock
                        lock (_resourceAccess) // If non-null, lock to create the pen for thread safety
                        {
                            if (_commonBorderPen == null) // Check again in case _pen was created within the last line
                            {
                                // Assume that the first render of Button uses the most common brush for the app.
                                // This breaks down if (a) the first Button is disabled, (b) the first Button is
                                // customized, or (c) ButtonChrome becomes more broadly used than just on Button.
                                //
                                // If these cons sufficiently weaken the effectiveness of this cache, then we need
                                // to build a larger brush-to-pen mapping cache.

                                // If the brush is not already frozen, we need to create our own
                                // copy.  Otherwise we will inadvertently freeze the user's
                                // BorderBrush when we freeze the pen below.
                                if (!border.IsFrozen && border.CanFreeze)
                                {
                                    border = border.Clone();
                                    border.Freeze();
                                }

                                var commonPen = new Pen(border, 1);
                                if (commonPen.CanFreeze)
                                {
                                    // Only save frozen pens, some brushes such as VisualBrush
                                    // can not be frozen
                                    commonPen.Freeze();
                                    _commonBorderPen = commonPen;
                                }
                            }
                        }

                    if (_commonBorderPen != null && border == _commonBorderPen.Brush)
                    {
                        pen = _commonBorderPen;
                    }
                    else
                    {
                        if (!border.IsFrozen && border.CanFreeze)
                        {
                            border = border.Clone();
                            border.Freeze();
                        }

                        pen = new Pen(border, 1);
                        if (pen.CanFreeze) pen.Freeze();
                    }
                }

                var overlayPen = BorderOverlayPen;

                if (pen != null || overlayPen != null)
                {
                    if (RoundCorners)
                    {
                        var rect = new Rect(bounds.Left + 0.5,
                            bounds.Top + 0.5,
                            bounds.Width - 1.0,
                            bounds.Height - 1.0);

                        if (IsEnabled && pen != null)
                            dc.DrawRoundedRectangle(null, pen, rect, 2.75, 2.75);

                        if (overlayPen != null)
                            dc.DrawRoundedRectangle(null, overlayPen, rect, 2.75, 2.75);
                    }
                    else
                    {
                        // Left side is flat, have to generate a geometry because
                        // DrawRoundedRectangle does not let you specify per corner radii
                        var borderFigure = new PathFigure();

                        borderFigure.StartPoint = new Point(0.5, 0.5);
                        borderFigure.Segments.Add(new LineSegment(new Point(0.5, bounds.Bottom - 0.5), true));
                        borderFigure.Segments.Add(new LineSegment(new Point(bounds.Right - 2.5, bounds.Bottom - 0.5),
                            true));
                        borderFigure.Segments.Add(new ArcSegment(new Point(bounds.Right - 0.5, bounds.Bottom - 2.5),
                            new Size(2.0, 2.0), 0.0, false, SweepDirection.Counterclockwise, true));
                        borderFigure.Segments.Add(
                            new LineSegment(new Point(bounds.Right - 0.5, bounds.Top + 2.5), true));
                        borderFigure.Segments.Add(new ArcSegment(new Point(bounds.Right - 2.5, bounds.Top + 0.5),
                            new Size(2.0, 2.0), 0.0, false, SweepDirection.Counterclockwise, true));
                        borderFigure.IsClosed = true;

                        var borderGeometry = new PathGeometry();
                        borderGeometry.Figures.Add(borderFigure);

                        if (IsEnabled && pen != null)
                            dc.DrawGeometry(null, pen, borderGeometry);

                        if (overlayPen != null)
                            dc.DrawGeometry(null, overlayPen, borderGeometry);
                    }
                }
            }
        }

        // Draw the inner border
        private void DrawInnerBorder(DrawingContext dc, ref Rect bounds)
        {
            if (!IsEnabled && !RoundCorners)
                return;

            if (bounds.Width >= 4.0 && bounds.Height >= 4.0)
            {
                var innerBorder = InnerBorderPen;

                if (innerBorder != null)
                    dc.DrawRoundedRectangle(null, innerBorder,
                        new Rect(bounds.Left + 1.5, bounds.Top + 1.5, bounds.Width - 3.0, bounds.Height - 3.0), 1.75,
                        1.75);
            }
        }

        private bool Animates =>
            SystemParameters.PowerLineStatus == PowerLineStatus.Online &&
            SystemParameters.ClientAreaAnimation &&
            RenderCapability.Tier > 0 &&
            IsEnabled;

        private static LinearGradientBrush CommonHoverBackgroundOverlay
        {
            get
            {
                if (_commonHoverBackgroundOverlay == null)
                    lock (_resourceAccess)
                    {
                        if (_commonHoverBackgroundOverlay == null)
                        {
                            var temp = new LinearGradientBrush();
                            temp.StartPoint = new Point(0, 0);
                            temp.EndPoint = new Point(0, 1);

                            temp.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xEA, 0xF6, 0xFD), 0));
                            temp.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xD9, 0xF0, 0xFC), 0.5));
                            temp.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xBE, 0xE6, 0xFD), 0.5));
                            temp.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xA7, 0xD9, 0xF5), 1));

                            temp.Freeze();

                            // Static field must not be set until the local has been frozen
                            _commonHoverBackgroundOverlay = temp;
                        }
                    }

                return _commonHoverBackgroundOverlay;
            }
        }

        private static LinearGradientBrush CommonPressedBackgroundOverlay
        {
            get
            {
                if (_commonPressedBackgroundOverlay == null)
                    lock (_resourceAccess)
                    {
                        if (_commonPressedBackgroundOverlay == null)
                        {
                            var temp = new LinearGradientBrush();
                            temp.StartPoint = new Point(0, 0);
                            temp.EndPoint = new Point(0, 1);

                            temp.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xC2, 0xE4, 0xF6), 0.5));
                            temp.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xAB, 0xDA, 0xF3), 0.5));
                            temp.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0x90, 0xCB, 0xEB), 1));

                            temp.Freeze();
                            _commonPressedBackgroundOverlay = temp;
                        }
                    }

                return _commonPressedBackgroundOverlay;
            }
        }

        private static SolidColorBrush CommonDisabledBackgroundOverlay
        {
            get
            {
                if (_commonDisabledBackgroundOverlay == null)
                    lock (_resourceAccess)
                    {
                        if (_commonDisabledBackgroundOverlay == null)
                        {
                            var temp = new SolidColorBrush(Color.FromRgb(0xF4, 0xF4, 0xF4));
                            temp.Freeze();
                            _commonDisabledBackgroundOverlay = temp;
                        }
                    }

                return _commonDisabledBackgroundOverlay;
            }
        }

        private Brush BackgroundOverlay
        {
            get
            {
                if (!IsEnabled) return CommonDisabledBackgroundOverlay;

                if (!Animates)
                {
                    if (RenderPressed)
                        return CommonPressedBackgroundOverlay;
                    if (RenderMouseOver)
                        return CommonHoverBackgroundOverlay;
                    return null;
                }

                if (_localResources != null)
                {
                    if (_localResources.BackgroundOverlay == null)
                    {
                        _localResources.BackgroundOverlay = CommonHoverBackgroundOverlay.Clone();
                        _localResources.BackgroundOverlay.Opacity = 0;
                    }

                    return _localResources.BackgroundOverlay;
                }

                return null;
            }
        }

        private static Pen CommonHoverBorderOverlay
        {
            get
            {
                if (_commonHoverBorderOverlay == null)
                    lock (_resourceAccess)
                    {
                        if (_commonHoverBorderOverlay == null)
                        {
                            var temp = new Pen();
                            temp.Thickness = 1;
                            temp.Brush = new SolidColorBrush(Color.FromRgb(0x3C, 0x7F, 0xB1));
                            temp.Freeze();
                            _commonHoverBorderOverlay = temp;
                        }
                    }

                return _commonHoverBorderOverlay;
            }
        }

        private static Pen CommonPressedBorderOverlay
        {
            get
            {
                if (_commonPressedBorderOverlay == null)
                    lock (_resourceAccess)
                    {
                        if (_commonPressedBorderOverlay == null)
                        {
                            var temp = new Pen();
                            temp.Thickness = 1;
                            temp.Brush = new SolidColorBrush(Color.FromRgb(0x2C, 0x62, 0x8B));
                            temp.Freeze();

                            _commonPressedBorderOverlay = temp;
                        }
                    }

                return _commonPressedBorderOverlay;
            }
        }

        private static Pen CommonDisabledBorderOverlay
        {
            get
            {
                if (_commonDisabledBorderOverlay == null)
                    lock (_resourceAccess)
                    {
                        if (_commonDisabledBorderOverlay == null)
                        {
                            var temp = new Pen();
                            temp.Thickness = 1;
                            temp.Brush = new SolidColorBrush(Color.FromRgb(0xAD, 0xB2, 0xB5));
                            temp.Freeze();
                            _commonDisabledBorderOverlay = temp;
                        }
                    }

                return _commonDisabledBorderOverlay;
            }
        }

        private Pen BorderOverlayPen
        {
            get
            {
                if (!IsEnabled)
                {
                    if (RoundCorners)
                        return CommonDisabledBorderOverlay;
                    return null;
                }

                if (!Animates)
                {
                    if (RenderPressed)
                        return CommonPressedBorderOverlay;
                    if (RenderMouseOver)
                        return CommonHoverBorderOverlay;
                    return null;
                }

                if (_localResources != null)
                {
                    if (_localResources.BorderOverlayPen == null)
                    {
                        _localResources.BorderOverlayPen = CommonHoverBorderOverlay.Clone();
                        _localResources.BorderOverlayPen.Brush.Opacity = 0;
                    }

                    return _localResources.BorderOverlayPen;
                }

                return null;
            }
        }

        private static Pen CommonInnerBorderPen
        {
            get
            {
                if (_commonInnerBorderPen == null)
                    lock (_resourceAccess)
                    {
                        if (_commonInnerBorderPen == null)
                        {
                            var temp = new Pen();

                            temp.Thickness = 1;

                            var brush = new LinearGradientBrush();
                            brush.StartPoint = new Point(0, 0);
                            brush.EndPoint = new Point(0, 1);

                            brush.GradientStops.Add(new GradientStop(Color.FromArgb(0xFA, 0xFF, 0xFF, 0xFF), 0));
                            brush.GradientStops.Add(new GradientStop(Color.FromArgb(0x85, 0xFF, 0xFF, 0xFF), 1));

                            temp.Brush = brush;
                            temp.Freeze();
                            _commonInnerBorderPen = temp;
                        }
                    }

                return _commonInnerBorderPen;
            }
        }

        private static Pen CommonDefaultedInnerBorderPen
        {
            get
            {
                if (_commonDefaultedInnerBorderPen == null)
                    lock (_resourceAccess)
                    {
                        if (_commonDefaultedInnerBorderPen == null)
                        {
                            var temp = new Pen();
                            temp.Thickness = 1;
                            temp.Brush = new SolidColorBrush(Color.FromArgb(0xF9, 0x00, 0xCC, 0xFF));
                            temp.Freeze();
                            _commonDefaultedInnerBorderPen = temp;
                        }
                    }

                return _commonDefaultedInnerBorderPen;
            }
        }

        private Pen InnerBorderPen
        {
            get
            {
                if (!IsEnabled) return CommonInnerBorderPen;

                if (!Animates)
                {
                    if (RenderPressed)
                        return null;
                    if (RenderDefaulted)
                        return CommonDefaultedInnerBorderPen;
                    return CommonInnerBorderPen;
                }

                if (_localResources != null)
                {
                    if (_localResources.InnerBorderPen == null)
                        _localResources.InnerBorderPen = CommonInnerBorderPen.Clone();
                    return _localResources.InnerBorderPen;
                }

                return CommonInnerBorderPen;
            }
        }

        private static LinearGradientBrush CommonPressedLeftDropShadowBrush
        {
            get
            {
                if (_commonPressedLeftDropShadowBrush == null)
                    lock (_resourceAccess)
                    {
                        if (_commonPressedLeftDropShadowBrush == null)
                        {
                            var temp = new LinearGradientBrush();
                            temp.StartPoint = new Point(0, 0);
                            temp.EndPoint = new Point(1, 0);

                            temp.GradientStops.Add(new GradientStop(Color.FromArgb(0x80, 0x33, 0x33, 0x33), 0));
                            temp.GradientStops.Add(new GradientStop(Color.FromArgb(0x00, 0x33, 0x33, 0x33), 1));

                            temp.Freeze();
                            _commonPressedLeftDropShadowBrush = temp;
                        }
                    }

                return _commonPressedLeftDropShadowBrush;
            }
        }

        private LinearGradientBrush LeftDropShadowBrush
        {
            get
            {
                if (!IsEnabled) return null;

                if (!Animates)
                {
                    if (RenderPressed)
                        return CommonPressedLeftDropShadowBrush;
                    return null;
                }

                if (_localResources != null)
                {
                    if (_localResources.LeftDropShadowBrush == null)
                    {
                        _localResources.LeftDropShadowBrush = CommonPressedLeftDropShadowBrush.Clone();
                        _localResources.LeftDropShadowBrush.Opacity = 0;
                    }

                    return _localResources.LeftDropShadowBrush;
                }

                return null;
            }
        }

        private static LinearGradientBrush CommonPressedTopDropShadowBrush
        {
            get
            {
                if (_commonPressedTopDropShadowBrush == null)
                    lock (_resourceAccess)
                    {
                        if (_commonPressedTopDropShadowBrush == null)
                        {
                            var temp = new LinearGradientBrush();
                            temp.StartPoint = new Point(0, 0);
                            temp.EndPoint = new Point(0, 1);

                            temp.GradientStops.Add(new GradientStop(Color.FromArgb(0x80, 0x33, 0x33, 0x33), 0));
                            temp.GradientStops.Add(new GradientStop(Color.FromArgb(0x00, 0x33, 0x33, 0x33), 1));

                            temp.Freeze();
                            _commonPressedTopDropShadowBrush = temp;
                        }
                    }

                return _commonPressedTopDropShadowBrush;
            }
        }

        private LinearGradientBrush TopDropShadowBrush
        {
            get
            {
                if (!IsEnabled) return null;

                if (!Animates)
                {
                    if (RenderPressed)
                        return CommonPressedTopDropShadowBrush;
                    return null;
                }

                if (_localResources != null)
                {
                    if (_localResources.TopDropShadowBrush == null)
                    {
                        _localResources.TopDropShadowBrush = CommonPressedTopDropShadowBrush.Clone();
                        _localResources.TopDropShadowBrush.Opacity = 0;
                    }

                    return _localResources.TopDropShadowBrush;
                }

                return null;
            }
        }

        // Common LocalResources
        private static Pen _commonBorderPen;
        private static Pen _commonInnerBorderPen;

        private static Pen _commonDisabledBorderOverlay;
        private static SolidColorBrush _commonDisabledBackgroundOverlay;

        private static Pen _commonDefaultedInnerBorderPen;

        private static LinearGradientBrush _commonHoverBackgroundOverlay;
        private static Pen _commonHoverBorderOverlay;

        private static LinearGradientBrush _commonPressedBackgroundOverlay;
        private static Pen _commonPressedBorderOverlay;

        private static LinearGradientBrush _commonPressedLeftDropShadowBrush;
        private static LinearGradientBrush _commonPressedTopDropShadowBrush;

        private static readonly object _resourceAccess = new object();

        // Per instance resources

        private LocalResources _localResources;

        private class LocalResources
        {
            public LinearGradientBrush BackgroundOverlay;
            public Pen BorderOverlayPen;
            public Pen InnerBorderPen;
            public LinearGradientBrush LeftDropShadowBrush;
            public LinearGradientBrush TopDropShadowBrush;
        }
    }
}


text:
@implementation EGOQuickPhotoSource
@synthesize photos=_photos, numberOfPhotos=_numberOfPhotos;

- (id)initWithPhotos:(NSArray*)photos {
	if (self = [super init]) {
		_photos = photos;
		_numberOfPhotos = [_photos count];

	}

	return self;
}

- (id<EGOPhoto>)photoAtIndex:(NSInteger)index {
	return [_photos objectAtIndex:index];
}

- (void)dealloc{
	_photos=nil;
}

@end

redpajama_set_name: RedPajamaGithub


text:
package net.automatalib.incremental;

/**
 * Conflict exception. Thrown when a data point to be inserted conflicts with
 * definitive information already existing.
 *
 * @author Malte Isberner
 *
 */
public class ConflictException extends IllegalArgumentException {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 * @see IllegalArgumentException#IllegalArgumentException()
	 */
	public ConflictException() {
		super();
	}

	/**
	 * Constructor.
	 * @see IllegalArgumentException#IllegalArgumentException(String, Throwable)
	 */
	public ConflictException(String message, Throwable cause) {
		super(message, cause);
	}

	/**
	 * Constructor.
	 * @see IllegalArgumentException#IllegalArgumentException(String)
	 */
	public ConflictException(String s) {
		super(s);
	}

	/**
	 * Constructor.
	 * @see IllegalArgumentException#IllegalArgumentException(Throwable)
	 */
	public ConflictException(Throwable cause) {
		super(cause);
	}

}


text:
<?php

App::uses('HtmlElement', 'Ctk.View/Factory/Html/Objects');

/**
 * Creates an object representing an OBJECT element in HTML.
 *
 * @package       Ctk.Factory
 */
class HtmlObject extends HtmlElement {

/**
 * The template to use for this object.
 *
 * @var string The name of the template.
 */
	protected $_template = 'object';

/**
 * The configuration parameters used by the template for this object.
 *
 * @var array The template configuration parameters.
 */
	protected $_params = array(
		'data' => null,
		'form' => null,
		'height' => null,
		'name' => null,
		'type' => null,
		'usemap' => null,
		'width' => null
	);

/**
 * The type of element this object represents.
 *
 * @var string The element type.
 */
	protected $_nodeType = 'object';
}


text:
#ifndef WEBRTC_MODULES_VIDEO_CODING_CODECS_TEST_VIDEOPROCESSOR_INTEGRATIONTEST_H_
#define WEBRTC_MODULES_VIDEO_CODING_CODECS_TEST_VIDEOPROCESSOR_INTEGRATIONTEST_H_

#include <math.h>

#include <limits>
#include <memory>
#include <string>
#include <utility>

#if defined(WEBRTC_ANDROID)
#include "webrtc/modules/video_coding/codecs/test/android_test_initializer.h"
#include "webrtc/sdk/android/src/jni/androidmediadecoder_jni.h"
#include "webrtc/sdk/android/src/jni/androidmediaencoder_jni.h"
#elif defined(WEBRTC_IOS)
#include "webrtc/sdk/objc/Framework/Classes/h264_video_toolbox_decoder.h"
#include "webrtc/sdk/objc/Framework/Classes/h264_video_toolbox_encoder.h"
#endif

#include "webrtc/base/checks.h"
#include "webrtc/base/file.h"
#include "webrtc/base/logging.h"
#include "webrtc/media/engine/webrtcvideodecoderfactory.h"
#include "webrtc/media/engine/webrtcvideoencoderfactory.h"
#include "webrtc/modules/video_coding/codecs/h264/include/h264.h"
#include "webrtc/modules/video_coding/codecs/test/packet_manipulator.h"
#include "webrtc/modules/video_coding/codecs/test/videoprocessor.h"
#include "webrtc/modules/video_coding/codecs/vp8/include/vp8.h"
#include "webrtc/modules/video_coding/codecs/vp8/include/vp8_common_types.h"
#include "webrtc/modules/video_coding/codecs/vp9/include/vp9.h"
#include "webrtc/modules/video_coding/include/video_codec_interface.h"
#include "webrtc/modules/video_coding/include/video_coding.h"
#include "webrtc/modules/video_coding/utility/ivf_file_writer.h"
#include "webrtc/test/gtest.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/test/testsupport/frame_reader.h"
#include "webrtc/test/testsupport/frame_writer.h"
#include "webrtc/test/testsupport/metrics/video_metrics.h"
#include "webrtc/test/testsupport/packet_reader.h"
#include "webrtc/typedefs.h"

namespace webrtc {
namespace test {
// Maximum number of rate updates (i.e., calls to encoder to change bitrate
// and/or frame rate) for the current tests.
const int kMaxNumRateUpdates = 3;

// Maximum number of temporal layers to use in tests.
const int kMaxNumTemporalLayers = 3;

const int kPercTargetvsActualMismatch = 20;
const int kBaseKeyFrameInterval = 3000;

// Default sequence is foreman (CIF): may be better to use VGA for resize test.
const int kCifWidth = 352;
const int kCifHeight = 288;
const char kFilenameForemanCif[] = "foreman_cif";

// Codec and network settings.
struct CodecParams {
  VideoCodecType codec_type;
  bool hw_codec;
  bool use_single_core;

  int width;
  int height;

  int num_temporal_layers;
  int key_frame_interval;
  bool error_concealment_on;
  bool denoising_on;
  bool frame_dropper_on;
  bool spatial_resize_on;

  float packet_loss_probability;  // [0.0, 1.0].

  std::string filename;
  bool verbose_logging;

  // In batch mode, the VideoProcessor is fed all the frames for processing
  // before any metrics are calculated. This is useful for pipelining HW codecs,
  // for which some calculated metrics otherwise would be incorrect. The
  // downside with batch mode is that mid-test rate allocation is not supported.
  bool batch_mode;
};

// Thresholds for the quality metrics. Defaults are maximally minimal.
struct QualityThresholds {
  double min_avg_psnr = std::numeric_limits<double>::min();
  double min_min_psnr = std::numeric_limits<double>::min();
  double min_avg_ssim = 0;
  double min_min_ssim = 0;
};

// The sequence of bit rate and frame rate changes for the encoder, the frame
// number where the changes are made, and the total number of frames for the
// test.
struct RateProfile {
  int target_bit_rate[kMaxNumRateUpdates];
  int input_frame_rate[kMaxNumRateUpdates];
  int frame_index_rate_update[kMaxNumRateUpdates + 1];
  int num_frames;
};

// Thresholds for the rate control metrics. The rate mismatch thresholds are
// defined as percentages. |max_time_hit_target| is defined as number of frames,
// after a rate update is made to the encoder, for the encoder to reach within
// |kPercTargetvsActualMismatch| of new target rate. The thresholds are defined
// for each rate update sequence.
struct RateControlThresholds {
  int max_num_dropped_frames;
  int max_key_frame_size_mismatch;
  int max_delta_frame_size_mismatch;
  int max_encoding_rate_mismatch;
  int max_time_hit_target;
  int num_spatial_resizes;  // Set to -1 to disable check.
  int num_key_frames;       // Set to -1 to disable check.
};

// Should video files be saved persistently to disk for post-run visualization?
struct VisualizationParams {
  bool save_source_y4m;
  bool save_encoded_ivf;
  bool save_decoded_y4m;
};

#if !defined(WEBRTC_IOS)
const int kNumFramesShort = 100;
#endif
const int kNumFramesLong = 299;

// Parameters from VP8 wrapper, which control target size of key frames.
const float kInitialBufferSize = 0.5f;
const float kOptimalBufferSize = 0.6f;
const float kScaleKeyFrameSize = 0.5f;

// Integration test for video processor. Encodes+decodes a clip and
// writes it to the output directory. After completion, quality metrics
// (PSNR and SSIM) and rate control metrics are computed and compared to given
// thresholds, to verify that the quality and encoder response is acceptable.
// The rate control tests allow us to verify the behavior for changing bit rate,
// changing frame rate, frame dropping/spatial resize, and temporal layers.
// The thresholds for the rate control metrics are set to be fairly
// conservative, so failure should only happen when some significant regression
// or breakdown occurs.
class VideoProcessorIntegrationTest : public testing::Test {
 protected:
  VideoProcessorIntegrationTest() {
#if defined(WEBRTC_VIDEOPROCESSOR_INTEGRATIONTEST_HW_CODECS_ENABLED) && \
    defined(WEBRTC_ANDROID)
    InitializeAndroidObjects();

    external_encoder_factory_.reset(
        new webrtc_jni::MediaCodecVideoEncoderFactory());
    external_decoder_factory_.reset(
        new webrtc_jni::MediaCodecVideoDecoderFactory());
#endif
  }
  virtual ~VideoProcessorIntegrationTest() = default;

  void CreateEncoderAndDecoder(bool hw_codec, VideoCodecType codec_type) {
    if (hw_codec) {
#if defined(WEBRTC_VIDEOPROCESSOR_INTEGRATIONTEST_HW_CODECS_ENABLED)
#if defined(WEBRTC_ANDROID)
      // In general, external codecs should be destroyed by the factories that
      // allocated them. For the particular case of the Android
      // MediaCodecVideo{En,De}coderFactory's, however, it turns out that it is
      // fine for the std::unique_ptr to destroy the owned codec directly.
      switch (codec_type) {
        case kVideoCodecH264:
          encoder_.reset(external_encoder_factory_->CreateVideoEncoder(
              cricket::VideoCodec(cricket::kH264CodecName)));
          decoder_.reset(
              external_decoder_factory_->CreateVideoDecoder(kVideoCodecH264));
          break;
        case kVideoCodecVP8:
          encoder_.reset(external_encoder_factory_->CreateVideoEncoder(
              cricket::VideoCodec(cricket::kVp8CodecName)));
          decoder_.reset(
              external_decoder_factory_->CreateVideoDecoder(kVideoCodecVP8));
          break;
        case kVideoCodecVP9:
          encoder_.reset(external_encoder_factory_->CreateVideoEncoder(
              cricket::VideoCodec(cricket::kVp9CodecName)));
          decoder_.reset(
              external_decoder_factory_->CreateVideoDecoder(kVideoCodecVP9));
          break;
        default:
          RTC_NOTREACHED();
          break;
      }
#elif defined(WEBRTC_IOS)
      ASSERT_EQ(kVideoCodecH264, codec_type)
          << "iOS HW codecs only support H264.";
      encoder_.reset(new H264VideoToolboxEncoder(
          cricket::VideoCodec(cricket::kH264CodecName)));
      decoder_.reset(new H264VideoToolboxDecoder());
#else
      RTC_NOTREACHED() << "Only support HW codecs on Android and iOS.";
#endif
#endif  // WEBRTC_VIDEOPROCESSOR_INTEGRATIONTEST_HW_CODECS_ENABLED
      RTC_CHECK(encoder_) << "HW encoder not successfully created.";
      RTC_CHECK(decoder_) << "HW decoder not successfully created.";
      return;
    }

    // SW codecs.
    switch (codec_type) {
      case kVideoCodecH264:
        encoder_.reset(
            H264Encoder::Create(cricket::VideoCodec(cricket::kH264CodecName)));
        decoder_.reset(H264Decoder::Create());
        break;
      case kVideoCodecVP8:
        encoder_.reset(VP8Encoder::Create());
        decoder_.reset(VP8Decoder::Create());
        break;
      case kVideoCodecVP9:
        encoder_.reset(VP9Encoder::Create());
        decoder_.reset(VP9Decoder::Create());
        break;
      default:
        RTC_NOTREACHED();
        break;
    }
  }

  void SetUpCodecConfig(const CodecParams& process,
                        const VisualizationParams* visualization_params) {
    CreateEncoderAndDecoder(process.hw_codec, process.codec_type);

    // Configure input filename.
    config_.input_filename = test::ResourcePath(process.filename, "yuv");
    if (process.verbose_logging)
      printf("Filename: %s\n", process.filename.c_str());
    // Generate an output filename in a safe way.
    config_.output_filename = test::TempFilename(
        test::OutputPath(), "videoprocessor_integrationtest");

    config_.frame_length_in_bytes =
        CalcBufferSize(kI420, process.width, process.height);
    config_.verbose = process.verbose_logging;
    config_.use_single_core = process.use_single_core;
    // Key frame interval and packet loss are set for each test.
    config_.keyframe_interval = process.key_frame_interval;
    config_.networking_config.packet_loss_probability =
        packet_loss_probability_;

    // Configure codec settings.
    VideoCodingModule::Codec(process.codec_type, &codec_settings_);
    config_.codec_settings = &codec_settings_;
    config_.codec_settings->startBitrate = start_bitrate_;
    config_.codec_settings->width = process.width;
    config_.codec_settings->height = process.height;

    // These features may be set depending on the test.
    switch (config_.codec_settings->codecType) {
      case kVideoCodecH264:
        config_.codec_settings->H264()->frameDroppingOn =
            process.frame_dropper_on;
        config_.codec_settings->H264()->keyFrameInterval =
            kBaseKeyFrameInterval;
        break;
      case kVideoCodecVP8:
        config_.codec_settings->VP8()->errorConcealmentOn =
            process.error_concealment_on;
        config_.codec_settings->VP8()->denoisingOn = process.denoising_on;
        config_.codec_settings->VP8()->numberOfTemporalLayers =
            num_temporal_layers_;
        config_.codec_settings->VP8()->frameDroppingOn =
            process.frame_dropper_on;
        config_.codec_settings->VP8()->automaticResizeOn =
            process.spatial_resize_on;
        config_.codec_settings->VP8()->keyFrameInterval = kBaseKeyFrameInterval;
        break;
      case kVideoCodecVP9:
        config_.codec_settings->VP9()->denoisingOn = process.denoising_on;
        config_.codec_settings->VP9()->numberOfTemporalLayers =
            num_temporal_layers_;
        config_.codec_settings->VP9()->frameDroppingOn =
            process.frame_dropper_on;
        config_.codec_settings->VP9()->automaticResizeOn =
            process.spatial_resize_on;
        config_.codec_settings->VP9()->keyFrameInterval = kBaseKeyFrameInterval;
        break;
      default:
        RTC_NOTREACHED();
        break;
    }

    // Create file objects for quality analysis.
    analysis_frame_reader_.reset(new test::YuvFrameReaderImpl(
        config_.input_filename, config_.codec_settings->width,
        config_.codec_settings->height));
    analysis_frame_writer_.reset(new test::YuvFrameWriterImpl(
        config_.output_filename, config_.codec_settings->width,
        config_.codec_settings->height));
    RTC_CHECK(analysis_frame_reader_->Init());
    RTC_CHECK(analysis_frame_writer_->Init());

    if (visualization_params) {
      // clang-format off
      const std::string output_filename_base =
          test::OutputPath() + process.filename +
          "_cd-" + CodecTypeToPayloadName(process.codec_type).value_or("") +
          "_hw-" + std::to_string(process.hw_codec) +
          "_fr-" + std::to_string(start_frame_rate_) +
          "_br-" + std::to_string(static_cast<int>(start_bitrate_));
      // clang-format on
      if (visualization_params->save_source_y4m) {
        source_frame_writer_.reset(new test::Y4mFrameWriterImpl(
            output_filename_base + "_source.y4m", config_.codec_settings->width,
            config_.codec_settings->height, start_frame_rate_));
        RTC_CHECK(source_frame_writer_->Init());
      }
      if (visualization_params->save_encoded_ivf) {
        rtc::File post_encode_file =
            rtc::File::Create(output_filename_base + "_encoded.ivf");
        encoded_frame_writer_ =
            IvfFileWriter::Wrap(std::move(post_encode_file), 0);
      }
      if (visualization_params->save_decoded_y4m) {
        decoded_frame_writer_.reset(new test::Y4mFrameWriterImpl(
            output_filename_base + "_decoded.y4m",
            config_.codec_settings->width, config_.codec_settings->height,
            start_frame_rate_));
        RTC_CHECK(decoded_frame_writer_->Init());
      }
    }

    packet_manipulator_.reset(new test::PacketManipulatorImpl(
        &packet_reader_, config_.networking_config, config_.verbose));
    processor_.reset(new test::VideoProcessorImpl(
        encoder_.get(), decoder_.get(), analysis_frame_reader_.get(),
        analysis_frame_writer_.get(), packet_manipulator_.get(), config_,
        &stats_, source_frame_writer_.get(), encoded_frame_writer_.get(),
        decoded_frame_writer_.get()));
    RTC_CHECK(processor_->Init());
  }

  // Reset quantities after each encoder update, update the target
  // per-frame bandwidth.
  void ResetRateControlMetrics(int num_frames_to_hit_target) {
    for (int i = 0; i < num_temporal_layers_; i++) {
      num_frames_per_update_[i] = 0;
      sum_frame_size_mismatch_[i] = 0.0f;
      sum_encoded_frame_size_[i] = 0.0f;
      encoding_bitrate_[i] = 0.0f;
      // Update layer per-frame-bandwidth.
      per_frame_bandwidth_[i] = static_cast<float>(bit_rate_layer_[i]) /
                                static_cast<float>(frame_rate_layer_[i]);
    }
    // Set maximum size of key frames, following setting in the VP8 wrapper.
    float max_key_size = kScaleKeyFrameSize * kOptimalBufferSize * frame_rate_;
    // We don't know exact target size of the key frames (except for first one),
    // but the minimum in libvpx is ~|3 * per_frame_bandwidth| and maximum is
    // set by |max_key_size_  * per_frame_bandwidth|. Take middle point/average
    // as reference for mismatch. Note key frames always correspond to base
    // layer frame in this test.
    target_size_key_frame_ = 0.5 * (3 + max_key_size) * per_frame_bandwidth_[0];
    num_frames_total_ = 0;
    sum_encoded_frame_size_total_ = 0.0f;
    encoding_bitrate_total_ = 0.0f;
    perc_encoding_rate_mismatch_ = 0.0f;
    num_frames_to_hit_target_ = num_frames_to_hit_target;
    encoding_rate_within_target_ = false;
    sum_key_frame_size_mismatch_ = 0.0;
    num_key_frames_ = 0;
  }

  // For every encoded frame, update the rate control metrics.
  void UpdateRateControlMetrics(int frame_number) {
    RTC_CHECK_GE(frame_number, 0);
    int tl_idx = TemporalLayerIndexForFrame(frame_number);
    FrameType frame_type = processor_->EncodedFrameType(frame_number);
    float encoded_size_kbits =
        processor_->EncodedFrameSize(frame_number) * 8.0f / 1000.0f;

    // Update layer data.
    // Update rate mismatch relative to per-frame bandwidth for delta frames.
    if (frame_type == kVideoFrameDelta) {
      // TODO(marpan): Should we count dropped (zero size) frames in mismatch?
      sum_frame_size_mismatch_[tl_idx] +=
          fabs(encoded_size_kbits - per_frame_bandwidth_[tl_idx]) /
          per_frame_bandwidth_[tl_idx];
    } else {
      float target_size = (frame_number == 0) ? target_size_key_frame_initial_
                                              : target_size_key_frame_;
      sum_key_frame_size_mismatch_ +=
          fabs(encoded_size_kbits - target_size) / target_size;
      num_key_frames_ += 1;
    }
    sum_encoded_frame_size_[tl_idx] += encoded_size_kbits;
    // Encoding bit rate per temporal layer: from the start of the update/run
    // to the current frame.
    encoding_bitrate_[tl_idx] = sum_encoded_frame_size_[tl_idx] *
                                frame_rate_layer_[tl_idx] /
                                num_frames_per_update_[tl_idx];
    // Total encoding rate: from the start of the update/run to current frame.
    sum_encoded_frame_size_total_ += encoded_size_kbits;
    encoding_bitrate_total_ =
        sum_encoded_frame_size_total_ * frame_rate_ / num_frames_total_;
    perc_encoding_rate_mismatch_ =
        100 * fabs(encoding_bitrate_total_ - bit_rate_) / bit_rate_;
    if (perc_encoding_rate_mismatch_ < kPercTargetvsActualMismatch &&
        !encoding_rate_within_target_) {
      num_frames_to_hit_target_ = num_frames_total_;
      encoding_rate_within_target_ = true;
    }
  }

  // Verify expected behavior of rate control and print out data.
  void VerifyRateControlMetrics(int update_index,
                                const RateControlThresholds& rc_expected) {
    int num_dropped_frames = processor_->NumberDroppedFrames();
    int num_resize_actions = processor_->NumberSpatialResizes();
    printf(
        "For update #: %d,\n"
        " Target Bitrate: %d,\n"
        " Encoding bitrate: %f,\n"
        " Frame rate: %d \n",
        update_index, bit_rate_, encoding_bitrate_total_, frame_rate_);
    printf(
        " Number of frames to approach target rate: %d, \n"
        " Number of dropped frames: %d, \n"
        " Number of spatial resizes: %d, \n",
        num_frames_to_hit_target_, num_dropped_frames, num_resize_actions);
    EXPECT_LE(perc_encoding_rate_mismatch_,
              rc_expected.max_encoding_rate_mismatch);
    if (num_key_frames_ > 0) {
      int perc_key_frame_size_mismatch =
          100 * sum_key_frame_size_mismatch_ / num_key_frames_;
      printf(
          " Number of Key frames: %d \n"
          " Key frame rate mismatch: %d \n",
          num_key_frames_, perc_key_frame_size_mismatch);
      EXPECT_LE(perc_key_frame_size_mismatch,
                rc_expected.max_key_frame_size_mismatch);
    }
    printf("\n");
    printf("Rates statistics for Layer data \n");
    for (int i = 0; i < num_temporal_layers_; i++) {
      printf("Temporal layer #%d \n", i);
      int perc_frame_size_mismatch =
          100 * sum_frame_size_mismatch_[i] / num_frames_per_update_[i];
      int perc_encoding_rate_mismatch =
          100 * fabs(encoding_bitrate_[i] - bit_rate_layer_[i]) /
          bit_rate_layer_[i];
      printf(
          " Target Layer Bit rate: %f \n"
          " Layer frame rate: %f, \n"
          " Layer per frame bandwidth: %f, \n"
          " Layer Encoding bit rate: %f, \n"
          " Layer Percent frame size mismatch: %d,  \n"
          " Layer Percent encoding rate mismatch: %d, \n"
          " Number of frame processed per layer: %d \n",
          bit_rate_layer_[i], frame_rate_layer_[i], per_frame_bandwidth_[i],
          encoding_bitrate_[i], perc_frame_size_mismatch,
          perc_encoding_rate_mismatch, num_frames_per_update_[i]);
      EXPECT_LE(perc_frame_size_mismatch,
                rc_expected.max_delta_frame_size_mismatch);
      EXPECT_LE(perc_encoding_rate_mismatch,
                rc_expected.max_encoding_rate_mismatch);
    }
    printf("\n");
    EXPECT_LE(num_frames_to_hit_target_, rc_expected.max_time_hit_target);
    EXPECT_LE(num_dropped_frames, rc_expected.max_num_dropped_frames);
    if (rc_expected.num_spatial_resizes >= 0) {
      EXPECT_EQ(rc_expected.num_spatial_resizes, num_resize_actions);
    }
    if (rc_expected.num_key_frames >= 0) {
      EXPECT_EQ(rc_expected.num_key_frames, num_key_frames_);
    }
  }

  void VerifyQuality(const test::QualityMetricsResult& psnr_result,
                     const test::QualityMetricsResult& ssim_result,
                     const QualityThresholds& quality_thresholds) {
    EXPECT_GT(psnr_result.average, quality_thresholds.min_avg_psnr);
    EXPECT_GT(psnr_result.min, quality_thresholds.min_min_psnr);
    EXPECT_GT(ssim_result.average, quality_thresholds.min_avg_ssim);
    EXPECT_GT(ssim_result.min, quality_thresholds.min_min_ssim);
  }

  // Temporal layer index corresponding to frame number, for up to 3 layers.
  int TemporalLayerIndexForFrame(int frame_number) {
    int tl_idx = -1;
    switch (num_temporal_layers_) {
      case 1:
        tl_idx = 0;
        break;
      case 2:
        // temporal layer 0:  0     2     4 ...
        // temporal layer 1:     1     3
        tl_idx = (frame_number % 2 == 0) ? 0 : 1;
        break;
      case 3:
        // temporal layer 0:  0            4            8 ...
        // temporal layer 1:        2            6
        // temporal layer 2:     1      3     5      7
        if (frame_number % 4 == 0) {
          tl_idx = 0;
        } else if ((frame_number + 2) % 4 == 0) {
          tl_idx = 1;
        } else if ((frame_number + 1) % 2 == 0) {
          tl_idx = 2;
        }
        break;
      default:
        RTC_NOTREACHED();
        break;
    }
    return tl_idx;
  }

  // Set the bit rate and frame rate per temporal layer, for up to 3 layers.
  void SetTemporalLayerRates() {
    RTC_DCHECK_LE(num_temporal_layers_, kMaxNumTemporalLayers);
    for (int i = 0; i < num_temporal_layers_; i++) {
      float bit_rate_ratio =
          kVp8LayerRateAlloction[num_temporal_layers_ - 1][i];
      if (i > 0) {
        float bit_rate_delta_ratio =
            kVp8LayerRateAlloction[num_temporal_layers_ - 1][i] -
            kVp8LayerRateAlloction[num_temporal_layers_ - 1][i - 1];
        bit_rate_layer_[i] = bit_rate_ * bit_rate_delta_ratio;
      } else {
        bit_rate_layer_[i] = bit_rate_ * bit_rate_ratio;
      }
      frame_rate_layer_[i] =
          frame_rate_ / static_cast<float>(1 << (num_temporal_layers_ - 1));
    }
    if (num_temporal_layers_ == 3) {
      frame_rate_layer_[2] = frame_rate_ / 2.0f;
    }
  }

  // Processes all frames in the clip and verifies the result.
  // TODO(brandtr): Change the second last argument to be a
  // const std::vector<RateControlThresholds>&, so we can ensure that the user
  // does not expect us to do mid-clip rate updates when we are not able to,
  // e.g., when we are operating in batch mode.
  void ProcessFramesAndVerify(QualityThresholds quality_thresholds,
                              RateProfile rate_profile,
                              CodecParams process,
                              RateControlThresholds* rc_thresholds,
                              const VisualizationParams* visualization_params) {
    // Codec/config settings.
    start_bitrate_ = rate_profile.target_bit_rate[0];
    start_frame_rate_ = rate_profile.input_frame_rate[0];
    packet_loss_probability_ = process.packet_loss_probability;
    num_temporal_layers_ = process.num_temporal_layers;
    SetUpCodecConfig(process, visualization_params);
    // Update the temporal layers and the codec with the initial rates.
    bit_rate_ = rate_profile.target_bit_rate[0];
    frame_rate_ = rate_profile.input_frame_rate[0];
    SetTemporalLayerRates();
    // Set the initial target size for key frame.
    target_size_key_frame_initial_ =
        0.5 * kInitialBufferSize * bit_rate_layer_[0];
    processor_->SetRates(bit_rate_, frame_rate_);

    // Process each frame, up to |num_frames|.
    int frame_number = 0;
    int update_index = 0;
    int num_frames = rate_profile.num_frames;
    ResetRateControlMetrics(
        rate_profile.frame_index_rate_update[update_index + 1]);

    if (process.batch_mode) {
      // In batch mode, we calculate the metrics for all frames after all frames
      // have been sent for encoding.

      // TODO(brandtr): Refactor "frame number accounting" so we don't have to
      // call ProcessFrame num_frames+1 times here.
      for (frame_number = 0; frame_number <= num_frames; ++frame_number) {
        EXPECT_TRUE(processor_->ProcessFrame(frame_number));
      }

      for (frame_number = 0; frame_number < num_frames; ++frame_number) {
        ++num_frames_per_update_[TemporalLayerIndexForFrame(frame_number)];
        ++num_frames_total_;
        UpdateRateControlMetrics(frame_number);
      }
    } else {
      // In online mode, we calculate the metrics for a given frame right after
      // it has been sent for encoding.

      if (process.hw_codec) {
        LOG(LS_WARNING) << "HW codecs should mostly be run in batch mode, "
                           "since they may be pipelining.";
      }

      while (frame_number < num_frames) {
        EXPECT_TRUE(processor_->ProcessFrame(frame_number));

        ++num_frames_per_update_[TemporalLayerIndexForFrame(frame_number)];
        ++num_frames_total_;
        UpdateRateControlMetrics(frame_number);

        ++frame_number;

        // If we hit another/next update, verify stats for current state and
        // update layers and codec with new rates.
        if (frame_number ==
            rate_profile.frame_index_rate_update[update_index + 1]) {
          VerifyRateControlMetrics(update_index, rc_thresholds[update_index]);

          // Update layer rates and the codec with new rates.
          ++update_index;
          bit_rate_ = rate_profile.target_bit_rate[update_index];
          frame_rate_ = rate_profile.input_frame_rate[update_index];
          SetTemporalLayerRates();
          ResetRateControlMetrics(
              rate_profile.frame_index_rate_update[update_index + 1]);
          processor_->SetRates(bit_rate_, frame_rate_);
        }
      }
      // TODO(brandtr): Refactor "frame number accounting" so we don't have to
      // call ProcessFrame one extra time here.
      EXPECT_TRUE(processor_->ProcessFrame(frame_number));
    }

    // Verify rate control metrics for all frames (if in batch mode), or for all
    // frames since the last rate update (if not in batch mode).
    VerifyRateControlMetrics(update_index, rc_thresholds[update_index]);
    EXPECT_EQ(num_frames, frame_number);
    EXPECT_EQ(num_frames + 1, static_cast<int>(stats_.stats_.size()));

    // Release encoder and decoder to make sure they have finished processing.
    EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, encoder_->Release());
    EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, decoder_->Release());

    // Close the analysis files before we use them for SSIM/PSNR calculations.
    analysis_frame_reader_->Close();
    analysis_frame_writer_->Close();

    // Close visualization files.
    if (source_frame_writer_) {
      source_frame_writer_->Close();
    }
    if (encoded_frame_writer_) {
      EXPECT_TRUE(encoded_frame_writer_->Close());
    }
    if (decoded_frame_writer_) {
      decoded_frame_writer_->Close();
    }

    // TODO(marpan): Should compute these quality metrics per SetRates update.
    test::QualityMetricsResult psnr_result, ssim_result;
    EXPECT_EQ(0, test::I420MetricsFromFiles(config_.input_filename.c_str(),
                                            config_.output_filename.c_str(),
                                            config_.codec_settings->width,
                                            config_.codec_settings->height,
                                            &psnr_result, &ssim_result));
    printf("PSNR avg: %f, min: %f\nSSIM avg: %f, min: %f\n",
           psnr_result.average, psnr_result.min, ssim_result.average,
           ssim_result.min);
    VerifyQuality(psnr_result, ssim_result, quality_thresholds);
    stats_.PrintSummary();

    // Remove analysis file.
    if (remove(config_.output_filename.c_str()) < 0) {
      fprintf(stderr, "Failed to remove temporary file!\n");
    }
  }

  static void SetCodecParams(CodecParams* process_settings,
                             VideoCodecType codec_type,
                             bool hw_codec,
                             bool use_single_core,
                             float packet_loss_probability,
                             int key_frame_interval,
                             int num_temporal_layers,
                             bool error_concealment_on,
                             bool denoising_on,
                             bool frame_dropper_on,
                             bool spatial_resize_on,
                             int width,
                             int height,
                             const std::string& filename,
                             bool verbose_logging,
                             bool batch_mode) {
    process_settings->codec_type = codec_type;
    process_settings->hw_codec = hw_codec;
    process_settings->use_single_core = use_single_core;
    process_settings->packet_loss_probability = packet_loss_probability;
    process_settings->key_frame_interval = key_frame_interval;
    process_settings->num_temporal_layers = num_temporal_layers,
    process_settings->error_concealment_on = error_concealment_on;
    process_settings->denoising_on = denoising_on;
    process_settings->frame_dropper_on = frame_dropper_on;
    process_settings->spatial_resize_on = spatial_resize_on;
    process_settings->width = width;
    process_settings->height = height;
    process_settings->filename = filename;
    process_settings->verbose_logging = verbose_logging;
    process_settings->batch_mode = batch_mode;
  }

  static void SetCodecParams(CodecParams* process_settings,
                             VideoCodecType codec_type,
                             bool hw_codec,
                             bool use_single_core,
                             float packet_loss_probability,
                             int key_frame_interval,
                             int num_temporal_layers,
                             bool error_concealment_on,
                             bool denoising_on,
                             bool frame_dropper_on,
                             bool spatial_resize_on) {
    SetCodecParams(process_settings, codec_type, hw_codec, use_single_core,
                   packet_loss_probability, key_frame_interval,
                   num_temporal_layers, error_concealment_on, denoising_on,
                   frame_dropper_on, spatial_resize_on, kCifWidth, kCifHeight,
                   kFilenameForemanCif, false /* verbose_logging */,
                   false /* batch_mode */);
  }

  static void SetQualityThresholds(QualityThresholds* quality_thresholds,
                                   double min_avg_psnr,
                                   double min_min_psnr,
                                   double min_avg_ssim,
                                   double min_min_ssim) {
    quality_thresholds->min_avg_psnr = min_avg_psnr;
    quality_thresholds->min_min_psnr = min_min_psnr;
    quality_thresholds->min_avg_ssim = min_avg_ssim;
    quality_thresholds->min_min_ssim = min_min_ssim;
  }

  static void SetRateProfile(RateProfile* rate_profile,
                             int update_index,
                             int bit_rate,
                             int frame_rate,
                             int frame_index_rate_update) {
    rate_profile->target_bit_rate[update_index] = bit_rate;
    rate_profile->input_frame_rate[update_index] = frame_rate;
    rate_profile->frame_index_rate_update[update_index] =
        frame_index_rate_update;
  }

  static void SetRateControlThresholds(RateControlThresholds* rc_thresholds,
                                       int update_index,
                                       int max_num_dropped_frames,
                                       int max_key_frame_size_mismatch,
                                       int max_delta_frame_size_mismatch,
                                       int max_encoding_rate_mismatch,
                                       int max_time_hit_target,
                                       int num_spatial_resizes,
                                       int num_key_frames) {
    rc_thresholds[update_index].max_num_dropped_frames = max_num_dropped_frames;
    rc_thresholds[update_index].max_key_frame_size_mismatch =
        max_key_frame_size_mismatch;
    rc_thresholds[update_index].max_delta_frame_size_mismatch =
        max_delta_frame_size_mismatch;
    rc_thresholds[update_index].max_encoding_rate_mismatch =
        max_encoding_rate_mismatch;
    rc_thresholds[update_index].max_time_hit_target = max_time_hit_target;
    rc_thresholds[update_index].num_spatial_resizes = num_spatial_resizes;
    rc_thresholds[update_index].num_key_frames = num_key_frames;
  }

  // Codecs.
  std::unique_ptr<VideoEncoder> encoder_;
  std::unique_ptr<cricket::WebRtcVideoEncoderFactory> external_encoder_factory_;
  std::unique_ptr<VideoDecoder> decoder_;
  std::unique_ptr<cricket::WebRtcVideoDecoderFactory> external_decoder_factory_;
  VideoCodec codec_settings_;

  // Helper objects.
  std::unique_ptr<test::FrameReader> analysis_frame_reader_;
  std::unique_ptr<test::FrameWriter> analysis_frame_writer_;
  test::PacketReader packet_reader_;
  std::unique_ptr<test::PacketManipulator> packet_manipulator_;
  test::Stats stats_;
  test::TestConfig config_;
  // Must be destroyed before |encoder_| and |decoder_|.
  std::unique_ptr<test::VideoProcessor> processor_;

  // Visualization objects.
  std::unique_ptr<test::FrameWriter> source_frame_writer_;
  std::unique_ptr<IvfFileWriter> encoded_frame_writer_;
  std::unique_ptr<test::FrameWriter> decoded_frame_writer_;

  // Quantities defined/updated for every encoder rate update.
  int num_frames_per_update_[kMaxNumTemporalLayers];
  float sum_frame_size_mismatch_[kMaxNumTemporalLayers];
  float sum_encoded_frame_size_[kMaxNumTemporalLayers];
  float encoding_bitrate_[kMaxNumTemporalLayers];
  float per_frame_bandwidth_[kMaxNumTemporalLayers];
  float bit_rate_layer_[kMaxNumTemporalLayers];
  float frame_rate_layer_[kMaxNumTemporalLayers];
  int num_frames_total_;
  float sum_encoded_frame_size_total_;
  float encoding_bitrate_total_;
  float perc_encoding_rate_mismatch_;
  int num_frames_to_hit_target_;
  bool encoding_rate_within_target_;
  int bit_rate_;
  int frame_rate_;
  float target_size_key_frame_initial_;
  float target_size_key_frame_;
  float sum_key_frame_size_mismatch_;
  int num_key_frames_;
  float start_bitrate_;
  int start_frame_rate_;

  // Codec and network settings.
  float packet_loss_probability_;
  int num_temporal_layers_;
};

}  // namespace test
}  // namespace webrtc

#endif  // WEBRTC_MODULES_VIDEO_CODING_CODECS_TEST_VIDEOPROCESSOR_INTEGRATIONTEST_H_


text:
<?php
namespace Nodes\Services\Twilio\Exceptions;

use Nodes\Exceptions\Exception as NodesException;

/**
 * Class Exception
 *
 * @package Nodes\Services\Twilio\Exception
 */
class Exception extends NodesException
{
    /**
     * Exception constructor
     *
     * @author Morten Rugaard <moru@nodes.dk>
     *
     * @access public
     * @param  object $data
     */
    public function __construct($data)
    {
        // Error message
        $message = sprintf('Error #%d. Reason: %s', $data->code, $data->message);

        // Add "more info" if available
        if (!empty($data->more_info)) {
            $message .= sprintf(' More info: %s', $data->more_info);
        }

        parent::__construct($message, $data->code, [], true);
    }
}


text:
<ion-header>
  <ion-navbar>
    <ion-title>{{ currentAchievement.name || achievementName }}</ion-title>
    <button (click)="closeModal()" class="close" menuClose="right">×</button>
  </ion-navbar>
</ion-header>
<ion-content class="ahievements-popup">
  <ion-grid>
    <ion-row>
       <ion-col>

{{ currentAchievement.description || description }}

      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>


text:
    <hgroup>

Register

    </hgroup>

    <form role="form" data-ng-submit="submit()" novalidate>

                First Name

            <input data-ng-model="model.firstname" type="text" class="form-control" />

                Last Name

            <input data-ng-model="model.lastname" type="text" class="form-control" />

                Email

            <input data-ng-model="model.emailaddress" type="text" class="form-control" />

                Password

            <input data-ng-model="model.password" type="password" class="form-control" />

                Confirm Password

            <input data-ng-model="model.confirmpassword" type="password" class="form-control" />

            <input type="submit" value="register" class="btn btn-lrg" />

    </form>


text:
import Vue from 'vue'
import { shallowMount, createLocalVue } from '@vue/test-utils'
import { BoxIcon, TagIcon } from 'vue-feather-icons'
import Button from '@/components/Button'
import PlantFooter from '@/app/plant/components/PlantFooter'

describe('app/plant/PlantFooter.vue', async () => {
  const localVue = createLocalVue()
  const options = {
    localVue,
    stubs: {
      'v-button': Button,
      'feather-box': BoxIcon,
      'feather-tag': TagIcon
    }
  }

  it('is a Vue component', () => {
    const wrapper = shallowMount(PlantFooter, options)
    expect(wrapper.isVueInstance()).toEqual(true)
  })

  it('has correct default props data', () => {
    const wrapper = shallowMount(PlantFooter, options)
    expect(wrapper.props().noModules).toEqual(true)
    expect(wrapper.props().showTagButton).toEqual(false)
  })

  it('toggles a message if noModules prop is changed', async () => {
    const wrapper = shallowMount(PlantFooter, options)
    expect(wrapper.find('p').exists()).toBe(true)
    wrapper.setProps({ noModules: false })
    await Vue.nextTick()
    expect(wrapper.find('p').exists()).toBe(false)
  })

  it('shows the tag button if prop is set', async () => {
    const wrapper = shallowMount(PlantFooter, options)
    let TagButton = wrapper.find('v-button.footer-tags')

    expect(TagButton.exists()).toBe(false)
    wrapper.setProps({ showTagButton: true })
    await Vue.nextTick()

    TagButton = wrapper.find('.footer-tags')
    expect(TagButton.exists()).toBe(true)
    expect(TagButton.is(Button)).toBe(true)
  })

  it('emits event when tag button is tapped', () => {
    const wrapper = shallowMount(PlantFooter, { ...options, propsData: { showTagButton: true } })
    const TagButton = wrapper.find('.footer-tags')
    expect(TagButton.exists()).toBe(true)
    TagButton.trigger('click')
    expect(wrapper.emitted('show-tags')).toBeTruthy()
  })

  it('emits event when modules button is tapped', () => {
    const wrapper = shallowMount(PlantFooter, options)
    const ModulesButton = wrapper.find('.footer-modules')
    expect(ModulesButton.exists()).toBe(true)
    ModulesButton.trigger('click')
    expect(wrapper.emitted('manage-modules')).toBeTruthy()
  })
})


text:
package com.dscleaver.sbt.quickfix

import sbt._
import sbt.TestResult.Value
import sbt.testing.Status._
import sbt.testing.Event

class QuickFixTestListener(output: File, srcFiles: => Seq[File], vimExec: String, enableServer: Boolean) extends TestReportListener {
  import QuickFixLogger._
  import VimInteraction._

  type TFE = Exception {
    def failedCodeFileName: Option[String]
    def failedCodeLineNumber: Option[Int]
  }

  IO.delete(output)
  IO.touch(List(output))

  def startGroup(name: String): Unit = {}

  def testEvent(event: TestEvent): Unit = {
    writeFailure(event)
    if (enableServer && event.detail.exists(e => e.status == Failure)) {
      call(vimExec, "<esc>:cfile %s<cr>".format(output.toString))
    }
  }

  def endGroup(name: String, t: Throwable): Unit = {}

  def endGroup(name: String, v: Value): Unit = {}

  def writeFailure(event: TestEvent): Unit =
    for {
      detail <- event.detail
      if writeable(detail)
      (file, line) <- find(detail.throwable.get)
    } append(output, "error", file, line, detail.throwable.get.getMessage)

  def writeable(detail: Event): Boolean =
    detail.status == Failure && detail.throwable.isDefined

  def find(error: Throwable): Option[(File, Int)] = error match {
    case e: { def failedCodeStackDepth: Int } =>
      try {
        val stackTrace = error.getStackTrace()(e.failedCodeStackDepth)
        for {
          file <- findSource(stackTrace.getFileName)
        } yield (file, stackTrace.getLineNumber)
      } catch {
        case _ =>
          findInStackTrace(error.getStackTrace)
      }
  }

  def findInStackTrace(trace: Array[StackTraceElement]): Option[(File, Int)] =
    { for {
      elem <- trace
      file <- findSource(elem.getFileName)
    } yield (file, elem.getLineNumber) }.headOption

  def findSource(name: String): Option[File] =
    srcFiles find { file => file.getName endsWith name }
}

object QuickFixTestListener {
  def apply(output: File, srcFiles: Seq[File], vimExec: String, enableServer: Boolean): TestReportListener =
    new QuickFixTestListener(output, srcFiles, vimExec, enableServer)
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import * as R from 'ramda';
import { Observable } from 'rxjs/Observable';
import Helmet from 'react-helmet';
import TabItem from 'mcs-lite-ui/lib/TabItem';
import A from 'mcs-lite-ui/lib/A';
import isJSONValidator from 'validator/lib/isJSON';
import DashboardTitle from '../../components/DashboardTitle';
import DashboardDesc from '../../components/DashboardDesc';
import DialogConfirm from '../../components/DialogConfirm';
import {
  componentFromStream,
  createEventHandler,
} from '../../utils/recomposeHelper';
import {
  StyledButton,
  TabWrapper,
  StyledLoadableCodeMirror,
  Message,
} from './styled-components';

const TABS = ['db', 'oauth', 'rest', 'wot'];
export const DEFAULT_TAB_VALUE = 'db';
const OPTIONS = { mode: 'javascript', lineNumbers: true };

const System = componentFromStream(props$ => {
  const {
    handler: onTabItemClick,
    stream: onTabItemClick$,
  } = createEventHandler();
  const {
    handler: onCodeMirrorChange,
    stream: onCodeMirrorChange$,
  } = createEventHandler();
  const { handler: onSaveClick, stream: onSaveClick$ } = createEventHandler();
  const { handler: onResetClick, stream: onResetClick$ } = createEventHandler();
  const { handler: onCancel, stream: onCancel$ } = createEventHandler();
  const { handler: onSubmit, stream: onSubmit$ } = createEventHandler();

  const tabValue$ = onTabItemClick$
    .map(value => value)
    .startWith(DEFAULT_TAB_VALUE)
    .distinctUntilChanged();

  const code$ = tabValue$
    .combineLatest(props$, (tabValue, { system }) => system[tabValue])
    .startWith('');

  const isJSON$ = code$.map(R.anyPass([R.isEmpty, isJSONValidator]));

  const isDialogShow$ = Observable.merge(
    onResetClick$.mapTo(true),
    onCancel$.mapTo(false),
    onSubmit$.mapTo(false),
  ).startWith(false);

  // Remind: There are four fetch Side-effects below.
  tabValue$
    .combineLatest(props$, (tabValue, { fetchSystemByType }) =>
      fetchSystemByType.bind(null, tabValue),
    )
    .subscribe(R.call);
  onCodeMirrorChange$
    .withLatestFrom(tabValue$, props$, (value, tabValue, { setSystemByType }) =>
      setSystemByType.bind(null, { data: value, type: tabValue }),
    )
    .subscribe(R.call);
  onSaveClick$
    .withLatestFrom(
      tabValue$,
      props$,
      (e, tabValue, { uploadSystemByType, getMessages: t }) =>
        uploadSystemByType.bind(null, tabValue, t('save.success')),
    )
    .subscribe(R.call);
  onSubmit$
    .withLatestFrom(props$, (e, { postReset, getMessages: t }) =>
      postReset.bind(null, t('reset.success')),
    )
    .subscribe(R.call);

  const onTabItemClickValue = (e, value) => onTabItemClick(value);

  return props$.combineLatest(
    tabValue$,
    code$,
    isJSON$,
    isDialogShow$,
    ({ getMessages: t }, tabValue, code, isJSON, isDialogShow) => (

        <Helmet>
          <title>{t('systemManagement')}</title>
        </Helmet>
        <DialogConfirm
          show={isDialogShow}
          onCancel={onCancel}
          onSubmit={onSubmit}
        >
          {t('reset.confirm')}
        </DialogConfirm>

        <DashboardTitle title={t('systemManagement')}>
          {t('reset')}
        </DashboardTitle>
        <DashboardDesc>{t('description')}</DashboardDesc>

        <TabWrapper>
          {TABS.map(value => (
            <TabItem
              key={value}
              value={value}
              onClick={onTabItemClickValue}
              active={tabValue === value}
            >
              {value}.json
            </TabItem>
          ))}
        </TabWrapper>

    ),
  );
});

System.displayName = 'System';
System.propTypes = {
  // Redux State
  system: PropTypes.shape({
    db: PropTypes.string.isRequired,
    oauth: PropTypes.string.isRequired,
    rest: PropTypes.string.isRequired,
    wot: PropTypes.string.isRequired,
  }).isRequired,

  // Redux Action
  fetchSystemByType: PropTypes.func.isRequired,
  uploadSystemByType: PropTypes.func.isRequired,
  postReset: PropTypes.func.isRequired,
  setSystemByType: PropTypes.func.isRequired,

  // React-intl I18n
  getMessages: PropTypes.func.isRequired,
};

export default System;


text:
<?php

/**
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 *
 * @author Leo Moll <leo@yeasoft.com>
 * @author Florian Anderiasch <fa@art-core.org>
 * @author Robin Kluth <commi1993@gmail.com>
 * @author Arne Pelka <mail@arnepelka.de>
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author Dirk Einecke <dirk@dirkeinecke.de>
 * @author Blitzi94@gmx.de
 * @author Robert Bogenschneider <robog@GMX.de>
 * @author Robert Bogenschneider <robog@gmx.de>
 * @author Niels Lange <niels@boldencursief.nl>
 * @author Christian Wichmann <nospam@zone0.de>
 * @author Paul Lachewsky <kaeptn.haddock@gmail.com>
 * @author Pierre Corell <info@joomla-praxis.de>
 */
$lang['name']                  = 'Popularitäts-Feedback (Eventuell längere Ladezeit)';
$lang['submit']                = 'Daten senden';
$lang['autosubmit']            = 'Daten einmal im Monat automatisch senden';
$lang['submissionFailed']      = 'Die Daten konnten aufgrund des folgenden Fehlers nicht gesendet werden: ';
$lang['submitDirectly']        = 'Sie können die Daten durch Betätigung des Buttons manuell versenden.';
$lang['autosubmitError']       = 'Beim letzten automatischen Versuch die Daten zu senden, ist folgender Fehler aufgetreten: ';
$lang['lastSent']              = 'Die Daten wurden gesendet';


text:
package com.sequenceiq.it.cloudbreak.action.v4.environment;

import com.sequenceiq.it.cloudbreak.EnvironmentClient;
import com.sequenceiq.it.cloudbreak.action.Action;
import com.sequenceiq.it.cloudbreak.context.TestContext;
import com.sequenceiq.it.cloudbreak.dto.environment.EnvironmentTestDto;
import com.sequenceiq.it.cloudbreak.log.Log;

public class EnvironmentGetByCrnAction implements Action<EnvironmentTestDto, EnvironmentClient> {

    @Override
    public EnvironmentTestDto action(TestContext testContext, EnvironmentTestDto testDto, EnvironmentClient environmentClient) throws Exception {
        testDto.setResponse(
                environmentClient.getDefaultClient()
                        .environmentV1Endpoint()
                        .getByCrn(testDto.getCrn()));
        Log.whenJson("Environment get response: ", testDto.getResponse());
        return testDto;
    }
}


text:
import clockFormatter from './clock-formatter';
import getTotalPauseTime from './get-total-pause-time';
import _map from 'lodash/map';

export default function (options) {

    const TICK_TIME = (options || {}).tickTime || 300;

    var globalCountdown,
        globalLocalTime,
        pauses = [], isTimerRunning, stopped;

    var onTickCallbacks = [];

    var self = this;
    this.applyCountdown = applyCountdown;
    this.onTick = onTick;
    this.updateCountDown = updateCountDown;
    this.pause = pause;
    this.resume = resume;
    this.pauses = pauses;
    this.isPaused = undefined;

    this.stop = () => {
      stopped = true;
    };

    this.destroy = () => {

    };

    function resume(resumeDate){
        //pauses[pauses.length -1].resumeTime = resumeDate.getTime();
        self.isPaused = false;
        applyTick();
    }

    function pause(pauseDate){
        var secondsBetweenInitialTimeAndPause = Math.floor( (pauseDate.getTime() - globalLocalTime )/1000 );
        var differenceInSeconds = globalCountdown-secondsBetweenInitialTimeAndPause;
        differenceInSeconds += Math.floor(getTotalPauseTime(pauses)/1000);
        self.isPaused = true;
        triggerOnTick(clockFormatter(differenceInSeconds), differenceInSeconds, globalCountdown);
        pauses.push({
            pauseTime:pauseDate.getTime()
        });
    }

    function updateCountDown(countDown, initialTime){
        //TODO not used?
        globalCountdown = countDown;
        globalLocalTime = initialTime;
    }

    function convertPausesFromDateToTime(pauses){
        return _map(pauses, function(pauseItem){
            return {
                pauseTime:(new Date(pauseItem.pauseTime)).getTime(),
                resumeTime:(new Date(pauseItem.resumeTime)).getTime(),
            }
        });
    }

    function applyCountdown(countdown, initialDate, serverPauses) {
        pauses = convertPausesFromDateToTime(serverPauses) || [];
        self.isPaused = false;
        globalCountdown = countdown;
        globalLocalTime = initialDate.getTime() || (new Date()).getTime();
        if(pauses.length && !pauses[pauses.length-1].resumeTime){
          self.isPaused = true;
            var pauseTime = pauses[pauses.length-1].pauseTime;
            var secondsBetweenInitialTimeAndPause = Math.floor( (pauseTime - globalLocalTime )/1000 );
            var differenceInSeconds = globalCountdown-secondsBetweenInitialTimeAndPause;
            differenceInSeconds += Math.floor(getTotalPauseTime(pauses)/1000);
            triggerOnTick(clockFormatter(differenceInSeconds), differenceInSeconds, globalCountdown);
        }
        if (!isTimerRunning && !self.isPaused) {
            //TODO can do multiple timers? review
            setTimeout(function () {
                applyTick();
            }, TICK_TIME);
        }
        if(self.isPaused && pauses[pauses.length-1].resumeTime){
          resume();
        }
    }

    function onTick(callback) {
        onTickCallbacks.push(callback);

        return function () {
            //TODO return an unregister function, remove callback
        };
    }

    function triggerOnTick(timeString, differenceInSeconds, globalCountdown) {
        onTickCallbacks.forEach(function (onTickCallback) {
            onTickCallback(timeString, differenceInSeconds, globalCountdown);
        });
    }

    function applyTick() {
        if(!self.isPaused && !stopped){
            var now = new Date();

            var differenceInSeconds = Math.floor(globalCountdown - (now.getTime() - globalLocalTime) / 1000);
            differenceInSeconds += Math.floor(getTotalPauseTime(pauses)/1000);

            triggerOnTick(clockFormatter(differenceInSeconds), differenceInSeconds, globalCountdown);

            setTimeout(function () {
                applyTick();
            }, TICK_TIME);
        }
        if(stopped){
          isTimerRunning = false;
          stopped = false;
        }
    }
}