text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

using LinqToDB;
using LinqToDB.Mapping;
using LinqToDB.Tools;
using LinqToDB.Tools.Comparers;

using NUnit.Framework;

namespace Tests.Linq
{
	using Model;
	using System.Text.RegularExpressions;

	[TestFixture]
	public class WhereTests : TestBase
	{
		[Test]
		public void MakeSubQuery([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(
					from p in db.Person
					select new { PersonID = p.ID + 1, p.FirstName } into p
					where p.PersonID == 2
					select new Person(p.PersonID - 1) { FirstName = p.FirstName });
		}

		[Test]
		public void MakeSubQueryWithParam([DataSources] string context)
		{
			var n = 1;

			using (var db = GetDataContext(context))
				TestOneJohn(
					from p in db.Person
					select new { PersonID = p.ID + n, p.FirstName } into p
					where p.PersonID == 2
					select new Person(p.PersonID - 1) { FirstName = p.FirstName });
		}

		[Test]
		public void DoNotMakeSubQuery([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(
					from p1 in db.Person
					select new { p1.ID, Name = p1.FirstName + "\r\r\r" } into p2
					where p2.ID == 1
					select new Person(p2.ID) { FirstName = p2.Name.TrimEnd('\r') });
		}

		[Test]
		public void EqualsConst([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(from p in db.Person where p.ID == 1 select p);
		}

		[Test]
		public void EqualsConsts([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(from p in db.Person where p.ID == 1 && p.FirstName == "John" select p);
		}

		[Test]
		public void EqualsConsts2([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(
					from p in db.Person
					where (p.FirstName == "John" || p.FirstName == "John's") && p.ID > 0 && p.ID < 2 && p.LastName != "123"
					select p);
		}

		[Test]
		public void EqualsParam([DataSources] string context)
		{
			var id = 1;
			using (var db = GetDataContext(context))
				TestOneJohn(from p in db.Person where p.ID == id select p);
		}

		[Test]
		public void EqualsParams([DataSources] string context)
		{
			var id   = 1;
			var name = "John";
			using (var db = GetDataContext(context))
				TestOneJohn(from p in db.Person where p.ID == id && p.FirstName == name select p);
		}

		[Test]
		public void NullParam1([DataSources] string context)
		{
			var     id   = 1;
			string? name = null;
			using (var db = GetDataContext(context))
				TestOneJohn(from p in db.Person where p.ID == id && p.MiddleName == name select p);
		}

		[Test]
		public void NullParam2([DataSources] string context)
		{
			var     id   = 1;
			string? name = null;

			using (var db = GetDataContext(context))
			{
				(from p in db.Person where p.ID == id && p.MiddleName == name select p).ToList();
				var q = from p in db.Person where p.ID == id && p.MiddleName == name select p;

				TestOneJohn(q);
			}
		}

		int TestMethod()
		{
			return 1;
		}

		[Test]
		public void MethodParam([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(from p in db.Person where p.ID == TestMethod() select p);
		}

		static int StaticTestMethod()
		{
			return 1;
		}

		[Test]
		public void StaticMethodParam([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(from p in db.Person where p.ID == StaticTestMethod() select p);
		}

		class TestMethodClass
		{
			private readonly int _n;

			public TestMethodClass(int n)
			{
				_n = n;
			}

			public int TestMethod()
			{
				return _n;
			}
		}

		public void MethodParam(int n, string context)
		{
			var t = new TestMethodClass(n);

			using (var db = GetDataContext(context))
			{
				var id = (from p in db.Person where p.ID == t.TestMethod() select new { p.ID }).ToList().First();
				Assert.AreEqual(n, id.ID);
			}
		}

		[Test]
		public void MethodParam2([DataSources] string context)
		{
			MethodParam(1, context);
			MethodParam(2, context);
		}

		static IQueryable<Person> TestDirectParam(ITestDataContext db, int id)
		{
			var name = "John";
			return from p in db.Person where p.ID == id && p.FirstName == name select p;
		}

		[Test]
		public void DirectParams([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(TestDirectParam(db, 1));
		}

		[Test]
		public void BinaryAdd([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(from p in db.Person where p.ID + 1 == 2 select p);
		}

		[Test]
		public void BinaryDivide([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(from p in db.Person where (p.ID + 9) / 10 == 1 && p.ID == 1 select p);
		}

		[Test]
		public void BinaryModulo([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(from p in db.Person where p.ID % 2 == 1 && p.ID == 1 select p);
		}

		[Test]
		public void BinaryMultiply([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(from p in db.Person where p.ID * 10 - 9 == 1 select p);
		}

		[Test]
		public void BinaryXor([DataSources(TestProvName.AllAccess)] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(from p in db.Person where (p.ID ^ 2) == 3 select p);
		}

		[Test]
		public void BinaryAnd([DataSources(TestProvName.AllAccess)] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(from p in db.Person where (p.ID & 3) == 1 select p);
		}

		[Test]
		public void BinaryOr([DataSources(TestProvName.AllAccess)] string context)
		{
			using (var db = GetDataContext(context))
			{
				AreEqual(
					   Person.Where(p => (p.ID | 2) == 3),
					db.Person.Where(p => (p.ID | 2) == 3));
			}
		}

		[Test]
		public void BinarySubtract([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(from p in db.Person where p.ID - 1 == 0 select p);
		}

		[Test]
		public void EqualsNull([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(from p in db.Person where p.ID == 1 && p.MiddleName == null select p);
		}

		[Test]
		public void EqualsNull2([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(from p in db.Person where p.ID == 1 && null == p.MiddleName select p);
		}

		[Test]
		public void NotEqualNull([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(from p in db.Person where p.ID == 1 && p.FirstName != null select p);
		}

		[Test]
		public void NotEqualNull2([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(from p in db.Person where p.ID == 1 && null != p.FirstName select p);
		}

		[Test]
		public void ComparisionNullCheckOn1([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					   Parent.Where(p => p.Value1 != 1),
					db.Parent.Where(p => p.Value1 != 1));
		}

		[Test]
		public void ComparisionNullCheckOn2([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					   Parent.Where(p => 1 != p.Value1),
					db.Parent.Where(p => 1 != p.Value1));
		}

		[Test]
		public void ComparisionNullCheckOff([DataSources] string context)
		{
			using (new WithoutComparisonNullCheck())
			using (var db = GetDataContext(context))
				AreEqual(
					   Parent.Where(p => p.Value1 != 1 && p.Value1 != null),
					db.Parent.Where(p => p.Value1 != 1));
		}

		[Test]
		public void NotTest([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(from p in db.Person where p.ID == 1 && !(p.MiddleName != null) select p);
		}

		[Test]
		public void NotTest2([DataSources] string context)
		{
			var n = 2;
			using (var db = GetDataContext(context))
				TestOneJohn(from p in db.Person where p.ID == 1 && !(p.MiddleName != null && p.ID == n) select p);
		}

		[Test]
		public void Coalesce1([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(
					from p in db.Person
					where
						p.ID == 1 &&
						(p.MiddleName ?? "None") == "None" &&
						(p.FirstName ?? "None") == "John"
					select p);
		}

		[Test]
		public void Coalesce2([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				Assert.AreEqual(1, (from p in db.Parent where p.ParentID == 1 ? true : false select p).ToList().Count);
		}

		[Test]
		public void Coalesce3([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				Assert.AreEqual(1, (from p in db.Parent where p.ParentID != 1 ? false : true select p).ToList().Count);
		}

		[Test]
		public void Coalesce4([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent where p.ParentID == 1 ? false : true select p,
					from p in db.Parent where p.ParentID == 1 ? false : true select p);
		}

		[Test]
		public void Coalesce5([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				Assert.AreEqual(2, (from p in db.Parent where (p.Value1 == 1 ? 10 : 20) == 10 select p).ToList().Count);
		}

		[Test]
		public void Coalesce6([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent where (p.Value1 == 1 ? 10 : 20) == 20 select p,
					from p in db.Parent where (p.Value1 == 1 ? 10 : 20) == 20 select p);
		}

		[Test]
		public void Coalesce7([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent where (p.ParentID == 1 ? 10 : 20) == 20 select p,
					from p in db.Parent where (p.ParentID == 1 ? 10 : 20) == 20 select p);
		}

		[Test]
		public void Conditional([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(
					from p in db.Person
					where
						p.ID == 1 &&
						(p.MiddleName == null ? 1 : 2) == 1 &&
						(p.FirstName != null ? 1 : 2) == 1
					select p);
		}

		[Test]
		public void Conditional2([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(
					from p in db.Person
					where
						p.ID == 1 &&
						(p.MiddleName != null ? 3 : p.MiddleName == null ? 1 : 2) == 1 &&
						(p.FirstName == null ? 3 : p.FirstName != null ? 1 : 2) == 1
					select p);
		}

		[Test]
		public void Conditional3([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				TestOneJohn(
					from p in db.Person
					where
						p.ID == 1 &&
						(p.MiddleName != null ? 3 : p.ID == 2 ? 2 : p.MiddleName != null ? 0 : 1) == 1 &&
						(p.FirstName == null ? 3 : p.ID == 2 ? 2 : p.FirstName == null ? 0 : 1) == 1
					select p);
		}

		[Test]
		public void MultipleQuery1([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				var id = 1;
				var q  = from p in db.Person where p.ID == id select p;

				var list = q.ToList();
				Assert.AreEqual(1, list[0].ID);

				id = 2;
				list = q.ToList();
				Assert.AreEqual(2, list[0].ID);
			}
		}

		[Test]
		public void MultipleQuery2([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				string? str = null;
				var     q   = from p in db.Person where p.MiddleName == str select p;

				var list = q.ToList();
				Assert.AreNotEqual(0, list.Count);

				str = "123";
				list = q.ToList();
				Assert.AreEqual(0, list.Count);
			}
		}

		[Test]
		public void HasValue1([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent where p.Value1.HasValue select p,
					from p in db.Parent where p.Value1.HasValue select p);
		}

		[Test]
		public void HasValue2([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				Assert.AreEqual(2, (from p in db.Parent where !p.Value1.HasValue select p).ToList().Count);
		}

		[Test]
		public void Value([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				Assert.AreEqual(2, (from p in db.Parent where p.Value1!.Value == 1 select p).ToList().Count);
		}

		[Test]
		public void CompareNullable1([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				Assert.AreEqual(2, (from p in db.Parent where p.Value1 == 1 select p).ToList().Count);
		}

		[Test]
		public void CompareNullable2([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				Assert.AreEqual(1, (from p in db.Parent where p.ParentID == p.Value1 && p.Value1 == 1 select p).ToList().Count);
		}

		[Test]
		public void CompareNullable3([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				Assert.AreEqual(1, (from p in db.Parent where p.Value1 == p.ParentID && p.Value1 == 1 select p).ToList().Count);
		}

		[Test]
		public void SubQuery([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from t in
						from ch in Child
						select ch.ParentID * 1000
					where t > 2000
					select t / 1000,
					from t in
						from ch in db.Child
						select ch.ParentID * 1000
					where t > 2000
					select t / 1000);
		}

		[Test]
		public void AnonymousEqual1([DataSources] string context)
		{
			var child = new { ParentID = 2, ChildID = 21 };

			using (var db = GetDataContext(context))
				AreEqual(
					from ch in Child
					where ch.ParentID == child.ParentID && ch.ChildID == child.ChildID
					select ch
					,
					from ch in db.Child
					where new { ch.ParentID, ch.ChildID } == child
					select ch);
		}

		[Test]
		public void AnonymousEqual2([DataSources] string context)
		{
			var child = new { ParentID = 2, ChildID = 21 };

			using (var db = GetDataContext(context))
				AreEqual(
					from ch in Child
					where !(ch.ParentID == child.ParentID && ch.ChildID == child.ChildID) && ch.ParentID > 0
					select ch
					,
					from ch in db.Child
					where child != new { ch.ParentID, ch.ChildID } && ch.ParentID > 0
					select ch);
		}

		[Test]
		public void AnonymousEqual31([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from ch in Child
					where ch.ParentID == 2 && ch.ChildID == 21
					select ch
					,
					from ch in db.Child
					where new { ch.ParentID, ch.ChildID } == new { ParentID = 2, ChildID = 21 }
					select ch);
		}

		[Test]
		public void AnonymousEqual32([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from ch in Child
					where ch.ParentID == 2 && ch.ChildID == 21
					select ch
					,
					from ch in db.Child
					where new { ParentID = 2, ChildID = 21 } == new { ch.ParentID, ch.ChildID }
					select ch);
		}

		[Test]
		public void AnonymousEqual4([DataSources] string context)
		{
			var parent = new { ParentID = 2, Value1 = (int?)null };

			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent
					where p.ParentID == parent.ParentID && p.Value1 == parent.Value1
					select p
					,
					from p in db.Parent
					where new { p.ParentID, p.Value1 } == parent
					select p);
		}

		[Test]
		public void AnonymousEqual5([DataSources] string context)
		{
			var parent = new { ParentID = 3, Value1 = (int?)3 };

			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent
					where p.ParentID == parent.ParentID && p.Value1 == parent.Value1
					select p
					,
					from p in db.Parent
					where new { p.ParentID, p.Value1 } == parent
					select p);
		}

		[Test]
		public void CheckLeftJoin1([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent
					join ch in Child on p.ParentID equals ch.ParentID into lj1
					from ch in lj1.DefaultIfEmpty()
					where ch == null
					select p
					,
					from p in db.Parent
					join ch in db.Child on p.ParentID equals ch.ParentID into lj1
					from ch in lj1.DefaultIfEmpty()
					where ch == null
					select p);
		}

		[Test]
		public void CheckLeftJoin2([DataSources] string context)
		{
			using (var data = GetDataContext(context))
				AreEqual(
					from p in Parent
					join ch in Child on p.ParentID equals ch.ParentID into lj1
					from ch in lj1.DefaultIfEmpty()
					where ch != null
					select p
					,
					CompiledQuery.Compile<ITestDataContext, IQueryable<Parent>>(db =>
						 from p in db.Parent
						 join ch in db.Child on p.ParentID equals ch.ParentID into lj1
						 from ch in lj1.DefaultIfEmpty()
						 where null != ch
						 select p)(data));
		}

		[Test]
		public void CheckLeftJoin3([DataSources(ProviderName.Access)]
			string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent
					join ch in
						from c in GrandChild
						where c.ParentID > 0
						select new { ParentID = 1 + c.ParentID, c.ChildID }
					on p.ParentID equals ch.ParentID into lj1
					from ch in lj1.DefaultIfEmpty()
					where ch == null && ch == null
					select p
					,
					from p in db.Parent
					join ch in
						from c in db.GrandChild
						where c.ParentID > 0
						select new { ParentID = 1 + c.ParentID, c.ChildID }
					on p.ParentID equals ch.ParentID into lj1
					from ch in lj1.DefaultIfEmpty()
					where ch == null && ch == null
					select p);
		}

		[Test]
		public void CheckLeftJoin4([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent
					join ch in
						from c in Child
						where c.ParentID > 0
						select new { c.ParentID, c.ChildID }
					on p.ParentID equals ch.ParentID into lj1
					from ch in lj1.DefaultIfEmpty()
					where ch == null
					select p
					,
					from p in db.Parent
					join ch in
						from c in db.Child
						where c.ParentID > 0
						select new { c.ParentID, c.ChildID }
					on p.ParentID equals ch.ParentID into lj1
					from ch in lj1.DefaultIfEmpty()
					where ch == null
					select p);
		}

		[Test]
		public void CheckNull1([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent where p != null select p,
					from p in db.Parent where p != null select p);
		}

		[Test]
		public void CheckNull2([DataSources] string context)
		{
			int? n = null;

			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent where n != null || p.ParentID > 1 select p,
					from p in db.Parent where n != null || p.ParentID > 1 select p);
		}

		[Test]
		public void CheckNull3([DataSources(ProviderName.SqlCe)] string context)
		{
			int? n = 1;

			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent where n != null || p.ParentID > 1 select p,
					from p in db.Parent where n != null || p.ParentID > 1 select p);
		}

		[Test]
		public void CheckCondition1([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent
					where p.ParentID == 1 && p.Value1 == 1 || p.ParentID == 2 && p.Value1.HasValue
					select p
					,
					from p in db.Parent
					where p.ParentID == 1 && p.Value1 == 1 || p.ParentID == 2 && p.Value1.HasValue
					select p);
		}

		[Test]
		public void CheckCondition2([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent
					where p.ParentID == 1 && p.Value1 == 1 || p.ParentID == 2 && (p.ParentID != 3 || p.ParentID == 4) && p.Value1.HasValue
					select p
					,
					from p in db.Parent
					where p.ParentID == 1 && p.Value1 == 1 || p.ParentID == 2 && (p.ParentID != 3 || p.ParentID == 4) && p.Value1.HasValue
					select p);
		}

		[Test]
		public void CompareObject1([DataSources] string context)
		{
			var child = (from ch in Child where ch.ParentID == 2 select ch).First();

			using (var db = GetDataContext(context))
				AreEqual(
					from ch in Child where ch == child select ch,
					from ch in db.Child where ch == child select ch);
		}

		[Test]
		public void CompareObject2([DataSources] string context)
		{
			var parent = (from p in Parent where p.ParentID == 2 select p).First();

			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent where parent == p select p,
					from p in db.Parent where parent == p select p);
		}

		[Test]
		public void CompareObject3([DataSources] string context)
		{
			var child = (from ch in Child where ch.ParentID == 2 select ch).First();

			using (var db = GetDataContext(context))
				AreEqual(
					from ch in Child where ch != child select ch,
					from ch in db.Child where ch != child select ch);
		}

		[Test]
		public void OrAnd([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from c in Child
					where (c.ParentID == 2 || c.ParentID == 3) && c.ChildID != 21
					select c
					,
					from c in db.Child
					where (c.ParentID == 2 || c.ParentID == 3) && c.ChildID != 21
					select c);
		}

		[Test]
		public void NotOrAnd([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from c in Child
					where !(c.ParentID == 2 || c.ParentID == 3) && c.ChildID != 44
					select c
					,
					from c in db.Child
					where !(c.ParentID == 2 || c.ParentID == 3) && c.ChildID != 44
					select c);
		}

		[Test]
		public void AndOr([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent
					where p.ParentID == 1 || (p.ParentID == 2 || p.ParentID == 3) && (p.ParentID == 3 || p.ParentID == 1)
					select p,
					from p in db.Parent
					where p.ParentID == 1 || (p.ParentID == 2 || p.ParentID == 3) && (p.ParentID == 3 || p.ParentID == 1)
					select p);
		}

		[Test]
		public void Contains1([DataSources] string context)
		{
			var words = new [] { "John", "Pupkin" };

			using (var db = GetDataContext(context))
				AreEqual(
					from p in Person
					where words.Contains(p.FirstName) || words.Contains(p.LastName)
					select p
					,
					from p in db.Person
					where words.Contains(p.FirstName) || words.Contains(p.LastName)
					select p);
		}

		[Test]
		public void Contains2([DataSources] string context)
		{
			IEnumerable<int> ids = new [] { 2, 3 };

			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent where ids.Contains(p.ParentID) select p,
					from p in db.Parent where ids.Contains(p.ParentID) select p);
		}

		static IEnumerable<int> GetIds()
		{
			yield return 1;
			yield return 2;
		}

		[Test]
		public void Contains3([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent where GetIds().Contains(p.ParentID) select p,
					from p in db.Parent where GetIds().Contains(p.ParentID) select p);
		}

		static IEnumerable<int> GetIds(int start, int n)
		{
			for (int i = 0; i < n; i++)
				yield return start + i;
		}

		[Test]
		public void Contains4([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent where GetIds(1, 2).Contains(p.ParentID) || GetIds(3, 0).Contains(p.ParentID) select p,
					from p in db.Parent where GetIds(1, 2).Contains(p.ParentID) || GetIds(3, 0).Contains(p.ParentID) select p);
		}

		[Test]
		public void Contains5([DataSources] string context)
		{
			IEnumerable<int> ids = new int[0];

			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent where !ids.Contains(p.ParentID) select p,
					from p in db.Parent where !ids.Contains(p.ParentID) select p);
		}

		[Test]
		public void AliasTest1([DataSources] string context)
		{
			int user = 3;

			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent where p.ParentID == user select p,
					from p in db.Parent where p.ParentID == user select p);
		}

		[Test]
		public void AliasTest2([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					   Parent.Where(_ => _.ParentID == 3),
					db.Parent.Where(_ => _.ParentID == 3));
		}

		[Test]
		public void AliasTest3([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					   Parent.Where(_p => _p.ParentID == 3),
					db.Parent.Where(_p => _p.ParentID == 3));
		}

		[Test]
		public void AliasTest4([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					   Parent.Where(тбл => тбл.ParentID == 3),
					db.Parent.Where(тбл => тбл.ParentID == 3));
		}

		[Test]
		public void AliasTest5([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					   Parent.Where(p_ => p_.ParentID == 3),
					db.Parent.Where(p_ => p_.ParentID == 3));
		}

		[Test]
		public void SelectNestedCalculatedTest([NorthwindDataContext] string context)
		{
			using (var db = new NorthwindDB(context))
			{
				var dd = GetNorthwindAsList(context);
				AreEqual(
					from r in from o in dd.Order select o.Freight * 1000 where r > 100000 select r / 1000,
					from r in from o in db.Order select o.Freight * 1000 where r > 100000 select r / 1000);
			}
		}

		[Test]
		public void CheckField1([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent
					select new { p } into p
					where p.p.ParentID == 1
					select p.p
					,
					from p in db.Parent
					select new { p } into p
					where p.p.ParentID == 1
					select p.p);
		}

		[Test]
		public void CheckField2([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent
					select new { p } into p
					where p.p.ParentID == 1
					select new { p.p.Value1, p },
					from p in db.Parent
					select new { p } into p
					where p.p.ParentID == 1
					select new { p.p.Value1, p });
		}

		[Test]
		public void CheckField3([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent
					select new { p } into p
					where p.p.ParentID == 1
					select new { p.p.Value1, p.p },
					from p in db.Parent
					select new { p } into p
					where p.p.ParentID == 1
					select new { p.p.Value1, p.p });
		}

		[Test]
		public void CheckField4([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					   Parent.Select(p => new { p }).Where(p => p.p.ParentID == 1),
					db.Parent.Select(p => new { p }).Where(p => p.p.ParentID == 1));
		}

		[Test]
		public void CheckField5([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					   Parent.Select(p => new { Value = p.Value1 + 1, p }).Where(p => p.Value == 2 && p.p.ParentID == 1),
					db.Parent.Select(p => new { Value = p.Value1 + 1, p }).Where(p => p.Value == 2 && p.p.ParentID == 1));
		}

		[Test]
		public void CheckField6([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent
					select new { p, Value = p.Value1 * 100 } into p
					where p.p.ParentID == 1 && p.Value > 0 select new { p.p.Value1, p.Value, p.p, p1 = p },
					from p in db.Parent
					select new { p, Value = p.Value1 * 100 } into p
					where p.p.ParentID == 1 && p.Value > 0 select new { p.p.Value1, p.Value, p.p, p1 = p });
		}

		[Test]
		public void SubQuery1([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				var q = from p in db.Types
						select new { Value = Math.Round(p.MoneyValue, 2) } into pp
						where pp.Value != 0 && pp.Value != 7
						select pp.Value;

				if (context.StartsWith("DB2"))
					q = q.AsQueryable().Select(t => Math.Round(t, 2));

				AreEqual(
					from p in Types
					select new { Value = Math.Round(p.MoneyValue, 2) } into pp
					where pp.Value != 0 && pp.Value != 7
					select pp.Value
					,
					q);
			}
		}

		[Test]
		public void SearchCondition1([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from t in Types
					where !t.BoolValue && t.MoneyValue > 1 && (t.SmallIntValue == 5 || t.SmallIntValue == 7 || t.SmallIntValue == 8)
					select t,
					from t in db.Types
					where !t.BoolValue && t.MoneyValue > 1 && (t.SmallIntValue == 5 || t.SmallIntValue == 7 || t.SmallIntValue == 8)
					select t);
		}

		[Test]
		public void GroupBySubQquery1([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				var p1    = Child;
				var qry1  = p1.GroupBy(x => x.ParentID).Select(x => x.Max(y => y.ChildID));
				var qry12 = p1.Where(x => qry1.Any(y => y == x.ChildID));

				var p2    = db.Child;
				var qry2  = p2.GroupBy(x => x.ParentID).Select(x => x.Max(y => y.ChildID));
				var qry22 = p2.Where(x => qry2.Any(y => y == x.ChildID));

				AreEqual(qry12, qry22);
			}
		}

		[Test]
		public void GroupBySubQquery2([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				var p1    = Child;
				var qry1  = p1.GroupBy(x => x.ParentID).Select(x => x.Max(y => y.ChildID));
				var qry12 = p1.Where(x => qry1.Contains(x.ChildID));

				var p2    = db.Child;
				var qry2  = p2.GroupBy(x => x.ParentID).Select(x => x.Max(y => y.ChildID));
				var qry22 = p2.Where(x => qry2.Contains(x.ChildID));

				AreEqual(qry12, qry22);
			}
		}

		[Test]
		public void GroupBySubQquery2In([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				var p1    = Child;
				var qry1  = p1.GroupBy(x => x.ParentID).Select(x => x.Max(y => y.ChildID));
				var qry12 = p1.Where(x => x.ChildID.In(qry1));

				var p2    = db.Child;
				var qry2  = p2.GroupBy(x => x.ParentID).Select(x => x.Max(y => y.ChildID));
				var qry22 = p2.Where(x => x.ChildID.In(qry2));

				AreEqual(qry12, qry22);
			}
		}

		[Test]
		public void HavingTest1([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				AreEqual(
					Child
						.GroupBy(c => c.ParentID)
						.Where(c => c.Count() > 1)
						.Select(g => new { count = g.Count() }),
					db.Child
						.GroupBy(c => c.ParentID)
						.Where(c => c.Count() > 1)
						.Select(g => new { count = g.Count() }));
			}
		}

		[Test]
		public void HavingTest2([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				AreEqual(
					Child
						.GroupBy(c => c.ParentID)
						.Select(g => new { count = g.Count() })
						.Where(c => c.count > 1),
					db.Child
						.GroupBy(c => c.ParentID)
						.Select(g => new { count = g.Count() })
						.Having(c => c.count > 1)
						.Where(c => c.count > 1));
			}
		}

		[Test]
		public void HavingTest3([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				AreEqual(
					Child
						.GroupBy(c => c.ParentID)
						.Where(c => c.Key > 1 && c.Count() > 1)
						.Select(g => g.Count()),
					db.Child
						.GroupBy(c => c.ParentID)
						.Where(c => c.Key > 1 && c.Count() > 1)
						.Having(c => c.Key > 1)
						.Select(g => g.Count()));
			}
		}

		[Test]
		public void WhereDateTimeTest1([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				AreEqual(
					   Types
						.Where(_ => _.DateTimeValue > new DateTime(2009, 1, 1))
						.Select(_ => _),
					db.Types
						.Where(_ => _.DateTimeValue > new DateTime(2009, 1, 1))
						.Select(_ => _));
			}
		}

		[Test]
		public void WhereDateTimeTest2([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				AreEqual(
					   Types
						.Where(_ => _.DateTimeValue > new DateTime(2009, 1, 1))
						.Select(_ => _),
					db.Types
						.Where(_ => _.DateTimeValue > new DateTime(2009, 1, 1))
						.Select(_ => _));
			}
		}

		[Test]
		public void WhereDateTimeTest3([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				AreEqual(
					GetTypes(context)
						.Where(_ => _.DateTimeValue == new DateTime(2009, 9, 27))
						.Select(_ => _),
					db.Types
						.Where(_ => _.DateTimeValue == new DateTime(2009, 9, 27))
						.Select(_ => _));
			}
		}

		[Test]
		public void WhereDateTimeTest4([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				AreEqual(
					   Types2
						.Where(_ => _.DateTimeValue == new DateTime(2009, 9, 27))
						.Select(_ => _),
					db.Types2
						.Where(_ => _.DateTimeValue == new DateTime(2009, 9, 27))
						.Select(_ => _));
			}
		}

		[Test]
		public void WhereDateTimeTest5([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				AreEqual(
					GetTypes(context)
						.Where(_ => _.DateTimeValue.Date == new DateTime(2009, 9, 20).Date)
						.Select(_ => _),
					db.Types
						.Where(_ => _.DateTimeValue.Date == new DateTime(2009, 9, 20).Date)
						.Select(_ => _));
			}
		}

		[Test]
		public void WhereDateTimeTest6([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				AreEqual(
					   AdjustExpectedData(db, Types2
						.Where(_ => _.DateTimeValue!.Value.Date == new DateTime(2009, 9, 20).Date)
						.Select(_ => _)),
					db.Types2
						.Where(_ => _.DateTimeValue!.Value.Date == new DateTime(2009, 9, 20).Date)
						.Select(_ => _));
			}
		}

		class WhereCases
		{
			[PrimaryKey]
			public int Id { get; set; }
			[Column]
			[Column(Configuration = ProviderName.DB2, DbType = "smallint")]
			public bool BoolValue { get; set; }
			[Column]
			[Column(Configuration = ProviderName.DB2, DbType = "smallint")]
			public bool? NullableBoolValue { get; set; }

			public static readonly IEqualityComparer<WhereCases> Comparer = ComparerBuilder.GetEqualityComparer<WhereCases>();
		}

		[Test]
		public void WhereBooleanTest2([DataSources(TestProvName.AllSybase, TestProvName.AllFirebird)] string context)
		{
			void AreEqualLocal(IEnumerable<WhereCases> expected, IQueryable<WhereCases> actual, Expression<Func<WhereCases, bool>> predicate)
			{
				var exp = expected.Where(predicate.Compile());
				var act = actual.  Where(predicate);
				AreEqual(exp, act, WhereCases.Comparer);
				Assert.That(act.ToString(), Does.Not.Contain("<>"));

				var notPredicate = Expression.Lambda<Func<WhereCases, bool>>(
					Expression.Not(predicate.Body), predicate.Parameters);

				var expNot      = expected.Where(notPredicate.Compile()).ToArray();
				var actNotQuery = actual.Where(notPredicate);
				var actNot      = actNotQuery.ToArray();
				AreEqual(expNot, actNot, WhereCases.Comparer);

				Assert.That(actNotQuery.ToString(), Does.Not.Contain("<>"));
			}

			void AreEqualLocalPredicate(IEnumerable<WhereCases> expected, IQueryable<WhereCases> actual, Expression<Func<WhereCases, bool>> predicate, Expression<Func<WhereCases, bool>> localPredicate)
			{
				var actualQuery = actual.Where(predicate);
				AreEqual(expected.Where(localPredicate.Compile()), actualQuery, WhereCases.Comparer);
				Assert.That(actualQuery.ToString(), Does.Not.Contain("<>"));

				var notLocalPredicate = Expression.Lambda<Func<WhereCases, bool>>(
					Expression.Not(localPredicate.Body), localPredicate.Parameters);

				var notPredicate = Expression.Lambda<Func<WhereCases, bool>>(
					Expression.Not(predicate.Body), predicate.Parameters);

				var expNot = expected.Where(notLocalPredicate.Compile()).ToArray();
				var actualNotQuery = actual.Where(notPredicate);

				var actNot = actualNotQuery.ToArray();
				AreEqual(expNot, actNot, WhereCases.Comparer);

				Assert.That(actualNotQuery.ToString(), Does.Not.Contain("<>"));
			}

			using (var db = GetDataContext(context))
			using (var table = db.CreateLocalTable(new[]
			{
				new WhereCases { Id = 1,  BoolValue = true,  NullableBoolValue = null  },
				new WhereCases { Id = 2,  BoolValue = true,  NullableBoolValue = true  },
				new WhereCases { Id = 3,  BoolValue = true,  NullableBoolValue = null  },
				new WhereCases { Id = 4,  BoolValue = true,  NullableBoolValue = true  },
				new WhereCases { Id = 5,  BoolValue = true,  NullableBoolValue = true  },

				new WhereCases { Id = 11, BoolValue = false, NullableBoolValue = null  },
				new WhereCases { Id = 12, BoolValue = false, NullableBoolValue = false },
				new WhereCases { Id = 13, BoolValue = false, NullableBoolValue = null  },
				new WhereCases { Id = 14, BoolValue = false, NullableBoolValue = false },
				new WhereCases { Id = 15, BoolValue = false, NullableBoolValue = false },
			}))
			{
				var local = table.ToArray();

				AreEqualLocal(local, table, t => !t.BoolValue && t.Id > 0);
				AreEqualLocal(local, table, t => !(t.BoolValue != true) && t.Id > 0);
				AreEqualLocal(local, table, t => t.BoolValue == true && t.Id > 0);
				AreEqualLocal(local, table, t => t.BoolValue != true && t.Id > 0);
				AreEqualLocal(local, table, t => t.BoolValue == false && t.Id > 0);

				AreEqualLocalPredicate(local, table,
					t => !t.NullableBoolValue!.Value && t.Id > 0,
					t => (!t.NullableBoolValue.HasValue || !t.NullableBoolValue.Value) && t.Id > 0);

				AreEqualLocal(local, table, t => !(t.NullableBoolValue != true) && t.Id > 0);
				AreEqualLocal(local, table, t => t.NullableBoolValue == true && t.Id > 0);

				if (!context.StartsWith(ProviderName.Access))
				{
					AreEqualLocal(local, table, t => t.NullableBoolValue == null && t.Id > 0);
					AreEqualLocal(local, table, t => t.NullableBoolValue != null && t.Id > 0);

					AreEqualLocal(local, table, t => !(t.NullableBoolValue == null) && t.Id > 0);
					AreEqualLocal(local, table, t => !(t.NullableBoolValue != null) && t.Id > 0);
				}

				AreEqualLocal(local, table, t => (!t.BoolValue && t.NullableBoolValue != true) && t.Id > 0);
				AreEqualLocal(local, table, t => !(!t.BoolValue && t.NullableBoolValue != true) && t.Id > 0);

				AreEqualLocal(local, table, t => (!t.BoolValue && t.NullableBoolValue == false) && t.Id > 0);

				AreEqualLocal(local, table, t => !(!t.BoolValue && t.NullableBoolValue == false) && t.Id > 0);
			}
		}

		[Test]
		public void IsNullTest([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				AreEqual(
					from p in db.Person.AsEnumerable()
					select p.MiddleName into nm
					where !(nm == null)
					select new { nm }
					,
					from p in db.Person
					select p.MiddleName into nm
					where !(nm == null)
					select new { nm });
			}
		}

		[Test]
		public void IsNullOrEmptyTest1([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				AreEqual(
					from p in db.Person.AsEnumerable()
					select p.MiddleName into nm
					where !(string.IsNullOrEmpty(nm))
					select new { nm }
					,
					from p in db.Person
					select p.MiddleName into nm
					where !(string.IsNullOrEmpty(nm))
					select new { nm });
			}
		}

		[Test]
		public void IsNullOrEmptyTest2([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				AreEqual(
					from p in db.Person.AsEnumerable()
					select p.FirstName into nm
					where !(string.IsNullOrEmpty(nm))
					select new { nm }
					,
					from p in db.Person
					select p.FirstName into nm
					where !(string.IsNullOrEmpty(nm))
					select new { nm });
			}
		}

		[Test]
		public void LengthTest1([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				AreEqual(
					from p in db.Person.AsEnumerable()
					select p.MiddleName into nm
					where !(nm?.Length == 0)
					select new { nm }
					,
					from p in db.Person
					select p.MiddleName into nm
					where !(nm.Length == 0)
					select new { nm });
			}
		}

		[Test]
		public void LengthTest2([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				AreEqual(
					from p in db.Person.AsEnumerable()
					select p.FirstName into nm
					where !(nm.Length == 0)
					select new { nm }
					,
					from p in db.Person
					select p.FirstName into nm
					where !(nm.Length == 0)
					select new { nm });
			}
		}

		[Test]
		public void Issue1755Test1([DataSources] string context, [Values(1, 2)] int id, [Values(null, true, false)] bool? flag)
		{
			using (var db = GetDataContext(context))
			{
				var results = (from c in db.Parent
							   where c.ParentID == id
								   && (!flag.HasValue || flag.Value && c.Value1 == null || !flag.Value && c.Value1 != null)
							   select c);

				var sql = results.ToString();

				AreEqual(
					from c in db.Parent.AsEnumerable()
					where c.ParentID == id
						&& (!flag.HasValue || flag.Value && c.Value1 == null || !flag.Value && c.Value1 != null)
					select c,
					results,
					true);

				// remote context doesn't have access to final SQL
				if (!context.EndsWith(".LinqService"))
					Assert.AreEqual(flag == null ? 0 : 1, Regex.Matches(sql, " AND ").Count);
			}
		}

		[Test]
		public void Issue1755Test2([DataSources] string context, [Values(1, 2)] int id, [Values(null, true, false)] bool? flag)
		{
			using (var db = GetDataContext(context))
			{
				var results = (from c in db.Parent
							   where c.ParentID == id
								   && (flag == null || flag.Value && c.Value1 == null || !flag.Value && c.Value1 != null)
							   select c);

				var sql = results.ToString();

				AreEqual(
					from c in db.Parent.AsEnumerable()
					where c.ParentID == id
						&& (flag == null || flag.Value && c.Value1 == null || !flag.Value && c.Value1 != null)
					select c,
					results,
					true);

				// remote context doesn't have access to final SQL
				if (!context.EndsWith(".LinqService"))
					Assert.AreEqual(flag == null ? 0 : 1, Regex.Matches(sql, " AND ").Count);
			}
		}

		[Test]
		public void ExistsSqlTest1([DataSources(false)] string context)
		{
			using (var db = new TestDataConnection(context))
			using (db.BeginTransaction())
			{
				db.Parent.Where(p => db.Child.Select(c => c.ParentID).Contains(p.ParentID)).Delete();

				Assert.False(db.LastQuery!.ToLower().Contains("iif(exists(") || db.LastQuery!.ToLower().Contains("when exists("));
			}
		}

		[Test]
		public void ExistsSqlTest2([DataSources(false)] string context)
		{
			using (var db = new TestDataConnection(context))
			using (db.BeginTransaction())
			{
				db.Parent.Where(p => p.Children.Any()).Delete();

				Assert.False(db.LastQuery!.ToLower().Contains("iif(exists(") || db.LastQuery!.ToLower().Contains("when exists("));
			}
		}

		[ActiveIssue(1767)]
		[Test]
		public void Issue1767Test([DataSources(false)] string context)
		{
			using (var db = new TestDataConnection(context))
			using (db.BeginTransaction())
			{
				db.Person.FirstOrDefault(p => p.MiddleName != null && p.MiddleName != "test");

				Assert.True(db.LastQuery!.Contains("IS NOT NULL"));
				Assert.False(db.LastQuery!.Contains("IS NULL"));
			}
		}

		class Parameter
		{
			public int Id;
		}

		[Test]
		public void OptionalObjectInCondition([DataSources(false)] string context)
		{
			using (var db = new TestDataConnection(context))
			using (db.BeginTransaction())
			{
				var p  = new Parameter() { Id = 1};
				db.Person.Where(r => r.FirstName == (p != null ? p.Id.ToString() : null)).ToList();
				p = null;
				db.Person.Where(r => r.FirstName == (p != null ? p.Id.ToString() : null)).ToList();
				p = new Parameter() { Id = 1 };
				db.Person.Where(r => r.FirstName == (p != null ? p.Id.ToString() : null)).ToList();
			}
		}

		[Test]
		public void SrtingInterpolationTests([DataSources(false)] string context)
		{
			using (var db = GetDataContext(context))
			{
				var cnt = db.Person
					.Count(p => p.LastName + ", " + p.FirstName == $"{p.LastName}, {p.FirstName}"
					            && "<" + p.LastName + ", " + p.FirstName + ">" == $"<{p.LastName}, {p.FirstName}>"
					            && "<" + p.LastName + p.FirstName + ">" == $"<{p.LastName}{p.FirstName}>"
					            && "<{p.LastName}, " + p.FirstName + " {" + p.LastName + "}" + ">" == $"<{{p.LastName}}, {p.FirstName} {{{p.LastName}}}>"
					            && "{}" + p.LastName == $"{{}}{p.LastName}"
					);

				Assert.That(cnt, Is.EqualTo(db.Person.Count()));
			}
		}

		#region issue 2424
		class Isue2424Table
		{
			[Column] public int    Id;
			[Column] public string StrValue = null!;

			public static readonly Isue2424Table[] Data = new[]
			{
				new Isue2424Table(){ Id = 1, StrValue = "1" },
				new Isue2424Table(){ Id = 3, StrValue = "3" },
				new Isue2424Table(){ Id = 5, StrValue = "5" }
			};
		}

		[Test]
		public void Issue2424([DataSources(false)] string context)
		{
			using (var db = GetDataContext(context))
			using (db.CreateLocalTable(Isue2424Table.Data))
			{
				var record = db.GetTable<Isue2424Table>().Single(i => 0 <= i.StrValue.CompareTo("4"));
				Assert.AreEqual(5, record.Id);
				record = db.GetTable<Isue2424Table>().Single(i => i.StrValue.CompareTo("4") >= 0);
				Assert.AreEqual(5, record.Id);

				record = db.GetTable<Isue2424Table>().Single(i => 0 >= i.StrValue.CompareTo("2"));
				Assert.AreEqual(1, record.Id);
				record = db.GetTable<Isue2424Table>().Single(i => i.StrValue.CompareTo("2") <= 0);
				Assert.AreEqual(1, record.Id);

				record = db.GetTable<Isue2424Table>().Single(i => 0 < i.StrValue.CompareTo("3"));
				Assert.AreEqual(5, record.Id);
				record = db.GetTable<Isue2424Table>().Single(i => i.StrValue.CompareTo("3") > 0);
				Assert.AreEqual(5, record.Id);

				record = db.GetTable<Isue2424Table>().Single(i => 0 > i.StrValue.CompareTo("3"));
				Assert.AreEqual(1, record.Id);
				record = db.GetTable<Isue2424Table>().Single(i => i.StrValue.CompareTo("3") < 0);
				Assert.AreEqual(1, record.Id);

				record = db.GetTable<Isue2424Table>().Single(i => 0 == i.StrValue.CompareTo("3"));
				Assert.AreEqual(3, record.Id);
				record = db.GetTable<Isue2424Table>().Single(i => i.StrValue.CompareTo("3") == 0);
				Assert.AreEqual(3, record.Id);

				record = db.GetTable<Isue2424Table>().Single(i => 0 >= i.StrValue.CompareTo("2"));
				Assert.AreEqual(1, record.Id);
				record = db.GetTable<Isue2424Table>().Single(i => i.StrValue.CompareTo("2") <= 0);
				Assert.AreEqual(1, record.Id);

				record = db.GetTable<Isue2424Table>().Single(i => 0 <= i.StrValue.CompareTo("4"));
				Assert.AreEqual(5, record.Id);
				record = db.GetTable<Isue2424Table>().Single(i => i.StrValue.CompareTo("4") >= 0);
				Assert.AreEqual(5, record.Id);

				record = db.GetTable<Isue2424Table>().Single(i => 0 > i.StrValue.CompareTo("3"));
				Assert.AreEqual(1, record.Id);
				record = db.GetTable<Isue2424Table>().Single(i => i.StrValue.CompareTo("3") < 0);
				Assert.AreEqual(1, record.Id);

				record = db.GetTable<Isue2424Table>().Single(i => 0 < i.StrValue.CompareTo("3"));
				Assert.AreEqual(5, record.Id);
				record = db.GetTable<Isue2424Table>().Single(i => i.StrValue.CompareTo("3") > 0);
				Assert.AreEqual(5, record.Id);

				record = db.GetTable<Isue2424Table>().Single(i => 0 <= i.StrValue.CompareTo("5"));
				Assert.AreEqual(5, record.Id);
				record = db.GetTable<Isue2424Table>().Single(i => i.StrValue.CompareTo("5") >= 0);
				Assert.AreEqual(5, record.Id);

				record = db.GetTable<Isue2424Table>().Single(i => 0 >= i.StrValue.CompareTo("1"));
				Assert.AreEqual(1, record.Id);
				record = db.GetTable<Isue2424Table>().Single(i => i.StrValue.CompareTo("1") <= 0);
				Assert.AreEqual(1, record.Id);
			}
		}
		#endregion
	}
}


text:
Suggested features:

<button title="Sort by votes" ng-click="changeSort(1)" class="btn btn-default" ng-class="{'active':sortID==1}">Votes </button>
<button title="Sort by date added" ng-click="changeSort(2)" class="btn btn-default" ng-class="{'active':sortID==2}">Date </button>
<button title="Sort by number of comments" ng-click="changeSort(3)" class="btn btn-default" ng-class="{'active':sortID==3}">Comments </button>

<input type="checkbox" ng-model="displayAccepted" ng-change="updatePages()"> Display already accepted features

<ng-include src="'/views/pagination.html'"></ng-include>

{{f.upvotes - f.downvotes}}

                {{f.username | formatName}}{{f.stamp | getDelay}} ago
                 lastVisit">NEW
                | Added {{f.acceptedStamp | getDelay}} ago
                | Accepted for implementation

                {{f.desc}}

 0">
                    {{c.comment}} — {{c.username | formatName}} {{c.stamp | getDelay}} ago

 0 && f.showCommentForm == true">

                <button class="btn-primary btn-xs" ng-click="f.showCommentForm = true" ng-show="!f.showCommentForm">Add a comment</button>

                    <form name="commentForm" ng-submit="postComment(f)">

                            Name
                            <input type="text" maxlength="30" class="form-control mb-2 mr-sm-2 mb-sm-0" id="commentNameInput" ng-model="f.commentUsername" placeholder="Username (optional)">

                            Comment
                            <textarea maxlength="200" class="form-control" id="commentInput" rows="3" ng-model="f.comment"
                                      placeholder="Enter a comment (max. 200 characters)"></textarea>

                        <button type="submit" class="btn btn-primary">Submit</button>
                        Your comment was successfully added
                    </form>

<ng-include src="'/views/pagination.html'"></ng-include>
{{features.length}} features proposed so far

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe "cms_pages" do
  subject(:site) { cms_site }
  subject(:item) { Cms::Page.last }
  subject(:index_path) { cms_pages_path site.id }
  subject(:new_path) { new_cms_page_path site.id }
  subject(:show_path) { cms_page_path site.id, item }
  subject(:edit_path) { edit_cms_page_path site.id, item }
  subject(:delete_path) { delete_cms_page_path site.id, item }
  subject(:move_path) { move_cms_page_path site.id, item }
  subject(:copy_path) { copy_cms_page_path site.id, item }
  subject(:contain_links_path) { contain_links_cms_page_path site.id, item }

  it "without login" do
    visit index_path
    expect(current_path).to eq sns_login_path
  end

  it "without auth" do
    login_ss_user
    visit index_path
    expect(status_code).to eq 403
  end

  context "with auth" do
    before { login_cms_user }

    it "#index" do
      visit index_path
      expect(current_path).not_to eq sns_login_path
    end

    it "#new" do
      visit new_path
      within "form#item-form" do
        fill_in "item[name]", with: "sample"
        fill_in "item[basename]", with: "sample"
        click_button "保存"
      end
      expect(status_code).to eq 200
      expect(current_path).not_to eq new_path
      expect(page).to have_no_css("form#item-form")
    end

    it "#show" do
      visit show_path
      expect(status_code).to eq 200
      expect(current_path).not_to eq sns_login_path
    end

    it "#edit" do
      visit edit_path
      within "form#item-form" do
        fill_in "item[name]", with: "modify"
        click_button "保存"
      end
      expect(current_path).not_to eq sns_login_path
      expect(page).to have_no_css("form#item-form")
    end

    it "#move" do
      visit move_path
      within "form" do
        fill_in "destination", with: "destination"
        click_button "保存"
      end
      expect(status_code).to eq 200
      expect(current_path).to eq move_path
      expect(page).to have_css("form#item-form h2", text: "destination.html")

      within "form" do
        fill_in "destination", with: "sample"
        click_button "保存"
      end
      expect(status_code).to eq 200
      expect(current_path).to eq move_path
      expect(page).to have_css("form#item-form h2", text: "sample.html")
    end

    it "#copy" do
      visit copy_path
      within "form" do
        click_button "保存"
      end
      expect(status_code).to eq 200
      expect(current_path).to eq index_path
      expect(page).to have_css("a", text: "[複製] modify")
      expect(page).to have_css(".state", text: "非公開")
    end

    it "#delete" do
      visit delete_path
      within "form" do
        click_button "削除"
      end
      expect(current_path).to eq index_path
    end

    it "#contain_links" do
      visit contain_links_path
      expect(status_code).to eq 200
    end
  end

  # check_mobile_html_size at addon body
  describe "addon body", js: true do
    let(:site) { cms_site }

    context "check_mobile_html_size" do
      it "on click check_size_button html_size too big", fragile: true do
        site.mobile_size = 1_024
        site.save!

        login_cms_user
        visit new_cms_page_path(site)

        html_text = ""
        10.times.each do
          html_text += "
あいうえおカキクケコ

あいうえおカキクケコ

あいうえおカキクケコ
"
        end

        fill_in_ckeditor "item_html", with: html_text
        click_on I18n.t("cms.mobile_size_check")
        expect(page).to have_css "form #errorMobileChecker"
        expect(page).to have_selector "form #errorMobileChecker p.error", text: /携帯で表示する場合、本文のデータサイズが(.+)/i
      end

      it "on click check_size_button html_size ok" do

        html_text = "
あいうえおカキクケコ
"

        login_cms_user
        visit new_cms_page_path(site)

        fill_in_ckeditor "item_html", with: html_text
        click_on I18n.t("cms.mobile_size_check")

        expect(page).to have_css "form #errorMobileChecker"
        expect(page).to have_selector "form #errorMobileChecker p", text: I18n.t('errors.messages.mobile_size_check_size')
      end
    end

    context "check_file_size" do
      let(:file) { create(:ss_file, filename: "logo.png") }
      let(:test_file_path) { Rails.root.join("spec", "fixtures", "ss", "logo.png") }

      it "mobile_size 1", fragile: true do
        site.mobile_state = "enabled"
        site.mobile_size = 1_024
        site.save!

        html_text = ""

        login_cms_user
        visit new_cms_page_path(site)

        fill_in_ckeditor "item_html", with: html_text
        click_on I18n.t("cms.mobile_size_check")

        expect(page).to have_css "form #errorMobileChecker"
        expect(page).to have_selector "form #errorMobileChecker p", text: /携帯電話で表示する場合、ファイルサイズ合計(.+)/i
      end

      it "mobile_size 100" do
        site.mobile_state = "enabled"
        site.mobile_size = 100 * 1_024
        site.save!
        site.reload

        html_text = ""
        html_text += ""

        login_cms_user
        visit new_cms_page_path(site)

        fill_in_ckeditor "item_html", with: html_text
        click_on I18n.t("cms.mobile_size_check")
        expect(page).to have_selector "form #errorMobileChecker p", text: I18n.t('errors.messages.mobile_size_check_size')
      end

      it "many same files in html" do

        site.mobile_state = "enabled"
        site.mobile_size = 20 * 1_024
        site.save!
        site.reload

        html_text = ""
        html_text += ""

        login_cms_user
        visit new_cms_page_path(site)

        fill_in_ckeditor "item_html", with: html_text
        click_on I18n.t("cms.mobile_size_check")
        expect(page).to have_selector "#errorMobileChecker p", text: I18n.t('errors.messages.mobile_size_check_size')

        3.times.each do
          html_text += ""
        end

        fill_in_ckeditor "item_html", with: html_text
        click_on I18n.t("cms.mobile_size_check")
        expect(page).to have_selector "#errorMobileChecker p", text: I18n.t('errors.messages.mobile_size_check_size')
      end

      it "many different files in html", fragile: true do

        site.mobile_state = "enabled"
        site.mobile_size = 6 * 1_024
        site.save!
        site.reload

        file2 = Cms::File.new model: "cms/file", site_id: site.id
        file_path = Rails.root.join("spec", "fixtures", "ss", "file", "keyvisual.jpg")
        Fs::UploadedFile.create_from_file(file_path, basename: "spec") do |test_file|
          file2.in_file = test_file
          file2.save!
        end

        html_text = ""
        html_text += ""
        html_text += ""

        login_cms_user
        visit new_cms_page_path(site)

        fill_in_ckeditor "item_html", with: html_text
        click_on I18n.t("cms.mobile_size_check")
        expect(page).to have_selector "form #errorMobileChecker p", text: /携帯電話で表示する場合、ファイルサイズ合計(.+)/i
      end
    end
  end

  def fill_in_ckeditor(locator, opts)
    content = opts.fetch(:with).to_json
    page.execute_script <<-SCRIPT
      $('textarea##{locator}').text(#{content});
      CKEDITOR.instances['#{locator}'].setData(#{content});
    SCRIPT
  end
end


text:
import React from 'react'
import PropTypes from 'prop-types'
import { DragDropContext, Droppable } from 'react-beautiful-dnd'
import { pure } from 'recompose'

import Draggable from './Draggable'

import { reorder, scrollToElem } from '../../utils'

const Toc = ({ steps, onReorderSteps }) => (

TOC

     scrollToElem(document.querySelector('html'), 0, 300)}>
      Details

    <DragDropContext
      onDragEnd={result => onDragEnd(result, steps, onReorderSteps)}
    >
      <Droppable droppableId='droppable'>
        {(provided, snapshot) => (

              {steps.map(({ title }, sIdx) => (
                <Draggable key={sIdx} sIdx={sIdx} title={title} />
              ))}

            {provided.placeholder}

        )}
      </Droppable>
    </DragDropContext>

)

Toc.propTypes = {
  steps: PropTypes.array.isRequired,
  onReorderSteps: PropTypes.func.isRequired,
}

export default pure(Toc)

function onDragEnd(result, steps, onReorderSteps) {
  // dropped outside the list
  if (!result.destination) {
    return
  }
  onReorderSteps(reorder(steps, result.source.index, result.destination.index))
}

const grid = 2

// function getItemStyle(draggableStyle, isDragging) {
//   return {
//     // some basic styles to make the items look a bit nicer
//     userSelect: 'none',
//     padding: grid * 2,
//     margin: `0 0 ${grid}px 0`,
//     // change background colour if dragging
//     background: isDragging ? 'lightgreen' : '',
//     border: '1px solid #000',
//     // styles we need to apply on draggables
//     ...draggableStyle,
//   }
// }

function getListStyle(isDraggingOver) {
  return {
    background: isDraggingOver ? 'lightblue' : 'lightgrey',
    padding: grid,
  }
}


text:
from __future__ import absolute_import
from ..base import BaseService

class DockerService(BaseService):
    def get_event(self, request, body):
        return 'push'  # docker hub only has push event


text:
<?php

namespace Fly\Mvc\Router\Exception;

use Fly\Mvc\Exception\ExceptionInterface as Exception;

interface ExceptionInterface extends Exception
{
}


text:
/**
 * @author alteredq / http://alteredqualia.com/
 * @author mr.doob / http://mrdoob.com/
 */

const WEBGL = {
  isWebGLAvailable: function() {
    try {
      var canvas = document.createElement('canvas')
      return !!(
        window.WebGLRenderingContext &&
        (canvas.getContext('webgl') || canvas.getContext('experimental-webgl'))
      )
    } catch (e) {
      return false
    }
  },

  isWebGL2Available: function() {
    try {
      var canvas = document.createElement('canvas')
      return !!(window.WebGL2RenderingContext && canvas.getContext('webgl2'))
    } catch (e) {
      return false
    }
  },

  getWebGLErrorMessage: function() {
    return this.getErrorMessage(1)
  },

  getWebGL2ErrorMessage: function() {
    return this.getErrorMessage(2)
  },

  getErrorMessage: function(version) {
    var names = {
      1: 'WebGL',
      2: 'WebGL 2'
    }

    var contexts = {
      1: window.WebGLRenderingContext,
      2: window.WebGL2RenderingContext
    }

    var message =
      'Your $0 does not seem to support $1'

    var element = document.createElement('div')
    element.id = 'webglmessage'
    element.style.fontFamily = 'monospace'
    element.style.fontSize = '13px'
    element.style.fontWeight = 'normal'
    element.style.textAlign = 'center'
    element.style.background = '#fff'
    element.style.color = '#000'
    element.style.padding = '1.5em'
    element.style.width = '400px'
    element.style.margin = '5em auto 0'

    if (contexts[version]) {
      message = message.replace('$0', 'graphics card')
    } else {
      message = message.replace('$0', 'browser')
    }

    message = message.replace('$1', names[version])

    element.innerHTML = message

    return element
  }
}

export default WEBGL


text:
package org.incode.module.classification.integtests.classification;

import javax.inject.Inject;

import org.junit.Before;
import org.junit.Test;

import org.incode.module.classification.dom.impl.applicability.ApplicabilityRepository;
import org.incode.module.classification.dom.impl.category.Category;
import org.incode.module.classification.dom.impl.category.CategoryRepository;
import org.incode.module.classification.dom.impl.classification.Classification;
import org.incode.module.classification.dom.impl.classification.ClassificationRepository;
import org.incode.module.classification.dom.spi.ApplicationTenancyService;
import org.incode.module.classification.fixture.dom.demo.first.DemoObject;
import org.incode.module.classification.fixture.dom.demo.first.DemoObjectMenu;
import org.incode.module.classification.fixture.scripts.scenarios.ClassifiedDemoObjectsFixture;
import org.incode.module.classification.integtests.ClassificationModuleIntegTest;

import static org.assertj.core.api.Assertions.assertThat;

public class Classification_remove_IntegTest extends ClassificationModuleIntegTest {

    @Inject
    ClassificationRepository classificationRepository;
    @Inject
    CategoryRepository categoryRepository;
    @Inject
    ApplicabilityRepository applicabilityRepository;

    @Inject
    DemoObjectMenu demoObjectMenu;
    @Inject
    ApplicationTenancyService applicationTenancyService;

    Object classified;

    @Before
    public void setUpData() throws Exception {
        fixtureScripts.runFixtureScript(new ClassifiedDemoObjectsFixture(), null);
    }

    @Test
    public void happy_case() {
        // given
        DemoObject demoFooInItaly = demoObjectMenu.listAll().stream()
                .filter(demoObject -> demoObject.getName().equals("Demo foo (in Italy)"))
                .findFirst()
                .get();

        Classification italianClassificationRed = classificationRepository.findByClassified(demoFooInItaly)
                .stream()
                .filter(classification -> classification.getCategory().getName().equals("Red"))
                .findFirst()
                .get();

        // when
        wrap(italianClassificationRed).remove();

        // then
        assertThat(classificationRepository.findByClassified(demoFooInItaly))
                .extracting(Classification::getCategory)
                .extracting(Category::getName)
                .doesNotContain("Red");

    }

}


text:
ENV["RAILS_ENV"] ||= 'test'
if ENV['COVERAGE']
  require 'simplecov'
  SimpleCov.start
end
require 'cyrax'


text:
exopy.instruments.user module
============================

.. automodule:: exopy.instruments.user
    :members:
    :undoc-members:
    :show-inheritance:


text:
@interface BMYViewController : UIViewController

@end


text:
package jacobi.core.impl;

import jacobi.api.Matrix;
import jacobi.api.annotations.Delegate;
import jacobi.api.annotations.Pure;
import jacobi.api.ext.Op;
import jacobi.api.ext.Prop;
import jacobi.core.util.Throw;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.DoubleStream;

/**
 *
 * Implementation of a diagonal matrix. This class stores the diagonal values
 * only, which saves many un-necessary zero elements. To maintain being
 * diagonal, this class is immutable.
 *
 * @author Y.K. Chan
 */
public class DiagonalMatrix extends ImmutableMatrix {

    /**
     * Constructor.
     * @param vector  Diagonal elements
     */
    public DiagonalMatrix(double[] vector) {
        this(vector.length, vector.length, vector);
    }

    /**
     * Constructor.
     * @param vector  Diagonal elements
     * @param rowCount  Number of rows
     * @param colCount  Number of columns
     */
    public DiagonalMatrix(int rowCount, int colCount, double[] vector) {
        this.vector = Arrays.copyOf(vector, vector.length);
        this.rowCount = rowCount;
    }

    @Override
    public int getRowCount() {
        return this.rowCount;
    }

    @Override
    public int getColCount() {
        return this.vector.length;
    }

    @Override
    public double[] getRow(int index) {
        double[] row = new double[this.getColCount()];
        if(index < this.vector.length){
            row[index] = this.vector[index];
        }
        return row;
    }

    @Override
    public double get(int i, int j) {
        return i == j ? this.vector[i] : 0.0;
    }

    @Override
    public Matrix copy() {
        return CopyOnWriteMatrix.of(new DiagonalMatrix(this.rowCount, this.colCount, this.vector));
    }

    /**
     * Determinant of the diagonal matrix.
     * @return  det(A), which A is this matrix
     */
    @Pure
    @Delegate(facade = Prop.class, method = "det")
    public double det() {
        return DoubleStream.of(this.vector).reduce(1.0, (a, b) -> a * b);
    }

    /**
     * Inverse of the diagonal matrix.
     * @return  A^-1
     */
    @Pure
    @Delegate(facade = Prop.class, method = "inv")
    public Optional<Matrix> inv() {
        double[] diag = new double[this.vector.length];
        for(int i = 0; i < diag.length; i++){
            if(Math.abs(this.vector[i]) < 1e-12){
                return Optional.empty();
            }
            diag[i] = 1.0 / this.vector[i];
        }
        return Optional.of(CopyOnWriteMatrix.of(new DiagonalMatrix(diag)));
    }

    /**
     * Compute D * B where D is this diagonal matrix.
     * @param b  Input matrix B
     * @return  D * B
     */
    @Pure
    @Delegate(facade = Op.class, method = "mul")
    public Matrix mul(Matrix b) {
        Throw.when()
            .isNull(() -> b, () -> "Missing 2nd operand.")
            .isTrue(
                () -> b.getRowCount() != this.getRowCount(),
                () -> "Dimension mismatch. Expects "
                        + this.getRowCount()
                        + " rows, actual operand has "
                        + b.getRowCount()
                        + " rows.");
        if(b instanceof DiagonalMatrix){
            return this.mul((DiagonalMatrix) b);
        }
        if(b instanceof ColumnVector){
            return this.mul((ColumnVector) b);
        }
        Matrix ans = new DefaultMatrix(b);
        for(int i = 0; i < this.vector.length; i++){
            double[] row = ans.getRow(i);
            double k = this.vector[i];
            for(int j = 0; j < row.length; j++){
                row[j] *= k;
            }
            ans.setRow(i, row);
        }
        return ans;
    }

    private Matrix mul(DiagonalMatrix diag) {
        return CopyOnWriteMatrix.of(new DiagonalMatrix(
                this.mul(this.vector, diag.vector)
        ));
    }

    private Matrix mul(ColumnVector v) {
        return new ColumnVector(this.mul(this.vector, v.getVector()));
    }

    private double[] mul(double[] u, double[] v) {
        double[] w = new double[this.vector.length];
        for(int i = 0; i < w.length; i++){
            w[i] = u[i] * v[i];
        }
        return w;
    }

    private double[] vector;
    private int rowCount, colCount;
}


text:
<rtr-router> is a router built on top of Polymer
======================================================
* Routing for anchor tag click events and form submit events.
* Optional lazy loading of route handlers.
* Static and parameterized paths.
* Form submits are conveniently routed to their handlers with a hash of input values.
* Conveniently bootstrap your application prior to processing its first routing request.
* Everything is a custom element so there is nothing new to learn.

Quick Start
===========
Two quick start options are available:
* Clone the repo: git clone https://github.com/jeffschwartz/rtr.git.
* Install with [Bower](http://bower.io): bower install rtr --save.

Documentation And Demo
======================
See the [component page](http://jeffschwartz.github.io/rtr/components/rtr/) for complete documentation and demo.

Example
=======
Define your routes using JavaScript:

    <link rel="import" href="../../polymer/polymer.html">
    <link rel="import" href="../rtr-route.html">
    <polymer-element name="demo-routes" extends="rtr-route">
        <template>
        </template>

    </polymer-element>

Declare your routes in your markup:

    <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
    <title>rtr Demo</title>

    <link rel="import" href="rtr-router.html">
    <link rel="import" href="demo/demo-routes.html">

    ...
    <rtr-router>

        <demo-routes
            routes='[{
                "method": "get",
                "path": "/rtr/components/rtr/demo-staticpath",
                "handler": "staticPath"
            }, {
                "method": "get",
                "path": "/rtr/components/rtr/demo-parameterizedpath/year/:y/month/:m/day/:d",
                "handler": "parameterizedPath"
            }, {
                "method": "post",
                "path": "/rtr/components/rtr/demo-formsubmit",
                "handler": "formSubmit"
            }]'></demo-routes>
    </rtr-router>
    ...

How you can contribute to this project
======================================
No project is an island and this project is no different. Your participation is fundamental to this project's success. It needs your feedback in the form of bug reports and feature requests, both of which can be filed [here](https://github.com/jeffschwartz/rtr/issues).

Watch this repo for further progress
=====================================
The master branch represents the current stable tip of the repo. Development branches are merged into the master branch as the development branche matures. If you are daring then checkout the development branch which gets merged with feature branches as they mature. If you are really daring then checkout the feature branches (if there are any).

LICENSE
=======
Copyright (c) 2015 Jeffrey Schwartz. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Jeffrey Schwartz nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOTLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


text:
'use strict';

var mongoose = require('mongoose');
var AssignedActivity = mongoose.model('AssignedActivity');

var errorHandler = require('../errors');
var is = require('is-js');
var _ = require('lodash');

var u = require('underscore');

exports.create = function(req, res) {
	if (is.empty(req.body.assignedActivity)) {
		return res.jsonp({
			err: 'Post (create): Does not exist',
			message: 'req.body.assignedActivity did not get send to backend',
			changes: 'No AssignedActivity Created'
		});
	}

	var assignedActivity = new AssignedActivity({
		year: req.body.assignedActivity.year,

		springTeaching: req.body.assignedActivity.springTeaching,
		springResearch: req.body.assignedActivity.springResearch,
		springService: req.body.assignedActivity.springService,

		fallTeaching: req.body.assignedActivity.fallTeaching,
		fallResearch: req.body.assignedActivity.fallResearch,
		fallService: req.body.assignedActivity.fallService,

		summerTeaching: req.body.assignedActivity.summerTeaching,
		summerResearch: req.body.assignedActivity.summerResearch,
		summerService: req.body.assignedActivity.summerService,

		user: req.user,
		report: req.report
	});

	assignedActivity.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(assignedActivity);
		}
	});
};

exports.update = function(req, res) {
//	console.log(require('util').inspect(req.body));

	if (is.empty(req.body.assignedActivity)) {
		res.status(400);
		return res.jsonp({
			err: 'Put (update): Does not exist',
			message: 'req.body.assignedActivity did not get send to backend',
			changes: 'No Changes Made'
		});
	}

	var assignedActivity = req.assignedActivity;

	assignedActivity = _.extend(assignedActivity, req.body.assignedActivity);

	assignedActivity.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(assignedActivity);
		}
	});
};

exports.readFromReport = function(req, res) {
	AssignedActivity.findOne({report: req.report})
	.populate('user', 'displayName')
	.populate('report', 'reportName')
	.exec(function(err, result) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		}
		return res.jsonp(result);
	});
};

exports.read = function(req, res) {
	res.jsonp(req.assignedActivity);
};

exports.assignedActivityById = function(req, res, next, id) {
	AssignedActivity.findById(id)
	.populate('user', 'displayName')
	.populate('report', 'reportName')
	.exec(function(err, assignedActivity) {
		if (err) return next(err);
		if (!assignedActivity) return next(new Error('Failed to load AssignedActivity ' + id));
		req.assignedActivity = assignedActivity;
		next();
	});
};

exports.hasAuthorization = function(req, res, next) {
	if (req.assignedActivity.user.id !== req.user.id && !u.contains(req.user.roles, 'admin')) {
		return res.status(403).send({
			message: 'User is not authorized'
		});
	}

	next();
};


text:
package org.apache.commons.math3;

import java.lang.annotation.*;

/**
 * Annotation that enables test retries.
 * @version $Id$
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Retry {
    int value() default 2;
}


text:
<?php

namespace Unm\Laravel\Facebook;

use Illuminate\Support\Facades\Facade;

/**
 * Facade for the Facebook service
 */
class FacebookFacade extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'facebook';
    }
}


text:
from django.test import TestCase
from django_dynamic_fixture import G

from oscar.apps.offer import custom, models
from oscar.apps.basket.models import Basket
from oscar.core.compat import get_user_model

User = get_user_model()

class BasketOwnerCalledBarry(models.Condition):

    class Meta:
        proxy = True

    def is_satisfied(self, basket):
        if not basket.owner:
            return False
        return basket.owner.first_name.lower() == 'barry'

    def can_apply_condition(self, product):
        return False

class TestCustomCondition(TestCase):

    def setUp(self):
        self.condition = custom.create_condition(BasketOwnerCalledBarry)
        self.offer = models.ConditionalOffer(
            condition=self.condition)
        self.basket = Basket()

    def test_is_not_satified_by_non_match(self):
        self.basket.owner = G(User, first_name="Alan")
        self.assertFalse(self.offer.is_condition_satisfied(self.basket))

    def test_is_satified_by_match(self):
        self.basket.owner = G(User, first_name="Barry")
        self.assertTrue(self.offer.is_condition_satisfied(self.basket))


text:
import { graphqlExpress, graphiqlExpress } from 'graphql-server-express'
import bodyParser from 'body-parser';
import express from 'express';
import fs from 'fs';
import schema from './graphql/schema.js';
import webpack from 'webpack';
import webpackConfig from './webpack.config.js';
import webpackDevMiddleware from 'webpack-dev-middleware';

const app = express();

const compiler = webpack(webpackConfig);

app.use(webpackDevMiddleware(compiler, {
  hot: true,
  filename: 'bundle.js',
  publicPath: '/',
  stats: {
    colors: true,
  },
  historyApiFallback: true,
}));

app.use(bodyParser.json())

app.use('/graphql', graphqlExpress(req => ({
  schema,
  context: {
    readJson: (entity) => {
      const json = fs.readFileSync(`./graphql/data/${entity}.json`)
      return JSON.parse(json)
    },
    writeJson: (entity, data) => {
      fs.writeFileSync(`./graphql/data/${entity}.json`, JSON.stringify(data, null, 2))
    },
    readJsonAsync: (entity) => {
      return new Promise((resolve, reject) => {
        fs.readFile(`./graphql/data/${entity}.json`, (err, data) => {
          if (err) {
            reject(err)
          }

          resolve(JSON.parse(data))
        })
      })
    }
  },
})))

app.use('/graphiql', graphiqlExpress({
  endpointURL: '/graphql',
  subscriptionsEndpoint: 'ws://localhost:3000/subs',
}))

app.get('*', (req, res) => {
  res.sendFile(__dirname + '/www/index.html')
})

const server = app.listen(3000, function() {
  const host = server.address().address;
  const port = server.address().port;
  console.log('Example app listening at http://%s:%s', host, port);
});


text:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>AdminLTE | Dashboard</title>
        <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>

        <link href="../../css/bootstrap.min.css" rel="stylesheet" type="text/css"/>

        <link href="../../css/font-awesome.min.css" rel="stylesheet" type="text/css"/>

        <link href="../../css/ionicons.min.css" rel="stylesheet" type="text/css"/>

        <link href="../../css/AdminLTE.css" rel="stylesheet" type="text/css"/>

        <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jasny-bootstrap/3.1.3/css/jasny-bootstrap.min.css">

                V-Vote Polls

                    Toggle navigation

                                Sumit Singh

                                        Sumit Singh
                                        Member since Nov. 2012

                                        Profile

                                        Sign out

Bordered Table

                            #
                            Option 1
                            Option 2
                            Option 2

                            Picture

                            Caption
                            Salmaan Khan - The Kick Hero
                            Salmaan Khan - The Kick Hero
                            Salmaan Khan - The Kick Hero

                            Percentage %
                            55%
                            55%
                            85%

«

1

2

3

»


text:
package org.ovirt.engine.core.dao;

import org.ovirt.engine.core.common.businessentities.async_tasks;
import org.ovirt.engine.core.compat.Guid;

public class AsyncTaskDAOHibernateImpl extends BaseDAOHibernateImpl<async_tasks, Guid> implements AsyncTaskDAO {
    public AsyncTaskDAOHibernateImpl() {
        super(async_tasks.class);
    }

}


text:
/**
 * This depends on the group feature and should come after it
 */

import { Token, TokenType } from '../tokenize';
import { isNum } from '../utils';
import { OutputGlobalState } from './handleOutput.types';
import { ControlHandlers, FeatureHandler, TokenHandler, TokenHandlers } from './types';

function flushBuffers(global: OutputGlobalState) {
    if (global._bufferedUnicodeOutput) {
        // We got some other control token that is not a chain of Unicode
        const str = global._bufferedUnicodeOutput.join('');
        global._pushOutput(str);
        delete global._bufferedUnicodeOutput;
    }

    if (global._bufferedBinaryOutput) {
        // We got some other control token that is not a chain of hex escapes
        global._pushOutput(Buffer.concat(global._bufferedBinaryOutput));
        delete global._bufferedBinaryOutput;
    }
}

const allTokenHandler: TokenHandler<OutputGlobalState, Token> = (global, token) => {
    if (global._bufferedUnicodeOutput && (token.type !== TokenType.CONTROL || (token.word !== 'uc' && token.word !== 'u'))) {
        // Continue Buffering Unicode as long as we get \uc or \u control words
        flushBuffers(global);
    } else if (global._bufferedBinaryOutput && (token.type !== TokenType.CONTROL || token.word !== "'")) {
        // Continue Buffering Unicode as long as we get \' control words
        flushBuffers(global);
    }
};

const tokenHandlers: TokenHandlers<OutputGlobalState> = {
    /*
        [TokenType.GROUP_START]: flushBuffers,
        [TokenType.GROUP_END]: flushBuffers,
        [TokenType.CONTROL]: (global, token) => {
            if (global._bufferedUnicodeOutput && token.word !== 'uc' && token.word !== 'u') {
                flushBuffers(global);
            }

            if (global._bufferedBinaryOutput && token.word !== "'") {
                flushBuffers(global);
            }
        },
    */
    [TokenType.TEXT]: (globals, token) => {
        flushBuffers(globals);

        // Emit the text
        globals._pushOutput(token.data);
    },
};

const unicodeControlHandlers: ControlHandlers<OutputGlobalState> = {
    u: (global, token) => {
        if (!isNum(token.param)) {
            throw new Error('Unicode control word with no param');
        }

        const newCodeUnit = token.param < 0
            ? String.fromCodePoint(token.param + 0x10000)
            : String.fromCodePoint(token.param);

        global._bufferedUnicodeOutput = global._bufferedUnicodeOutput || [];
        global._bufferedUnicodeOutput.push(newCodeUnit);
    },

    // Special one for hex escape
    "'": (global, token) => {
        global._bufferedBinaryOutput = global._bufferedBinaryOutput || [];
        global._bufferedBinaryOutput.push(token.data!);
    }
};

export const handleOutput: FeatureHandler<OutputGlobalState> = {
    allTokenHandler: allTokenHandler,
    tokenHandlers: tokenHandlers,
    controlHandlers: unicodeControlHandlers,
};


text:
using System.Data.Entity.Migrations;
using Tripso.Infrastructure;

namespace Tripso.Migrations
{
    internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
            context.Countries.AddOrUpdate(
                p => p.CountryName,
                new Country {CountryName = "Poland"},
                new Country {CountryName = "UK"},
                new Country {CountryName = "Italy"},
                new Country {CountryName = "Germany"},
                new Country {CountryName = "Netherlands"},
                new Country {CountryName = "Greece"}
            );

            context.Kinds.AddOrUpdate(
                p => p.KindName,
                new Kind {KindName = "Offer"},
                new Kind {KindName = "Order"}
            );
        }
    }
}


text:
package com.tornado.authserver.dto.resp;

import java.io.Serializable;
import java.util.Set;

import com.google.common.collect.Sets;

import lombok.Data;

/**
 * 用户基本信息
 *
 * @author dante
 *
 */
@Data
public class UserRespDTO implements Serializable {

	private static final long serialVersionUID = -697606318323663547L;

	private Long id;
	private String account;
	private String name;
	private String email;
	private String lastPwdUpdateDate;
	private Set<String> authoritys;

	public Set<String> getAuthoritys() {
		if(this.authoritys == null) {
			this.authoritys = Sets.newHashSet();
		}
		return this.authoritys;
	}

}


text:
<?php
namespace Api\Models;

use Phalcon\Mvc\Model,
    Phalcon\Annotations\Adapter\Memory,
    Phalcon\Mvc\Model\Validator\Uniqueness,
    Phalcon\Mvc\Model\Validator\Email as EmailValidator,
    Phalcon\Mvc\Model\Validator\StringLength as StringLengthValidator,
    Phalcon\Mvc\Model\Validator\PresenceOf as PresenceOfValidator,
    Phalcon\Mvc\Model\Validator\Regex as RegexValidator;

class AppModel extends Model {

    public function validation() {
        $clasname = get_class($this);
        $reader = new Memory();
        $reflector = $reader->get($clasname);

        $fileds = $reflector->getPropertiesAnnotations();

        foreach ($fileds as $field => $collection) {
            foreach ($collection as $annotation) {
                switch($annotation->getName()){
                    case 'Primary':

                        break;
                    case 'Unique':
                        $this->validate(new Uniqueness(
                            array(
                                'field' => $field,
                                'message' => 'The field %field% must be unique'
                            )
                        ));
                        break;
                    case 'Column':
                        $arguments = $annotation->getArguments();
                        $this->validateColumn($field, $arguments);
                        break;
                }
            }
        }

        if ($this->validationHasFailed() == true) {
            return false;
        }
        return true;
    }

    protected function validateColumn($field, $arguments) {
        if(isset($arguments['type'])){
            switch($arguments['type']) {
                case 'integer':
                     $this->validate(new RegexValidator(
                        array(
                            'field' => $field,
                            'pattern' => '/^[a-zA-Z0-9]*$/',
                            'message' => 'The field %field% must be a integer'
                        )
                    ));
                break;
                case 'email':
                    $this->validate(new EmailValidator(
                        array(
                            'field' => $field,
                            'message' => 'The field %field% must be a valid email'
                        )
                    ));
                break;
                case 'string':
                    $min = 1;
                    $max = 45;

                    if(isset($arguments['min'])){
                        $min = intval($arguments['min']);
                    }
                    if(isset($arguments['max'])){
                        $max = intval($arguments['max']);
                    }
                    if($min > $max) {
                        $min = $max;
                    }
                    $this->validate(new StringLengthValidator(
                        array(
                            'field' => $field,
                            'max' => $max,
                            'min' => $min,
                            'messageMaximum' => 'The field %field% is too large',
                            'messageMinimum' => 'The field %field% is too short'
                        )
                    ));
                break;
                case 'datetime':
                    $this->validate(new RegexValidator(
                        array(
                            'field' => $field,
                            'pattern' => '/^[0-9]{4}-(0[0-9]|1[0-2])-(0[0-9]|[1-2][0-9]|3[0-1]) (0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/',
                            'message' => 'The field %field% must be Y-m-d H:i:s format'
                        )
                    ));
                break;
            }
        }
        if(isset($arguments['nullable']) && $arguments['nullable'] == false) {
            $this->validate(new PresenceOfValidator(
                array(
                    'field' => $field,
                    'message' => 'The field %field% is required'
                )
            ));
        }
    }
}


text:
import * as React from "react"
import { BoxProps, ProgressBar } from "@artsy/palette"
import { Time } from "Utils/getSaleOrLotTimerInfo"

export interface ArtworkSidebarAuctionProgressBarProps extends BoxProps {
  time: Time
  extendedBiddingPeriodMinutes: number
  hasBeenExtended: boolean
  extendedBiddingIntervalMinutes: number
}

export const ArtworkSidebarAuctionProgressBar: React.FC<ArtworkSidebarAuctionProgressBarProps> = ({
  time,
  extendedBiddingPeriodMinutes,
  hasBeenExtended,
  extendedBiddingIntervalMinutes,
  ...rest
}) => {
  const { days, hours, minutes, seconds } = time

  const parsedDaysUntilEnd = parseInt(days, 10)
  const parsedHoursUntilEnd = parseInt(hours, 10)
  const parsedMinutesUntilEnd = parseInt(minutes, 10)
  const parsedSecondsUntilEnd = parseInt(seconds, 10)

  const isWithinExtendedBiddingPeriod =
    parsedDaysUntilEnd < 1 &&
    parsedHoursUntilEnd < 1 &&
    parsedMinutesUntilEnd < extendedBiddingPeriodMinutes

  const extendedBiddingDuration = hasBeenExtended
    ? extendedBiddingIntervalMinutes
    : extendedBiddingPeriodMinutes

  const percentComplete =
    (parsedSecondsUntilEnd + parsedMinutesUntilEnd * 60) /
    (extendedBiddingDuration * 60)

  const renderProgressBar = isWithinExtendedBiddingPeriod || hasBeenExtended

  return (
    <>
      {renderProgressBar && (
        <ProgressBar
          highlight="red100"
          percentComplete={percentComplete * 100}
          {...rest}
        />
      )}
    </>
  )
}


text:
package net.derpz.sbrankup.nms;

import net.minecraft.server.v1_9_R2.IChatBaseComponent.ChatSerializer;
import net.minecraft.server.v1_9_R2.PacketPlayOutChat;
import org.bukkit.craftbukkit.v1_9_R2.entity.CraftPlayer;
import org.bukkit.entity.Player;

/**
 * Created by xiurobert on 21-Sep-17.
 */
public class JsonMessage_1_9_R2 implements JsonMessage{
    public void sendJsonMessage(Player p, String s){
        PacketPlayOutChat packetPlayOutChat = new PacketPlayOutChat(ChatSerializer.a(s));
        ((CraftPlayer) p).getHandle().playerConnection.sendPacket(packetPlayOutChat);
    }
}


text:
<?php
/**
 * Description of MainController
 *
 * @author darkredz
 */
class MainController extends DooController{

    public function index(){
        $data['baseurl'] = Doo::conf()->APP_URL;
        $this->view()->render('about', $data);
    }

    public function test(){
        $this->load()->model('Food');
        $food = new Food;
        echo '
';

        //print_r( $food->getById(14) );
        //print_r( $food->getById(14, array('limit'=>1)) );

        //print_r( $food->limit(10) );
        //print_r( $food->limit(10,'id,name') );
        //print_r( $food->limit(10,'name','id') );
        //print_r( $food->limit(10,'name,id','location') );
        //print_r( Food::_limit(10) );

        //print_r( $food->getOne() );
        //print_r( Food::_getOne() );
        //$food->location = 'Asia';
        //$food->food_type_id = 10;
        print_r( $food->count() );
        print_r( Food::_count() );
        print_r( Food::_count($food) );
        //Doo::cache('php')->set('foodtotal', Food::_count($food));
        //echo '
'. Doo::cache('php')->get('foodtotal') .'
';

        print_r(  Food::getById__first(6) );

        //$food->id = 14;
        //print_r( $food->getOne() );
        // print_r( $food->find() );

        //print_r( Food::_find($food) );

        //print_r( $food->getById_location__first(6, 'Malaysia') );
        //print_r( $food->getById_location(6, 'Malaysia', array('limit'=>1)) );
        //print_r( $food->relateFoodType($food, array('limit'=>'first')) );
        //print_r( $food->relateFoodType($food) );
        //print_r( $food->relateFoodType__first($food) );

        //print_r( Food::getById__location__first(6, 'Malaysia') );
        //print_r( Food::getById__location(6, 'Malaysia') );
        //print_r( Food::getById__first(6) );
        //print_r( Food::getByLocation('Malaysia') );
        //print_r( Food::relateFoodType__first($food) );
        //print_r( Food::relateFoodType() );
        //print_r( Food::relateFoodType_first() );
        //print_r( Food::_relate('', 'FoodType') );
        //
        //$f = new Food;
        //print_r( $f->relate('FoodType') );
        //print_r( $f->relate('FoodType', array('limit'=>'first')) );

        # if update/delete/insert cache auto purged on the Model.
        //$food->id = 6;
        //$food->name = 'Wan Tan Mee';
        //$food->update();
        //print_r($food->find());

        //$food->purgeCache();  #to delete cache manually
        //Food::_purgeCache();  #to delete cache manually

        # If no SQL is displayed, it means that the data are read from cache.
        # And of course your Model have to extend DooSmartModel
        print_r(Doo::db()->showSQL());
    }

    public function gen_models(){
        Doo::loadCore('db/DooModelGen');
        DooModelGen::genMySQL();
    }

    public function url(){
        $data['title'] = 'URL used in this demo';
        $data['content'] = 'Replace :var with your values.
Request type */GET = You can test and visit these links.';
        $data['baseurl'] = Doo::conf()->APP_URL;

        include Doo::conf()->SITE_PATH .'protected/config/routes.conf.php';
        $data['printr'] = array();
        $n = 1;
        foreach($route as $req=>$r){
            foreach($r as $rname=>$value){
                //$rname_strip = (strpos($rname, '/')===0)? substr($rname, 1, strlen($rname)) : $rname;
                $rname_strip = 'index.php'.$rname;
                $data['printr'][$n++ .strtoupper(" $req")] = 'APP_URL.$rname_strip.'">'.$rname.'';
            }
        }
        $this->view()->render('template', $data);
    }

    public function example(){
        $data['baseurl'] = Doo::conf()->APP_URL;
        $data['printr'] = file_get_contents(Doo::conf()->SITE_PATH .'protected/config/routes.conf.php');
        $this->view()->render('example', $data);
    }

}
?>