text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.ComponentModel;

namespace Oranikle.DesignBase.UI.Docking
{
    partial class DockPanel
    {
        private sealed class DockDragHandler : DragHandler
        {
            private class DockIndicator : DragForm
            {
                #region IHitTest
                private interface IHitTest
                {
                    DockStyle HitTest(Point pt);
                    DockStyle Status { get;	set;	}
                }
                #endregion

                #region PanelIndicator
                private class PanelIndicator : PictureBox, IHitTest
                {
                    private static Image _imagePanelLeft = Resources.DockIndicator_PanelLeft;
                    private static Image _imagePanelRight = Resources.DockIndicator_PanelRight;
                    private static Image _imagePanelTop = Resources.DockIndicator_PanelTop;
                    private static Image _imagePanelBottom = Resources.DockIndicator_PanelBottom;
                    private static Image _imagePanelFill = Resources.DockIndicator_PanelFill;
                    private static Image _imagePanelLeftActive = Resources.DockIndicator_PanelLeft_Active;
                    private static Image _imagePanelRightActive = Resources.DockIndicator_PanelRight_Active;
                    private static Image _imagePanelTopActive = Resources.DockIndicator_PanelTop_Active;
                    private static Image _imagePanelBottomActive = Resources.DockIndicator_PanelBottom_Active;
                    private static Image _imagePanelFillActive = Resources.DockIndicator_PanelFill_Active;

                    public PanelIndicator(DockStyle dockStyle)
                    {
                        m_dockStyle = dockStyle;
                        SizeMode = PictureBoxSizeMode.AutoSize;
                        Image = ImageInactive;
                    }

                    private DockStyle m_dockStyle;
                    private DockStyle DockStyle
                    {
                        get { return m_dockStyle; }
                    }

                    private DockStyle m_status;
                    public DockStyle Status
                    {
                        get { return m_status; }
                        set
                        {
                            if (value != DockStyle && value != DockStyle.None)
                                throw new InvalidEnumArgumentException();

                            if (m_status == value)
                                return;

                            m_status = value;
                            IsActivated = (m_status != DockStyle.None);
                        }
                    }

                    private Image ImageInactive
                    {
                        get
                        {
                            if (DockStyle == DockStyle.Left)
                                return _imagePanelLeft;
                            else if (DockStyle == DockStyle.Right)
                                return _imagePanelRight;
                            else if (DockStyle == DockStyle.Top)
                                return _imagePanelTop;
                            else if (DockStyle == DockStyle.Bottom)
                                return _imagePanelBottom;
                            else if (DockStyle == DockStyle.Fill)
                                return _imagePanelFill;
                            else
                                return null;
                        }
                    }

                    private Image ImageActive
                    {
                        get
                        {
                            if (DockStyle == DockStyle.Left)
                                return _imagePanelLeftActive;
                            else if (DockStyle == DockStyle.Right)
                                return _imagePanelRightActive;
                            else if (DockStyle == DockStyle.Top)
                                return _imagePanelTopActive;
                            else if (DockStyle == DockStyle.Bottom)
                                return _imagePanelBottomActive;
                            else if (DockStyle == DockStyle.Fill)
                                return _imagePanelFillActive;
                            else
                                return null;
                        }
                    }

                    private bool m_isActivated = false;
                    private bool IsActivated
                    {
                        get { return m_isActivated; }
                        set
                        {
                            m_isActivated = value;
                            Image = IsActivated ? ImageActive : ImageInactive;
                        }
                    }

                    public DockStyle HitTest(Point pt)
                    {
                        return this.Visible && ClientRectangle.Contains(PointToClient(pt)) ? DockStyle : DockStyle.None;
                    }
                }
                #endregion PanelIndicator

                #region PaneIndicator
                private class PaneIndicator : PictureBox, IHitTest
                {
                    private struct HotSpotIndex
                    {
                        public HotSpotIndex(int x, int y, DockStyle dockStyle)
                        {
                            m_x = x;
                            m_y = y;
                            m_dockStyle = dockStyle;
                        }

                        private int m_x;
                        public int X
                        {
                            get { return m_x; }
                        }

                        private int m_y;
                        public int Y
                        {
                            get { return m_y; }
                        }

                        private DockStyle m_dockStyle;
                        public DockStyle DockStyle
                        {
                            get { return m_dockStyle; }
                        }
                    }

                    private static Bitmap _bitmapPaneDiamond = Resources.DockIndicator_PaneDiamond;
                    private static Bitmap _bitmapPaneDiamondLeft = Resources.DockIndicator_PaneDiamond_Left;
                    private static Bitmap _bitmapPaneDiamondRight = Resources.DockIndicator_PaneDiamond_Right;
                    private static Bitmap _bitmapPaneDiamondTop = Resources.DockIndicator_PaneDiamond_Top;
                    private static Bitmap _bitmapPaneDiamondBottom = Resources.DockIndicator_PaneDiamond_Bottom;
                    private static Bitmap _bitmapPaneDiamondFill = Resources.Dockindicator_PaneDiamond_Fill;
                    private static Bitmap _bitmapPaneDiamondHotSpot = Resources.DockIndicator_PaneDiamond_Hotspot;
                    private static Bitmap _bitmapPaneDiamondHotSpotIndex = Resources.DockIndicator_PaneDiamond_HotspotIndex;
                    private static HotSpotIndex[] _hotSpots = new HotSpotIndex[]
			{
				new HotSpotIndex(1, 0, DockStyle.Top),
				new HotSpotIndex(0, 1, DockStyle.Left),
				new HotSpotIndex(1, 1, DockStyle.Fill),
				new HotSpotIndex(2, 1, DockStyle.Right),
				new HotSpotIndex(1, 2, DockStyle.Bottom)
			};
                    private static GraphicsPath _displayingGraphicsPath = DrawHelper.CalculateGraphicsPathFromBitmap(_bitmapPaneDiamond);

                    public PaneIndicator()
                    {
                        SizeMode = PictureBoxSizeMode.AutoSize;
                        Image = _bitmapPaneDiamond;
                        Region = new Region(DisplayingGraphicsPath);
                    }

                    public static GraphicsPath DisplayingGraphicsPath
                    {
                        get { return _displayingGraphicsPath; }
                    }

                    public DockStyle HitTest(Point pt)
                    {
                        if (!Visible)
                            return DockStyle.None;

                        pt = PointToClient(pt);
                        if (!ClientRectangle.Contains(pt))
                            return DockStyle.None;

                        for (int i = _hotSpots.GetLowerBound(0); i <= _hotSpots.GetUpperBound(0); i++)
                        {
                            if (_bitmapPaneDiamondHotSpot.GetPixel(pt.X, pt.Y) == _bitmapPaneDiamondHotSpotIndex.GetPixel(_hotSpots[i].X, _hotSpots[i].Y))
                                return _hotSpots[i].DockStyle;
                        }

                        return DockStyle.None;
                    }

                    private DockStyle m_status = DockStyle.None;
                    public DockStyle Status
                    {
                        get { return m_status; }
                        set
                        {
                            m_status = value;
                            if (m_status == DockStyle.None)
                                Image = _bitmapPaneDiamond;
                            else if (m_status == DockStyle.Left)
                                Image = _bitmapPaneDiamondLeft;
                            else if (m_status == DockStyle.Right)
                                Image = _bitmapPaneDiamondRight;
                            else if (m_status == DockStyle.Top)
                                Image = _bitmapPaneDiamondTop;
                            else if (m_status == DockStyle.Bottom)
                                Image = _bitmapPaneDiamondBottom;
                            else if (m_status == DockStyle.Fill)
                                Image = _bitmapPaneDiamondFill;
                        }
                    }
                }
                #endregion PaneIndicator

                #region consts
                private int _PanelIndicatorMargin = 10;
                #endregion

                private DockDragHandler m_dragHandler;

                public DockIndicator(DockDragHandler dragHandler)
                {
                    m_dragHandler = dragHandler;
                    Controls.AddRange(new Control[] {
			            PaneDiamond,
			            PanelLeft,
			            PanelRight,
			            PanelTop,
			            PanelBottom,
			            PanelFill
			            });
                    Region = new Region(Rectangle.Empty);
                }

                private PaneIndicator m_paneDiamond = null;
                private PaneIndicator PaneDiamond
                {
                    get
                    {
                        if (m_paneDiamond == null)
                            m_paneDiamond = new PaneIndicator();

                        return m_paneDiamond;
                    }
                }

                private PanelIndicator m_panelLeft = null;
                private PanelIndicator PanelLeft
                {
                    get
                    {
                        if (m_panelLeft == null)
                            m_panelLeft = new PanelIndicator(DockStyle.Left);

                        return m_panelLeft;
                    }
                }

                private PanelIndicator m_panelRight = null;
                private PanelIndicator PanelRight
                {
                    get
                    {
                        if (m_panelRight == null)
                            m_panelRight = new PanelIndicator(DockStyle.Right);

                        return m_panelRight;
                    }
                }

                private PanelIndicator m_panelTop = null;
                private PanelIndicator PanelTop
                {
                    get
                    {
                        if (m_panelTop == null)
                            m_panelTop = new PanelIndicator(DockStyle.Top);

                        return m_panelTop;
                    }
                }

                private PanelIndicator m_panelBottom = null;
                private PanelIndicator PanelBottom
                {
                    get
                    {
                        if (m_panelBottom == null)
                            m_panelBottom = new PanelIndicator(DockStyle.Bottom);

                        return m_panelBottom;
                    }
                }

                private PanelIndicator m_panelFill = null;
                private PanelIndicator PanelFill
                {
                    get
                    {
                        if (m_panelFill == null)
                            m_panelFill = new PanelIndicator(DockStyle.Fill);

                        return m_panelFill;
                    }
                }

                private bool m_fullPanelEdge = false;
                public bool FullPanelEdge
                {
                    get { return m_fullPanelEdge; }
                    set
                    {
                        if (m_fullPanelEdge == value)
                            return;

                        m_fullPanelEdge = value;
                        RefreshChanges();
                    }
                }

                public DockDragHandler DragHandler
                {
                    get { return m_dragHandler; }
                }

                public DockPanel DockPanel
                {
                    get { return DragHandler.DockPanel; }
                }

                private DockPane m_dockPane = null;
                public DockPane DockPane
                {
                    get { return m_dockPane; }
                    internal set
                    {
                        if (m_dockPane == value)
                            return;

                        DockPane oldDisplayingPane = DisplayingPane;
                        m_dockPane = value;
                        if (oldDisplayingPane != DisplayingPane)
                            RefreshChanges();
                    }
                }

                private IHitTest m_hitTest = null;
                private IHitTest HitTestResult
                {
                    get { return m_hitTest; }
                    set
                    {
                        if (m_hitTest == value)
                            return;

                        if (m_hitTest != null)
                            m_hitTest.Status = DockStyle.None;

                        m_hitTest = value;
                    }
                }

                private DockPane DisplayingPane
                {
                    get { return ShouldPaneDiamondVisible() ? DockPane : null; }
                }

                private void RefreshChanges()
                {
                    Region region = new Region(Rectangle.Empty);
                    Rectangle rectDockArea = FullPanelEdge ? DockPanel.DockArea : DockPanel.DocumentWindowBounds;

                    rectDockArea = RectangleToClient(DockPanel.RectangleToScreen(rectDockArea));
                    if (ShouldPanelIndicatorVisible(DockState.DockLeft))
                    {
                        PanelLeft.Location = new Point(rectDockArea.X + _PanelIndicatorMargin, rectDockArea.Y + (rectDockArea.Height - PanelRight.Height) / 2);
                        PanelLeft.Visible = true;
                        region.Union(PanelLeft.Bounds);
                    }
                    else
                        PanelLeft.Visible = false;

                    if (ShouldPanelIndicatorVisible(DockState.DockRight))
                    {
                        PanelRight.Location = new Point(rectDockArea.X + rectDockArea.Width - PanelRight.Width - _PanelIndicatorMargin, rectDockArea.Y + (rectDockArea.Height - PanelRight.Height) / 2);
                        PanelRight.Visible = true;
                        region.Union(PanelRight.Bounds);
                    }
                    else
                        PanelRight.Visible = false;

                    if (ShouldPanelIndicatorVisible(DockState.DockTop))
                    {
                        PanelTop.Location = new Point(rectDockArea.X + (rectDockArea.Width - PanelTop.Width) / 2, rectDockArea.Y + _PanelIndicatorMargin);
                        PanelTop.Visible = true;
                        region.Union(PanelTop.Bounds);
                    }
                    else
                        PanelTop.Visible = false;

                    if (ShouldPanelIndicatorVisible(DockState.DockBottom))
                    {
                        PanelBottom.Location = new Point(rectDockArea.X + (rectDockArea.Width - PanelBottom.Width) / 2, rectDockArea.Y + rectDockArea.Height - PanelBottom.Height - _PanelIndicatorMargin);
                        PanelBottom.Visible = true;
                        region.Union(PanelBottom.Bounds);
                    }
                    else
                        PanelBottom.Visible = false;

                    if (ShouldPanelIndicatorVisible(DockState.Document))
                    {
                        Rectangle rectDocumentWindow = RectangleToClient(DockPanel.RectangleToScreen(DockPanel.DocumentWindowBounds));
                        PanelFill.Location = new Point(rectDocumentWindow.X + (rectDocumentWindow.Width - PanelFill.Width) / 2, rectDocumentWindow.Y + (rectDocumentWindow.Height - PanelFill.Height) / 2);
                        PanelFill.Visible = true;
                        region.Union(PanelFill.Bounds);
                    }
                    else
                        PanelFill.Visible = false;

                    if (ShouldPaneDiamondVisible())
                    {
                        Rectangle rect = RectangleToClient(DockPane.RectangleToScreen(DockPane.ClientRectangle));
                        PaneDiamond.Location = new Point(rect.Left + (rect.Width - PaneDiamond.Width) / 2, rect.Top + (rect.Height - PaneDiamond.Height) / 2);
                        PaneDiamond.Visible = true;
                        using (GraphicsPath graphicsPath = PaneIndicator.DisplayingGraphicsPath.Clone() as GraphicsPath)
                        {
                            Point[] pts = new Point[]
						{
							new Point(PaneDiamond.Left, PaneDiamond.Top),
							new Point(PaneDiamond.Right, PaneDiamond.Top),
							new Point(PaneDiamond.Left, PaneDiamond.Bottom)
						};
                            using (Matrix matrix = new Matrix(PaneDiamond.ClientRectangle, pts))
                            {
                                graphicsPath.Transform(matrix);
                            }
                            region.Union(graphicsPath);
                        }
                    }
                    else
                        PaneDiamond.Visible = false;

                    Region = region;
                }

                private bool ShouldPanelIndicatorVisible(DockState dockState)
                {
                    if (!Visible)
                        return false;

                    if (DockPanel.DockWindows[dockState].Visible)
                        return false;

                    return DragHandler.DragSource.IsDockStateValid(dockState);
                }

                private bool ShouldPaneDiamondVisible()
                {
                    if (DockPane == null)
                        return false;

                    if (!DockPanel.AllowEndUserNestedDocking)
                        return false;

                    return DragHandler.DragSource.CanDockTo(DockPane);
                }

                public override void Show(bool bActivate)
                {
                    base.Show(bActivate);
                    Bounds = SystemInformation.VirtualScreen;
                    RefreshChanges();
                }

                public void TestDrop()
                {
                    Point pt = Control.MousePosition;
                    DockPane = DockHelper.PaneAtPoint(pt, DockPanel);

                    if (TestDrop(PanelLeft, pt) != DockStyle.None)
                        HitTestResult = PanelLeft;
                    else if (TestDrop(PanelRight, pt) != DockStyle.None)
                        HitTestResult = PanelRight;
                    else if (TestDrop(PanelTop, pt) != DockStyle.None)
                        HitTestResult = PanelTop;
                    else if (TestDrop(PanelBottom, pt) != DockStyle.None)
                        HitTestResult = PanelBottom;
                    else if (TestDrop(PanelFill, pt) != DockStyle.None)
                        HitTestResult = PanelFill;
                    else if (TestDrop(PaneDiamond, pt) != DockStyle.None)
                        HitTestResult = PaneDiamond;
                    else
                        HitTestResult = null;

                    if (HitTestResult != null)
                    {
                        if (HitTestResult is PaneIndicator)
                            DragHandler.Outline.Show(DockPane, HitTestResult.Status);
                        else
                            DragHandler.Outline.Show(DockPanel, HitTestResult.Status, FullPanelEdge);
                    }
                }

                private static DockStyle TestDrop(IHitTest hitTest, Point pt)
                {
                    return hitTest.Status = hitTest.HitTest(pt);
                }
            }

            private class DockOutline : DockOutlineBase
            {
                public DockOutline()
                {
                    m_dragForm = new DragForm();
                    SetDragForm(Rectangle.Empty);
                    DragForm.BackColor = SystemColors.ActiveCaption;
                    DragForm.Opacity = 0.5;
                    DragForm.Show(false);
                }

                DragForm m_dragForm;
                private DragForm DragForm
                {
                    get { return m_dragForm; }
                }

                protected override void OnShow()
                {
                    CalculateRegion();
                }

                protected override void OnClose()
                {
                    DragForm.Close();
                }

                private void CalculateRegion()
                {
                    if (SameAsOldValue)
                        return;

                    if (!FloatWindowBounds.IsEmpty)
                        SetOutline(FloatWindowBounds);
                    else if (DockTo is DockPanel)
                        SetOutline(DockTo as DockPanel, Dock, (ContentIndex != 0));
                    else if (DockTo is DockPane)
                        SetOutline(DockTo as DockPane, Dock, ContentIndex);
                    else
                        SetOutline();
                }

                private void SetOutline()
                {
                    SetDragForm(Rectangle.Empty);
                }

                private void SetOutline(Rectangle floatWindowBounds)
                {
                    SetDragForm(floatWindowBounds);
                }

                private void SetOutline(DockPanel dockPanel, DockStyle dock, bool fullPanelEdge)
                {
                    Rectangle rect = fullPanelEdge ? dockPanel.DockArea : dockPanel.DocumentWindowBounds;
                    rect.Location = dockPanel.PointToScreen(rect.Location);
                    if (dock == DockStyle.Top)
                    {
                        int height = dockPanel.GetDockWindowSize(DockState.DockTop);
                        rect = new Rectangle(rect.X, rect.Y, rect.Width, height);
                    }
                    else if (dock == DockStyle.Bottom)
                    {
                        int height = dockPanel.GetDockWindowSize(DockState.DockBottom);
                        rect = new Rectangle(rect.X, rect.Bottom - height, rect.Width, height);
                    }
                    else if (dock == DockStyle.Left)
                    {
                        int width = dockPanel.GetDockWindowSize(DockState.DockLeft);
                        rect = new Rectangle(rect.X, rect.Y, width, rect.Height);
                    }
                    else if (dock == DockStyle.Right)
                    {
                        int width = dockPanel.GetDockWindowSize(DockState.DockRight);
                        rect = new Rectangle(rect.Right - width, rect.Y, width, rect.Height);
                    }
                    else if (dock == DockStyle.Fill)
                    {
                        rect = dockPanel.DocumentWindowBounds;
                        rect.Location = dockPanel.PointToScreen(rect.Location);
                    }

                    SetDragForm(rect);
                }

                private void SetOutline(DockPane pane, DockStyle dock, int contentIndex)
                {
                    if (dock != DockStyle.Fill)
                    {
                        Rectangle rect = pane.DisplayingRectangle;
                        if (dock == DockStyle.Right)
                            rect.X += rect.Width / 2;
                        if (dock == DockStyle.Bottom)
                            rect.Y += rect.Height / 2;
                        if (dock == DockStyle.Left || dock == DockStyle.Right)
                            rect.Width -= rect.Width / 2;
                        if (dock == DockStyle.Top || dock == DockStyle.Bottom)
                            rect.Height -= rect.Height / 2;
                        rect.Location = pane.PointToScreen(rect.Location);

                        SetDragForm(rect);
                    }
                    else if (contentIndex == -1)
                    {
                        Rectangle rect = pane.DisplayingRectangle;
                        rect.Location = pane.PointToScreen(rect.Location);
                        SetDragForm(rect);
                    }
                    else
                    {
                        using (GraphicsPath path = pane.TabStripControl.GetOutline(contentIndex))
                        {
                            RectangleF rectF = path.GetBounds();
                            Rectangle rect = new Rectangle((int)rectF.X, (int)rectF.Y, (int)rectF.Width, (int)rectF.Height);
                            using (Matrix matrix = new Matrix(rect, new Point[] { new Point(0, 0), new Point(rect.Width, 0), new Point(0, rect.Height) }))
                            {
                                path.Transform(matrix);
                            }
                            Region region = new Region(path);
                            SetDragForm(rect, region);
                        }
                    }
                }

                private void SetDragForm(Rectangle rect)
                {
                    DragForm.Bounds = rect;
                    if (rect == Rectangle.Empty)
                        DragForm.Region = new Region(Rectangle.Empty);
                    else if (DragForm.Region != null)
                        DragForm.Region = null;
                }

                private void SetDragForm(Rectangle rect, Region region)
                {
                    DragForm.Bounds = rect;
                    DragForm.Region = region;
                }
            }

            public DockDragHandler(DockPanel panel)
                : base(panel)
            {
            }

            public new IDockDragSource DragSource
            {
                get { return base.DragSource as IDockDragSource; }
                set { base.DragSource = value; }
            }

            private DockOutlineBase m_outline;
            public DockOutlineBase Outline
            {
                get { return m_outline; }
                private set { m_outline = value; }
            }

            private DockIndicator m_indicator;
            private DockIndicator Indicator
            {
                get { return m_indicator; }
                set { m_indicator = value; }
            }

            private Rectangle m_floatOutlineBounds;
            private Rectangle FloatOutlineBounds
            {
                get { return m_floatOutlineBounds; }
                set { m_floatOutlineBounds = value; }
            }

            public void BeginDrag(IDockDragSource dragSource)
            {
                DragSource = dragSource;

                if (!BeginDrag())
                {
                    DragSource = null;
                    return;
                }

                Outline = new DockOutline();
                Indicator = new DockIndicator(this);
                Indicator.Show(false);

                FloatOutlineBounds = DragSource.BeginDrag(StartMousePosition);
            }

            protected override void OnDragging()
            {
                TestDrop();
            }

            protected override void OnEndDrag(bool abort)
            {
                DockPanel.SuspendLayout(true);

                Outline.Close();
                Indicator.Close();

                EndDrag(abort);

                // Queue a request to layout all children controls
                DockPanel.PerformMdiClientLayout();

                DockPanel.ResumeLayout(true, true);

                DragSource = null;
            }

            private void TestDrop()
            {
                Outline.FlagTestDrop = false;

                Indicator.FullPanelEdge = ((Control.ModifierKeys & Keys.Shift) != 0);

                if ((Control.ModifierKeys & Keys.Control) == 0)
                {
                    Indicator.TestDrop();

                    if (!Outline.FlagTestDrop)
                    {
                        DockPane pane = DockHelper.PaneAtPoint(Control.MousePosition, DockPanel);
                        if (pane != null && DragSource.IsDockStateValid(pane.DockState))
                            pane.TestDrop(DragSource, Outline);
                    }

                    if (!Outline.FlagTestDrop && DragSource.IsDockStateValid(DockState.Float))
                    {
                        FloatWindow floatWindow = DockHelper.FloatWindowAtPoint(Control.MousePosition, DockPanel);
                        if (floatWindow != null)
                            floatWindow.TestDrop(DragSource, Outline);
                    }
                }
                else
                    Indicator.DockPane = DockHelper.PaneAtPoint(Control.MousePosition, DockPanel);

                if (!Outline.FlagTestDrop)
                {
                    if (DragSource.IsDockStateValid(DockState.Float))
                    {
                        Rectangle rect = FloatOutlineBounds;
                        rect.Offset(Control.MousePosition.X - StartMousePosition.X, Control.MousePosition.Y - StartMousePosition.Y);
                        Outline.Show(rect);
                    }
                }

                if (!Outline.FlagTestDrop)
                {
                    Cursor.Current = Cursors.No;
                    Outline.Show();
                }
                else
                    Cursor.Current = DragControl.Cursor;
            }

            private void EndDrag(bool abort)
            {
                if (abort)
                    return;

                if (!Outline.FloatWindowBounds.IsEmpty)
                    DragSource.FloatAt(Outline.FloatWindowBounds);
                else if (Outline.DockTo is DockPane)
                {
                    DockPane pane = Outline.DockTo as DockPane;
                    DragSource.DockTo(pane, Outline.Dock, Outline.ContentIndex);
                }
                else if (Outline.DockTo is DockPanel)
                {
                    DockPanel panel = Outline.DockTo as DockPanel;
                    panel.UpdateDockWindowZOrder(Outline.Dock, Outline.FlagFullEdge);
                    DragSource.DockTo(panel, Outline.Dock);
                }
            }
        }

        private DockDragHandler m_dockDragHandler = null;
        private DockDragHandler GetDockDragHandler()
        {
            if (m_dockDragHandler == null)
                m_dockDragHandler = new DockDragHandler(this);
            return m_dockDragHandler;
        }

        internal void BeginDrag(IDockDragSource dragSource)
        {
            GetDockDragHandler().BeginDrag(dragSource);
        }
    }
}


text:
import os

from lxml import etree
from django.test import TestCase

from corehq.apps.app_manager.models import Application
from corehq.apps.app_manager.tests.util import SuiteMixin
from corehq.apps.app_manager.translations import escape_output_value

import commcare_translations

class AppManagerTranslationsTest(TestCase, SuiteMixin):
    root = os.path.dirname(__file__)
    file_path = ('data', 'suite')

    def test_escape_output_value(self):
        test_cases = [
            ('hello', '<value>hello</value>'),
            ('abc < def > abc', '<value>abc < def > abc</value>'),
            ("bee's knees", "<value>bee's knees</value>"),
            ('unfortunate <xml expression', '<value>unfortunate <xml expression</value>'),
            (u'क्लिक', '<value>क्लिक</value>'),
            ('&#39', '<value>&#39</value>'),
            ('question1 is <output value="/data/question1" vellum:value="#form/question1"/> !',
             '<value>question1 is <output value="/data/question1" vellum:value="#form/question1"/> !</value>'),
            ('Here is a ref <output value="/data/no_media"/> with some "trailing" text & that\'s some bad < xml.',
             '<value>Here is a ref <output value="/data/no_media"/> with some "trailing" text & that\'s some bad < xml.</value>')

        ]
        for input, expected_output in test_cases:
            self.assertEqual(expected_output, etree.tostring(escape_output_value(input)))

    def test_language_names(self):
        app_json = self.get_json('app')
        app_json['langs'] = ['en', 'fra', 'hin', 'pol']
        app = Application.wrap(app_json)
        app.create_suite()
        app_strings = app.create_app_strings('default')
        app_strings_dict = commcare_translations.loads(app_strings)
        self.assertEqual(app_strings_dict['en'], 'English')
        self.assertEqual(app_strings_dict['fra'], u'Français')
        self.assertEqual(app_strings_dict['hin'], u'हिंदी')
        self.assertEqual(app_strings_dict['pol'], 'polski')

redpajama_set_name: RedPajamaGithub


text:
package org.jetbrains.plugins.github.api.data;

import com.intellij.openapi.util.text.StringUtil;
import com.intellij.tasks.impl.gson.Mandatory;
import com.intellij.tasks.impl.gson.RestModel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Date;

@RestModel
@SuppressWarnings("UnusedDeclaration")
public class GithubPullRequest {
  @Mandatory private Long number;
  @Mandatory private String state;
  @Mandatory private String title;
  private String body;
  private String bodyHtml;

  private String url;
  @Mandatory private String htmlUrl;
  @Mandatory private String diffUrl;
  @Mandatory private String patchUrl;
  @Mandatory private String issueUrl;

  private Boolean merged;
  private Boolean mergeable;

  private Integer comments;
  private Integer commits;
  private Integer additions;
  private Integer deletions;
  private Integer changedFiles;

  @Mandatory private Date createdAt;
  @Mandatory private Date updatedAt;
  private Date closedAt;
  private Date mergedAt;

  @Mandatory private GithubUser user;

  @Mandatory private Link head;
  @Mandatory private Link base;

  @RestModel
  public static class Link {
    @Mandatory private String label;
    @Mandatory private String ref;
    @Mandatory private String sha;

    private GithubRepo repo;
    @Mandatory private GithubUser user;

    @NotNull
    public String getLabel() {
      return label;
    }

    @NotNull
    public String getRef() {
      return ref;
    }

    @NotNull
    public String getSha() {
      return sha;
    }

    @Nullable
    public GithubRepo getRepo() {
      return repo;
    }

    @NotNull
    public GithubUser getUser() {
      return user;
    }
  }

  public long getNumber() {
    return number;
  }

  @NotNull
  public String getState() {
    return state;
  }

  @NotNull
  public String getTitle() {
    return title;
  }

  @NotNull
  public String getBodyHtml() {
    return StringUtil.notNullize(bodyHtml);
  }

  @NotNull
  public String getHtmlUrl() {
    return htmlUrl;
  }

  @NotNull
  public String getDiffUrl() {
    return diffUrl;
  }

  @NotNull
  public String getPatchUrl() {
    return patchUrl;
  }

  @NotNull
  public String getIssueUrl() {
    return issueUrl;
  }

  @NotNull
  public Date getCreatedAt() {
    return createdAt;
  }

  @NotNull
  public Date getUpdatedAt() {
    return updatedAt;
  }

  @Nullable
  public Date getClosedAt() {
    return closedAt;
  }

  @Nullable
  public Date getMergedAt() {
    return mergedAt;
  }

  @NotNull
  public GithubUser getUser() {
    return user;
  }

  @NotNull
  public Link getHead() {
    return head;
  }

  @NotNull
  public Link getBase() {
    return base;
  }
}


text:
using JustLogic.Core;
using System.Collections.Generic;
using UnityEngine;

[UnitMenu("Physics/Add Explosion Force (Rigidbody)")]
[UnitFriendlyName("Rigidbody.Add Explosion Force")]
public class JLRigidbodyAddExplosionForce3 : JLAction
{
    [Parameter(ExpressionType = typeof(Rigidbody))]
    public JLExpression OperandValue;

    [Parameter(ExpressionType = typeof(System.Single))]
    public JLExpression ExplosionForce;

    [Parameter(ExpressionType = typeof(Vector3))]
    public JLExpression ExplosionPosition;

    [Parameter(ExpressionType = typeof(System.Single))]
    public JLExpression ExplosionRadius;

    [Parameter(ExpressionType = typeof(System.Single))]
    public JLExpression UpwardsModifier;

    [Parameter(ExpressionType = typeof(ForceMode))]
    public JLExpression Mode;

    protected override IEnumerator<YieldMode> OnExecute(IExecutionContext context)
    {
        Rigidbody opValue = OperandValue.GetResult<Rigidbody>(context);
        opValue.AddExplosionForce(ExplosionForce.GetResult<System.Single>(context), ExplosionPosition.GetResult<Vector3>(context), ExplosionRadius.GetResult<System.Single>(context), UpwardsModifier.GetResult<System.Single>(context), Mode.GetResult<ForceMode>(context));
        return null;
    }
}


text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.api.ads.admanager.jaxws.v202211;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for DaiAuthenticationKeyType.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="DaiAuthenticationKeyType">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="UNKNOWN"/>
 *     <enumeration value="API"/>
 *     <enumeration value="HMAC"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "DaiAuthenticationKeyType")
@XmlEnum
public enum DaiAuthenticationKeyType {

    /**
     *
     *                 The value returned if the actual value is not exposed by the requested API version.
     *
     *
     */
    UNKNOWN,

    /**
     *
     *                 Indicates that the key is a standard API key and should be used with the api-key SDK parameter
     *                 when authenticating stream create requests.
     *
     *
     */
    API,

    /**
     *
     *                 Indicates that the key is an HMAC key and should be used to generate a signature for the stream
     *                 create request with the auth-token SDK parameter.
     *
     *
     */
    HMAC;

    public String value() {
        return name();
    }

    public static DaiAuthenticationKeyType fromValue(String v) {
        return valueOf(v);
    }

}


text:
<?xml version="1.0"?>
<document>

        <title>
	Apache Lucene - Basic Demo Sources Walk-through
		</title>

<properties>
<author email="acoliver@apache.org">Andrew C. Oliver</author>
</properties>

<title>About the Code</title>

In this section we walk through the sources behind the command-line Lucene demo: where to find them,
their parts and their function.  This section is intended for Java developers wishing to understand
how to use Lucene in their applications.

<title>Location of the source</title>

Relative to the directory created when you extracted Lucene or retrieved it from Subversion, you
should see a directory called src which in turn contains a directory called
demo.  This is the root for all of the Lucene demos.  Under this directory is
org/apache/lucene/demo.  This is where all the Java sources for the demos live.

Within this directory you should see the IndexFiles.java class we executed earlier.
Bring it up in vi or your editor of choice and let's take a look at it.

<title>IndexFiles</title>

As we discussed in the previous walk-through, the IndexFiles class creates a Lucene
Index. Let's take a look at how it does this.

The first substantial thing the main function does is instantiate IndexWriter.  It passes the string
"index" and a new instance of a class called StandardAnalyzer.
The "index" string is the name of the filesystem directory where all index information
should be stored.  Because we're not passing a full path, this will be created as a subdirectory of
the current working directory (if it does not already exist). On some platforms, it may be created
in other directories (such as the user's home directory).

The IndexWriter is the main
class responsible for creating indices.  To use it you must instantiate it with a path that it can
write the index into.  If this path does not exist it will first create it.  Otherwise it will
refresh the index at that path.  You can also create an index using one of the subclasses of Directory.  In any case, you must also pass an
instance of org.apache.lucene.analysis.Analyzer.

The particular Analyzer we
are using, StandardAnalyzer, is
little more than a standard Java Tokenizer, converting all strings to lowercase and filtering out
useless words and characters from the index.  By useless words and characters I mean common language
words such as articles (a, an, the, etc.) and other strings that would be useless for searching
(e.g. 's) .  It should be noted that there are different rules for every language, and you
should use the proper analyzer for each.  Lucene currently provides Analyzers for a number of
different languages (see the *Analyzer.java sources under contrib/analyzers/src/java/org/apache/lucene/analysis).

Looking further down in the file, you should see the indexDocs() code.  This recursive
function simply crawls the directories and uses FileDocument to create Document objects.  The Document is simply a data object to
represent the content in the file as well as its creation time and location.  These instances are
added to the indexWriter.  Take a look inside FileDocument.  It's not particularly
complicated.  It just adds fields to the Document.

As you can see there isn't much to creating an index.  The devil is in the details.  You may also
wish to examine the other samples in this directory, particularly the IndexHTML class.  It is a bit more
complex but builds upon this example.

<title>Searching Files</title>

The SearchFiles class is
quite simple.  It primarily collaborates with an IndexSearcher, StandardAnalyzer
(which is used in the IndexFiles class as well) and a
QueryParser.  The
query parser is constructed with an analyzer used to interpret your query text in the same way the
documents are interpreted: finding the end of words and removing useless words like 'a', 'an' and
'the'.  The Query object contains
the results from the QueryParser which is passed to
the searcher.  Note that it's also possible to programmatically construct a rich Query object without using the query
parser.  The query parser just enables decoding the Lucene query
syntax into the corresponding Query object.  The searcher results are
returned in a collection of Documents called Hits which is then iterated through and
displayed to the user.

<title>The Web example...</title>

read on>>>

</document>


text:
// The MIT License (MIT)
//
// Copyright (c) 2017 PubNative GmbH
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

package net.pubnative.sdk.core.insights.model;

import android.content.Context;
import android.text.TextUtils;

import net.pubnative.sdk.core.config.model.PNPriorityRuleModel;
import net.pubnative.sdk.core.insights.PNInsightsManager;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

public class PNInsightModel {

    private static final String TAG = PNInsightModel.class.getSimpleName();

    public static final int ERORR_LINES_COUNT = 10;

    protected String              mRequestInsightURL;
    protected String              mImpressionInsightURL;
    protected String              mClickInsightURL;
    protected String              mRescueRequestURL;
    protected Context             mContext;
    protected PNInsightDataModel  mData;
    protected Map<String, String> mExtras;

    public PNInsightModel(Context context) {

        mContext = context;
        mData = new PNInsightDataModel(context);
    }

    public PNInsightDataModel getData() {
        return mData;
    }

    public void setData(PNInsightDataModel data) {
        mData = data;
    }

    /**
     * Adds extra fields to be added in the insight query string
     *
     * @param extras dictionary with extras key and values
     */
    public void addExtras(Map<String, String> extras) {
        if (extras != null) {
            if (mExtras == null) {
                mExtras = new HashMap<String, String>();
            }
            mExtras.putAll(extras);
        }
    }

    /**
     * Adds extra fields to be added in the insight query string
     *
     * @param key   key string
     * @param value value string
     */
    public void addExtra(String key, String value) {
        if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) {
            if (mExtras == null) {
                mExtras = new HashMap<String, String>();
            }
            mExtras.put(key, value);
        }
    }

    /**
     * This will set up the insight urls to use in the track process
     *
     * @param requestUrl    valid request url string
     * @param impressionUrl valid impression url string
     * @param clickUrl      valid click url string
     * @param rescueUrl     valid rescue url string
     */
    public void setInsightURLs(String requestUrl, String impressionUrl, String clickUrl, String rescueUrl) {
        mRequestInsightURL = requestUrl;
        mImpressionInsightURL = impressionUrl;
        mClickInsightURL = clickUrl;
        mRescueRequestURL = rescueUrl;
    }
    //==============================================================================================
    // Tracking
    //==============================================================================================

    /**
     * Sets the current network as unreachable due to the passed exception
     *
     * @param priorityRuleModel valid model
     * @param responseTime      time in milliseconds that this network took to fail
     * @param exception         exception with the details
     */
    public void trackUnreachableNetwork(PNPriorityRuleModel priorityRuleModel, long responseTime, Exception exception) {
        if (priorityRuleModel != null && !TextUtils.isEmpty(priorityRuleModel.network_code)) {
            mData.addUnreachableNetwork(priorityRuleModel.network_code);
        }
        PNInsightCrashModel crashModel = null;
        if (exception != null) {
            crashModel = new PNInsightCrashModel();
            crashModel.error = getExceptionDescription(exception);
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            exception.printStackTrace(pw);
            crashModel.details = sw.toString();
        }
        mData.addNetwork(priorityRuleModel, responseTime, crashModel);
    }

    /**
     * Sets the current network as attempted but failed
     *
     * @param priorityRuleModel valid model
     * @param responseTime      time in milliseconds that this attempt took to fail
     * @param exception         exception with details
     */
    public void trackAttemptedNetwork(PNPriorityRuleModel priorityRuleModel, long responseTime, Exception exception) {
        if (priorityRuleModel != null && !TextUtils.isEmpty(priorityRuleModel.network_code)) {
            mData.addAttemptedNetwork(priorityRuleModel.network_code);
        }
        PNInsightCrashModel crashModel = null;
        if (exception != null) {
            crashModel = new PNInsightCrashModel();
            crashModel.error = getExceptionDescription(exception);
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            exception.printStackTrace(pw);
            crashModel.details = sw.toString();
        }
        mData.addNetwork(priorityRuleModel, responseTime, crashModel);
    }

    /**
     * Sets the current network as succeded
     *
     * @param priorityRuleModel valid model
     * @param responseTime      time in milliseconds that it took this request to be success
     */
    public void trackSuccededNetwork(PNPriorityRuleModel priorityRuleModel, long responseTime) {
        if (priorityRuleModel != null && !TextUtils.isEmpty(priorityRuleModel.network_code)) {
            mData.network = priorityRuleModel.network_code;
        }
        mData.addNetwork(priorityRuleModel, responseTime, null);
    }

    /**
     * Sends request insight data
     */
    public void sendRequestInsight(Map<String, String> extras) {
        Map<String, String> insightExtras = new HashMap<String, String>();
        if (mExtras != null) {
            insightExtras.putAll(mExtras);
        }
        if (extras != null) {
            insightExtras.putAll(extras);
        }
        PNInsightsManager.trackData(mContext, mRequestInsightURL, insightExtras, mData);
    }

    /**
     * Sends impression insight data
     */
    public void sendImpressionInsight() {
        PNInsightsManager.trackData(mContext, mImpressionInsightURL, mExtras, mData);
    }

    /**
     * Sends a request insight data
     */
    public void sendClickInsight() {
        PNInsightsManager.trackData(mContext, mClickInsightURL, mExtras, mData);
    }

    /**
     * Sends a request for rescue insight data
     */
    public void sendRescueInsight(String network, long responseTime) {
        if (!TextUtils.isEmpty(network)) {
            mData.network = network;
            mData.response_time = responseTime;
            PNInsightsManager.trackData(mContext, mRescueRequestURL, mExtras, mData);
        }
    }

    private String getExceptionDescription(Exception exception) {
        StringBuilder errorDesc = new StringBuilder();
        StackTraceElement[] stackTrace = exception.getStackTrace();
        for (int i = 0; i < ERORR_LINES_COUNT && i < stackTrace.length; i++) {
            errorDesc.append(stackTrace[i])
                    .append("\n");
        }
        return errorDesc.toString();
    }
}


text:
<?php

namespace Difftechnology\Notifynder\Senders;

use Difftechnology\Notifynder\Contracts\DefaultSender;
use Difftechnology\Notifynder\Contracts\StoreNotification;

/**
 * Class SendMultiple.
 *
 * Send multiple categories
 */
class SendMultiple implements DefaultSender
{
    /**
     * @var array
     */
    protected $infoNotifications = [];

    /**
     * @param $infoNotifications
     */
    public function __construct($infoNotifications)
    {
        $this->infoNotifications = $infoNotifications;
    }

    /**
     * Send multiple notifications.
     *
     * @param  StoreNotification $sender
     * @return mixed
     */
    public function send(StoreNotification $sender)
    {
        return $sender->storeMultiple($this->infoNotifications);
    }
}


text:
title: 'Heading to JavaOne – Back in a week.'
author: ajordens
layout: post
permalink: /2008/05/heading-to-javaone-back-in-a-week/
categories:
  - General Discussions
  - Java
---
Just about to head to the airport enroute to San Francisco.

Really looking forward to the conference. Rather than attempt to blog a lot, I’m going to experiment with [Twitter][1]. Crazy Bob has compiled a [list of JavaOne twitter’s][2].

 [1]: http://twitter.com/ajordens
 [2]: http://crazybob.org/2008/05/going-to-javaone-sign-up-for-twitter.html


text:
package reflex.app;

import org.apache.log4j.Logger;

import reflex.DebugLevel;
import reflex.IReflexDebugHandler;

public class ReflexStdOutDebugHandler implements IReflexDebugHandler {
    private Logger log = Logger.getLogger(this.getClass().getName());

    @Override
    public void debugOut(int arg0, DebugLevel arg1, String arg2) {
        String message = "Line: " + arg0 + ", " + arg2;
        switch (arg1) {
        case SPAM:
            log.info(message);
            break;
        case INFO:
            log.info(message);
            break;
        case WARNING:
            log.warn(message);
            break;
        case ERROR:
            log.error(message);
            break;
        }
    }

    @Override
    public void statementReached(int arg0, DebugLevel arg1, String arg2) {
        debugOut(arg0, arg1, arg2);
    }

    @Override
    public boolean hasCapability() {
        return true;
    }

}


text:
#import "AWSCognitoSyncService.h"
#import "AWSNetworking.h"
#import "AWSCategory.h"
#import "AWSNetworking.h"
#import "AWSSignature.h"
#import "AWSService.h"
#import "AWSNetworking.h"
#import "AWSURLRequestSerialization.h"
#import "AWSURLResponseSerialization.h"
#import "AWSURLRequestRetryHandler.h"
#import "AWSSynchronizedMutableDictionary.h"

NSString *const AWSCognitoSyncDefinitionFileName = @"cognito-sync-2014-06-30";

@interface AWSCognitoSyncResponseSerializer : AWSJSONResponseSerializer

@end

@implementation AWSCognitoSyncResponseSerializer

#pragma mark - Service errors

static NSDictionary *errorCodeDictionary = nil;
+ (void)initialize {
    errorCodeDictionary = @{
                            @"IncompleteSignature" : @(AWSCognitoSyncErrorIncompleteSignature),
                            @"InvalidClientTokenId" : @(AWSCognitoSyncErrorInvalidClientTokenId),
                            @"MissingAuthenticationToken" : @(AWSCognitoSyncErrorMissingAuthenticationToken),
                            @"AlreadyStreamedException" : @(AWSCognitoSyncErrorAlreadyStreamed),
                            @"DuplicateRequestException" : @(AWSCognitoSyncErrorDuplicateRequest),
                            @"InternalErrorException" : @(AWSCognitoSyncErrorInternalError),
                            @"InvalidConfigurationException" : @(AWSCognitoSyncErrorInvalidConfiguration),
                            @"InvalidLambdaFunctionOutputException" : @(AWSCognitoSyncErrorInvalidLambdaFunctionOutput),
                            @"InvalidParameterException" : @(AWSCognitoSyncErrorInvalidParameter),
                            @"LambdaThrottledException" : @(AWSCognitoSyncErrorLambdaThrottled),
                            @"LimitExceededException" : @(AWSCognitoSyncErrorLimitExceeded),
                            @"NotAuthorizedErrorException" : @(AWSCognitoSyncErrorNotAuthorized),
                            @"ResourceConflictException" : @(AWSCognitoSyncErrorResourceConflict),
                            @"ResourceNotFoundException" : @(AWSCognitoSyncErrorResourceNotFound),
                            @"TooManyRequestsException" : @(AWSCognitoSyncErrorTooManyRequests),
                            };
}

- (id)responseObjectForResponse:(NSHTTPURLResponse *)response
                originalRequest:(NSURLRequest *)originalRequest
                 currentRequest:(NSURLRequest *)currentRequest
                           data:(id)data
                          error:(NSError *__autoreleasing *)error {
    id responseObject = [super responseObjectForResponse:response
                                         originalRequest:originalRequest
                                          currentRequest:currentRequest
                                                    data:data
                                                   error:error];
    if (!*error && [responseObject isKindOfClass:[NSDictionary class]]) {
        NSString *errorTypeStr = [[response allHeaderFields] objectForKey:@"x-amzn-ErrorType"];
        NSString *errorTypeHeader = [[errorTypeStr componentsSeparatedByString:@":"] firstObject];

        if ([errorTypeStr length] > 0 && errorTypeHeader) {
            if (errorCodeDictionary[errorTypeHeader]) {
                if (error) {
                    NSDictionary *userInfo = @{NSLocalizedDescriptionKey : [responseObject objectForKey:@"message"]?[responseObject objectForKey:@"message"]:[NSNull null], NSLocalizedFailureReasonErrorKey: errorTypeStr};
                    *error = [NSError errorWithDomain:AWSCognitoSyncErrorDomain
                                                 code:[[errorCodeDictionary objectForKey:errorTypeHeader] integerValue]
                                             userInfo:userInfo];
                }
                return responseObject;
            } else if (errorTypeHeader) {
                if (error) {
                    NSDictionary *userInfo = @{NSLocalizedDescriptionKey : [responseObject objectForKey:@"message"]?[responseObject objectForKey:@"message"]:[NSNull null], NSLocalizedFailureReasonErrorKey: errorTypeStr};
                    *error = [NSError errorWithDomain:AWSCognitoSyncErrorDomain
                                                 code:AWSCognitoSyncErrorUnknown
                                             userInfo:userInfo];
                }
                return responseObject;
            }
        }

        if (self.outputClass) {
            responseObject = [MTLJSONAdapter modelOfClass:self.outputClass
                                       fromJSONDictionary:responseObject
                                                    error:error];
        }
    }

    return responseObject;
}

@end

@interface AWSCognitoSyncRequestRetryHandler : AWSURLRequestRetryHandler

@end

@implementation AWSCognitoSyncRequestRetryHandler

- (AWSNetworkingRetryType)shouldRetry:(uint32_t)currentRetryCount
                             response:(NSHTTPURLResponse *)response
                                 data:(NSData *)data
                                error:(NSError *)error {
    AWSNetworkingRetryType retryType = [super shouldRetry:currentRetryCount
                                                 response:response
                                                     data:data
                                                    error:error];
    if(retryType == AWSNetworkingRetryTypeShouldNotRetry
       && [error.domain isEqualToString:AWSCognitoSyncErrorDomain]
       && currentRetryCount < self.maxRetryCount) {
        switch (error.code) {
            case AWSCognitoSyncErrorIncompleteSignature:
            case AWSCognitoSyncErrorInvalidClientTokenId:
            case AWSCognitoSyncErrorMissingAuthenticationToken:
            retryType = AWSNetworkingRetryTypeShouldRefreshCredentialsAndRetry;
            break;

            default:
            break;
        }
    }

    return retryType;
}

@end

@interface AWSRequest()

@property (nonatomic, strong) AWSNetworkingRequest *internalRequest;

@end

@interface AWSCognitoSync()

@property (nonatomic, strong) AWSNetworking *networking;
@property (nonatomic, strong) AWSServiceConfiguration *configuration;
@property (nonatomic, strong) AWSEndpoint *endpoint;

@end

@implementation AWSCognitoSync

static AWSSynchronizedMutableDictionary *_serviceClients = nil;

+ (instancetype)defaultCognitoSync {
    if (![AWSServiceManager defaultServiceManager].defaultServiceConfiguration) {
        return nil;
    }

    static AWSCognitoSync *_defaultCognitoSync = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        _defaultCognitoSync = [[AWSCognitoSync alloc] initWithConfiguration:AWSServiceManager.defaultServiceManager.defaultServiceConfiguration];
#pragma clang diagnostic pop
    });

    return _defaultCognitoSync;
}

+ (void)registerCognitoSyncWithConfiguration:(AWSServiceConfiguration *)configuration forKey:(NSString *)key {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _serviceClients = [AWSSynchronizedMutableDictionary new];
    });
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    [_serviceClients setObject:[[AWSCognitoSync alloc] initWithConfiguration:configuration]
                        forKey:key];
#pragma clang diagnostic pop
}

+ (instancetype)CognitoSyncForKey:(NSString *)key {
    return [_serviceClients objectForKey:key];
}

+ (void)removeCognitoSyncForKey:(NSString *)key {
    [_serviceClients removeObjectForKey:key];
}

- (instancetype)init {
    @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                   reason:@"`- init` is not a valid initializer. Use `+ defaultCognitoSync` or `+ CognitoSyncForKey:` instead."
                                 userInfo:nil];
    return nil;
}

- (instancetype)initWithConfiguration:(AWSServiceConfiguration *)configuration {
    if (self = [super init]) {
        _configuration = [configuration copy];

        _endpoint = [[AWSEndpoint alloc] initWithRegion:_configuration.regionType
                                                service:AWSServiceCognitoService
                                           useUnsafeURL:NO];

        AWSSignatureV4Signer *signer = [AWSSignatureV4Signer signerWithCredentialsProvider:_configuration.credentialsProvider
                                                                                endpoint:_endpoint];

        _configuration.baseURL = _endpoint.URL;
        _configuration.requestSerializer = [AWSJSONRequestSerializer new];
        _configuration.requestInterceptors = @[[AWSNetworkingRequestInterceptor new], signer];
        _configuration.retryHandler = [[AWSCognitoSyncRequestRetryHandler alloc] initWithMaximumRetryCount:_configuration.maxRetryCount];
        _configuration.headers = @{@"Host" : _endpoint.hostName,
                                   @"Content-Type" : @"application/x-amz-json-1.1"};

        _networking = [AWSNetworking networking:_configuration];
    }

    return self;
}

- (BFTask *)invokeRequest:(AWSRequest *)request
               HTTPMethod:(AWSHTTPMethod)HTTPMethod
                URLString:(NSString *) URLString
             targetPrefix:(NSString *)targetPrefix
            operationName:(NSString *)operationName
              outputClass:(Class)outputClass {
    if (!request) {
        request = [AWSRequest new];
    }

    AWSNetworkingRequest *networkingRequest = request.internalRequest;
    if (request) {
        networkingRequest.parameters = [[MTLJSONAdapter JSONDictionaryFromModel:request] aws_removeNullValues];
    } else {
        networkingRequest.parameters = @{};
    }

    NSMutableDictionary *headers = [NSMutableDictionary new];

    networkingRequest.headers = headers;
    networkingRequest.HTTPMethod = HTTPMethod;
    networkingRequest.requestSerializer = [[AWSJSONRequestSerializer alloc] initWithResource:AWSCognitoSyncDefinitionFileName
                                                                                actionName:operationName
                                                                              classForBundle:[self class]];
    networkingRequest.responseSerializer = [[AWSCognitoSyncResponseSerializer alloc] initWithResource:AWSCognitoSyncDefinitionFileName
                                                                                actionName:operationName
                                                                                outputClass:outputClass
                                                                                classForBundle:[self class]];
    return [self.networking sendRequest:networkingRequest];
}

#pragma mark - Service method

- (BFTask *)bulkPublish:(AWSCognitoSyncBulkPublishRequest *)request {
    return [self invokeRequest:request
                    HTTPMethod:AWSHTTPMethodPOST
                     URLString:@"/identitypools/{IdentityPoolId}/bulkpublish"
                  targetPrefix:@""
                 operationName:@"BulkPublish"
                   outputClass:[AWSCognitoSyncBulkPublishResponse class]];
}

- (BFTask *)deleteDataset:(AWSCognitoSyncDeleteDatasetRequest *)request {
    return [self invokeRequest:request
                    HTTPMethod:AWSHTTPMethodDELETE
                     URLString:@"/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}"
                  targetPrefix:@""
                 operationName:@"DeleteDataset"
                   outputClass:[AWSCognitoSyncDeleteDatasetResponse class]];
}

- (BFTask *)describeDataset:(AWSCognitoSyncDescribeDatasetRequest *)request {
    return [self invokeRequest:request
                    HTTPMethod:AWSHTTPMethodGET
                     URLString:@"/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}"
                  targetPrefix:@""
                 operationName:@"DescribeDataset"
                   outputClass:[AWSCognitoSyncDescribeDatasetResponse class]];
}

- (BFTask *)describeIdentityPoolUsage:(AWSCognitoSyncDescribeIdentityPoolUsageRequest *)request {
    return [self invokeRequest:request
                    HTTPMethod:AWSHTTPMethodGET
                     URLString:@"/identitypools/{IdentityPoolId}"
                  targetPrefix:@""
                 operationName:@"DescribeIdentityPoolUsage"
                   outputClass:[AWSCognitoSyncDescribeIdentityPoolUsageResponse class]];
}

- (BFTask *)describeIdentityUsage:(AWSCognitoSyncDescribeIdentityUsageRequest *)request {
    return [self invokeRequest:request
                    HTTPMethod:AWSHTTPMethodGET
                     URLString:@"/identitypools/{IdentityPoolId}/identities/{IdentityId}"
                  targetPrefix:@""
                 operationName:@"DescribeIdentityUsage"
                   outputClass:[AWSCognitoSyncDescribeIdentityUsageResponse class]];
}

- (BFTask *)getBulkPublishDetails:(AWSCognitoSyncGetBulkPublishDetailsRequest *)request {
    return [self invokeRequest:request
                    HTTPMethod:AWSHTTPMethodPOST
                     URLString:@"/identitypools/{IdentityPoolId}/getBulkPublishDetails"
                  targetPrefix:@""
                 operationName:@"GetBulkPublishDetails"
                   outputClass:[AWSCognitoSyncGetBulkPublishDetailsResponse class]];
}

- (BFTask *)getCognitoEvents:(AWSCognitoSyncGetCognitoEventsRequest *)request {
    return [self invokeRequest:request
                    HTTPMethod:AWSHTTPMethodGET
                     URLString:@"/identitypools/{IdentityPoolId}/events"
                  targetPrefix:@""
                 operationName:@"GetCognitoEvents"
                   outputClass:[AWSCognitoSyncGetCognitoEventsResponse class]];
}

- (BFTask *)getIdentityPoolConfiguration:(AWSCognitoSyncGetIdentityPoolConfigurationRequest *)request {
    return [self invokeRequest:request
                    HTTPMethod:AWSHTTPMethodGET
                     URLString:@"/identitypools/{IdentityPoolId}/configuration"
                  targetPrefix:@""
                 operationName:@"GetIdentityPoolConfiguration"
                   outputClass:[AWSCognitoSyncGetIdentityPoolConfigurationResponse class]];
}

- (BFTask *)listDatasets:(AWSCognitoSyncListDatasetsRequest *)request {
    return [self invokeRequest:request
                    HTTPMethod:AWSHTTPMethodGET
                     URLString:@"/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets"
                  targetPrefix:@""
                 operationName:@"ListDatasets"
                   outputClass:[AWSCognitoSyncListDatasetsResponse class]];
}

- (BFTask *)listIdentityPoolUsage:(AWSCognitoSyncListIdentityPoolUsageRequest *)request {
    return [self invokeRequest:request
                    HTTPMethod:AWSHTTPMethodGET
                     URLString:@"/identitypools"
                  targetPrefix:@""
                 operationName:@"ListIdentityPoolUsage"
                   outputClass:[AWSCognitoSyncListIdentityPoolUsageResponse class]];
}

- (BFTask *)listRecords:(AWSCognitoSyncListRecordsRequest *)request {
    return [self invokeRequest:request
                    HTTPMethod:AWSHTTPMethodGET
                     URLString:@"/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}/records"
                  targetPrefix:@""
                 operationName:@"ListRecords"
                   outputClass:[AWSCognitoSyncListRecordsResponse class]];
}

- (BFTask *)registerDevice:(AWSCognitoSyncRegisterDeviceRequest *)request {
    return [self invokeRequest:request
                    HTTPMethod:AWSHTTPMethodPOST
                     URLString:@"/identitypools/{IdentityPoolId}/identity/{IdentityId}/device"
                  targetPrefix:@""
                 operationName:@"RegisterDevice"
                   outputClass:[AWSCognitoSyncRegisterDeviceResponse class]];
}

- (BFTask *)setCognitoEvents:(AWSCognitoSyncSetCognitoEventsRequest *)request {
    return [self invokeRequest:request
                    HTTPMethod:AWSHTTPMethodPOST
                     URLString:@"/identitypools/{IdentityPoolId}/events"
                  targetPrefix:@""
                 operationName:@"SetCognitoEvents"
                   outputClass:nil];
}

- (BFTask *)setIdentityPoolConfiguration:(AWSCognitoSyncSetIdentityPoolConfigurationRequest *)request {
    return [self invokeRequest:request
                    HTTPMethod:AWSHTTPMethodPOST
                     URLString:@"/identitypools/{IdentityPoolId}/configuration"
                  targetPrefix:@""
                 operationName:@"SetIdentityPoolConfiguration"
                   outputClass:[AWSCognitoSyncSetIdentityPoolConfigurationResponse class]];
}

- (BFTask *)subscribeToDataset:(AWSCognitoSyncSubscribeToDatasetRequest *)request {
    return [self invokeRequest:request
                    HTTPMethod:AWSHTTPMethodPOST
                     URLString:@"/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}/subscriptions/{DeviceId}"
                  targetPrefix:@""
                 operationName:@"SubscribeToDataset"
                   outputClass:[AWSCognitoSyncSubscribeToDatasetResponse class]];
}

- (BFTask *)unsubscribeFromDataset:(AWSCognitoSyncUnsubscribeFromDatasetRequest *)request {
    return [self invokeRequest:request
                    HTTPMethod:AWSHTTPMethodDELETE
                     URLString:@"/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}/subscriptions/{DeviceId}"
                  targetPrefix:@""
                 operationName:@"UnsubscribeFromDataset"
                   outputClass:[AWSCognitoSyncUnsubscribeFromDatasetResponse class]];
}

- (BFTask *)updateRecords:(AWSCognitoSyncUpdateRecordsRequest *)request {
    return [self invokeRequest:request
                    HTTPMethod:AWSHTTPMethodPOST
                     URLString:@"/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}"
                  targetPrefix:@""
                 operationName:@"UpdateRecords"
                   outputClass:[AWSCognitoSyncUpdateRecordsResponse class]];
}

@end


text:
import * as _ from 'lodash'
import * as parseUrl from 'url-parse'
import {createConnection, DatabaseConnection} from './database'
import {DB_NAME} from './settings'
import * as parseArgs from 'minimist'
const argv = parseArgs(process.argv.slice(2))
import { getVariableData } from './models/Variable'
import * as fs from 'fs-extra'
import * as filenamify from 'filenamify'
const md5 = require('md5')

declare var global: any
global.window = { location: { search: "" }}
global.App = { isEditor: false }
global.Global = { rootUrl: "https://ourworldindata.org/grapher" }

require('module-alias').addAliases({
    'react'  : 'preact-compat',
    'react-dom': 'preact-compat'
})

import ChartConfig, { ChartConfigProps } from '../js/charts/ChartConfig'

async function getChartsBySlug(db: DatabaseConnection) {
    const chartsBySlug: Map<string, ChartConfigProps> = new Map()
    const chartsById = new Map()

    const chartsQuery = db.query(`SELECT * FROM charts`)
    const redirectQuery = db.query(`SELECT slug, chart_id FROM chart_slug_redirects`)

    for (const row of await chartsQuery) {
        const chart = JSON.parse(row.config)
        chart.id = row.id
        chartsBySlug.set(chart.slug, chart)
        chartsById.set(row.id, chart)
    }

    for (const row of await redirectQuery) {
        chartsBySlug.set(row.slug, chartsById.get(row.chart_id))
    }

    return chartsBySlug
}

async function main(chartUrls: string[], outDir: string) {
    const db = createConnection({ database: DB_NAME })
    try {
        await fs.mkdirp(outDir)
        const chartsBySlug = await getChartsBySlug(db)

        for (const urlStr of chartUrls) {
            const url = parseUrl(urlStr)
            const slug = _.last(url.pathname.split('/')) as string
            const jsonConfig = chartsBySlug.get(slug)
            if (jsonConfig) {
                const queryStr = url.query as any

                const chart = new ChartConfig(jsonConfig, { queryStr: queryStr })
                chart.isLocalExport = true
                const {width, height} = chart.idealBounds
                const outPath = `${outDir}/${slug}${queryStr ? "-"+md5(queryStr) : ""}_v${jsonConfig.version}_${width}x${height}.svg`
                console.log(outPath)

                if (!fs.existsSync(outPath)) {
                    const variableIds = _.uniq(chart.dimensions.map(d => d.variableId))
                    const vardata = await getVariableData(variableIds)
                    chart.vardata.receiveData(vardata)
                    fs.writeFile(outPath, chart.staticSVG)
                }
            }
        }
    } finally {
        db.end()
    }
}

main(argv._.slice(0, -1), argv._[argv._.length-1])


text:
/**
 * @fileoverview Manages all the file operations
 * @author Gyandeep Singh
 */

"use strict";

var path = require("path");
var nodeDir = require("node-dir");
var minimatch = require("minimatch");
var fs = require("fs");

/**
 * Checks for patter matching on the file path
 * @param {String} filePath - Path of the file
 * @param {String[]} ignorePattern - Collection of ignore patterns
 * @returns {Boolean} true if there is a match else false
 * @private
 */
function patternMatching(filePath, ignorePattern){
    return ignorePattern.some(function(pattern){
        return minimatch(filePath, pattern);
    });
}

/**
 * Filters the file collection based on the ignore patterns and
 * @param {string[]} files - Collection of files
 * @param {string} ignorePattern - Patterns to ignore
 * @param {string} [fileType=.js] - File extension
 * @returns {*} filtered file collection
 * @private
 */
function filterFileCollection(files, ignorePattern, fileType){
    if(!fileType){
        fileType = ".js";
    }

    if(typeof ignorePattern === "string"){
        ignorePattern = [ignorePattern];
    }

    return files.filter(function(file){
        if(path.extname(file) === fileType && !patternMatching(file, ignorePattern)){
            return file;
        }
    });
}

/**
 * Load the files from directories
 * @param {String} dir - Path to the directory
 * @param {String | String[]} ignorePattern - Collection of ignore paths
 * @param {String} fileType - Types of files
 * @param {Function} callback - Function to be called after the reading is done.
 * @returns {void}
 * @public
 */
function loadFiles(dir, ignorePattern, fileType, callback){
    nodeDir.files(path.resolve(process.cwd(), dir), function(err, files){
        /* istanbul ignore if */
        if(err){
            console.error(err);
        }
        /* istanbul ignore else */
        else if(callback){
            callback(filterFileCollection(files, ignorePattern, fileType));
        }
    });
}

/**
 * Loads the collection of all the files needed
 * @param {Object} dirCollection - Collection of directories to read
 * @param {String | String[]} ignorePattern - Collection of ignore paths
 * @param {String} fileType - Types of files
 * @param {Function} callback - Function to be called after the reading is done.
 * @returns {void}
 * @public
 */
function loadFileCollection(dirCollection, ignorePattern, fileType, callback){
    var callCounter = 0;
    var finalDirFileCollection = {};

    function updateCollection(key, files){
        if(!finalDirFileCollection[key]){
            finalDirFileCollection[key] = [];
        }
        finalDirFileCollection[key].push(files);
    }

    Object.keys(dirCollection).forEach(function(key){
        var collection = [dirCollection[key]];

        collection = collection.concat.apply([], collection); //flatten the array to single level

        collection.forEach(function(item){
            if(fs.statSync(path.resolve(process.cwd(), item)).isDirectory()){
                callCounter++;
                loadFiles(item, ignorePattern, fileType, function(files){
                    callCounter--;
                    updateCollection(key, files);
                    if(callCounter === 0){
                        callback(finalDirFileCollection);
                    }
                });
            }
            else{
                updateCollection(key, filterFileCollection([path.resolve(process.cwd(), item)], ignorePattern, fileType));
            }
        });
    });
}

module.exports.loadFiles = loadFiles;
module.exports.loadFileCollection = loadFileCollection;


text:
package org.patrickyu.util.vo;

public class MailSender {
	private String email;
	private String name;

	public MailSender() {
	}
	public MailSender(String email) {
		this.setEmail(email);
	}
	public MailSender(String email, String name) {
		this.setEmail(email);
		this.setName(name);
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="fab_margin">16dp</dimen>
    <dimen name="app_bar_height">200dp</dimen>
    <dimen name="item_width">200dp</dimen>
    <dimen name="text_margin">16dp</dimen>
    <dimen name="category_width">40dp</dimen>
    <dimen name="category_height">35dp</dimen>
    <dimen name="category_item_height">100dp</dimen>
    <dimen name="category_right_margin">2dp</dimen>
    <dimen name="category_upper_margin">3dp</dimen>
    <dimen name="tab_width">60dp</dimen>
    <dimen name="category_image_length">75dp</dimen>
</resources>


text:
import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})

export class AppComponent {
    date: any = new jqx.date(2016, 11, 23);

    source: any =
    {
        dataType: 'json',
        dataFields: [
            { name: 'id', type: 'string' },
            { name: 'status', type: 'string' },
            { name: 'about', type: 'string' },
            { name: 'address', type: 'string' },
            { name: 'company', type: 'string' },
            { name: 'name', type: 'string' },
            { name: 'style', type: 'string' },
            { name: 'calendar', type: 'string' },
            { name: 'start', type: 'date', format: 'yyyy-MM-dd HH:mm' },
            { name: 'end', type: 'date', format: 'yyyy-MM-dd HH:mm' }
        ],
        id: 'id',
        url: '../sampledata/appointments.txt'
    };

    dataAdapter: any = new jqx.dataAdapter(this.source);

    appointmentDataFields: any =
    {
        from: 'start',
        to: 'end',
        id: 'id',
        description: 'about',
        location: 'address',
        subject: 'name',
        style: 'style',
        status: 'status'
    };

    views: any[] =
    [
        { type: 'dayView', showWeekends: true, timeRuler: { hidden: false, timeZones: [{ id: 'UTC', text: 'UTC' }, { id: 'Pacific Standard Time', text: 'PST' }] } },
        { type: 'weekView', showWeekends: true, timeRuler: { hidden: false, timeZones: [{ id: 'UTC', text: 'UTC' }, { id: 'Pacific Standard Time', text: 'PST' }] } },
        'monthView'
    ];
}


text: export * from './swagger-ui/swagger-ui.component';


text:
<bill session="110" type="h" number="5396" updated="2009-01-09T04:05:04-05:00">
	<status><introduced date="1202792400" datetime="2008-02-12"/></status>

	<introduced date="1202792400" datetime="2008-02-12"/>
	<titles>
		<title type="official" as="introduced">To designate the Cold War Museum in Fairfax, Virginia, as the National Cold War Museum.</title>
	</titles>
	<sponsor id="400098"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1202792400" datetime="2008-02-12"><text>Referred to the House Committee on Armed Services.</text></action>
		<action date="1204261200" datetime="2008-02-29"><text>Referred to the Subcommittee on Readiness.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	2/12/2008--Introduced.
Designates the Cold War Museum in Fairfax, Virginia, as the "National Cold War Museum."

</bill>


text:
set -e

#####
## See the README for an explanation of what each of these files test.
#####

# These tests should pass
$SAW test-appropriate-overrides.saw
$SAW test-global-initializer.saw
$SAW test-sketchy-overrides-O2.saw

# These tests should fail
! $SAW test-no-init.saw
! $SAW test-sketchy-overrides-O1.saw


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/REC-html401/strict.dtd">

      <title>Text Object Test - Interactive</title>

Text Object Test - Interactive

         The popup window is for reportrs from the different event
         handlers. Click the links below and test the key event handlers
         by entering something in the textfield.
         onblur, onchange, onfocus, onselect.

         Bug, onblur().
         Opera for Linux, Opera 6.02, it doesn't trigger if select() is issued first.
         Onlywhen focus() is issued first. On windows, Opera 6.04, it doesn't
         trigger anyhow.

      <form id="theform" name="theform">
         <input id="thetext" name="thetext"
                type="text"
                onblur="reportEvent( 'onblur' );"
                onchange="reportEvent( 'onchange' );"
                onfocus="reportEvent( 'onfocus' );"
                onselect="reportEvent( 'onselect' );"
                value="This is Text object test text!">
      </form>

User interaction

            Select text

            Remove focus

            Get focus in the textfield


text:
package org.apereo.cas.web.flow;

import org.apereo.cas.authentication.CoreAuthenticationTestUtils;
import org.apereo.cas.mock.MockTicketGrantingTicket;
import org.apereo.cas.services.DefaultRegisteredServiceAcceptableUsagePolicy;
import org.apereo.cas.services.RegisteredServiceTestUtils;
import org.apereo.cas.web.support.WebUtils;

import lombok.val;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.webflow.context.servlet.ServletExternalContext;
import org.springframework.webflow.execution.Action;
import org.springframework.webflow.test.MockRequestContext;

import static org.junit.jupiter.api.Assertions.*;

/**
 * This is {@link AcceptableUsagePolicyVerifyActionTests}.
 *
 * @author Misagh Moayyed
 * @since 5.3.0
 */
@DirtiesContext
@Tag("WebflowActions")
public class AcceptableUsagePolicyVerifyActionTests extends BaseAcceptableUsagePolicyActionTests {

    @Autowired
    @Qualifier("acceptableUsagePolicyVerifyAction")
    private Action acceptableUsagePolicyVerifyAction;

    @Test
    public void verifyAction() throws Exception {
        val context = new MockRequestContext();
        val request = new MockHttpServletRequest();
        context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse()));
        WebUtils.putCredential(context, CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword());
        WebUtils.putTicketGrantingTicketInScopes(context, new MockTicketGrantingTicket("casuser"));
        WebUtils.putAuthentication(CoreAuthenticationTestUtils.getAuthentication(), context);
        assertEquals(CasWebflowConstants.TRANSITION_ID_AUP_MUST_ACCEPT, acceptableUsagePolicyVerifyAction.execute(context).getId());
    }

    @Test
    public void verifyActionWithService() throws Exception {
        val context = new MockRequestContext();
        val request = new MockHttpServletRequest();
        context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse()));
        WebUtils.putCredential(context, CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword());
        WebUtils.putTicketGrantingTicketInScopes(context, new MockTicketGrantingTicket("casuser"));
        WebUtils.putAuthentication(CoreAuthenticationTestUtils.getAuthentication(), context);
        val registeredService = RegisteredServiceTestUtils.getRegisteredService();
        val policy = new DefaultRegisteredServiceAcceptableUsagePolicy();
        policy.setEnabled(false);
        registeredService.setAcceptableUsagePolicy(policy);
        WebUtils.putRegisteredService(context, registeredService);
        assertEquals(CasWebflowConstants.TRANSITION_ID_AUP_ACCEPTED, acceptableUsagePolicyVerifyAction.execute(context).getId());
    }
}


text:
var _typeof = require("next/dist/compiled/@babel/runtime/helpers/typeof")["default"];

var assertThisInitialized = require("./assertThisInitialized.js");

function _possibleConstructorReturn(self, call) {
  if (call && (_typeof(call) === "object" || typeof call === "function")) {
    return call;
  } else if (call !== void 0) {
    throw new TypeError("Derived constructors may only return object or undefined");
  }

  return assertThisInitialized(self);
}

module.exports = _possibleConstructorReturn;
module.exports["default"] = module.exports, module.exports.__esModule = true;


text:
#pragma once

#include "saiga/vision/ba/BABase.h"
#include "saiga/vision/scene/Scene.h"

#include "Recursive.h"

namespace Saiga
{
class SAIGA_VISION_API BAPointOnly : public BABase
{
   public:
    static constexpr int blockSizePoint = 3;
    using T                             = double;

    using DiagType = Eigen::Matrix<T, blockSizePoint, blockSizePoint, Eigen::RowMajor>;
    using ResType  = Eigen::Matrix<T, blockSizePoint, 1>;

    /**
     * Optimize the camera extrinics of all cameras.
     * The world points are kept constant.
     *
     *
     */
    BAPointOnly() : BABase("Point Only BA") {}
    virtual ~BAPointOnly() {}

    virtual void create(Scene& scene) { _scene = &scene; }

    OptimizationOptions optimizationOptions;

    OptimizationResults initAndSolve();

   private:
    int n;
    Scene* _scene;

    AlignedVector<DiagType> diagBlocks;
    AlignedVector<ResType> resBlocks;
    AlignedVector<Vec3> x_v, oldx_v;
    AlignedVector<Vec3> delta_x;

    std::vector<double> chi2_per_point, chi2_per_point_new;
    // ============= Multi Threading Stuff ===========
    int threads = 1;
    std::vector<AlignedVector<DiagType>> diagTemp;
    std::vector<AlignedVector<ResType>> resTemp;
    // ============== LM Functions ==============

    virtual void init();
    OptimizationResults solve();
    virtual double computeQuadraticForm();
    virtual void addLambda(double lambda);
    virtual bool addDelta();
    virtual void solveLinearSystem();
    virtual double computeCost();
    virtual void finalize();

    virtual void setThreadCount(int n) { threads = n; }
    virtual bool supportOMP() { return true; }
};

}  // namespace Saiga


text:
<?php

defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
$year = get_value ( $category, "year", get_current_year () );
$yearEnd = $year + 1;
?>
<tr <?=($action == "insert"?"id='tr-teach_$kTeach'":"");?>>
	<input type="text" name="category" class="<?=$action;?>-category"
		id="category_<?=get_value($category,"kCategory","new");?>"
		value="<?=get_value($category,"category");?>" />
	<input type="text" name="weight" class="<?=$action;?>-weight"
		id="weight_<?=get_value($category,"kCategory","new");?>"
		value="<?=get_value($category,"weight");?>" size="4" />
	<input type="text" name="gradeStart"
		class="<?=$action;?>-gradeStart"
		id="gradeStart_<?=get_value($category,"kCategory","new");?>"
		value="<?=get_value($category,"gradeStart");?>" size="2" />
	<input type="text" name="gradeEnd" class="<?=$action;?>-gradeEnd"
		id="gradeEnd_<?=get_value($category,"kCategory","new");?>"
		value="<?=get_value($category,"gradeEnd");?>" size="2" />

	<?=get_term_menu(sprintf("term_%s",get_value($category,"kCategory","new")), get_value($category,"term",get_current_term()),FALSE,array("classes"=>sprintf("%s-term",$action)));?>

	<?=form_dropdown("year", get_year_list(FALSE,TRUE), $year ,sprintf("id='year_%s' class='year %s-year'",get_value($category,"kCategory","new"),$action)); ?>
	-<input type="text" name="yearEnd" id="yearEnd"
		readonly value="<?=$yearEnd;?>" size="4" />

	<span class="button category-<?=$action;?>"
		id="<?=$action;?>-category_<?=get_value($category,"kCategory",$kTeach,"new");?>"><?=ucfirst($action);?>


text:
circleduino
================

Arduino library for Circular LED bargraph


text:
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new FOS\UserBundle\FOSUserBundle(),
            new Evheniy\MaterializeBundle\MaterializeBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new AppBundle\AppBundle(),
            new FOSChildBundle\FOSChildBundle(),
            new JavierEguiluz\Bundle\EasyAdminBundle\EasyAdminBundle(),
        ];

        if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
            $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    public function getRootDir()
    {
        return __DIR__;
    }

    public function getCacheDir()
    {
        return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
    }

    public function getLogDir()
    {
        return dirname(__DIR__).'/var/logs';
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
    }
}


text:
FROM airdock/base:jessie
MAINTAINER Jerome Guibert <jguibert@gmail.com>

# Add java dynamic memory script
COPY java-dynamic-memory-opts /srv/java/

# Install Oracle JDK 8u25
RUN cd /tmp && \
    curl -L -O -H "Cookie: oraclelicense=accept-securebackup-cookie" -k "http://download.oracle.com/otn-pub/java/jdk/8u25-b17/jdk-8u25-linux-x64.tar.gz" && \
    tar xf jdk-8u25-linux-x64.tar.gz -C /srv/java && \
    rm -f jdk-8u25-linux-x64.tar.gz && \
    ln -s /srv/java/jdk* /srv/java/jdk && \
    ln -s /srv/java/jdk /srv/java/jvm && \
    chown -R java:java /srv/java && \
    /root/post-install

# Define commonly used JAVA_HOME variable
# Add /srv/java and jdk on PATH variable
ENV JAVA_HOME=/srv/java/jdk \
    PATH=${PATH}:/srv/java/jdk/bin:/srv/java


text:
package com.intellij.execution.junit;

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

import javax.annotation.Nonnull;
import com.intellij.openapi.roots.ExternalLibraryDescriptor;

/**
 * @author nik
 */
public abstract class JUnitExternalLibraryDescriptor extends ExternalLibraryDescriptor
{
	public static final ExternalLibraryDescriptor JUNIT3 = new JUnitExternalLibraryDescriptor("3")
	{
		@Nonnull
		@Override
		public List<String> getLibraryClassesRoots()
		{
			return Collections.emptyList();
		}
	};
	public static final ExternalLibraryDescriptor JUNIT4 = new JUnitExternalLibraryDescriptor("4")
	{
		@Nonnull
		@Override
		public List<String> getLibraryClassesRoots()
		{
			return Collections.emptyList();
		}
	};
	public static final ExternalLibraryDescriptor JUNIT5 = new JUnitExternalLibraryDescriptor("org.junit.jupiter", "junit-jupiter-api", "5.0")
	{
		@Nonnull
		@Override
		public List<String> getLibraryClassesRoots()
		{
			return Collections.emptyList();
		}
	};
	private final String myVersion;

	private JUnitExternalLibraryDescriptor(String version)
	{
		this("junit", "junit", version);
	}

	private JUnitExternalLibraryDescriptor(final String groupId, final String artifactId, final String version)
	{
		super(groupId, artifactId, version + ".0", version + ".+");
		myVersion = version;
	}

	@Override
	public String getPresentableName()
	{
		return "JUnit" + myVersion;
	}
}


text:
package com.andyadc.scaffold.showcase.common.enums;

/**
 * 删除状态枚举
 *
 * @author andaicheng
 * @version 2017/2/23
 */
public enum DeletionEnum {
    DELETED(1, "已删除"),
    UNDELETED(0, "未删除");

    private int state;
    private String desc;

    DeletionEnum(int state, String desc) {
        this.state = state;
        this.desc = desc;
    }

    public int getState() {
        return state;
    }

    public String getDesc() {
        return desc;
    }
}


text:
CastleDev Newsletter

Dicas semanais de como destacar sua presença digital

					<form action="//castledev.us16.list-manage.com/subscribe/post?u=4c6a7b6ee15e8fd0e7700919e&id=3250bc1f5e" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

							<input type="hidden" name="b_4c6a7b6ee15e8fd0e7700919e_3250bc1f5e" tabindex="-1" value="">

							<input type="email" value="" name="EMAIL"  id="mce-EMAIL" placeholder="Seu melhor email" required>

							<input type="submit" value="Quero receber!" name="subscribe" id="mc-embedded-subscribe">

					</form>


text:
package com.soulkey.calltalent.utils.rxpreferences;

import android.content.SharedPreferences;
import android.support.annotation.NonNull;

@SuppressWarnings("ALL")
final class LongAdapter implements Preference.Adapter<Long> {
    static final LongAdapter INSTANCE = new LongAdapter();

    @Override
    public Long get(@NonNull String key, @NonNull SharedPreferences preferences) {
        return preferences.getLong(key, 0L);
    }

    @Override
    public void set(@NonNull String key, @NonNull Long value,
                    @NonNull SharedPreferences.Editor editor) {
        editor.putLong(key, value);
    }
}


text:
package io.truthencode.ddo.support.requisite
import io.truthencode.ddo.model.favor.FavorPatron
import io.truthencode.ddo.support.requisite.RequirementImplicits.patronToReq
/**
 * Created by adarr on 2/11/2017.
 */
trait PatronRequisite {

  def anyOfPatron: Seq[(FavorPatron, Int)] = IndexedSeq.apply()

  def allOfPatron: Seq[(FavorPatron, Int)] = IndexedSeq.apply()

  def noneOfPatron: Seq[(FavorPatron, Int)] = IndexedSeq.apply()
}

trait FreePatron extends PatronRequisite with RequiresNone with RequiredExpression with Requisite

trait RequiresAnyOfPatron extends PatronRequisite with RequiresOneOf[Requirement] with Requisite {

  abstract override def oneOf: Seq[Requirement] = super.oneOf ++ {
    anyOfPatron.collect(patronToReq)
  }
}

trait RequiresAllOfPatron extends PatronRequisite with RequiresAllOf[Requirement] with Requisite {

  abstract override def allOf: Seq[Requirement] = super.allOf ++ {
    allOfPatron.collect(patronToReq)
  }
}

trait RequiresNoneOfPatron extends PatronRequisite with RequiresNoneOf[Requirement] with Requisite {

  abstract override def noneOf: Seq[Requirement] = super.noneOf ++ {
    noneOfPatron.collect(patronToReq)
  }
}