text:
using MatterHackers.Agg.Image;
#if !__ANDROID__
using MatterHackers.GuiAutomation;
#endif
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using MatterHackers.Agg.Font;
using MatterHackers.VectorMath;
using NUnit.Framework;
using TestInvoker;

namespace MatterHackers.Agg.UI.Tests
{
#if !__ANDROID__
	[TestFixture, Category("Agg.UI"), Parallelizable(ParallelScope.All)]
#endif
	public class TextEditTests
	{
		public static bool SaveImagesForDebug = false;

		private void OutputImage(ImageBuffer imageToOutput, string fileName)
		{
			if (SaveImagesForDebug)
			{
				var dirAndFileName = Path.Combine("C:/Temp", fileName);
				ImageTgaIO.Save(imageToOutput, dirAndFileName);
			}
		}

		public void SendKeyDown(Keys keyDown, GuiWidget reciever)
		{
			var keyDownEvent = new KeyEventArgs(keyDown);
			reciever.OnKeyDown(keyDownEvent);
		}

		public void SendKey(Keys keyDown, char keyPressed, GuiWidget reciever)
		{
			var keyDownEvent = new KeyEventArgs(keyDown);
			reciever.OnKeyDown(keyDownEvent);
			if (!keyDownEvent.SuppressKeyPress)
			{
				var keyPressEvent = new KeyPressEventArgs(keyPressed);
				reciever.OnKeyPress(keyPressEvent);
			}
		}

		[Test, ChildProcessTest]
		public void CorectLineCounts()
		{
			var lines7 = @"; activate T0
; move up a bit
G91
G1 Z1 F1500
G90
; do the switch to T0
G1 X-29.5 F6000 ; NO_PROCESSING";
			var printer7 = new TypeFacePrinter(lines7);
			Assert.AreEqual(7, printer7.NumLines());

			var lines8 = @"; activate T0
; move up a bit
G91
G1 Z1 F1500
G90
; do the switch to T0
G1 X-29.5 F6000 ; NO_PROCESSING
";
			var printer8 = new TypeFacePrinter(lines8);
			Assert.AreEqual(8, printer8.NumLines());
		}

		[Test, ChildProcessTest]
		public void TextEditTextSelectionTests()
		{
			var container = new GuiWidget
			{
				LocalBounds = new RectangleDouble(0, 0, 200, 200)
			};
			var editField1 = new TextEditWidget("", 0, 0, pixelWidth: 51);
			container.AddChild(editField1);

			// select the control and type something in it
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 0, 0, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 0, 0, 0));
			SendKey(Keys.A, 'a', container);
			Assert.IsTrue(editField1.Text == "a", "It should have a in it.");

			// select the beginning again and type something else in it
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 0, 0, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 0, 0, 0));
			SendKey(Keys.B, 'b', container);
			Assert.IsTrue(editField1.Text == "ba", "It should have ba in it.");

			// select the ba and delete them
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 0, 0, 0));
			container.OnMouseMove(new MouseEventArgs(MouseButtons.Left, 0, 15, 0, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 15, 0, 0));
			SendKey(Keys.Back, ' ', container);
			Assert.IsTrue(editField1.Text == "", "It should have nothing in it.");

			// select the other way
			editField1.Text = "ab";
			Assert.IsTrue(editField1.Text == "ab", "It should have ab in it.");
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 15, 0, 0));
			container.OnMouseMove(new MouseEventArgs(MouseButtons.Left, 0, 0, 0, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 0, 0, 0));
			SendKey(Keys.Back, ' ', container);
			Assert.IsTrue(editField1.Text == "", "It should have nothing in it.");

			// select the other way but start far to the right
			editField1.Text = "abc";
			Assert.IsTrue(editField1.Text == "abc", "It should have abc in it.");
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 30, 0, 0));
			container.OnMouseMove(new MouseEventArgs(MouseButtons.Left, 0, 0, 0, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 0, 0, 0));
			SendKey(Keys.Back, ' ', container);
			Assert.IsTrue(editField1.Text == "", "It should have nothing in it.");

			// double click empty does nothing
			// select the other way but start far to the right
			editField1.Text = "";
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 1, 0, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 0, 0, 0));
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 2, 1, 0, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 0, 0, 0));
			Assert.AreEqual("", editField1.Selection, "First word selected");

			// double click first word selects
			editField1.Text = "abc 123";
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 1, 0, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 0, 0, 0));
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 2, 1, 0, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 0, 0, 0));
			Assert.AreEqual("abc", editField1.Selection, "First word selected");

			// double click last word selects
			editField1.Text = "abc 123";
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 30, 0, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 0, 0, 0));
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 2, 30, 0, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 0, 0, 0));
			Assert.AreEqual("123", editField1.Selection, "Second word selected");

			container.Close();
		}

		[Test, ChildProcessTest]
		public void TextSelectionWithShiftClick()
		{
			const string fullText = "This is a text";

			var container = new GuiWidget(200, 200);
			var editField1 = new TextEditWidget(fullText, pixelWidth: 100);
			container.AddChild(editField1);

			// select all from left to right with shift click
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 1, 0, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 1, 0, 0));
			Assert.AreEqual(0, editField1.CharIndexToInsertBefore);
			Assert.AreEqual("", editField1.Selection);
			Keyboard.SetKeyDownState(Keys.Shift, true);
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 100, 0, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 100, 0, 0));
			Keyboard.SetKeyDownState(Keys.Shift, false);
			Assert.AreEqual(fullText.Length, editField1.CharIndexToInsertBefore);
			Assert.AreEqual(fullText, editField1.Selection, "It should select full text");

			// select all from right to left with shift click
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 100, 0, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 100, 0, 0));
			Assert.AreEqual(fullText.Length, editField1.CharIndexToInsertBefore);
			Assert.AreEqual("", editField1.Selection);
			Keyboard.SetKeyDownState(Keys.Shift, true);
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 1, 0, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 1, 0, 0));
			Keyboard.SetKeyDownState(Keys.Shift, false);
			Assert.AreEqual(0, editField1.CharIndexToInsertBefore);
			Assert.AreEqual(fullText, editField1.Selection, "It should select full text");

			// select parts of the text with shift click
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 1, 0, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 1, 0, 0));
			SendKey(Keys.Control | Keys.Right, ' ', container);
			SendKey(Keys.Control | Keys.Right, ' ', container);
			Assert.AreEqual("This is ".Length, editField1.CharIndexToInsertBefore);
			Assert.AreEqual("", editField1.Selection);
			Keyboard.SetKeyDownState(Keys.Shift, true);
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 100, 0, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 100, 0, 0));
			Keyboard.SetKeyDownState(Keys.Shift, false);
			Assert.AreEqual(fullText.Length, editField1.CharIndexToInsertBefore);
			Assert.AreEqual("a text", editField1.Selection, "It should select second part of the text");
			Keyboard.SetKeyDownState(Keys.Shift, true);
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 1, 0, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 1, 0, 0));
			Keyboard.SetKeyDownState(Keys.Shift, false);
			Assert.AreEqual(0, editField1.CharIndexToInsertBefore);
			Assert.AreEqual("This is ", editField1.Selection, "It should select first part of the text");

			container.Close();
		}

		[Test, ChildProcessTest]
		public void TextChangedEventsTests()
		{
			var container = new GuiWidget
			{
				Name = "container",
				LocalBounds = new RectangleDouble(0, 0, 200, 200)
			};
			var editField1 = new TextEditWidget("", 0, 0, pixelWidth: 20)
			{
				Name = "editField1"
			};
			Assert.IsTrue(editField1.BoundsRelativeToParent.Top < 40, "We make this assumption in the code below, so make sure it's true.");
			bool textField1EditComplete = false;
			editField1.EditComplete += (sender, e) => { textField1EditComplete = true; };
			bool textField1LostFocus = false;
			bool textField1GotFocus = false;
			editField1.ContainsFocusChanged += (sender, e) =>
			{
				if ((sender as GuiWidget) != null
					&& (sender as GuiWidget).ContainsFocus)
				{
					textField1GotFocus = true;
				}
				else
				{
					textField1LostFocus = true;
				}
			};
			container.AddChild(editField1);

			var editField2 = new TextEditWidget("", 0, 40, pixelWidth: 20)
			{
				Name = "editField2"
			};
			container.AddChild(editField2);

			// mouse select on the control when it contains nothing
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 1, 1, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 1, 1, 0));
			Assert.IsTrue(textField1GotFocus);
			Assert.IsFalse(textField1EditComplete);
			SendKey(Keys.B, 'b', container);
			Assert.IsTrue(editField1.Text == "b");
			Assert.IsFalse(textField1EditComplete, "We do not change with each keystroke.");
			SendKey(Keys.Enter, '\n', container);
			Assert.IsTrue(textField1EditComplete, "Enter must send a EditComplete if changed.");
			textField1EditComplete = false;
			SendKey(Keys.A, 'a', container);
			Assert.IsTrue(editField1.Text == "ba");
			Assert.IsFalse(textField1EditComplete, "We do not change with each keystroke.");

			Assert.IsFalse(textField1LostFocus);
			textField1GotFocus = false;
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 1, 41, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 1, 1, 0));
			SendKey(Keys.E, 'e', container);
			Assert.IsTrue(textField1LostFocus);
			Assert.IsTrue(textField1EditComplete, "Loosing focus should send a text changed.");
			Assert.IsTrue(editField1.Text == "ba");
			Assert.IsTrue(editField2.Text == "e");

			textField1EditComplete = false;
			textField1LostFocus = false;
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 1, 1, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 1, 1, 0));
			Assert.IsFalse(textField1LostFocus);
			Assert.IsFalse(textField1EditComplete);
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 1, 41, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 1, 1, 0));
			Assert.IsTrue(textField1LostFocus);
			Assert.IsFalse(textField1EditComplete, "The text did not change even though we lost focus we should not call textChanged.");

			container.Close();
		}

		[Test, ChildProcessTest]
		public void TextEditGetsFocusTests()
		{
			var container = new GuiWidget
			{
				Name = "container",
				LocalBounds = new RectangleDouble(0, 0, 200, 200)
			};
			var editField1 = new TextEditWidget("", 0, 0, pixelWidth: 160)
			{
				Name = "editField1"
			};
			container.AddChild(editField1);

			var editField2 = new TextEditWidget("", 0, 20, pixelWidth: 160)
			{
				Name = "editField2"
			};
			container.AddChild(editField2);

			// select no edit field
			Assert.IsTrue(editField1.Text == "");
			SendKey(Keys.D, 'a', container);
			Assert.IsTrue(editField1.Text == "");
			Assert.IsTrue(editField2.Text == "");

			// select edit field 1
			container.OnMouseMove(new MouseEventArgs(MouseButtons.Left, 1, 1, 1, 0)); // we move into the widget to make sure we have separate focus and enter events.
			Assert.IsTrue(editField1.ContainsFocus == false);
			Assert.IsTrue(editField1.Focused == false);
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 1, 1, 0));
			Assert.IsTrue(editField1.ContainsFocus == true);
			Assert.IsTrue(editField1.Focused == false, "The internal text widget must be focused.");
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 1, 1, 1, 0));
			Assert.IsTrue(editField1.ContainsFocus == true);
			Assert.IsTrue(editField1.Focused == false);
			SendKey(Keys.B, 'b', container);
			Assert.IsTrue(editField1.Text == "b", "It should have b a in it.");
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 150, 1, 0));
			Assert.IsTrue(editField1.ContainsFocus == true);
			Assert.IsTrue(editField1.Focused == false, "The internal text widget must be focused.");
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 1, 150, 1, 0));
			Assert.IsTrue(editField1.ContainsFocus == true);
			Assert.IsTrue(editField1.Focused == false);
			SendKey(Keys.D, 'c', container);
			Assert.IsTrue(editField1.Text == "bc", "It should have b a in it.");

			// select edit field 2
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 1, 21, 0));
			Assert.IsTrue(editField2.ContainsFocus == true);
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 1, 1, 21, 0));
			SendKey(Keys.D, 'd', container);
			Assert.IsTrue(editField1.Text == "bc", "It should have a bc in it.");
			Assert.IsTrue(editField2.Text == "d", "It should have d in it.");

			container.Close();
		}

		[Test, ChildProcessTest]
		public void AddThenDeleteCausesNoVisualChange()
		{
			var container = new GuiWidget
			{
				DoubleBuffer = true,
				LocalBounds = new RectangleDouble(0, 0, 200, 200)
			};
			var editField1 = new TextEditWidget("Test", 10, 10, pixelWidth: 50);
			container.AddChild(editField1);
			container.BackBuffer.NewGraphics2D().Clear(Color.White);
			container.OnDraw(container.BackBuffer.NewGraphics2D());
			var beforeEditImage = new ImageBuffer(container.BackBuffer);
			RectangleDouble beforeLocalBounds = editField1.LocalBounds;
			Vector2 beforeOrigin = editField1.OriginRelativeParent;

			OutputImage(beforeEditImage, "z text un-edited.tga");

			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 10, 10, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 1, 10, 10, 0));
			Assert.IsTrue(editField1.ContainsFocus == true);
			SendKey(Keys.B, 'b', container);
			Assert.IsTrue(editField1.Text == "bTest", "It should have b a in it.");
			RectangleDouble afterBLocalBounds = editField1.LocalBounds;
			Assert.IsTrue(beforeLocalBounds.Bottom == afterBLocalBounds.Bottom && beforeLocalBounds.Top == afterBLocalBounds.Top);

			SendKey(Keys.Back, ' ', container);
			Assert.IsTrue(editField1.Text == "Test", "It should not have b a in it.");

			RectangleDouble afterLocalBounds = editField1.LocalBounds;
			Vector2 afterOrigin = editField1.OriginRelativeParent;

			Assert.IsTrue(beforeLocalBounds == afterLocalBounds);
			Assert.IsTrue(beforeOrigin == afterOrigin);

			// click off it so the cursor is not in it.
			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 1, 1, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 1, 1, 1, 0));
			Assert.IsTrue(editField1.Focused == false);

			container.BackBuffer.NewGraphics2D().Clear(Color.White);
			container.OnDraw(container.BackBuffer.NewGraphics2D());
			OutputImage(container.BackBuffer, "z text edited.tga");

			Assert.IsTrue(container.BackBuffer == beforeEditImage);
		}

		[Test, ChildProcessTest]
		public void MultiLineTests()
		{
			// make sure selection ranges are always working
			{
				Clipboard.SetSystemClipboard(new SimulatedClipboard());

				var singleLine = new InternalTextEditWidget("test", 12, false, 0);

				void TestRange(int start, int end, string expected)
				{
					singleLine.CharIndexToInsertBefore = start;
					singleLine.SelectionIndexToStartBefore = end;
					singleLine.Selecting = true;
					Assert.AreEqual(expected, singleLine.Selection);
					singleLine.CopySelection();

					Assert.AreEqual(expected, Clipboard.Instance.GetText());
				}

				// ask for some selections
				TestRange(-10, -8, "");
				TestRange(-8, -10, "");
				TestRange(18, 10, "");
				TestRange(10, 18, "");
				TestRange(2, -10, "te");
				TestRange(-10, 2, "te");
				TestRange(18, 2, "st");
				TestRange(3, 22, "t");
			}

			{
				var singleLine = new InternalTextEditWidget("test", 12, false, 0);
				var multiLine = new InternalTextEditWidget("test\ntest\ntest", 12, true, 0);
				Assert.IsTrue(multiLine.Height >= singleLine.Height * 3);
			}

			// we get the typed results we expect
			{
				var container = new GuiWidget
				{
					LocalBounds = new RectangleDouble(0, 0, 200, 200)
				};
				var multiLine = new InternalTextEditWidget("\n\n\n\n", 12, true, 0);
				container.AddChild(multiLine);

				container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 1, 1, 0));
				container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 1, 1, 1, 0));
				Assert.IsTrue(multiLine.ContainsFocus == true);
				Assert.IsTrue(multiLine.SelectionIndexToStartBefore == 4);
				Assert.IsTrue(multiLine.Text == "\n\n\n\n");
				SendKey(Keys.A, 'a', container);
				Assert.IsTrue(multiLine.Text == "\n\n\n\na");
				SendKey(Keys.Up, ' ', container);
				SendKey(Keys.A, 'a', container);
				Assert.IsTrue(multiLine.Text == "\n\n\na\na");

				container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 1, multiLine.Height - 1, 0));
				container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 1, 1, multiLine.Height - 1, 0));
				Assert.IsTrue(multiLine.ContainsFocus == true);
				Assert.IsTrue(multiLine.SelectionIndexToStartBefore == 0);
				Assert.IsTrue(multiLine.Text == "\n\n\na\na");
				SendKey(Keys.A, 'a', container);
				Assert.IsTrue(multiLine.Text == "a\n\n\na\na");
				SendKey(Keys.Down, ' ', container);
				SendKey(Keys.A | Keys.Shift, 'A', container);
				Assert.IsTrue(multiLine.Text == "a\nA\n\na\na");

				container.Close();
			}

			// make sure the insert position is correct when homed
			{
				var container = new GuiWidget
				{
					LocalBounds = new RectangleDouble(0, 0, 200, 200)
				};
				var multiLine = new InternalTextEditWidget("line1\nline2\nline3", 12, true, 0);
				container.AddChild(multiLine);

				container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 5, 1, 0));
				container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 1, 5, 1, 0));
				Assert.IsTrue(multiLine.ContainsFocus == true);
				Assert.IsTrue(multiLine.InsertBarPosition.Y == -32);
				SendKey(Keys.Home, ' ', container);
				Assert.IsTrue(multiLine.InsertBarPosition.Y == -32);
				Assert.IsTrue(multiLine.Text == "line1\nline2\nline3");
				SendKey(Keys.A, 'a', container);
				Assert.IsTrue(multiLine.Text == "line1\nline2\naline3");
				SendKey(Keys.Back, ' ', container);
				Assert.IsTrue(multiLine.Text == "line1\nline2\nline3");
				Assert.IsTrue(multiLine.InsertBarPosition.Y == -32);
				container.Close();
			}

			// make sure the insert position is correct when move left to end of line
			{
				var container = new GuiWidget
				{
					LocalBounds = new RectangleDouble(0, 0, 200, 200)
				};
				var multiLine = new InternalTextEditWidget("xx", 12, true, 0);
				container.AddChild(multiLine);

				container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 1, 1, 0));
				container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 1, 1, 1, 0));
				Assert.IsTrue(multiLine.ContainsFocus == true);
				Assert.IsTrue(multiLine.CharIndexToInsertBefore == 0);
				Assert.IsTrue(multiLine.InsertBarPosition.X == 0);
				SendKey(Keys.Home, ' ', container);
				Assert.IsTrue(multiLine.CharIndexToInsertBefore == 0);
				Assert.IsTrue(multiLine.InsertBarPosition.X == 0);
				SendKey(Keys.Right, ' ', container);
				Assert.IsTrue(multiLine.CharIndexToInsertBefore == 1);
				double leftOne = multiLine.InsertBarPosition.X;
				SendKey(Keys.Right, ' ', container);
				Assert.IsTrue(multiLine.CharIndexToInsertBefore == 2);
				Assert.IsTrue(multiLine.InsertBarPosition.X == leftOne * 2);
				container.Close();
			}

			// make sure the cursor is at the right hight when it is after a \n that is on the first line
			{
				var container = new GuiWidget
				{
					DoubleBuffer = true,
					LocalBounds = new RectangleDouble(0, 0, 200, 200)
				};
				var multiLine = new InternalTextEditWidget("\n1\n\n3\n", 12, true, 0);
				Assert.IsTrue(multiLine.LocalBounds.Height == 16 * 5);
				container.AddChild(multiLine);

				container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 1, multiLine.Height - 1, 0));
				container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 1, 1, multiLine.Height - 1, 0));

				Assert.IsTrue(multiLine.CharIndexToInsertBefore == 0);
				Assert.IsTrue(multiLine.InsertBarPosition.Y == 0);

				// move past \n
				SendKey(Keys.Right, ' ', container);
				Assert.IsTrue(multiLine.CharIndexToInsertBefore == 1);
				Assert.IsTrue(multiLine.InsertBarPosition.Y == -16);

				// move past 1
				SendKey(Keys.Right, ' ', container);
				Assert.IsTrue(multiLine.CharIndexToInsertBefore == 2);
				Assert.IsTrue(multiLine.InsertBarPosition.Y == -16);

				// move past \n
				SendKey(Keys.Right, ' ', container);
				Assert.IsTrue(multiLine.CharIndexToInsertBefore == 3);
				Assert.IsTrue(multiLine.InsertBarPosition.Y == -32);

				// move past \n
				SendKey(Keys.Right, ' ', container);
				Assert.IsTrue(multiLine.CharIndexToInsertBefore == 4);
				Assert.IsTrue(multiLine.InsertBarPosition.Y == -48);

				// move past 3
				SendKey(Keys.Right, ' ', container);
				Assert.IsTrue(multiLine.CharIndexToInsertBefore == 5);
				Assert.IsTrue(multiLine.InsertBarPosition.Y == -48);

				// move past \n
				SendKey(Keys.Right, ' ', container);
				Assert.IsTrue(multiLine.CharIndexToInsertBefore == 6);
				Assert.IsTrue(multiLine.InsertBarPosition.Y == -64);
				container.Close();
			}
		}

		[Test, ChildProcessTest]
		public void NumEditHandlesNonNumberChars()
		{
			var container = new GuiWidget
			{
				DoubleBuffer = true,
				LocalBounds = new RectangleDouble(0, 0, 200, 200)
			};
			var numberEdit = new NumberEdit(0, 0, 0, 12, 200, 16, true, true);
			container.AddChild(numberEdit);

			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 1, numberEdit.Height - 1, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 1, 1, numberEdit.Height - 1, 0));

			Assert.IsTrue(numberEdit.CharIndexToInsertBefore == 0);
			Assert.IsTrue(numberEdit.TopLeftOffset.Y == 0);

			// type a . (non numeric character)
			SendKey(Keys.Back, ' ', container);
			SendKey(Keys.Delete, ' ', container);
			SendKey(Keys.OemMinus, '-', container);
			Assert.IsTrue(numberEdit.Value == 0);
			SendKey(Keys.OemPeriod, '.', container);
			Assert.IsTrue(numberEdit.Value == 0);
			SendKey(Keys.D0, '.', container);
			Assert.IsTrue(numberEdit.Value == 0);
			SendKey(Keys.A, 'A', container);
			Assert.IsTrue(numberEdit.Value == 0);

			container.Close();
		}

#if __ANDROID__
		[Test, ChildProcessTest]
#else
		[Test, ChildProcessTest]
#endif
		public void TextEditingSpecialKeysWork()
		{
			var container = new GuiWidget
			{
				DoubleBuffer = true,
				LocalBounds = new RectangleDouble(0, 0, 200, 200)
			};
			var textEdit = new TextEditWidget("some starting text");
			container.AddChild(textEdit);

			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 1, textEdit.Height - 1, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 1, 1, textEdit.Height - 1, 0));

			Assert.IsTrue(textEdit.CharIndexToInsertBefore == 0);
			Assert.IsTrue(textEdit.TopLeftOffset.Y == 0);

			// test that we move to the next character correctly
			Assert.AreEqual(4, InternalTextEditWidget.IndexOfNextToken("235 12/6", 0));
			Assert.AreEqual(6, InternalTextEditWidget.IndexOfNextToken("235   12/6", 0));
			Assert.AreEqual(3, InternalTextEditWidget.IndexOfNextToken("235\n   12/6", 0));
			Assert.AreEqual(7, InternalTextEditWidget.IndexOfNextToken("235\n   12/6", 3));
			Assert.AreEqual(4, InternalTextEditWidget.IndexOfNextToken("235\n\n   12/6", 3));
			Assert.AreEqual(8, InternalTextEditWidget.IndexOfNextToken("235\n\n   12/6", 4));
			Assert.AreEqual(3, InternalTextEditWidget.IndexOfNextToken("123+ 235   12/6", 0));
			Assert.AreEqual(3, InternalTextEditWidget.IndexOfNextToken("235+12/6", 0));
			Assert.AreEqual(5, InternalTextEditWidget.IndexOfNextToken("+++++235   12/6", 0));
			Assert.AreEqual(5, InternalTextEditWidget.IndexOfNextToken("+++++235   12/6", 0));

			// test that we move to the previous character correctly
			Assert.AreEqual(7, InternalTextEditWidget.IndexOfPreviousToken("=35+12/6", 8));
			Assert.AreEqual(6, InternalTextEditWidget.IndexOfPreviousToken("35556+68384734", 10));
			Assert.AreEqual(5, InternalTextEditWidget.IndexOfPreviousToken("35556+68384734", 6));
			Assert.AreEqual(0, InternalTextEditWidget.IndexOfPreviousToken("35556+68384734", 5));

			Assert.AreEqual(11, InternalTextEditWidget.IndexOfPreviousToken("235\n\n   12/6", 12));
			Assert.AreEqual(10, InternalTextEditWidget.IndexOfPreviousToken("235\n\n   12/6", 11));
			Assert.AreEqual(8, InternalTextEditWidget.IndexOfPreviousToken("235\n\n   12/6", 10));
			Assert.AreEqual(5, InternalTextEditWidget.IndexOfPreviousToken("235\n\n   12/6", 8));
			Assert.AreEqual(4, InternalTextEditWidget.IndexOfPreviousToken("235\n\n   12/6", 5));
			Assert.AreEqual(0, InternalTextEditWidget.IndexOfPreviousToken("235\n\n   12/6", 4));
			Assert.AreEqual(0, InternalTextEditWidget.IndexOfPreviousToken("some starting text", 5));

			void RunWithSpecificChar(string sep, string first, string second, string third)
			{
				var startText = $"{first}{sep}{second}{sep}{third}";
				Assert.IsTrue(textEdit.Text == startText);
				// this is to select some text
				SendKey(Keys.Shift | Keys.Control | Keys.Right, ' ', container);
				Assert.IsTrue(textEdit.Selection == first+sep);
				Assert.IsTrue(textEdit.Text == startText);
				// this is to prove that we don't loose the selection when pressing Control
				SendKeyDown(Keys.Control, container);
				Assert.IsTrue(textEdit.Selection == first + sep);
				Assert.IsTrue(textEdit.Text == startText);
				// this is to prove that we don't loose the selection when pressing Shift
				SendKeyDown(Keys.Shift, container);
				Assert.IsTrue(textEdit.Text == startText);
				Assert.IsTrue(textEdit.Selection == first + sep);
				SendKeyDown(Keys.Right, container);
				Assert.IsTrue(textEdit.Selection == "");
				SendKey(Keys.Shift | Keys.Control | Keys.Left, ' ', container);
				Assert.IsTrue(textEdit.Selection == first + sep);
				SendKey(Keys.Delete, ' ', container);
				Assert.IsTrue(textEdit.Text == $"{second}{sep}{third}");
				SendKey(Keys.Shift | Keys.Control | Keys.Right, ' ', container);
				Assert.IsTrue(textEdit.Selection == $"{second}{sep}");

				// if this fails add
				// GuiHalWidget.SetClipboardFunctions(System.Windows.Forms.Clipboard.GetText, System.Windows.Forms.Clipboard.SetText, System.Windows.Forms.Clipboard.ContainsText);
				// before you call the unit tests
				Clipboard.SetSystemClipboard(new WindowsFormsClipboard());

				SendKey(Keys.Control | Keys.C, 'c', container);
				Assert.IsTrue(textEdit.Selection == $"{second}{sep}");
				Assert.IsTrue(textEdit.Text == $"{second}{sep}{third}");
				SendKeyDown(Keys.Right, container); // move to the right
				SendKey(Keys.Control | Keys.V, 'v', container);
				Assert.IsTrue(textEdit.Text == $"{second}{sep}{second}{sep}{third}");
			}

			void CheckChar(string sep)
			{
				textEdit.Text = $"some{sep}starting{sep}text";
				// spaces work as expected
				RunWithSpecificChar(sep, "some", "starting", "text");
				textEdit.Text = $"123{sep}is{sep}number";
				RunWithSpecificChar(sep, "123", "is", "number");
				textEdit.Text = $"123_1{sep}456_2{sep}789_3";
				RunWithSpecificChar(sep, "123_1", "456_2", "789_3");
			}

			CheckChar(" ");

			container.Close();
		}

		[Test, ChildProcessTest]
		public void ScrollingToEndShowsEnd()
		{
			var container = new GuiWidget
			{
				DoubleBuffer = true,
				LocalBounds = new RectangleDouble(0, 0, 110, 30)
			};
			var editField1 = new TextEditWidget("This is a nice long text string", 0, 0, pixelWidth: 100);
			container.AddChild(editField1);

			var firstWordText = new TextWidget("This");
			RectangleDouble bounds = firstWordText.LocalBounds;
			bounds.Offset(bounds.Left, bounds.Bottom);
			firstWordText.LocalBounds = bounds;

			firstWordText.BackBuffer.NewGraphics2D().Clear(Color.White);
			firstWordText.OnDraw(firstWordText.BackBuffer.NewGraphics2D());
			var lastWordText = new TextWidget("string");

			bounds = lastWordText.LocalBounds;
			bounds.Offset(bounds.Left, bounds.Bottom);
			lastWordText.LocalBounds = bounds;

			lastWordText.BackBuffer.NewGraphics2D().Clear(Color.White);
			lastWordText.OnDraw(lastWordText.BackBuffer.NewGraphics2D());
			container.BackBuffer.NewGraphics2D().Clear(Color.White);
			container.BackgroundColor = Color.White;

			container.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, 1, 1, 0));
			container.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 1, 1, 0));
			Assert.IsTrue(editField1.ContainsFocus == true);

			container.OnDraw(container.BackBuffer.NewGraphics2D());
			OutputImage(firstWordText.BackBuffer, "Control - Left.tga");
			OutputImage(lastWordText.BackBuffer, "Control - Right.tga");
			OutputImage(container.BackBuffer, "Test - Start.tga");
			container.BackBuffer.FindLeastSquaresMatch(firstWordText.BackBuffer, out _, out double bestLeastSquares);
			Assert.IsTrue(bestLeastSquares < 2000000);
			container.BackBuffer.FindLeastSquaresMatch(lastWordText.BackBuffer, out _, out bestLeastSquares);
			Assert.IsTrue(bestLeastSquares > 2000000);

			SendKeyDown(Keys.End, container);

			container.OnDraw(container.BackBuffer.NewGraphics2D());
			OutputImage(container.BackBuffer, "Test - Scrolled.tga");

			container.BackBuffer.FindLeastSquaresMatch(firstWordText.BackBuffer, out _, out bestLeastSquares);
			Assert.IsTrue(bestLeastSquares > 2000000);
			container.BackBuffer.FindLeastSquaresMatch(lastWordText.BackBuffer, out _, out bestLeastSquares);
			Assert.IsTrue(bestLeastSquares < 2000000);

			container.Close();
		}
	}

#if !__ANDROID__
	[TestFixture, Category("Agg.UI"), Parallelizable(ParallelScope.All)]
	public class TextEditFocusTests
	{
		[Test, ChildProcessTest]
		public async Task VerifyFocusMakesTextWidgetEditable()
		{
			TextEditWidget editField = null;
			var systemWindow = new SystemWindow(300, 200)
			{
				BackgroundColor = Color.Black,
			};

			Task TestToRun(AutomationRunner testRunner)
			{
				UiThread.RunOnIdle(editField.Focus);

				testRunner.Type("Test Text");

				testRunner.Delay(1);
				Assert.IsTrue(editField.Text == "Test Text", "validate text is typed");

				return Task.CompletedTask;
			}

			editField = new TextEditWidget(pixelWidth: 200)
			{
				HAnchor = HAnchor.Center,
				VAnchor = VAnchor.Center,
			};
			systemWindow.AddChild(editField);

			await AutomationRunner.ShowWindowAndExecuteTests(systemWindow, TestToRun);
		}

		[Test, ChildProcessTest]
		public async Task VerifyFocusProperty()
		{
			var systemWindow = new SystemWindow(300, 200)
			{
				BackgroundColor = Color.Black,
			};

			var editField = new TextEditWidget(pixelWidth: 200)
			{
				HAnchor = HAnchor.Center,
				VAnchor = VAnchor.Center,
			};
			systemWindow.AddChild(editField);

			Task TestToRun(AutomationRunner testRunner)
			{
				UiThread.RunOnIdle(editField.Focus);
				testRunner.WaitFor(() => editField.ContainsFocus);
				//if (!editField.ContainsFocus) { System.Diagnostics.Debugger.Launch(); System.Diagnostics.Debugger.Break(); }
				// NOTE: Okay. During parallel testing, it seems that the avalanche of windows causes test UIs to lose control focus and get confused.
				Assert.IsTrue(editField.ContainsFocus, "Focused property should be true after invoking Focus method");

				return Task.CompletedTask;
			}

			await AutomationRunner.ShowWindowAndExecuteTests(systemWindow, TestToRun);
		}

		[Test, ChildProcessTest]
		public async Task SelectAllOnFocusCanStillClickAfterSelection()
		{
			var editField = new TextEditWidget(pixelWidth: 200)
			{
				Name = "editField",
				Text = "Some Text",
				HAnchor = HAnchor.Center,
				VAnchor = VAnchor.Center,
			};

			var systemWindow = new SystemWindow(300, 200)
			{
				BackgroundColor = Color.Gray,
			};
			systemWindow.AddChild(editField);

			Task TestToRun(AutomationRunner testRunner)
			{
				editField.SelectAllOnFocus = true;
				testRunner.Delay(1);
				testRunner.ClickByName(editField.Name);

				editField.SelectAllOnFocus = true;
				testRunner.Type("123");
				Assert.AreEqual("123", editField.Text, "Text input on newly focused control should replace selection");

				testRunner.ClickByName(editField.Name);
				//testRunner.WaitFor(() => editField.ContainsFocus);

				testRunner.Type("123");
				//testRunner.WaitFor(() => "123123" == editField.Text, maxSeconds: 60);
				// NOTE: Used to get intermittent failures here. These issues might have been sorted out now.
				Assert.AreEqual("123123", editField.Text, "Text should be appended if control is focused and has already received input");

				return Task.CompletedTask;
			}

			await AutomationRunner.ShowWindowAndExecuteTests(systemWindow, TestToRun);
		}
	}
#endif
}


text:
package stripper_test

import (
	"io"
	"os"
	"strings"

	"github.com/docker-library/go-dockerlibrary/pkg/stripper"
)

func ExampleCommentStripper() {
	r := strings.NewReader(`
# opening comment
a: b
# comment!
c: d # not a comment

# another cheeky comment
e: f
`)

	comStrip := stripper.NewCommentStripper(r)

	// using CopyBuffer to force smaller Read sizes (better testing coverage that way)
	io.CopyBuffer(os.Stdout, comStrip, make([]byte, 32))

	// Output:
	// a: b
	// c: d # not a comment
	//
	// e: f
}

redpajama_set_name: RedPajamaGithub


text:
alter table ACT_RE_PROCDEF
    MODIFY KEY_ varchar(255) not null;

alter table ACT_RE_PROCDEF
    MODIFY VERSION_ integer not null;

-- https://activiti.atlassian.net/browse/ACT-1424
alter table ACT_RU_JOB
    MODIFY LOCK_EXP_TIME_ timestamp null;

alter table ACT_RE_DEPLOYMENT
    add CATEGORY_ varchar(255);

alter table ACT_RE_PROCDEF
    add DESCRIPTION_ varchar(4000);

alter table ACT_RU_TASK
    add SUSPENSION_STATE_ integer;

update ACT_RU_TASK set SUSPENSION_STATE_ = 1;

alter table ACT_RU_EXECUTION
    add constraint ACT_FK_EXE_PROCDEF
    foreign key (PROC_DEF_ID_)
    references ACT_RE_PROCDEF (ID_);

create table ACT_RE_MODEL (
    ID_ varchar(64) not null,
    REV_ integer,
    NAME_ varchar(255),
    KEY_ varchar(255),
    CATEGORY_ varchar(255),
    CREATE_TIME_ timestamp null,
    LAST_UPDATE_TIME_ timestamp null,
    VERSION_ integer,
    META_INFO_ varchar(4000),
    DEPLOYMENT_ID_ varchar(64),
    EDITOR_SOURCE_VALUE_ID_ varchar(64),
    EDITOR_SOURCE_EXTRA_VALUE_ID_ varchar(64),
    primary key (ID_)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_bin;

alter table ACT_RE_MODEL
    add constraint ACT_FK_MODEL_SOURCE
    foreign key (EDITOR_SOURCE_VALUE_ID_)
    references ACT_GE_BYTEARRAY (ID_);

alter table ACT_RE_MODEL
    add constraint ACT_FK_MODEL_SOURCE_EXTRA
    foreign key (EDITOR_SOURCE_EXTRA_VALUE_ID_)
    references ACT_GE_BYTEARRAY (ID_);

alter table ACT_RE_MODEL
    add constraint ACT_FK_MODEL_DEPLOYMENT
    foreign key (DEPLOYMENT_ID_)
    references ACT_RE_DEPLOYMENT (ID_);

delete from ACT_GE_PROPERTY where NAME_ = 'historyLevel';

alter table ACT_RU_JOB
    add PROC_DEF_ID_ varchar(64);

update ACT_GE_PROPERTY set VALUE_ = '5.11' where NAME_ = 'schema.version';


text:
<!--
  JS selector for site.
-->

<!-- layout specified -->

{% if page.layout == 'post' %}
  {% if site.google_analytics.pv.proxy_endpoint or site.google_analytics.pv.cache_path %}
    <!-- pv-report needs countup.js -->
    <script async src="https://cdn.jsdelivr.net/npm/countup.js@1.9.3/dist/countUp.min.js"></script>
    <script defer src="{{ '/assets/js/dist/pvreport.min.js' | relative_url }}"></script>
  {% endif %}
{% endif %}

{% if page.layout == 'post' or page.layout == 'page' %}
  <!-- image lazy-loading & popup -->
  <script src="https://cdn.jsdelivr.net/combine/npm/lozad/dist/lozad.min.js,npm/magnific-popup@1/dist/jquery.magnific-popup.min.js,npm/clipboard@2/dist/clipboard.min.js"></script>
{% endif %}

{% if page.layout == 'home'
    or page.layout == 'categories'
    or page.layout == 'post'
    or page.layout == 'page' %}
  {% assign type = page.layout %}
{% else %}
  {% assign type = "commons" %}
{% endif %}

{% assign js = type | prepend: '/assets/js/dist/' | append: '.min.js' %}
<script defer src="{{ js | relative_url }}"></script>

{% if page.math %}
  <!-- MathJax -->
  <script>
  /* see: <https://docs.mathjax.org/en/latest/options/input/tex.html#tex-options> */
  MathJax = {
    tex: {
      inlineMath: [              /* start/end delimiter pairs for in-line math */
        ['$','$'],
        ['\\(','\\)']
      ],
      displayMath: [             /* start/end delimiter pairs for display math */
        ['$$', '$$'],
        ['\\[', '\\]']
      ]
    }
  };
  </script>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
  <script type="text/javascript" id="MathJax-script" async
    src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js">
  </script>
{% endif %}

<!-- commons -->

<script src="https://cdn.jsdelivr.net/combine/npm/popper.js@1.16.1,npm/bootstrap@4/dist/js/bootstrap.min.js"></script>

{% if jekyll.environment == 'production' %}
  <!-- PWA -->
  <!-- <script defer src="{{ '/app.js' | relative_url }}"></script> -->

  <!-- GA -->
  {% if site.google_analytics.id %}
    {% include google-analytics.html %}
  {% endif %}

{% endif %}


text:
package com.endoftheworldimprov.service.impl;

import com.endoftheworldimprov.JsonUtils;
import com.endoftheworldimprov.model.domain.ActivationStatus;
import com.endoftheworldimprov.model.domain.Show;
import com.endoftheworldimprov.model.domain.Vote;
import com.endoftheworldimprov.model.dto.VoteDto;
import com.endoftheworldimprov.model.dto.VotesForShow;
import com.endoftheworldimprov.service.api.IPubSubService;
import com.endoftheworldimprov.service.api.IShowService;
import com.endoftheworldimprov.service.api.IVoteService;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * Service to deal with Votes
 * @author bgray
 **/
@Slf4j
@Transactional
public class VoteServiceImpl extends AbstractServiceImpl implements IVoteService {

    // IP used when the IP cannot be determined
    private static final String DEFAULT_IP = "default";

    @Setter
    private IShowService showService;

    @Autowired
    private IPubSubService pubSubService;

    @Value("${pubnub.voteChannel}")
    private String voteChannel;

    @Override
    public VotesForShow getVoteTotals(Long showKey) {
        log.debug("getVoteTotals");
        VotesForShow votes = new VotesForShow();
        votes.setShowKey(showKey);

        Map<String, Object> result = (Map<String, Object>) entityManager.createQuery(
                "SELECT new map( SUM(v.saveVote) as save, SUM(v.destroyVote) as destroy)" +
                "FROM Vote v " +
                "WHERE v.showKey = :showKey ")
            .setParameter("showKey", showKey)
            .getSingleResult();

        if (result.size() > 1) {
            votes.setSaveVotes(convertToInt(result, "save"));
            votes.setDestroyVotes(convertToInt(result, "destroy"));
        }
        return votes;
    }

    @Override
    public Long persist(VoteDto voteDto) {
        log.debug("create {}", voteDto);

        // check show exists and is active
        Show show = showService.find(voteDto.getShowKey());
        Preconditions.checkArgument(show != null && ActivationStatus.ACTIVE.equals(show.getActivationStatus()),
                "Show is invalid: {}", show);

        Vote toPersist = Vote.createVote(voteDto);
        Vote existingVote = getVoteByIp(voteDto.getIp());

        if (existingVote != null) {
            log.debug("Vote existed, updating");
            existingVote.setSaveVote(toPersist.getSaveVote());
            existingVote.setDestroyVote(toPersist.getDestroyVote());
            toPersist = existingVote;
        }

        Vote answer = entityManager.merge(toPersist);

        // notify pubnub
        pubSubService.publish(voteChannel, JsonUtils.convertToJson(show));
        return answer.getKey();
    }

    /**
     * Get an existing vote by IP
     * @param ip
     * @return vote if there is one, null otherwise
     */
    private Vote getVoteByIp(String ip) {
        if (!Strings.isNullOrEmpty(ip) && !DEFAULT_IP.equals(ip)) {
            List<Vote> votes = entityManager.createQuery("select v from Vote v where v.ip = :ip", Vote.class)
                    .setParameter("ip", ip).getResultList();
            return Iterables.getFirst(votes, null);
        }
        return null;
    }

    private int convertToInt(Map<String, Object> result, String key) {
        Long longValue = (Long) result.get(key);
        return longValue == null ? 0 : longValue.intValue();
    }
}


text:
//-----------------------------------------------------------------------
// <copyright file="FlowCompileSpec.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Threading.Tasks;
using Akka.Streams.Dsl;
using Akka.TestKit;
using FluentAssertions;
using Microsoft.CSharp.RuntimeBinder;
using Reactive.Streams;
using Xunit;
using Xunit.Abstractions;

namespace Akka.Streams.Tests.Dsl
{
    public class FlowCompileSpec : AkkaSpec
    {
        private ActorMaterializer Materializer { get; }

        public FlowCompileSpec(ITestOutputHelper helper) : base(helper)
        {
            var settings = ActorMaterializerSettings.Create(Sys);
            Materializer = ActorMaterializer.Create(Sys, settings);
        }

        private Source<int, NotUsed> IntSeq => Source.From(new [] {1,2,3});
        private Source<string, NotUsed> StringSeq => Source.From(new[] { "a", "b", "c" });

        [Fact]
        public void Flow_should_not_run()
        {
            dynamic open = Flow.Create<int>();
            Action compiler = () => open.Run(Materializer);
            compiler.ShouldThrow<RuntimeBinderException>();
        }

        [Fact]
        public void Flow_should_accept_Enumerable() => IntSeq.Via(Flow.Create<int>());

        [Fact]
        public void Flow_should_accept_Future() => Source.FromTask(Task.FromResult(3)).Via(Flow.Create<int>());

        [Fact]
        public void Flow_should_append_Flow()
        {
            var open1 = Flow.Create<int>().Select(x => x.ToString());
            var open2 = Flow.Create<string>().Select(x => x.GetHashCode());
            dynamic open3 = open1.Via(open2);
            Action compiler = () => open3.Run(Materializer);
            compiler.ShouldThrow<RuntimeBinderException>();

            dynamic closedSource = IntSeq.Via(open3);
            compiler = () => closedSource.Run(Materializer);
            compiler.ShouldThrow<RuntimeBinderException>();

            dynamic closedSink = open3.To(Sink.AsPublisher<int>(false));
            compiler = () => closedSink.Run(Materializer);
            compiler.ShouldThrow<RuntimeBinderException>();

            closedSource.To(Sink.AsPublisher<int>(false)).Run(Materializer);
            IntSeq.To(closedSink).Run(Materializer);
        }

        [Fact]
        public void Flow_should_append_Sink()
        {
            var open = Flow.Create<int>().Select(x => x.ToString());
            var closedSink = Flow.Create<string>().Select(x => x.GetHashCode()).To(Sink.AsPublisher<int>(false));
            dynamic appended = open.To(closedSink);
            Action compiler = () => appended.Run(Materializer);
            compiler.ShouldThrow<RuntimeBinderException>();
            compiler = () => appended.To(Sink.First<int>());
            compiler.ShouldThrow<RuntimeBinderException>();
            IntSeq.To(appended).Run(Materializer);
        }

        [Fact]
        public void Flow_should_append_Source()
        {
            var open = Flow.Create<int>().Select(x => x.ToString());
            var closedSource = StringSeq.Via(Flow.Create<string>().Select(x => x.GetHashCode()));
            dynamic closedSource2 = closedSource.Via(open);
            Action compiler = () => closedSource2.Run(Materializer);
            compiler.ShouldThrow<RuntimeBinderException>();
            compiler = () => StringSeq.To(closedSource2);
            compiler.ShouldThrow<RuntimeBinderException>();
            closedSource2.To(Sink.AsPublisher<string>(false)).Run(Materializer);
        }

        private Sink<int, NotUsed> OpenSink
            => Flow.Create<int>().Select(x => x.ToString()).To(Sink.AsPublisher<string>(false));

        [Fact]
        public void Sink_should_accept_Source() => IntSeq.To(OpenSink);

        [Fact]
        public void Sink_should_not_accept_Sink()
        {
            dynamic openSink = OpenSink;
            Action compiler = () => openSink.To(Sink.First<string>());
            compiler.ShouldThrow<RuntimeBinderException>();
        }

        [Fact]
        public void Sink_should_not_run()
        {
            dynamic openSink = OpenSink;
            Action compiler = () => openSink.Run(Materializer);
            compiler.ShouldThrow<RuntimeBinderException>();
        }

        private Source<string, NotUsed> OpenSource => Source.From(new[] {1, 2, 3}).Select(x => x.ToString());

        [Fact]
        public void Source_should_accept_Sink() => OpenSource.To(Sink.AsPublisher<string>(false));

        [Fact]
        public void Source_should_not_be_accepted_by_Source()
        {
            dynamic openSource = OpenSource;
            Action compiler = () => openSource.To(IntSeq);
            compiler.ShouldThrow<RuntimeBinderException>();
        }

        [Fact]
        public void Source_should_not_run()
        {
            dynamic openSource = OpenSource;
            Action compiler = () => openSource.Run(Materializer);
            compiler.ShouldThrow<RuntimeBinderException>();
        }

        private IRunnableGraph<IPublisher<string>> Closed
            =>
                Source.From(new[] {1, 2, 3})
                    .Select(x => x.ToString())
                    .ToMaterialized(Sink.AsPublisher<string>(false), Keep.Right);

        [Fact]
        public void RunnableGraph_should_run() => Closed.Run(Materializer);

        [Fact]
        public void RunnableGraph_should_not_be_accepted_by_Source()
        {
            dynamic intSeq = IntSeq;
            Action compiler = () => intSeq.To(Closed);
            compiler.ShouldThrow<RuntimeBinderException>();
        }

        [Fact]
        public void RunnableGraph_should_not_accepted_Sink()
        {
            dynamic closed = Closed;
            Action compiler = () => closed.To(Sink.First<string>());
            compiler.ShouldThrow<RuntimeBinderException>();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FtpServer.Core.Authentication
{
    public class AnonymousOnlyAuthenticationProvider : AuthenticationProvider
    {
        public bool Authenticate(string userName, string password) {
            return IsAnonymous(userName);
        }

        private bool IsAnonymous(string userName) {
            if (userName == null)
                return false;

            userName = userName.Trim();
            return userName.Equals("anonymous", StringComparison.InvariantCultureIgnoreCase);
        }
    }
}


text:
struct SWM_Source* SWM_CreateSource(struct SWM_Buffer* buffer, Uint32 flags)
{
    SWM_Source* source = malloc(sizeof(SWM_Source));
    source->buffer = buffer;
    source->flags = flags;

    source->pos = 0;
    source->playing = 0;
    source->paused = 0;
    source->stopped = 1;
    source->looping = 0;
    source->volume = 1.0f;
    source->pitch = 1.0f;
    source->pan = 0.0f;

    _SWM_slist = realloc(_SWM_slist, (_SWM_slistlen + 1) * sizeof(SWM_Source*));
    _SWM_slist[_SWM_slistlen++] = source;

    return source;
}
void SWM_DestroySource(struct SWM_Source* source)
{
    source->buffer->refcount--;
    if((source->buffer->refcount == 0) && (source->buffer->spec->flags & SWM_AUTOREMOVE))
        SWM_DestroyBuffer(source->buffer);

    ptrdiff_t i;
    for(i = 0; i < _SWM_slistlen; i++)
        if(_SWM_slist[i] == source)
        {
            memmove(_SWM_slist[i], _SWM_slist[i+1], (_SWM_slistlen - i - 1) * sizeof(SWM_Source*));
            _SWM_slist = realloc(_SWM_slist, --_SWM_slistlen * sizeof(SWM_Source*));
            break;
        }

    free(source);
}

void SWM_Play(struct SWM_Source* source)
{
    source->playing = 1;
    source->paused = 0;
    source->stopped = 0;
}
void SWM_PlayBlocking(struct SWM_Source* source)
{
    Uint8 looping = source->looping;

    source->playing = 1;
    source->paused = 0;
    source->stopped = 0;

    source->looping = 0; // can't block and loop...
    while(source->playing)
    {
    }
    source->looping = looping;
}
Uint8 SWM_IsPlaying(struct SWM_Source* source)
{
    return source->playing;
}
void SWM_Pause(struct SWM_Source* source)
{
    source->playing = 0;
    source->paused = 1;
    source->stopped = 0;
}
Uint8 SWM_IsPaused(struct SWM_Source* source)
{
    return source->paused;
}
void SWM_Stop(struct SWM_Source* source)
{
    source->pos = 0;
    source->playing = 0;
    source->paused = 0;
    source->stopped = 1;
}
Uint8 SWM_IsStopped(struct SWM_Source* source)
{
    return source->stopped;
}

void SWM_SetLooping(struct SWM_Source* source, Uint8 looping)
{
    source->looping = looping;
}
Uint8 SWM_GetLooping(struct SWM_Source* source) // should this be SWM_IsLooping?
{
    return source->looping;
}
void SWM_SetVolume(struct SWM_Source* source, float volume)
{
    source->volume = volume;
}
float SWM_GetVolume(struct SWM_Source* source)
{
    return source->volume;
}
void SWM_SetPitch(struct SWM_Source* source, float pitch)
{
    source->pitch = pitch;
}
float SWM_GetPitch(struct SWM_Source* source)
{
    return source->pitch;
}
void SWM_SetPan(struct SWM_Source* source, float pan)
{
    source->pan = pan;
}
float SWM_GetPan(struct SWM_Source* source)
{
    return source->pan;
}


text:
{% extends "base.html" %}

{% block content %}

Your Contacts

{% for contact in contacts %}

 {{ contact.name }}

{% endfor %}
{% endblock %}


text:
package org.hisp.dhis.minmax.hibernate;

import org.hisp.dhis.category.CategoryOptionCombo;
import org.hisp.dhis.common.Pager;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.hibernate.HibernateGenericStore;
import org.hisp.dhis.hibernate.JpaQueryParameters;
import org.hisp.dhis.minmax.MinMaxDataElement;
import org.hisp.dhis.minmax.MinMaxDataElementQueryParams;
import org.hisp.dhis.minmax.MinMaxDataElementStore;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.query.JpaQueryUtils;
import org.hisp.dhis.query.QueryParser;
import org.hisp.dhis.query.QueryParserException;
import org.hisp.dhis.query.planner.QueryPlanner;
import org.hisp.dhis.schema.Property;
import org.hisp.dhis.schema.Schema;
import org.hisp.dhis.schema.SchemaService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author Kristian Nordal
 */
public class HibernateMinMaxDataElementStore
    extends HibernateGenericStore<MinMaxDataElement>
    implements MinMaxDataElementStore
{
    @Autowired
    private QueryParser queryParser;

    @Autowired
    private QueryPlanner queryPlanner;

    @Autowired
    private SchemaService schemaService;

    // -------------------------------------------------------------------------
    // MinMaxDataElementStore Implementation
    // -------------------------------------------------------------------------

    @Override
    public MinMaxDataElement get( OrganisationUnit source, DataElement dataElement,
        CategoryOptionCombo optionCombo )
    {
        CriteriaBuilder builder = getCriteriaBuilder();

        return getSingleResult( builder, newJpaParameters()
            .addPredicate( root -> builder.equal( root.get( "source" ), source ) )
            .addPredicate( root -> builder.equal( root.get( "dataElement" ), dataElement ) )
            .addPredicate( root -> builder.equal( root.get( "optionCombo" ), optionCombo ) ) );
    }

    @Override
    public List<MinMaxDataElement> get( OrganisationUnit source, DataElement dataElement )
    {
        CriteriaBuilder builder = getCriteriaBuilder();

        return getList( builder, newJpaParameters()
            .addPredicate( root -> builder.equal( root.get( "source" ), source ) )
            .addPredicate( root -> builder.equal( root.get( "dataElement" ), dataElement ) ) );
    }

    @Override
    public List<MinMaxDataElement> get( OrganisationUnit source, Collection<DataElement> dataElements )
    {
        if ( dataElements.size() == 0 )
        {
            return new ArrayList<>();
        }

        CriteriaBuilder builder = getCriteriaBuilder();

        return getList( builder, newJpaParameters()
            .addPredicate( root -> builder.equal( root.get( "source" ), source ) )
            .addPredicate( root -> root.get( "dataElement" ).in( dataElements ) ) );
    }

    @Override
    public List<MinMaxDataElement> query(  MinMaxDataElementQueryParams query )
    {
        CriteriaBuilder builder = getCriteriaBuilder();

        JpaQueryParameters<MinMaxDataElement> parameters = newJpaParameters();
        parameters.addPredicate( root -> parseFilter( builder, root, query.getFilters() ) );

        if ( !query.isSkipPaging() )
        {
            Pager pager = query.getPager();
            parameters.setFirstResult( pager.getOffset() );
            parameters.setMaxResults( pager.getPageSize() );
        }

        return getList( builder, parameters );
    }

    @Override
    public int countMinMaxDataElements( MinMaxDataElementQueryParams query )
    {
        CriteriaBuilder builder = getCriteriaBuilder();

        return getCount( builder, newJpaParameters()
            .addPredicate( root -> parseFilter( builder, root, query.getFilters() ) )
            .setUseDistinct( true ) )
            .intValue();
    }

    @Override
    public void delete( OrganisationUnit organisationUnit )
    {
        String hql = "delete from MinMaxDataElement m where m.source = :source";

        getQuery( hql ).setParameter( "source", organisationUnit ).executeUpdate();
    }

    @Override
    public void delete( DataElement dataElement )
    {
        String hql = "delete from MinMaxDataElement m where m.dataElement = :dataElement";

        getQuery( hql ).setParameter( "dataElement", dataElement ).executeUpdate();
    }

    @Override
    public void delete( CategoryOptionCombo optionCombo )
    {
        String hql = "delete from MinMaxDataElement m where m.optionCombo = :optionCombo";

        getQuery( hql ).setParameter( "optionCombo", optionCombo ).executeUpdate();
    }

    @Override
    public void delete( Collection<DataElement> dataElements, OrganisationUnit parent )
    {
        String hql = "delete from MinMaxDataElement m where m.dataElement in (:dataElements) " +
            "and m.source in (select ou from OrganisationUnit ou where path like :path)";

        getQuery( hql )
            .setParameterList( "dataElements", dataElements )
            .setParameter( "path", parent.getPath() + "%" )
            .executeUpdate();
    }

    private Predicate parseFilter( CriteriaBuilder builder, Root root, List<String> filters )
    {
        Predicate conjunction = builder.conjunction();

        Schema schema = schemaService.getDynamicSchema( MinMaxDataElement.class );

        if ( !filters.isEmpty() )
        {
            for ( String filter : filters )
            {
                String[] split = filter.split( ":" );

                if ( split.length != 3 )
                {
                    throw new QueryParserException( "Invalid filter: " + filter );
                }

                Path queryPath = queryPlanner.getQueryPath( root, schema,  split[0] );

                Property property = queryParser.getProperty( schema, split[0] );

                Predicate predicate = JpaQueryUtils.getPredicate( builder, property, queryPath, split[1], split[2] );

                if ( predicate != null )
                {
                    conjunction.getExpressions().add( predicate );
                }
            }
        }

        return conjunction;
    }
}


text:
<?php

/**
 * Provides the framework a debugging view functionalities for viewing errors, call stack, context and exceptions.
 *
 * @author Leng Sheng Hong <darkredz@gmail.com>
 * @version $Id: debug.php 1000 2009-10-11 18:27:22
 * @package doo.diagnostic
 * @since 1.3
 */

ini_set('html_errors', 0);
set_error_handler('setErrorHandler');
set_exception_handler('setExceptionHandler');
register_shutdown_function('shutdown');
getImg();

function getImg(){
    if(isset($_GET['doodiagnostic_pic']) && file_exists(Doo::conf()->BASE_PATH . 'diagnostic/assets/'.$_GET['doodiagnostic_pic'])){
        Doo::app()->setRawHeader('Content-Type: image/png');
        Doo::app()->setRawHeader('Content-Length: '.filesize(Doo::conf()->BASE_PATH . 'diagnostic/assets/'.$_GET['doodiagnostic_pic']));
        ob_clean();
        readfile(Doo::conf()->BASE_PATH . 'diagnostic/assets/'.$_GET['doodiagnostic_pic']);
        exit;
    }
}

function setExceptionHandler($e){
	//echo 'Uncaught '.get_class($e).', code: ' . $e->getCode() . "
Message: " . htmlentities($e->getMessage());
	Doo::loadHelper('DooTextHelper');
	$err = printVar($e);
	global $errTrace;
	$errTrace = DooTextHelper::highlightPHP($err);
	if(preg_match_all('/\[file\] \=\> (.+)\n/', $err, $matches)){
		//print_r($matches);
		$last = $matches[sizeof($matches)-1];
		$lastfile = $last[sizeof($last)-1];

		preg_match_all('/\[line\] \=\> (.+)\n/', $err, $matches);
		$last2 = $matches[sizeof($matches)-1];
		$lastline = $last2[sizeof($last2)-1];

		if($e instanceof PDOException){
			foreach($last as $k=>$l){
				if(strpos(str_replace('\\','/',$l), str_replace('\\','/',Doo::conf()->SITE_PATH))===0){
					$lastfile = $l;
					break;
				}
			}
			$lastline = $last2[$k];
		}

		setErrorHandler('Exception', $e->getMessage(), $lastfile, $lastline);
	}
}

function setErrorHandler($errno, $errstr, $errfile, $errline, $errcontext=null){
  if (error_reporting() === 0
      && $errno !== E_ERROR
      && $errno !== E_CORE_ERROR
      && $errno !== E_COMPILE_ERROR
      && $errno !== E_USER_ERROR
      && $errno !== E_RECOVERABLE_ERROR
  ) {
    return;
  }
    Doo::loadHelper('DooTextHelper');

	//require
	if($errno==2 && strpos($errstr, 'require_once(')===0 && strpos(str_replace('\\','/',$errfile), str_replace('\\','/',Doo::conf()->BASE_PATH).'Doo.php')===0){
		$dmsg = debug_backtrace();
		foreach($dmsg as $k=>$a){
			//if is user file, and must be a load method
			if(strpos(str_replace('\\','/',$a['file']), str_replace('\\','/',Doo::conf()->SITE_PATH))===0
				&& stripos($a['function'], 'load')===0 ){
				//print_r($a);exit;
				$errfile = $a['file'];
				$errline = $a['line'];
				break;
			}
		}
	}
    else if($errno==2 && strpos(str_replace('\\','/',$errfile), str_replace('\\','/',Doo::conf()->BASE_PATH).'view/DooView.php')===0){
		$dmsg = debug_backtrace();
		foreach($dmsg as $k=>$a){
            if(strpos(str_replace('\\','/',$a['file']), str_replace('\\','/',Doo::conf()->SITE_PATH))===0
                && stripos(str_replace('\\','/',$a['file']), '/controller')!==false){
                    $errfile = $a['file'];
                    $errline = $a['line'];
                    if(strpos($errstr, 'file_get_contents')!==false){
                       $errstr = 'Template not found ' . str_replace('[function.file-get-contents]: failed to open stream: ','',str_replace('file_get_contents','',$errstr));
                    }
                    break;
            }
        }
    }
	if(strpos(str_replace('\\','/',$errfile), str_replace('\\','/',Doo::conf()->BASE_PATH))===0){
		$dmsg = debug_backtrace();
		$last = array_pop($dmsg);
		if(isset($last['file'])){
//			$errfile = $last['file'];
//			$errline = $last['line'];
		}else{
			$errfile = $dmsg[0]['args'][2];
			$errline = $dmsg[0]['args'][3];
		}
	}

    $script = file_get_contents($errfile);
    $script = DooTextHelper::highlightPHP($script);

	$pre = '';
    $Xpre = '';

	if(!empty($script)){
        //if template file addon the

        if(strpos(str_replace('\\','/',$errfile), str_replace('\\','/',Doo::conf()->SITE_PATH.Doo::conf()->PROTECTED_FOLDER).'view')===0){
            $pre = '
';
            $Xpre = '
';
        }

        $lines = explode('
', $script);

        $errLineContent = '
'.$pre.$lines[$errline-1].$Xpre.'
';

        //highlight the error line
		$lines[$errline-1] = '
' . $lines[$errline-1] . '
';

		//remove the code tag from 1st and last line
		$lines[0] = str_replace('','',$lines[0]);
		$lines[sizeof($lines)-1] = str_replace('','',$lines[sizeof($lines)-1]);
	}

    $imgloader = Doo::conf()->SUBFOLDER . 'index.php?doodiagnostic_pic=';

	if (ob_get_level() !== 0) {
		ob_clean();
	}
	$confData = traceVar(Doo::conf());
	$getData = traceVar($_GET);
	$postData = traceVar($_POST);
    if(isset ($_SESSION))
        $sessionData = traceVar($_SESSION);
    if(isset ($_COOKIE))
        $cookieData = traceVar($_COOKIE);

    echo "<title>DooPHP Diagnostics - $errstr</title>";
	echo '<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />';

    //css
    echo '';

    //script
    echo '';

    //headings
    echo "";
    echo '
';
    //echo "Unknown error type: [$errno] $errstr
\n";
    echo "DooPHP
$errstr
";
    echo '

';
    echo "
See file $errfile

";
    echo "
 + Error on line $errline
";

    if(isset($errLineContent)){
		echo "
".$errLineContent."
";
	}

    //error code script
    echo $pre.'';
	if(isset($lines)){
		echo implode('
', $lines);
    }
	echo ''.$Xpre;

    echo '

 * Stack Trace...
';
	global $errTrace;
	if(!empty($errTrace)){
		echo '
';
		echo $errTrace;
		echo '
';
	}else{
	    errorBacktrace();
	}

    echo '

 * Variables...  Conf  .  GET  .  POST  .  Session  .  Cookie
';

	//config data
    echo '
';

	$confData = str_replace(']=>
  ','] => ',DooTextHelper::highlightPHP($confData));
	echo str_replace('', '',$confData);

	if(!empty($_GET)){
		$getData = str_replace(']=>
  ','] => ',DooTextHelper::highlightPHP($getData));
		echo str_replace('', "\$_GET Variables", $getData);
	}

	if(!empty($_POST)){
		$postData = str_replace(']=>
  ','] => ',DooTextHelper::highlightPHP($postData));
		echo str_replace('', "\$_POST Variables", $postData);
	}

	if(isset($sessionData)){
		$sessionData = str_replace(']=>
  ','] => ',DooTextHelper::highlightPHP($sessionData));
		echo str_replace('', "\$_SESSION Variables", $sessionData);
	}

	if(isset($_COOKIE)){
		$cookieData = str_replace(']=>
  ','] => ',DooTextHelper::highlightPHP($cookieData));
		echo str_replace('', "\$_COOKIE Variables", $cookieData);
	}

    echo '

';

    echo "

BACK TO TOP
";
//    exit;
}

function traceVar($var){
    ob_start();
    var_dump($var);
	$var = ob_get_contents();
    ob_end_clean();
	return $var;
}

function printVar($var){
    ob_start();
    print_r($var);
	$var = ob_get_contents();
    ob_end_clean();
	return $var;
}

//only call this if debug on
function shutdown(){
    $isError = false;
    if ($error = error_get_last()){
        switch($error['type']){
            case E_ERROR:
            case E_CORE_ERROR:
            case E_COMPILE_ERROR:
            case E_USER_ERROR:
                $isError = true;
                break;
        }
    }
    if($isError){
		//print_r($error);exit;
		setErrorHandler($error['type'], $error['message'], $error['file'], $error['line']);
    }
}

function errorBacktrace() {
    $trace = array_reverse(debug_backtrace());
	array_pop($trace);
	array_pop($trace);
    echo '
';
    foreach($trace as $item)
        echo '
' . (isset($item['file']) ? $item['file'] : '<unknown file>') . '(' . (isset($item['line']) ? $item['line'] : '<unknown line>') . ') calling ' . $item['function'] . '()
';
    echo '
';
}

class DooDebugException extends Exception{
    public $var;

    public function __construct($var, $message='Debugging App',$code=999) {
        parent::__construct($message,$code);
        $this->var = $var;
    }
}


text:
from ..base import Task

def test_task_entrypoint():
    assert Task("name", "image", entrypoint="one-word").entrypoint == ["one-word"]
    assert Task("name", "image", entrypoint="two words").entrypoint == ["two", "words"]
    assert Task("name", "image", entrypoint=["the", "right", "way"]).entrypoint == [
        "the",
        "right",
        "way",
    ]


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;

namespace Indra.Sofia2.SSAP_UTests
{
    //[TestClass]
    //public class SSAPMessage<SSAPBodyMessage>
    //{
    //    private SSAP.SSAP.SSAPMessage<SSAPBodyMessage> CreateSSAPMessage<SSAPBodyMessage>(string sufix)
    //    {
    //        var message = new SSAP.SSAP.SSAPMessage<SSAPBodyMessage>()
    //        {
    //            Body = "Test Body" + sufix,
    //            Direction = SSAP.SSAP.SSAPMessage<SSAPBodyMessage>DirectionEnum.REQUEST,
    //            MessageId = "_message_id" + sufix,
    //            MessageType = SSAP.SSAP.SSAPMessage<SSAPBodyMessage>TypesEnum.CREATE,
    //            Ontology = "ontology" + sufix,
    //            SessionKey = "SESSION" + sufix
    //        };
    //        return message;
    //    }

    //    private string CreateJson(string sufix)
    //    {
    //        return "{\"MessageId\":\"_message_id{0}\",\"SessionKey\":\"SESSION{0}\",\"Ontology\":\"ontology{0}\",\"Direction\":0,\"MessageType\":11,\"Body\":\"Test Body{0}\"}".Replace("{0}", sufix);
    //    }

    //    [TestMethod]
    //    public void ToJson()
    //    {
    //        Assert.AreEqual(CreateSSAPMessage<SSAPBodyMessage>("1").ToJson(), CreateJson("1"));
    //    }

    //    [TestMethod]
    //    public void FromJson()
    //    {
    //        var messageFromJson = SSAP.SSAP.SSAPMessage<SSAPBodyMessage>.FromJson(CreateJson("1"));
    //        var message = CreateSSAPMessage<SSAPBodyMessage>("1");

    //        Assert.AreEqual(message.Body, messageFromJson.Body);
    //        Assert.AreEqual(message.Direction, messageFromJson.Direction);
    //        Assert.AreEqual(message.MessageId, messageFromJson.MessageId);
    //        Assert.AreEqual(message.MessageType, messageFromJson.MessageType);
    //        Assert.AreEqual(message.Ontology, messageFromJson.Ontology);
    //        Assert.AreEqual(message.SessionKey, messageFromJson.SessionKey);
    //    }

    //    [TestMethod]
    //    public void CollectionToJson()
    //    {
    //        List<SSAP.SSAP.SSAPMessage<SSAPBodyMessage>> messageList = new List<SSAP.SSAP.SSAPMessage<SSAPBodyMessage>>();
    //        string json = "[";
    //        for (int i=0; i<3; i++)
    //        {
    //            messageList.Add(CreateSSAPMessage<SSAPBodyMessage>(i.ToString()));
    //            json += CreateJson(i.ToString()) + ",";
    //        }
    //        json = json.Substring(0, json.Length - 1) + "]";
    //        Assert.AreEqual(SSAP.SSAP.SSAPMessage<SSAPBodyMessage>.ToJson(messageList), json);
    //    }

    //    [TestMethod]
    //    public void JsonFromCollection()
    //    {
    //        List<SSAP.SSAP.SSAPMessage<SSAPBodyMessage>> messageList = new List<SSAP.SSAP.SSAPMessage<SSAPBodyMessage>>();
    //        string json = "[";
    //        for (int i = 0; i < 3; i++)
    //        {
    //            messageList.Add(CreateSSAPMessage<SSAPBodyMessage>(i.ToString()));
    //            json += CreateJson(i.ToString()) + ",";
    //        }
    //        json = json.Substring(0, json.Length - 1) + "]";
    //        List<SSAP.SSAP.SSAPMessage<SSAPBodyMessage>> meesages = (List<SSAP.SSAP.SSAPMessage<SSAPBodyMessage>>)SSAP.SSAP.SSAPMessage<SSAPBodyMessage>.FromJsonArray(json);
    //        Assert.IsTrue(meesages != null && meesages.Count == 3);
    //    }

    //    [TestMethod]
    //    public void ToJsonWithFields()
    //    {
    //        var message = CreateSSAPMessage<SSAPBodyMessage>("0");
    //        var fields = new List<string>() { "Direction", "MessageId", "MessageType" };
    //        string json = message.ToJson(fields);
    //        var message_aux = SSAP.SSAP.SSAPMessage<SSAPBodyMessage>.FromJson(json);
    //        Assert.AreEqual(message.Direction, message_aux.Direction, "Direction obtenido: " + message_aux.Direction);
    //        Assert.AreEqual(message.MessageId, message_aux.MessageId, "MessageId obtenido: " + message_aux.MessageId);
    //        Assert.AreEqual(message.MessageType, message_aux.MessageType, "MessageType obtenido: " + message_aux.MessageType);
    //        Assert.IsNull(message_aux.Body, "Body obtenido: " + message_aux.Body);
    //        Assert.IsNull(message_aux.Ontology, "Ontology obtenido: " + message_aux.Ontology);
    //        Assert.IsNull(message_aux.SessionKey, "SessionKey obtenido: " + message_aux.SessionKey);
    //    }

    //    [TestMethod]
    //    public void CollectionToJsonWithFields()
    //    {
    //        List<SSAP.SSAP.SSAPMessage<SSAPBodyMessage>> messageList = new List<SSAP.SSAP.SSAPMessage<SSAPBodyMessage>>();
    //        var fields = new List<string>() { "Direction", "MessageId", "MessageType" };

    //        for (int i = 0; i < 3; i++)
    //        {
    //            messageList.Add(CreateSSAPMessage<SSAPBodyMessage>(i.ToString()));
    //        }
    //        var strMessages = SSAP.SSAP.SSAPMessage<SSAPBodyMessage>.ToJson(messageList, fields);
    //        var messageList_aux = (List<SSAP.SSAP.SSAPMessage<SSAPBodyMessage>>)SSAP.SSAP.SSAPMessage<SSAPBodyMessage>.FromJsonArray(strMessages);
    //        for (int i = 0; i < 3; i++)
    //        {
    //            Assert.AreEqual(messageList[i].Direction, messageList_aux[i].Direction, "Direction obtenido: " + messageList_aux[i].Direction);
    //            Assert.AreEqual(messageList[i].MessageId, messageList_aux[i].MessageId, "MessageId obtenido: " + messageList_aux[i].MessageId);
    //            Assert.AreEqual(messageList[i].MessageType, messageList_aux[i].MessageType, "MessageType obtenido: " + messageList_aux[i].MessageType);
    //            Assert.IsNull(messageList_aux[i].Body, "Body obtenido: " + messageList_aux[i].Body);
    //            Assert.IsNull(messageList_aux[i].Ontology, "Ontology obtenido: " + messageList_aux[i].Ontology);
    //            Assert.IsNull(messageList_aux[i].SessionKey, "SessionKey obtenido: " + messageList_aux[i].SessionKey);
    //        }
    //    }

    //}
}


text:
package com.box.l10n.mojito.rest.leveraging;

import static org.slf4j.LoggerFactory.getLogger;

import com.box.l10n.mojito.rest.asset.AssetWithIdNotFoundException;
import com.box.l10n.mojito.rest.repository.RepositoryWithIdNotFoundException;
import com.box.l10n.mojito.service.leveraging.LeveragingService;
import com.box.l10n.mojito.service.pollableTask.PollableFuture;
import com.box.l10n.mojito.service.repository.RepositoryRepository;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/** @author jaurambault */
@RestController
public class LeveragingWS {

  /** logger */
  static Logger logger = getLogger(LeveragingWS.class);

  @Autowired RepositoryRepository repositoryRepository;

  @Autowired LeveragingService leveragingService;

  /**
   * Copy the TM of a source repository into the a target repository.
   *
   * @param copyTmConfig config to perform the copy (source and target repositories).
   * @return the config updated with a pollable task
   */
  @RequestMapping(value = "/api/leveraging/copyTM", method = RequestMethod.POST)
  public CopyTmConfig copyTM(@RequestBody CopyTmConfig copyTmConfig)
      throws AssetWithIdNotFoundException, RepositoryWithIdNotFoundException {
    logger.debug("Copy repository TM");
    PollableFuture<Void> pollableFuture = leveragingService.copyTm(copyTmConfig);
    copyTmConfig.setPollableTask(pollableFuture.getPollableTask());
    return copyTmConfig;
  }
}


text:
using IdentityServer3.AccessTokenValidation;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security.Jwt;
using Microsoft.Owin.Security.OAuth;
using System;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Threading;

namespace Owin
{
    /// <summary>
    /// AppBuilder extensions for identity server token validation
    /// </summary>
    public static class IdentityServerBearerTokenValidationAppBuilderExtensions
    {
        /// <summary>
        /// Add identity server token authentication to the pipeline.
        /// </summary>
        /// <param name="app">The application.</param>
        /// <param name="options">The options.</param>
        /// <returns></returns>
        public static IAppBuilder UseIdentityServerBearerTokenAuthentication(this IAppBuilder app, IdentityServerBearerTokenAuthenticationOptions options)
        {
            if (app == null) throw new ArgumentNullException("app");
            if (options == null) throw new ArgumentNullException("options");

            var loggerFactory = app.GetLoggerFactory();
            var middlewareOptions = new IdentityServerOAuthBearerAuthenticationOptions();

            switch (options.ValidationMode)
            {
                case ValidationMode.Local:
                    middlewareOptions.LocalValidationOptions = ConfigureLocalValidation(options, loggerFactory);
                    break;
                case ValidationMode.ValidationEndpoint:
                    middlewareOptions.EndpointValidationOptions = ConfigureEndpointValidation(options, loggerFactory);
                    break;
                case ValidationMode.Both:
                    middlewareOptions.LocalValidationOptions = ConfigureLocalValidation(options, loggerFactory);
                    middlewareOptions.EndpointValidationOptions = ConfigureEndpointValidation(options, loggerFactory);
                    break;
                default:
                    throw new Exception("ValidationMode has invalid value");
            }

            if (!options.DelayLoadMetadata)
            {
                // evaluate the lazy members so that they can do their job

                if (middlewareOptions.LocalValidationOptions != null)
                {
                    var ignore = middlewareOptions.LocalValidationOptions.Value;
                }

                if (middlewareOptions.EndpointValidationOptions != null)
                {
                    var ignore = middlewareOptions.EndpointValidationOptions.Value;
                }
            }

            if (options.TokenProvider != null)
            {
                middlewareOptions.TokenProvider = options.TokenProvider;
            }

            app.Use<IdentityServerBearerTokenValidationMiddleware>(app, middlewareOptions, loggerFactory);

            if (options.RequiredScopes.Any())
            {
                var scopeOptions = new ScopeRequirementOptions
                {
                    AuthenticationType = options.AuthenticationType,
                    RequiredScopes = options.RequiredScopes
                };

                app.Use<ScopeRequirementMiddleware>(scopeOptions);
            }

            if (options.PreserveAccessToken)
            {
                app.Use<PreserveAccessTokenMiddleware>();
            }

            return app;
        }

        private static Lazy<OAuthBearerAuthenticationOptions> ConfigureEndpointValidation(IdentityServerBearerTokenAuthenticationOptions options, ILoggerFactory loggerFactory)
        {
            return new Lazy<OAuthBearerAuthenticationOptions>(() =>
            {
                if (options.EnableValidationResultCache)
                {
                    if (options.ValidationResultCache == null)
                    {
                        options.ValidationResultCache = new InMemoryValidationResultCache(options);
                    }
                }

                var bearerOptions = new OAuthBearerAuthenticationOptions
                {
                    AuthenticationMode = options.AuthenticationMode,
                    AuthenticationType = options.AuthenticationType,
                    Provider = new ContextTokenProvider(options.TokenProvider),
                };

                if (!string.IsNullOrEmpty(options.ClientId) || options.IntrospectionHttpHandler != null)
                {
                    bearerOptions.AccessTokenProvider = new IntrospectionEndpointTokenProvider(options, loggerFactory);
                }
                else
                {
                    bearerOptions.AccessTokenProvider = new ValidationEndpointTokenProvider(options, loggerFactory);
                }

                return bearerOptions;

            }, true);
        }

        internal static Lazy<OAuthBearerAuthenticationOptions> ConfigureLocalValidation(IdentityServerBearerTokenAuthenticationOptions options, ILoggerFactory loggerFactory)
        {
            return new Lazy<OAuthBearerAuthenticationOptions>(() =>
            {
                JwtFormat tokenFormat = null;

                // use static configuration
                if (!string.IsNullOrWhiteSpace(options.IssuerName) &&
                    options.SigningCertificate != null)
                {
                    var audience = options.IssuerName.EnsureTrailingSlash();
                    audience += "resources";

                    var valParams = new TokenValidationParameters
                    {
                        ValidIssuer = options.IssuerName,
                        ValidAudience = audience,
                        IssuerSigningToken = new X509SecurityToken(options.SigningCertificate),

                        NameClaimType = options.NameClaimType,
                        RoleClaimType = options.RoleClaimType,
                    };

                    tokenFormat = new JwtFormat(valParams);
                }
                else
                {
                    // use discovery endpoint
                    if (string.IsNullOrWhiteSpace(options.Authority))
                    {
                        throw new Exception("Either set IssuerName and SigningCertificate - or Authority");
                    }

                    var discoveryEndpoint = options.Authority.EnsureTrailingSlash();
                    discoveryEndpoint += ".well-known/openid-configuration";

                    var issuerProvider = new DiscoveryDocumentIssuerSecurityTokenProvider(
                        discoveryEndpoint,
                        options,
                        loggerFactory);

                    var valParams = new TokenValidationParameters
                    {
                        ValidAudience = issuerProvider.Audience,
                        NameClaimType = options.NameClaimType,
                        RoleClaimType = options.RoleClaimType,
                        IssuerSigningKeyResolver = options.IssuerSigningKeyResolver
                    };

                    tokenFormat = new JwtFormat(valParams, issuerProvider);
                }

                var bearerOptions = new OAuthBearerAuthenticationOptions
                {
                    AccessTokenFormat = tokenFormat,
                    AuthenticationMode = options.AuthenticationMode,
                    AuthenticationType = options.AuthenticationType,
                    Provider = new ContextTokenProvider(options.TokenProvider)
                };

                return bearerOptions;

            }, LazyThreadSafetyMode.PublicationOnly);
        }
    }
}