text:
using System;
using System.Reflection;
using PluginLoader;
using Terraria;
using Terraria.Chat;
using Terraria.GameContent.Achievements;
using Keys = Microsoft.Xna.Framework.Input.Keys;

namespace TranscendPlugins
{
    public class Events : MarshalByRefObject, IPlugin
    {
        private Keys bloodMoon, goblin, meteor, frost, pirates, martians, pumpkinMoon, frostMoon, lunarApocalypse, eclipse, moonLord;
        private MethodInfo triggerLunarApocalypse;
        private FieldInfo spawnMeteor;
        private MethodInfo dropMeteor;
        private bool SpawnMeteor
        {
            get { return (bool)spawnMeteor.GetValue(null); }
            set { spawnMeteor.SetValue(null, value); }
        }

        public Events()
        {
            var worldGen = Assembly.GetEntryAssembly().GetType("Terraria.WorldGen");
            triggerLunarApocalypse = worldGen.GetMethod("TriggerLunarApocalypse");
            spawnMeteor = worldGen.GetField("spawnMeteor");
            dropMeteor = worldGen.GetMethod("dropMeteor");

            if (!Keys.TryParse(IniAPI.ReadIni("Events", "Meteor", "NumPad0", writeIt: true), out meteor))
                meteor = Keys.NumPad0;
            if (!Keys.TryParse(IniAPI.ReadIni("Events", "BloodMoon", "NumPad1", writeIt: true), out bloodMoon))
                bloodMoon = Keys.NumPad1;
            if (!Keys.TryParse(IniAPI.ReadIni("Events", "GoblinArmy", "NumPad2", writeIt: true), out goblin))
                goblin = Keys.NumPad2;
            if (!Keys.TryParse(IniAPI.ReadIni("Events", "FrostLegion", "NumPad3", writeIt: true), out frost))
                frost = Keys.NumPad3;
            if (!Keys.TryParse(IniAPI.ReadIni("Events", "PirateInvasion", "NumPad4", writeIt: true), out pirates))
                pirates = Keys.NumPad4;
            if (!Keys.TryParse(IniAPI.ReadIni("Events", "SolarEclipse", "NumPad5", writeIt: true), out eclipse))
                eclipse = Keys.NumPad5;
            if (!Keys.TryParse(IniAPI.ReadIni("Events", "PumpkinMoon", "NumPad6", writeIt: true), out pumpkinMoon))
                pumpkinMoon = Keys.NumPad6;
            if (!Keys.TryParse(IniAPI.ReadIni("Events", "FrostMoon", "NumPad7", writeIt: true), out frostMoon))
                frostMoon = Keys.NumPad7;
            if (!Keys.TryParse(IniAPI.ReadIni("Events", "MartianMadness", "NumPad8", writeIt: true), out martians))
                martians = Keys.NumPad8;
            if (!Keys.TryParse(IniAPI.ReadIni("Events", "LunarApocalypse", "NumPad9", writeIt: true), out lunarApocalypse))
                lunarApocalypse = Keys.NumPad9;
            if (!Keys.TryParse(IniAPI.ReadIni("Events", "Moon Lord", "Add", writeIt: true), out moonLord))
                moonLord = Keys.Add;

            Loader.RegisterHotkey(() =>
            {
                if (Main.invasionType > 0)
                    Main.invasionSize = 0;
                else
                    Main.StartInvasion(1);
            }, goblin);
            Loader.RegisterHotkey(() =>
            {
                if (Main.invasionType > 0)
                    Main.invasionSize = 0;
                else
                    Main.StartInvasion(2);
            }, frost);
            Loader.RegisterHotkey(() =>
            {
                if (Main.invasionType > 0)
                    Main.invasionSize = 0;
                else
                    Main.StartInvasion(3);
            }, pirates);
            Loader.RegisterHotkey(() =>
            {
                if (Main.invasionType > 0)
                    Main.invasionSize = 0;
                else
                    Main.StartInvasion(4);
            }, martians);
            Loader.RegisterHotkey(() =>
            {
                if (Main.pumpkinMoon)
                    Main.stopMoonEvent();
                else
                    Main.startPumpkinMoon();
            }, pumpkinMoon);
            Loader.RegisterHotkey(() =>
            {
                if (Main.snowMoon)
                    Main.stopMoonEvent();
                else
                    Main.startSnowMoon();
            }, frostMoon);
            Loader.RegisterHotkey(() =>
            {
                if (Terraria.NPC.LunarApocalypseIsUp || Terraria.NPC.AnyNPCs(398))
                    StopLunarEvent();
                else
                    TriggerLunarApocalypse();
            }, lunarApocalypse);
            Loader.RegisterHotkey(() =>
            {
                if (Terraria.NPC.LunarApocalypseIsUp || Terraria.NPC.AnyNPCs(398))
                    StopLunarEvent();
                else
                    SpawnMoonLord();
            }, moonLord);
            Loader.RegisterHotkey(() =>
            {
                if (Main.bloodMoon)
                    Main.bloodMoon = false;
                else
                    TriggerBloodMoon();
            }, bloodMoon);
            Loader.RegisterHotkey(() =>
            {
                if (Main.eclipse)
                    Main.eclipse = false;
                else
                    TriggerEclipse();
            }, eclipse);
            Loader.RegisterHotkey(() =>
            {
                SpawnMeteor = false;
                DropMeteor();
            }, meteor);
        }

        private void DropMeteor()
        {
            dropMeteor.Invoke(null, null);
        }

        private void TriggerLunarApocalypse()
        {
            triggerLunarApocalypse.Invoke(null, null);
        }

        private void TriggerEclipse()
        {
            if (Main.netMode == 0)
            {
                Main.eclipse = true;
                Main.NewText(Lang.misc[20].Value, 50, 255, 130);
            }
            else
            {
                NetMessage.SendData(61, -1, -1, null, Main.myPlayer, -6f, 0f, 0f, 0, 0, 0);
            }
        }

        private void TriggerBloodMoon()
        {
            Main.bloodMoon = true;
            AchievementsHelper.NotifyProgressionEvent(4);
            if (Main.netMode == 0)
            {
                Main.NewText(Lang.misc[8].Value, 50, byte.MaxValue, 130);
            }
            else if (Main.netMode == 2)
            {
                ChatHelper.BroadcastChatMessage(Lang.misc[8].ToNetworkText(), new Microsoft.Xna.Framework.Color(50, 255, 130), -1);
            }
        }

        private void SpawnMoonLord()
        {
            if (Main.netMode == 0)
            {
                WorldGen.StartImpendingDoom();
            }
            else
            {
                NetMessage.SendData(61, -1, -1, null, Main.myPlayer, -8f, 0f, 0f, 0, 0, 0);
            }
        }

        private void StopLunarEvent()
        {
            Main.NewText("Stopped lunar event!", 50, 255, 130);
            Terraria.NPC.LunarApocalypseIsUp = false;
            for (int i = 0; i < 200; i++)
            {
                if (Main.npc[i].active)
                {
                    switch (Main.npc[i].type)
                    {
                        case 398: // Moon Lord
                        case 517: // Tower
                        case 422: // Tower
                        case 507: // Tower
                        case 493: // Tower
                            Main.npc[i].life = 0;
                            break;
                    }
                }
            }
        }
    }
}


text:
package monasca.statsd;

import java.util.HashMap;
import java.util.Map;

/**
 * An event message Java bean that is used to hold an event object (which is sent to the datadog agent)
 * @author arnab
 */
public class EventMessage {

	private String title, message, aggregationKey, sourceTypeName;

	private long dateHappened;

	private Priority priority;

	private AlertType alterType;

	private Map<String, String> dimensions = new HashMap<String, String>();;

        /**
         */
        public EventMessage() {
        }

	/**
	 * @param title
	 * @param message
	 */
	public EventMessage(String title, String message) {
            this.title = title;
            this.message = message;
	}

	/**
	 * @return
	 */
	public String getTitle() {
		return title;
	}

    public void setTitle(String title) {
        this.title = title;
    }

    public void setMessage(String message) {
        this.message = message;
    }

	/**
	 * @return
	 */
	public String getMessage() {
		return message;
	}

	/**
	 * @return
	 */
	public String getAggregationKey() {
		return aggregationKey;
	}

	/**
	 *
	 * @param aggregationKey
	 */
	public void setAggregationKey(String aggregationKey) {
		this.aggregationKey = aggregationKey;
	}

	/**
	 * @return
	 */
	public String getSourceTypeName() {
		return sourceTypeName;
	}

	/**
	 * @param sourceTypeName
	 */
	public void setSourceTypeName(String sourceTypeName) {
		this.sourceTypeName = sourceTypeName;
	}

	/**
	 * @return
	 */
	public long getDateHappened() {
		return dateHappened;
	}

	/**
	 * @param dateHappened
	 */
	public void setDateHappened(long dateHappened) {
		this.dateHappened = dateHappened;
	}

	/**
	 * @return
	 */
	public Priority getPriority() {
		return priority;
	}

	/**
	 * @param priority
	 */
	public void setPriority(Priority priority) {
		this.priority = priority;
	}

	/**
	 * @return
	 */
	public AlertType getAlterType() {
		return alterType;
	}

	/**
	 * @param alterType
	 */
	public void setAlterType(AlertType alterType) {
		this.alterType = alterType;
	}

	/**
	 * @return
	 */
	public Map<String, String> getDimensions() {
	    Map<String, String> returnMap = new HashMap <String, String>();
	    returnMap.putAll(dimensions);
		return returnMap;
	}

	/**
	 * @param dimensions
	 */
	public void setDimensions(Map<String, String> dimensions) {
		this.dimensions.putAll(dimensions);
	}

}

redpajama_set_name: RedPajamaGithub


text:
package constant;

/**
 * Created by mian on 2017/1/23.
 * 表达式类型
 */
public enum ExpressionType {
    XPath("xpath"),
    Css("css"),
    Regex("regex"),
    JsonPath("jsonPath"),
    Links("links");

    private String methodName;

    ExpressionType(String methodName) {
        this.methodName = methodName;
    }

    public String getMethodName() {
        return this.methodName;
    }
}


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

using NUnit.Framework;

using LinqToDB;

using static Tests.Model.Northwind;

namespace Tests.OrmBattle
{
	using Tests.Model;
	using Tests.OrmBattle.Helper;

	[TestFixture]
	public class OrmBattleTests : TestBase
	{
		private const double doubleDelta = 1E-9;
		private string _currentContext;
		protected NorthwindDB db;

		protected void Setup(string context)
		{
			if (_currentContext == context)
				return;

			using (db)
				db = null;

			using (new DisableLogging())
			{
				db = new NorthwindDB(context);

				Customers = db.Customer.ToList();
				Employees = db.Employee.ToList();
				Order = db.Order.ToList();
				Products = db.Product.ToList();

				foreach (var o in Order)
				{
					o.Customer = Customers.SingleOrDefault(c => c.CustomerID == o.CustomerID);
					o.Employee = Employees.SingleOrDefault(e => e.EmployeeID == o.EmployeeID);
				}

				foreach (var c in Customers)
					c.Orders = Order.Where(o => c.CustomerID == o.CustomerID).ToList();
			}

			_currentContext = context;
		}

		[TearDown]
		protected void TearDown()
		{
			_currentContext = null;

			using (db)
				db = null;
		}
#pragma warning disable 0169
		List<Northwind.Customer> Customers;
		List<Northwind.Employee> Employees;
		List<Northwind.Order> Order;
		List<Northwind.Product> Products;
//		List<Northwind.Category> Categories;
//		List<Northwind.Supplier> Suppliers;
//		List<Northwind.Product> DiscontinuedProducts;
//		List<Northwind.OrderDetail> OrderDetails;
#pragma warning restore 0169
		// DTO for testing purposes.
		public class OrderDTO
		{
			public int Id { get; set; }
			public string CustomerId { get; set; }
			public DateTime? OrderDate { get; set; }
		}

		#region Filtering tests

		[Test, Category("Filtering")]
		public void WhereTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = from o in db.Order
				where o.ShipCity == "Seattle"
				select o;
			var expected = from o in Order
				where o.ShipCity == "Seattle"
				select o;
			var list = result.ToList();
			Assert.AreEqual(14, list.Count);
			Assert.AreEqual(0, expected.Except(list).Count());
		}

		[Test, Category("Filtering")]
		public void WhereParameterTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var city = "Seattle";
			var result = from o in db.Order
				where o.ShipCity == city
				select o;
			var expected = from o in Order
				where o.ShipCity == city
				select o;
			var list = result.ToList();
			Assert.AreEqual(14, list.Count);
			Assert.AreEqual(0, expected.Except(list).Count());

			city = "Rio de Janeiro";
			list = result.ToList();
			Assert.AreEqual(34, list.Count);
			Assert.AreEqual(0, expected.Except(list).Count());
		}

		[Test, Category("Filtering")]
		public void WhereConditionsTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = from p in db.Product
				where p.UnitsInStock < p.ReorderLevel && p.UnitsOnOrder == 0
				select p;
			var list = result.ToList();
			Assert.AreEqual(1, list.Count);
		}

		[Test, Category("Filtering")]
		public void WhereNullTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = from o in db.Order
				where o.ShipRegion == null
				select o;
			var list = result.ToList();
			Assert.AreEqual(507, list.Count);
		}

		[Test, Category("Filtering")]
		public void WhereNullParameterTest([NorthwindDataContext] string context)
		{
			Setup(context);
			string region = null;
			var result = from o in db.Order
				where o.ShipRegion == region
				select o;
			var list = result.ToList();
			Assert.AreEqual(507, list.Count);

			region = "WA";
			list = result.ToList();
			Assert.AreEqual(19, list.Count);
		}

		[Test, Category("Filtering")]
		public void WhereNullableTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = from o in db.Order
				where !o.ShippedDate.HasValue
				select o;
			var list = result.ToList();
			Assert.AreEqual(21, list.Count);
		}

		[Test, Category("Filtering")]
		public void WhereNullableParameterTest([NorthwindDataContext] string context)
		{
			Setup(context);
			DateTime? shippedDate = null;
			var result = from o in db.Order
				where o.ShippedDate == shippedDate
				select o;
			var list = result.ToList();
			Assert.AreEqual(21, list.Count);
		}

		[Test, Category("Filtering")]
		public void WhereCoalesceTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = from o in db.Order
				where (o.ShipRegion ?? "N/A") == "N/A"
				select o;
			var list = result.ToList();
			Assert.AreEqual(507, list.Count);
		}

		[Test, Category("Filtering")]
		public void WhereConditionalTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = from o in db.Order
				where (o.ShipCity == "Seattle" ? "Home" : "Other") == "Home"
				select o;
			var list = result.ToList();
			Assert.AreEqual(14, list.Count);
		}

		[Test, Category("Filtering")]
		public void WhereConditionalBooleanTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = from o in db.Order
				where o.ShipCity == "Seattle" ? true : false
				select o;
			var list = result.ToList();
			Assert.AreEqual(14, list.Count);
		}

		[Test, Category("Filtering")]
		public void WhereAnonymousParameterTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var cityRegion = new {City = "Seattle", Region = "WA"};
			var result = from o in db.Order
				where new {City = o.ShipCity, Region = o.ShipRegion} == cityRegion
				select o;
			var list = result.ToList();
			Assert.AreEqual(14, list.Count);
		}

		[Test, Category("Filtering")]
		public void WhereEntityParameterTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var order = db.Order.OrderBy(o => o.OrderDate).First();
			var result = from o in db.Order
				where o == order
				select o;
			var list = result.ToList();
			Assert.AreEqual(1, list.Count);
			Assert.AreEqual(order, list[0]);
			//Assert.AreSame(order, list[0]);
		}

		#endregion

		#region Projection tests

		[Test, Category("Projections")]
		public void SelectTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = from o in db.Order
				select o.ShipRegion;
			var expected = from o in Order
				select o.ShipRegion;
			var list = result.ToList();
			Assert.AreEqual(expected.Count(), list.Count);
			Assert.AreEqual(0, expected.Except(list).Count());
		}

		[Test, Category("Projections")]
		public void SelectBooleanTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = from o in db.Order
				select o.ShipRegion == "WA";
			var expected = from o in Order
				select o.ShipRegion == "WA";
			var list = result.ToList();
			Assert.AreEqual(expected.Count(), list.Count);
			Assert.AreEqual(0, expected.Except(list).Count());
		}

		[Test, Category("Projections")]
		public void SelectCalculatedTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = from o in db.Order
				select o.Freight * 1000;
			var expected = from o in Order
				select o.Freight * 1000;
			var list = result.ToList();
			var expectedList = expected.ToList();
			list.Sort();
			expectedList.Sort();

			// Assert.AreEqual(expectedList.Count, list.Count);
			// expectedList.Zip(list, (i, j) => {
			//                       Assert.AreEqual(i,j);
			//                       return true;
			//                     });
			CollectionAssert.AreEquivalent(expectedList, list);
		}

		[Test, Category("Projections")]
		public void SelectNestedCalculatedTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = from r in
				from o in db.Order
				select o.Freight * 1000
				where r > 100000
				select r / 1000;
			var expected = from o in Order
				where o.Freight > 100
				select o.Freight;
			var list = result.ToList();
			var expectedList = expected.ToList();
			list.Sort();
			expectedList.Sort();
			Assert.AreEqual(187, list.Count);
			// Assert.AreEqual(expectedList.Count, list.Count);
			// expectedList.Zip(list, (i, j) => {
			//                       Assert.AreEqual(i,j);
			//                       return true;
			//                     });
			CollectionAssert.AreEquivalent(expectedList, list);
		}

		[Test, Category("Projections")]
		public void SelectAnonymousTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = from o in db.Order
				select new {OrderID = o.OrderID, o.OrderDate, o.Freight};
			var expected = from o in Order
				select new {OrderID = o.OrderID, o.OrderDate, o.Freight};
			var list = result.ToList();
			Assert.AreEqual(expected.Count(), list.Count);
			Assert.AreEqual(0, expected.Except(list).Count());
		}

		[Test, Category("WindowsOnly")]
		public void SelectSubqueryTest([NorthwindDataContext] string context)
		{
			using (new AllowMultipleQuery())
			{
				Setup(context);
				Assert.AreNotEqual(db.GetType().FullName, "OrmBattle.EF7Model.NorthwindContext",
					"EF7 has infinite loop here");

				var result = from o in db.Order
					select db.Customer.Where(c => c.CustomerID == o.Customer.CustomerID);
				var expected = from o in Order
					select Customers.Where(c => c.CustomerID == o.Customer.CustomerID);
				var list = result.ToList();

				var expectedList = expected.ToList();
				CollectionAssert.AreEquivalent(expectedList, list);

				//Assert.AreEqual(expected.Count(), list.Count);
				//expected.Zip(result, (expectedCustomers, actualCustomers) => {
				//                       Assert.AreEqual(expectedCustomers.Count(), actualCustomers.Count());
				//                       Assert.AreEqual(0, expectedCustomers.Except(actualCustomers));
				//                       return true;
				//                     });
			}
		}

		[Test, Category("Projections")]
		public void SelectDtoTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = from o in db.Order
				select new OrderDTO {Id = o.OrderID, CustomerId = o.Customer.CustomerID, OrderDate = o.OrderDate};
			var list = result.ToList();
			Assert.AreEqual(Order.Count(), list.Count);
		}

		[Test, Category("Projections")]
		public void SelectNestedDtoTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = from r in
				from o in db.Order
				select new OrderDTO {Id = o.OrderID, CustomerId = o.Customer.CustomerID, OrderDate = o.OrderDate}
				where r.OrderDate > new DateTime(1998, 01, 01)
				select r;
			var list = result.ToList();
			Assert.AreEqual(267, list.Count);
		}

		[Test, Category("Projections")]
		public void SelectManyAnonymousTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = from c in db.Customer
				from o in c.Orders
				where o.Freight < 500.00M
				select new {CustomerId = c.CustomerID, o.OrderID, o.Freight};
			var list = result.ToList();
			Assert.AreEqual(817, list.Count);
		}

		[Test, Category("Projections")]
		public void SelectManyLetTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = from c in db.Customer
				from o in c.Orders
				let freight = o.Freight
				where freight < 500.00M
				select new {CustomerId = c.CustomerID, o.OrderID, freight};
			var list = result.ToList();
			Assert.AreEqual(817, list.Count);
		}

		[Test, Category("Projections")]
		public void SelectManyGroupByTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = db.Order
				.GroupBy(o => o.Customer)
				.Where(g => g.Count() > 20)
				.SelectMany(g => g.Select(o => o.Customer));

			var list = result.ToList();
			Assert.AreEqual(89, list.Count);
		}

		[Test, Category("Projections")]
		public void SelectManyOuterProjectionTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = db.Customer.SelectMany(i => i.Orders.Select(t => i));

			var list = result.ToList();
			Assert.AreEqual(830, list.Count);
		}

		[Test, Category("Projections")]
		public void SelectManyLeftJoinTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				from c in db.Customer
				from o in c.Orders.Select(o => new {o.OrderID, c.CompanyName}).DefaultIfEmpty()
				select new {c.ContactName, o};

			var list = result.ToList();
			Assert.Greater(list.Count, 0);
		}

		#endregion

		#region Take / Skip tests

		[Test, Category("Take/Skip")]
		public void TakeTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = (from o in db.Order
				orderby o.OrderDate, o.OrderID
				select o).Take(10);
			var expected = (from o in Order
				orderby o.OrderDate, o.OrderID
				select o).Take(10);
			var list = result.ToList();
			Assert.AreEqual(10, list.Count);
			Assert.IsTrue(expected.SequenceEqual(list));
		}

		[Test, Category("Take/Skip")]
		public void SkipTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = (from o in db.Order
				orderby o.OrderDate, o.OrderID
				select o).Skip(10);
			var expected = (from o in Order
				orderby o.OrderDate, o.OrderID
				select o).Skip(10);
			var list = result.ToList();
			Assert.AreEqual(820, list.Count);
			Assert.IsTrue(expected.SequenceEqual(list));
		}

		[Test, Category("Take/Skip")]
		public void TakeSkipTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = (from o in db.Order
				orderby o.OrderDate, o.OrderID
				select o).Skip(10).Take(10);
			var expected = (from o in Order
				orderby o.OrderDate, o.OrderID
				select o).Skip(10).Take(10);
			var list = result.ToList();
			Assert.AreEqual(10, list.Count);
			Assert.IsTrue(expected.SequenceEqual(list));
		}

		[Test, Category("Take/Skip")]
		public void TakeNestedTest([NorthwindDataContext] string context)
		{
			using (new AllowMultipleQuery())
			{
				Setup(context);
				var result =
					from c in db.Customer
					select new {Customer = c, TopOrder = c.Orders.OrderByDescending(o => o.OrderDate).Take(5)};
				var expected =
					from c in Customers
					select new {Customer = c, TopOrder = c.Orders.OrderByDescending(o => o.OrderDate).Take(5)};
				var list = result.ToList();
				Assert.AreEqual(expected.Count(), list.Count);
				foreach (var anonymous in list)
				{
					var count = anonymous.TopOrder.ToList().Count;
					Assert.GreaterOrEqual(count, 0);
					Assert.LessOrEqual(count, 5);
				}
			}
		}

		[Test, Category("Take/Skip")]
		public void ComplexTakeSkipTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var original = db.Order.ToList()
				.OrderBy(o => o.OrderDate)
				.Skip(100)
				.Take(50)
				.OrderBy(o => o.RequiredDate)
				.Where(o => o.OrderDate != null)
				.Select(o => o.RequiredDate)
				.Distinct()
				.OrderByDescending(_ => _)
				.Skip(10);
			var result = db.Order
				.OrderBy(o => o.OrderDate)
				.Skip(100)
				.Take(50)
				.OrderBy(o => o.RequiredDate)
				.Where(o => o.OrderDate != null)
				.Select(o => o.RequiredDate)
				.Distinct()
				.OrderByDescending(_ => _)
				.Skip(10);
			var originalList = original.ToList();
			var resultList = result.ToList();
			Assert.AreEqual(originalList.Count, resultList.Count);
			Assert.IsTrue(originalList.SequenceEqual(resultList));
		}

		#endregion

		#region Ordering tests

		[Test, Category("Ordering")]
		public void OrderByTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				from o in db.Order
				orderby o.OrderDate, o.ShippedDate descending, o.OrderID
				select o;
			var expected =
				from o in Order
				orderby o.OrderDate, o.ShippedDate descending, o.OrderID
				select o;

			var list = result.ToList();
			var expectedList = expected.ToList();
			Assert.AreEqual(expectedList.Count, list.Count);
			Assert.IsTrue(expected.SequenceEqual(list));
		}

		[Test, Category("Ordering")]
		public void OrderByWhereTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = (from o in db.Order
				orderby o.OrderDate, o.OrderID
				where o.OrderDate > new DateTime(1997, 1, 1)
				select o).Take(10);
			var expected = (from o in Order
				where o.OrderDate > new DateTime(1997, 1, 1)
				orderby o.OrderDate, o.OrderID
				select o).Take(10);
			var list = result.ToList();
			Assert.AreEqual(10, list.Count);
			Assert.IsTrue(expected.SequenceEqual(list));
		}

		[Test, Category("Ordering")]
		public void OrderByCalculatedColumnTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				from o in db.Order
				orderby o.Freight * o.OrderID descending
				select o;
			var expected =
				from o in Order
				orderby o.Freight * o.OrderID descending
				select o;
			Assert.IsTrue(expected.SequenceEqual(result));
		}

		[Test, Category("Ordering")]
		public void OrderByEntityTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				from o in db.Order
				orderby o
				select o;
			var expected =
				from o in Order
				orderby o.OrderID
				select o;
			Assert.IsTrue(expected.SequenceEqual(result, new GenericEqualityComparer<Order>(o => o.OrderID)));
		}

		[Test, Category("Ordering")]
		public void OrderByAnonymousTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				from o in db.Order
				orderby new {o.OrderDate, o.ShippedDate, o.OrderID}
				select o;
			var expected =
				from o in Order
				orderby o.OrderDate, o.ShippedDate, o.OrderID
				select o;
			Assert.IsTrue(expected.SequenceEqual(result, new GenericEqualityComparer<Order>(o => o.OrderID)));
		}

		[Test, Category("Ordering")]
		[ActiveIssue("Bad database data", Configuration = TestProvName.AllSQLiteNorthwind)]
		public void OrderByDistinctTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = db.Customer
				.OrderBy(c => c.CompanyName)
				.Select(c => c.City)
				.Distinct()
				.OrderBy(c => c)
				.Select(c => c);
			var expected = Customers
				.OrderBy(c => c.CompanyName)
				.Select(c => c.City)
				.Distinct()
				.OrderBy(c => c)
				.Select(c => c);
			Assert.IsTrue(expected.SequenceEqual(result));
		}

		[Test]
		[Category("Ordering")]
		[ActiveIssue("Bad database data", Configuration = TestProvName.AllSQLiteNorthwind)]
		public void OrderBySelectManyTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				from c in db.Customer.OrderBy(c => c.ContactName)
				from o in db.Order.OrderBy(o => o.OrderDate)
				where c == o.Customer
				select new {c.ContactName, o.OrderDate};
			var expected =
				from c in Customers.OrderBy(c => c.ContactName)
				from o in Order.OrderBy(o => o.OrderDate)
				where c == o.Customer
				select new {c.ContactName, o.OrderDate};
			Assert.IsTrue(expected.SequenceEqual(result));
		}

		[Test, Category("Ordering")]
		public void OrderByPredicateTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				db.Order.OrderBy(o => o.Freight > 0 && o.ShippedDate != null).ThenBy(o => o.OrderID).Select(o => o.OrderID);
			var list = result.ToList();
			var original =
				Order.OrderBy(o => o.Freight > 0 && o.ShippedDate != null).ThenBy(o => o.OrderID).Select(o => o.OrderID).ToList();
			Assert.IsTrue(list.SequenceEqual(original));
		}

		#endregion

		#region Grouping tests

		[Test, Category("Grouping")]
		public void GroupByTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = from o in db.Order
				group o by o.OrderDate;
			var list = result.ToList();
			Assert.AreEqual(480, list.Count);
		}

		[Test, Category("Grouping")]
		public void GroupByReferenceTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = from o in db.Order
				group o by o.Customer;
			var list = result.ToList();
			Assert.AreEqual(89, list.Count);
		}

		[Test, Category("Grouping")]
		public void GroupByWhereTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				from o in db.Order
				group o by o.OrderDate
				into g
				where g.Count() > 5
				select g;
			var list = result.ToList();
			Assert.AreEqual(1, list.Count);
		}

		[Test, Category("Grouping")]
		public void GroupByTestAnonymous([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = from c in db.Customer
				group c by new {c.Region, c.City};
			var list = result.ToList();
			Assert.AreEqual(69, list.Count);
		}

		[Test, Category("Grouping")]
		public void GroupByCalculatedTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				from o in db.Order
				group o by o.Freight > 50 ? o.Freight > 100 ? "expensive" : "average" : "cheap"
				into g
				select g;
			var list = result.ToList();
			Assert.AreEqual(3, list.Count);
		}

		[Test, Category("Grouping")]
		public void GroupBySelectManyTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = db.Customer
				.GroupBy(c => c.City)
				.SelectMany(g => g);

			var list = result.ToList();
			Assert.AreEqual(91, list.Count);
		}

		[Test, Category("Grouping")]
		public void GroupByCalculateAggregateTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				from o in db.Order
				group o by o.Customer
				into g
				select g.Sum(o => o.Freight);

			var list = result.ToList();
			Assert.AreEqual(89, list.Count);
		}

		[Test, Category("Grouping")]
		public void GroupByCalculateManyAggreagetes([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				from o in db.Order
				group o by o.Customer
				into g
				select new
				{
					Sum = g.Sum(o => o.Freight),
					Min = g.Min(o => o.Freight),
					Max = g.Max(o => o.Freight),
					Avg = g.Average(o => o.Freight)
				};

			var list = result.ToList();
			Assert.AreEqual(89, list.Count);
		}

		[Test, Category("Grouping")]
		public void GroupByAggregate([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				from c in db.Customer
				group c by c.Orders.Average(o => o.Freight) >= 80;
			var list = result.ToList();
			Assert.AreEqual(2, list.Count);
			var firstGroupList = list.First(g => !g.Key).ToList();
			Assert.AreEqual(71, firstGroupList.Count);
		}

		[Test, Category("Grouping"), ActiveIssue(573)]
		public void ComplexGroupingTest([NorthwindDataContext] string context)
		{
			//TODO: sdanyliv: Nested queries support is not implemented. Possible in V2
			Setup(context);
			var result =
				from c in db.Customer
				select new
				{
					c.CompanyName,
					YearGroups =
					from o in c.Orders
					group o by o.OrderDate.Value.Year
					into yg
					select new
					{
						Year = yg.Key,
						MonthGroups =
						from o in yg
						group o by o.OrderDate.Value.Month
						into mg
						select new {Month = mg.Key, Order = mg}
					}
				};
			var list = result.ToList();
			foreach (var customer in list)
			{
				var OrderList = customer.YearGroups.ToList();
				Assert.LessOrEqual(OrderList.Count, 3);
			}
		}

		#endregion

		#region Set operations / Distinct tests

		[Test, Category("Set operations")]
		public void ConcatTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = db.Customer.Where(c => c.Orders.Count <= 1)
				.Concat(db.Customer.Where(c => c.Orders.Count > 1));
			var list = result.ToList();
			Assert.AreEqual(91, list.Count);
		}

		[Test, Category("Set operations")]
		public void UnionTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = (
					from c in db.Customer
					select c.Phone)
				.Union(
					from c in db.Customer
					select c.Fax)
				.Union(
					from e in db.Employee
					select e.HomePhone
				);

			var list = result.ToList();
			Assert.AreEqual(167, list.Count);
		}

		[Test, Category("Set operations")]
		public void ExceptTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				db.Customer.Except(db.Customer.Where(c => c.Orders.Count() > 0));
			var list = result.ToList();
			Assert.AreEqual(2, list.Count);
		}

		[Test, Category("Set operations")]
		public void IntersectTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				db.Customer.Intersect(db.Customer.Where(c => c.Orders.Count() > 0));
			var list = result.ToList();
			Assert.AreEqual(89, list.Count);
		}

		[Test, Category("Set operations")]
		public void DistinctTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = db.Order.Select(c => c.Freight).Distinct();
			var list = result.ToList();
			Assert.AreEqual(799, list.Count);
		}

		[Test, Category("Set operations")]
		public void DistinctTakeLastTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
			(from o in db.Order
				orderby o.OrderDate
				select o.OrderDate).Distinct().Take(5);
			var list = result.ToList();
			Assert.AreEqual(5, list.Count);
		}

		[Test, Category("Set operations")]
		public void DistinctTakeFirstTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
			(from o in db.Order
				orderby o.OrderDate
				select o.OrderDate).Take(5).Distinct();
			var list = result.ToList();
			Assert.AreEqual(4, list.Count);
		}

		[Test, Category("Set operations")]
		public void DistinctEntityTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = db.Customer.Distinct();
			var list = result.ToList();
			Assert.AreEqual(91, list.Count);
		}

		[Test, Category("Set operations")]
		public void DistinctAnonymousTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = db.Customer.Select(c => new {c.Region, c.City}).Distinct();
			var list = result.ToList();
			Assert.AreEqual(69, list.Count);
		}

		#endregion

		#region Type casts

		[Test, Category("Type casts")]
		public void TypeCastIsChildTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = db.Product.Where(p => p is DiscontinuedProduct);
			var expected = db.Product.ToList().Where(p => p is DiscontinuedProduct);
			var list = result.ToList();
			Assert.Greater(list.Count, 0);
			Assert.AreEqual(expected.Count(), list.Count);
		}

		[Test, Category("Type casts")]
		public void TypeCastIsParentTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = db.Product.Where(p => p is Product);
			var expected = db.Product.ToList();
			var list = result.ToList();
			Assert.Greater(list.Count, 0);
			Assert.AreEqual(expected.Count(), list.Count);
		}

		[Test, Category("Type casts"), ActiveIssue(573)]
		public void TypeCastIsChildConditionalTest([NorthwindDataContext] string context)
		{
			//TODO: sdanyliv: strange test for me
			Setup(context);
			var result = db.Product
				.Select(x => x is DiscontinuedProduct
					? x
					: null);

			var expected = db.Product.ToList()
				.Select(x => x is DiscontinuedProduct
					? x
					: null);

			var list = result.ToList();
			Assert.Greater(list.Count, 0);
			Assert.AreEqual(expected.Count(), list.Count);
			Assert.IsTrue(list.Except(expected).Count() == 0);
			Assert.IsTrue(list.Contains(null));
		}

		[Test, Category("Type casts")]
		public void TypeCastOfTypeTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = db.Product.OfType<DiscontinuedProduct>();
			var expected = db.Product.ToList().OfType<DiscontinuedProduct>();
			var list = result.ToList();
			Assert.Greater(list.Count, 0);
			Assert.AreEqual(expected.Count(), list.Count);
		}

		[Test, Category("Type casts")]
		public void TypeCastAsTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = db.DiscontinuedProduct
				.Select(discontinuedProduct => discontinuedProduct as Product)
				.Select(product =>
					product == null
						? "NULL"
						: product.ProductName);

			var expected = db.DiscontinuedProduct.ToList()
				.Select(discontinuedProduct => discontinuedProduct as Product)
				.Select(product =>
					product == null
						? "NULL"
						: product.ProductName);

			var list = result.ToList();
			Assert.Greater(list.Count, 0);
			Assert.AreEqual(expected.Count(), list.Count);
			Assert.IsTrue(list.Except(expected).Count() == 0);
		}

		#endregion

		#region Element operations

		[Test, Category("Element operations")]
		public void FirstTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var customer = db.Customer.First();
			Assert.IsNotNull(customer);
		}

		[Test, Category("Element operations")]
		public void FirstOrDefaultTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var customer = db.Customer.Where(c => c.CustomerID == "ALFKI").FirstOrDefault();
			Assert.IsNotNull(customer);
		}

		[Test, Category("Element operations")]
		public void FirstPredicateTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var customer = db.Customer.First(c => c.CustomerID == "ALFKI");
			Assert.IsNotNull(customer);
		}

		[Test, Category("Element operations")]
		public void NestedFirstOrDefaultTest([IncludeDataSources(TestProvName.Northwind)] string context)
		{
			Setup(context);
			var result =
				from p in db.Product
				select new
				{
					ProductID = p.ProductID,
					MaxOrder = db.OrderDetail
						.Where(od => od.Product == p)
						.OrderByDescending(od => od.UnitPrice * od.Quantity)
						.FirstOrDefault()
						.Order
				};
			var list = result.ToList();
			Assert.Greater(list.Count, 0);
		}

		[Test, Category("Element operations")]
		public void FirstOrDefaultEntitySetTest([IncludeDataSources(TestProvName.Northwind)] string context)
		{
			Setup(context);
			var customersCount = Customers.Count;
			var result = db.Customer.Select(c => c.Orders.FirstOrDefault());
			var list = result.ToList();
			Assert.AreEqual(customersCount, list.Count);
		}

		[Test, Category("Element operations")]
		public void NestedSingleOrDefaultTest([IncludeDataSources(TestProvName.Northwind)] string context)
		{
			Setup(context);
			var customersCount = Customers.Count;
			var result = db.Customer.Select(c => c.Orders.Take(1).SingleOrDefault());
			var list = result.ToList();
			Assert.AreEqual(customersCount, list.Count);
		}

		[Test, Category("Element operations")]
		public void NestedSingleTest([IncludeDataSources(TestProvName.Northwind)] string context)
		{
			Setup(context);
			var result = db.Customer.Where(c => c.Orders.Count() > 0).Select(c => c.Orders.Take(1).Single());
			var list = result.ToList();
			Assert.Greater(list.Count, 0);
		}

		[Test, Category("Element operations")]
		public void ElementAtTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var customer = db.Customer.OrderBy(c => c.CustomerID).ElementAt(15);
			Assert.IsNotNull(customer);
			Assert.AreEqual("CONSH", customer.CustomerID);
		}

		[Test, Category("Element operations")]
		public void NestedElementAtTest([IncludeDataSources(TestProvName.Northwind)] string context)
		{
			Setup(context);
			var result =
				from c in db.Customer
				where c.Orders.Count() > 5
				select c.Orders.ElementAt(3);

			var list = result.ToList();
			Assert.AreEqual(63, list.Count);
		}

		#endregion

		#region Contains / Any / All tests

		[Test, Category("All/Any/Contains")]
		public void AllNestedTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				from c in db.Customer
				where
				db.Order.Where(o => o.Customer == c)
					.All(o => db.Employee.Where(e => o.Employee == e).Any(e => e.FirstName.StartsWith("A")))
				select c;
			var list = result.ToList();
			Assert.AreEqual(2, list.Count);
		}

		[Test, Category("All/Any/Contains")]
		public void ComplexAllTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				(from o in db.Order
				where
				db.Customer.Where(c => c == o.Customer).All(c => c.CompanyName.StartsWith("A")) ||
				db.Employee.Where(e => e == o.Employee).All(e => e.FirstName.EndsWith("t"))
				select o).ToList();
			var expected =
				from o in Order
				where
				Customers.Where(c => c == o.Customer).All(c => c.CompanyName.StartsWith("A")) ||
				Employees.Where(e => e == o.Employee).All(e => e.FirstName.EndsWith("t"))
				select o;

			Assert.AreEqual(0, expected.Except(result).Count());
			Assert.AreEqual(result.ToList().Count, 366);
		}

		[Test, Category("All/Any/Contains")]
		public void ContainsNestedTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = from c in db.Customer
				select new
				{
					Customer = c,
					HasNewOrder = db.Order
						.Where(o => o.OrderDate > new DateTime(2001, 1, 1))
						.Select(o => o.Customer)
						.Contains(c)
				};

			var resultList = result.ToList();

			var expected =
				from c in Customers
				select new
				{
					Customer = c,
					HasNewOrder = Order
						.Where(o => o.OrderDate > new DateTime(2001, 1, 1))
						.Select(o => o.Customer)
						.Contains(c)
				};
			Assert.AreEqual(0, expected.Except(resultList).Count());
			Assert.AreEqual(0, resultList.Count(i => i.HasNewOrder));
		}

		[Test, Category("All/Any/Contains")]
		public void AnyTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = db.Customer.Where(c => c.Orders.Any(o => o.Freight > 400)).ToList();
			var expected = Customers.Where(c => c.Orders.Any(o => o.Freight > 400));
			Assert.AreEqual(0, expected.Except(result).Count());
			Assert.AreEqual(10, result.ToList().Count);
		}

		[Test, Category("All/Any/Contains"), ActiveIssue(573)]
		public void AnyParameterizedTest([NorthwindDataContext] string context)
		{
			//TODO: sdanyliv: It may take many efforts to implement. And I don't see any benefits.
			Setup(context);
			var ids = new[] {"ABCDE", "ALFKI"};
			var result = db.Customer.Where(c => ids.Any(id => c.CustomerID == id));
			var list = result.ToList();
			Assert.Greater(list.Count, 0);
		}

		[Test, Category("All/Any/Contains")]
		public void ContainsParameterizedTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var customerIDs = new[] {"ALFKI", "ANATR", "AROUT", "BERGS"};
			var result = db.Order.Where(o => customerIDs.Contains(o.Customer.CustomerID));
			var list = result.ToList();
			Assert.Greater(list.Count, 0);
			Assert.AreEqual(41, list.Count);
		}

		#endregion

		#region Aggregates tests

		[Test, Category("Aggregates")]
		public void SumTest([NorthwindDataContext(false, true)] string context)
		{
			Setup(context);
			var sum = db.Order.Select(o => o.Freight).Sum();
			var sum1 = Order.Select(o => o.Freight).Sum();
			Assert.AreEqual((double)sum1, (double)sum, doubleDelta);
		}

		[Test, Category("Aggregates")]
		public void CountPredicateTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var count = db.Order.Count(o => o.OrderID > 10);
			var count1 = Order.Count(o => o.OrderID > 10);
			Assert.AreEqual(count1, count);
		}

		[Test, Category("Aggregates")]
		public void NestedCountTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = db.Customer.Where(c => db.Order.Count(o => o.Customer.CustomerID == c.CustomerID) > 5);
			var expected = Customers.Where(c => db.Order.Count(o => o.Customer.CustomerID == c.CustomerID) > 5);

			Assert.IsTrue(expected.Except(result).Count() == 0);
		}

		[Test, Category("Aggregates")]
		public void NullableSumTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var sum = db.Order.Select(o => (int?) o.OrderID).Sum();
			var sum1 = Order.Select(o => (int?) o.OrderID).Sum();
			Assert.AreEqual(sum1, sum);
		}

		[Test, Category("Aggregates")]
		public void MaxCountTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var max = db.Customer.Max(c => db.Order.Count(o => o.Customer.CustomerID == c.CustomerID));
			var max1 = Customers.Max(c => Order.Count(o => o.Customer.CustomerID == c.CustomerID));
			Assert.AreEqual(max1, max);
		}

		#endregion

		#region Join tests

		[Test, Category("Join"), ActiveIssue(573)]
		public void GroupJoinTest([NorthwindDataContext] string context)
		{
			//TODO: sdanyliv: o.Customer.CustomerID - it is association that means additional JOIN. We have to decide if it is a bug.
			Setup(context);
			var result =
				from c in db.Customer
				join o in db.Order on c.CustomerID equals o.Customer.CustomerID into go
				join e in db.Employee on c.City equals e.City into ge
				select new
				{
					OrderCount = go.Count(),
					EmployeesCount = ge.Count()
				};
			var list = result.ToList();
			Assert.AreEqual(91, list.Count);
		}

		[Test, Category("Join")]
		public void JoinTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				from p in db.Product
				join s in db.Supplier on p.Supplier.SupplierID equals s.SupplierID
				select new {p.ProductName, s.ContactName, s.Phone};

			var list = result.ToList();
			Assert.Greater(list.Count, 0);
		}

		[Test, Category("Join")]
		public void JoinByAnonymousTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				from c in db.Customer
				join o in db.Order on new {Customer = c, Name = c.ContactName} equals
				new {o.Customer, Name = o.Customer.ContactName}
				select new {c.ContactName, o.OrderDate};

			var list = result.ToList();
			Assert.Greater(list.Count, 0);
		}

		[Test, Category("Join")]
		[ActiveIssue("Bad database data", Configuration = TestProvName.AllSQLiteNorthwind)]
		public void LeftJoinTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				from c in db.Category
				join p in db.Product on c.CategoryID equals p.Category.CategoryID into g
				from p in g.DefaultIfEmpty()
				select new {Name = p == null ? "Nothing!" : p.ProductName, c.CategoryName};

			var list = result.ToList();
			Assert.AreEqual(77, list.Count);
		}

		#endregion

		#region References tests

		[Test, Category("References")]
		public void JoinByReferenceTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				from c in db.Customer
				join o in db.Order on c equals o.Customer
				select new {c.ContactName, o.OrderDate};

			var list = result.ToList();
			Assert.AreEqual(830, list.Count);
		}

		[Test, Category("References")]
		public void CompareReferenceTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				from c in db.Customer
				from o in db.Order
				where c == o.Customer
				select new {c.ContactName, o.OrderDate};

			var list = result.ToList();
			Assert.AreEqual(830, list.Count);
		}

		[Test, Category("References")]
		public void ReferenceNavigationTestTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result =
				from od in db.OrderDetail
				where od.Product.Category.CategoryName == "Seafood"
				select new {od.Order, od.Product};

			var list = result.ToList();
			Assert.AreEqual(330, list.Count);
			foreach (var anonymous in list)
			{
				Assert.IsNotNull(anonymous);
				Assert.IsNotNull(anonymous.Order);
				Assert.IsNotNull(anonymous.Product);
			}
		}

		[Test, Category("References")]
		public void EntitySetCountTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = db.Category.Where(c => c.Products.Count > 10);
			var list = result.ToList();
			Assert.AreEqual(4, list.Count);
		}

		#endregion

		#region Complex tests

		[Test, Category("WindowsOnly")]
		public void ComplexTest1([NorthwindDataContext] string context)
		{
			using (new AllowMultipleQuery())
			{
				Setup(context);
				var result = db.Supplier.Select(
					supplier => db.Product.Select(
						product => db.Product.Where(p => p.ProductID == product.ProductID && p.Supplier.SupplierID == supplier.SupplierID)));
				var count = result.ToList().Count;
				Assert.Greater(count, 0);
				foreach (var queryable in result)
				{
					foreach (var queryable1 in queryable)
					{
						foreach (var product in queryable1)
						{
							Assert.IsNotNull(product);
						}
					}
				}
			}
		}

		[Test, Category("Complex"), ActiveIssue(573)]
		public void ComplexTest2([NorthwindDataContext] string context)
		{
			Setup(context);

			//TODO: sdanyliv: It can be replaced by the following linq expression. We have to decide that we have time to implement.
			var r = from c in db.Customer
				group c by c.Country
				into g
				from gi in g
				where gi.CompanyName.Substring(0, 1) == g.Key.Substring(0, 1)
				select gi;

			var result = db.Customer
				.GroupBy(c => c.Country,
					(country, customers) =>
						customers.Where(k => k.CompanyName.Substring(0, 1) == country.Substring(0, 1)))
				.SelectMany(k => k);
			var expected = Customers
				.GroupBy(c => c.Country,
					(country, customers) =>
						customers.Where(k => k.CompanyName.Substring(0, 1) == country.Substring(0, 1)))
				.SelectMany(k => k);

			Assert.AreEqual(0, expected.Except(result).Count());
		}

		[Test, Category("Complex")]
		public void ComplexTest3([NorthwindDataContext] string context)
		{
			using (new AllowMultipleQuery())
			{
				Setup(context);
				var products = db.Product;
				var suppliers = db.Supplier;
				var result = from p in products
							 select new
							 {
								 Product = p,
								 Suppliers = suppliers
									 .Where(s => s.SupplierID == p.Supplier.SupplierID)
									 .Select(s => s.CompanyName)
							 };
				var list = result.ToList();
				Assert.Greater(list.Count, 0);
				foreach (var p in list)
					foreach (var companyName in p.Suppliers)
						Assert.IsNotNull(companyName);
			}
		}

		[Test, Category("Complex"), ActiveIssue(573)]
		public void ComplexTest4([NorthwindDataContext] string context)
		{
			//TODO: sdanyliv: This is a bug
			Setup(context);
			var result = db.Customer
				.Take(2)
				.Select(
					c =>
						db.Order.Select(o => db.Employee.Take(2).Where(e => e.Orders.Contains(o)))
							.Where(o => o.Count() > 0))
				.Select(os => os);

			var list = result.ToList();
			Assert.Greater(list.Count, 0);

			foreach (var item in list)
				item.ToList();
		}

		[Test, Category("Complex")]
		public void ComplexTest5([NorthwindDataContext] string context)
		{
			using (new AllowMultipleQuery())
			{
				Setup(context);
				var result = db.Customer
					.Select(c => new { Customer = c, Order = db.Order })
					.Select(i => i.Customer.Orders);

				var list = result.ToList();
				Assert.Greater(list.Count, 0);

				foreach (var item in list)
					item.ToList();
			}
		}

		[Test, Category("Complex"), ActiveIssue(592)]
		public void ComplexTest6([NorthwindDataContext] string context)
		{
			Setup(context);
			//TODO: sdanyliv: Another strange query that needs efforts for implementation. Can be replaced by this one:
			var r =
				from c in db.Customer
				from o in db.Order
				where o.Customer == c
				select new
				{
					Customer = c,
					Order = o
				};

			var result = db.Customer
				.Select(c => new {Customer = c, Order = db.Order.Where(o => o.Customer == c)})
				.SelectMany(i => i.Order.Select(o => new {i.Customer, Order = o}));

			var list = result.ToList();
			Assert.Greater(list.Count, 0);
		}

		#endregion

		#region Standard functions tests

		[Test, Category("Standard functions")]
		public void StringStartsWithTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = db.Customer.Where(c => c.CustomerID.StartsWith("A") || c.CustomerID.StartsWith("L"));

			var list = result.ToList();
			Assert.AreEqual(13, list.Count);
		}

		[Test, Category("Standard functions")]
		public void StringStartsWithParameterizedTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var likeA = "A";
			var likeL = "L";
			var result = db.Customer.Where(c => c.CustomerID.StartsWith(likeA) || c.CustomerID.StartsWith(likeL));

			var list = result.ToList();
			Assert.AreEqual(13, list.Count);
		}

		[Test, Category("Standard functions")]
		public void StringLengthTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var customer = db.Customer.Where(c => c.City.Length == 7).First();
			Assert.IsNotNull(customer);
		}

		[Test, Category("Standard functions")]
		public void StringContainsTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var customer = db.Customer.Where(c => c.ContactName.Contains("and")).First();
			Assert.IsNotNull(customer);
		}

		[Test, Category("Standard functions")]
		public void StringToLowerTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var customer = db.Customer.Where(c => c.City.ToLower() == "seattle").First();
			Assert.IsNotNull(customer);
		}

		[Test, Category("Standard functions")]
		public void StringRemoveTest([NorthwindDataContext(false, true)] string context)
		{
			Setup(context);
			var customer = db.Customer.Where(c => c.City.Remove(3) == "Sea").First();
			Assert.IsNotNull(customer);
		}

		[Test, Category("Standard functions")]
		public void StringIndexOfTest([NorthwindDataContext(false, true)] string context)
		{
			Setup(context);
			var customer = db.Customer.Where(c => c.City.IndexOf("tt") == 3).First();
			Assert.IsNotNull(customer);
		}

		[Test, Category("Standard functions")]
		public void StringLastIndexOfTest([NorthwindDataContext(false, true)] string context)
		{
			Setup(context);
			var customer = db.Customer.Where(c => c.City.LastIndexOf("t", 1, 3) == 3).First();
			Assert.IsNotNull(customer);
		}

		[Test, Category("Standard functions")]
		public void StringPadLeftTest([NorthwindDataContext(false, true)] string context)
		{
			Setup(context);
			var customer = db.Customer.Where(c => "123" + c.City.PadLeft(8) == "123 Seattle").First();
			Assert.IsNotNull(customer);
		}

		[Test, Category("Standard functions")]
		public void DateTimeTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var order = db.Order.Where(o => o.OrderDate >= new DateTime(o.OrderDate.Value.Year, 1, 1)).First();
			Assert.IsNotNull(order);
		}

		[Test, Category("Standard functions")]
		public void DateTimeDayTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var order = db.Order.Where(o => o.OrderDate.Value.Day == 5).First();
			Assert.IsNotNull(order);
		}

		[Test, Category("Standard functions")]
		public void DateTimeDayOfWeek([NorthwindDataContext] string context)
		{
			Setup(context);
			var order = db.Order.Where(o => o.OrderDate.Value.DayOfWeek == DayOfWeek.Friday).First();
			Assert.IsNotNull(order);
		}

		[Test, Category("Standard functions")]
		public void DateTimeDayOfYear([NorthwindDataContext] string context)
		{
			Setup(context);
			var order = db.Order.Where(o => o.OrderDate.Value.DayOfYear == 360).First();
			Assert.IsNotNull(order);
		}

		[Test, Category("Standard functions")]
		public void MathAbsTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var order = db.Order.Where(o => Math.Abs(o.OrderID) == 10 || o.OrderID > 0).First();
			Assert.IsNotNull(order);
		}

		[Test, Category("Standard functions")]
		public void MathTrignometricTest([NorthwindDataContext(false, true)] string context)
		{
			Setup(context);
			var order = db.Order.Where(o => Math.Asin(Math.Cos(o.OrderID)) == 0 || o.OrderID > 0).First();
			Assert.IsNotNull(order);
		}

		[Test, Category("Standard functions")]
		public void MathFloorTest([NorthwindDataContext(false, true)] string context)
		{
			Setup(context);
			var result = db.Order.Where(o => Math.Floor(o.Freight) == 140);
			var list = result.ToList();
			Assert.AreEqual(2, list.Count);
		}

		[Test, Category("Standard functions")]
		public void MathCeilingTest([NorthwindDataContext(false, true)] string context)
		{
			Setup(context);
			var result = db.Order.Where(o => Math.Ceiling(o.Freight) == 141);
			var list = result.ToList();
			Assert.AreEqual(2, list.Count);
		}

		[Test, Category("Standard functions")]
		public void MathTruncateTest([NorthwindDataContext(false, true)] string context)
		{
			Setup(context);
			var result = db.Order.Where(o => Math.Truncate(o.Freight) == 141);
			var list = result.ToList();
			Assert.AreEqual(2, list.Count);
		}

		[Test, Category("Standard functions")]
		public void MathRoundAwayFromZeroTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = db.Order.Where(o => Math.Round(o.Freight / 10, 1, MidpointRounding.AwayFromZero) == 6.5m);
			var list = result.ToList();
			Assert.AreEqual(7, list.Count);
		}

		[Test, Category("Standard functions")]
		public void MathRoundToEvenTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = db.Order.Where(o => Math.Round(o.Freight / 10, 1, MidpointRounding.ToEven) == 6.5m);
			var list = result.ToList();
			Assert.AreEqual(6, list.Count);
		}

		[Test, Category("Standard functions")]
		public void MathRoundDefaultTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var result = db.Order.Where(o => Math.Round(o.Freight / 10, 1) == 6.5m);
			var list = result.ToList();
			Assert.AreEqual(6, list.Count);
		}

		[Test, Category("Standard functions")]
		public void ConvertToInt32([NorthwindDataContext(false, true)] string context)
		{
			Setup(context);
			var expected = Order.Where(o => Convert.ToInt32(o.Freight * 10) == 592);
			var result = db.Order.Where(o => Convert.ToInt32(o.Freight * 10) == 592);
			var list = result.ToList();
			Assert.AreEqual(expected.Count(), list.Count);
		}

		[Test, Category("Standard functions")]
		public void StringCompareToTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var customer = db.Customer.Where(c => c.City.CompareTo("Seattle") >= 0).First();
			Assert.IsNotNull(customer);
		}

		[Test, Category("Standard functions")]
		public void ComparisonWithNullTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var customer = db.Customer.Where(c => null != c.City).First();
			Assert.IsNotNull(customer);
		}

		[Test, Category("Standard functions")]
		public void EqualsWithNullTest([NorthwindDataContext] string context)
		{
			Setup(context);
			var customer = db.Customer.Where(c => !c.Address.Equals(null)).First();
			Assert.IsNotNull(customer);
		}

		#endregion
	}
}


text:
from ..engine import Layer, InputSpec
from .. import initializations, regularizers
from .. import backend as K

class BatchNormalization(Layer):
    '''Normalize the activations of the previous layer at each batch,
    i.e. applies a transformation that maintains the mean activation
    close to 0 and the activation standard deviation close to 1.

    # Arguments
        epsilon: small float > 0. Fuzz parameter.
        mode: integer, 0, 1 or 2.
            - 0: feature-wise normalization.
                Each feature map in the input will
                be normalized separately. The axis on which
                to normalize is specified by the `axis` argument.
                Note that if the input is a 4D image tensor
                using Theano conventions (samples, channels, rows, cols)
                then you should set `axis` to `1` to normalize along
                the channels axis.
                During training we use per-batch statistics to normalize
                the data, and during testing we use running averages
                computed during the training phase.
            - 1: sample-wise normalization. This mode assumes a 2D input.
            - 2: feature-wise normalization, like mode 0, but
                using per-batch statistics to normalize the data during both
                testing and training.
        axis: integer, axis along which to normalize in mode 0. For instance,
            if your input tensor has shape (samples, channels, rows, cols),
            set axis to 1 to normalize per feature map (channels axis).
        momentum: momentum in the computation of the
            exponential average of the mean and standard deviation
            of the data, for feature-wise normalization.
        weights: Initialization weights.
            List of 2 Numpy arrays, with shapes:
            `[(input_shape,), (input_shape,)]`
            Note that the order of this list is [gamma, beta, mean, std]
        beta_init: name of initialization function for shift parameter
            (see [initializations](../initializations.md)), or alternatively,
            Theano/TensorFlow function to use for weights initialization.
            This parameter is only relevant if you don't pass a `weights` argument.
        gamma_init: name of initialization function for scale parameter (see
            [initializations](../initializations.md)), or alternatively,
            Theano/TensorFlow function to use for weights initialization.
            This parameter is only relevant if you don't pass a `weights` argument.
        gamma_regularizer: instance of [WeightRegularizer](../regularizers.md)
            (eg. L1 or L2 regularization), applied to the gamma vector.
        beta_regularizer: instance of [WeightRegularizer](../regularizers.md),
            applied to the beta vector.

    # Input shape
        Arbitrary. Use the keyword argument `input_shape`
        (tuple of integers, does not include the samples axis)
        when using this layer as the first layer in a model.

    # Output shape
        Same shape as input.

    # References
        - [Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift](http://jmlr.org/proceedings/papers/v37/ioffe15.pdf)
    '''
    def __init__(self, epsilon=1e-5, mode=0, axis=-1, momentum=0.99,
                 weights=None, beta_init='zero', gamma_init='one',
                 gamma_regularizer=None, beta_regularizer=None, **kwargs):
        self.supports_masking = True
        self.beta_init = initializations.get(beta_init)
        self.gamma_init = initializations.get(gamma_init)
        self.epsilon = epsilon
        self.mode = mode
        self.axis = axis
        self.momentum = momentum
        self.gamma_regularizer = regularizers.get(gamma_regularizer)
        self.beta_regularizer = regularizers.get(beta_regularizer)
        self.initial_weights = weights
        if self.mode == 0:
            self.uses_learning_phase = True
        super(BatchNormalization, self).__init__(**kwargs)

    def build(self, input_shape):
        self.input_spec = [InputSpec(shape=input_shape)]
        shape = (input_shape[self.axis],)

        self.gamma = self.gamma_init(shape, name='{}_gamma'.format(self.name))
        self.beta = self.beta_init(shape, name='{}_beta'.format(self.name))
        self.trainable_weights = [self.gamma, self.beta]

        self.regularizers = []
        if self.gamma_regularizer:
            self.gamma_regularizer.set_param(self.gamma)
            self.regularizers.append(self.gamma_regularizer)

        if self.beta_regularizer:
            self.beta_regularizer.set_param(self.beta)
            self.regularizers.append(self.beta_regularizer)

        self.running_mean = K.zeros(shape,
                                    name='{}_running_mean'.format(self.name))
        self.running_std = K.ones(shape,
                                  name='{}_running_std'.format(self.name))
        self.non_trainable_weights = [self.running_mean, self.running_std]

        if self.initial_weights is not None:
            self.set_weights(self.initial_weights)
            del self.initial_weights
        self.built = True

    def call(self, x, mask=None):
        if self.mode == 0 or self.mode == 2:
            assert self.built, 'Layer must be built before being called'
            input_shape = self.input_spec[0].shape

            reduction_axes = list(range(len(input_shape)))
            del reduction_axes[self.axis]
            broadcast_shape = [1] * len(input_shape)
            broadcast_shape[self.axis] = input_shape[self.axis]

            if self.mode == 2:
                x_normed, mean, std = K.normalize_batch_in_training(
                    x, self.gamma, self.beta, reduction_axes,
                    epsilon=self.epsilon)
            else:
                # mode 0
                x_normed, mean, std = K.normalize_batch_in_training(
                    x, self.gamma, self.beta, reduction_axes,
                    epsilon=self.epsilon)

                self.add_updates([K.moving_average_update(self.running_mean, mean, self.momentum),
                                  K.moving_average_update(self.running_std, std, self.momentum)], x)

                if K.backend() == 'tensorflow' and sorted(reduction_axes) == range(K.ndim(x))[:-1]:
                    x_normed_running = K.batch_normalization(
                        x, self.running_mean, self.running_std,
                        self.beta, self.gamma,
                        epsilon=self.epsilon)
                else:
                    # need broadcasting
                    broadcast_running_mean = K.reshape(self.running_mean, broadcast_shape)
                    broadcast_running_std = K.reshape(self.running_std, broadcast_shape)
                    broadcast_beta = K.reshape(self.beta, broadcast_shape)
                    broadcast_gamma = K.reshape(self.gamma, broadcast_shape)
                    x_normed_running = K.batch_normalization(
                        x, broadcast_running_mean, broadcast_running_std,
                        broadcast_beta, broadcast_gamma,
                        epsilon=self.epsilon)

                # pick the normalized form of x corresponding to the training phase
                x_normed = K.in_train_phase(x_normed, x_normed_running)

        elif self.mode == 1:
            # sample-wise normalization
            m = K.mean(x, axis=-1, keepdims=True)
            std = K.sqrt(K.var(x, axis=-1, keepdims=True) + self.epsilon)
            x_normed = (x - m) / (std + self.epsilon)
            x_normed = self.gamma * x_normed + self.beta
        return x_normed

    def get_config(self):
        config = {'epsilon': self.epsilon,
                  'mode': self.mode,
                  'axis': self.axis,
                  'gamma_regularizer': self.gamma_regularizer.get_config() if self.gamma_regularizer else None,
                  'beta_regularizer': self.beta_regularizer.get_config() if self.beta_regularizer else None,
                  'momentum': self.momentum}
        base_config = super(BatchNormalization, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))


text:
import React       from 'react'
import {render}    from 'react-dom'
import {Action, S} from 'slope'
import {lift}      from '../../../dist'

const count   = Action()
const countS  = S.fork(count.stream)
const counter = S.scan((p, n) => p + n, 0)(countS)
const clicks  = S.scan(p => p + 1, 0)(countS)

const App = () => (

Current value of the counter is {lift(counter)} and the controls have been clicked {lift(clicks)} times.

      <button onClick={() => count(1)}>+</button>
      <button onClick={() => count(-1)}>-</button>

)

render(
  <App/>,
  document.getElementById('app')
)


text:
[![Build Status](https://travis-ci.org/fpco/monad-unlift.svg?branch=master)](https://travis-ci.org/fpco/monad-unlift)

Provides some concrete transformer implementations based on [monad-unlift](https://www.stackage.org/package/monad-unlift). See that package for more information.


text:
#include "third_party/blink/renderer/core/page/plugin_data.h"

#include "base/metrics/histogram_macros.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "third_party/blink/public/common/thread_safe_browser_interface_broker_proxy.h"
#include "third_party/blink/public/mojom/plugins/plugin_registry.mojom-blink.h"
#include "third_party/blink/public/platform/file_path_conversion.h"
#include "third_party/blink/public/platform/platform.h"

namespace blink {

void MimeClassInfo::Trace(Visitor* visitor) const {
  visitor->Trace(plugin_);
}

MimeClassInfo::MimeClassInfo(const String& type,
                             const String& description,
                             PluginInfo& plugin,
                             const Vector<String> extensions)
    : type_(type),
      description_(description),
      extensions_(std::move(extensions)),
      plugin_(&plugin) {}

void PluginInfo::Trace(Visitor* visitor) const {
  visitor->Trace(mimes_);
}

PluginInfo::PluginInfo(const String& name,
                       const String& filename,
                       const String& description,
                       Color background_color,
                       bool may_use_external_handler)
    : name_(name),
      filename_(filename),
      description_(description),
      background_color_(background_color),
      may_use_external_handler_(may_use_external_handler) {}

void PluginInfo::AddMimeType(MimeClassInfo* info) {
  mimes_.push_back(info);
}

const MimeClassInfo* PluginInfo::GetMimeClassInfo(wtf_size_t index) const {
  if (index >= mimes_.size())
    return nullptr;
  return mimes_[index];
}

const MimeClassInfo* PluginInfo::GetMimeClassInfo(const String& type) const {
  for (MimeClassInfo* mime : mimes_) {
    if (mime->Type() == type)
      return mime;
  }

  return nullptr;
}

wtf_size_t PluginInfo::GetMimeClassInfoSize() const {
  return mimes_.size();
}

void PluginData::Trace(Visitor* visitor) const {
  visitor->Trace(plugins_);
  visitor->Trace(mimes_);
}

// static
void PluginData::RefreshBrowserSidePluginCache() {
  mojo::Remote<mojom::blink::PluginRegistry> registry;
  Platform::Current()->GetBrowserInterfaceBroker()->GetInterface(
      registry.BindNewPipeAndPassReceiver());
  Vector<mojom::blink::PluginInfoPtr> plugins;
  registry->GetPlugins(true, &plugins);
}

void PluginData::UpdatePluginList() {
  if (updated_)
    return;

  SCOPED_UMA_HISTOGRAM_TIMER("Blink.Plugin.UpdateTime");
  ResetPluginData();
  updated_ = true;

  mojo::Remote<mojom::blink::PluginRegistry> registry;
  Platform::Current()->GetBrowserInterfaceBroker()->GetInterface(
      registry.BindNewPipeAndPassReceiver());
  Vector<mojom::blink::PluginInfoPtr> plugins;
  registry->GetPlugins(false, &plugins);
  for (const auto& plugin : plugins) {
    auto* plugin_info = MakeGarbageCollected<PluginInfo>(
        std::move(plugin->name), FilePathToWebString(plugin->filename),
        std::move(plugin->description), plugin->background_color,
        plugin->may_use_external_handler);
    plugins_.push_back(plugin_info);
    for (const auto& mime : plugin->mime_types) {
      auto* mime_info = MakeGarbageCollected<MimeClassInfo>(
          std::move(mime->mime_type), std::move(mime->description),
          *plugin_info, std::move(mime->file_extensions));
      plugin_info->AddMimeType(mime_info);
      mimes_.push_back(mime_info);
    }
  }

  std::sort(
      plugins_.begin(), plugins_.end(),
      [](const Member<PluginInfo>& lhs, const Member<PluginInfo>& rhs) -> bool {
        return WTF::CodeUnitCompareLessThan(lhs->Name(), rhs->Name());
      });
  std::sort(mimes_.begin(), mimes_.end(),
            [](const Member<MimeClassInfo>& lhs,
               const Member<MimeClassInfo>& rhs) -> bool {
              return WTF::CodeUnitCompareLessThan(lhs->Type(), rhs->Type());
            });
}

void PluginData::ResetPluginData() {
  plugins_.clear();
  mimes_.clear();
  updated_ = false;
}

bool PluginData::SupportsMimeType(const String& mime_type) const {
  for (const MimeClassInfo* info : mimes_) {
    if (info->type_ == mime_type)
      return true;
  }

  return false;
}

Color PluginData::PluginBackgroundColorForMimeType(
    const String& mime_type) const {
  for (const MimeClassInfo* info : mimes_) {
    if (info->type_ == mime_type)
      return info->Plugin()->BackgroundColor();
  }
  NOTREACHED();
  return Color();
}

bool PluginData::IsExternalPluginMimeType(const String& mime_type) const {
  for (const MimeClassInfo* info : mimes_) {
    if (info->type_ == mime_type)
      return info->Plugin()->MayUseExternalHandler();
  }
  return false;
}

}  // namespace blink


text:
{% extends "page-base.html" %}
{% load humanize %}
{% load comments %}

{% block title %}{{item.title}}{% endblock %}

{% block pageContent %}

		{% if item.entry.sub_type == 'snippet' %}

		{% endif %}
		{% if item.entry.sub_type == 'package' %}

		{% endif %}
		{% if item.entry.sub_type == 'link' %}

		{% endif %}

{{item.title}}

		{% if not preview %}

{% if item.previous_submission %}Previous{% endif %}

{% if item.next_submission %}Next{% endif %}

		{% endif %}

Submitted by

{% if item.entry.created_by.profile.is_validated %}{{item.entry.created_by.username}} on {% if item.entry.date_created %}{{item.entry.date_created|naturalday:"d F Y"}}{% else %}today{% endif %}{% else %}Your name will be here once you validate yourself by email{% endif %}

	{% if item.entry.sub_type == "link" %}

Link

{{item.item_url}}

	{% endif %}

	{% if item.entry.sub_type == "snippet" %}

Download

		{% if preview %}
			Links to the ZIP file contents will appear here
		{% else %}
			File
		{% endif %}

	{% endif %}

	{% if item.entry.sub_type == "package" %}

Download

		{% if preview %}
			Links to the ZIP file contents will appear here
		{% else %}
			All files
		{% endif %}

	{% endif %}

	{% if item.entry.num_revisions > 1 %}

Update history

{{ item.human_revision_string }}:
		{% if item.previous_revision %}
			previous
		{% endif %}
		{% if item.next_revision %}next{% endif %}

Updated by

		{% if item.created_by.profile.is_validated %}{{item.created_by.username}}{% else %}Unvalidated user{% endif %} on {% if item.date_created %}{{item.date_created|naturalday:"d F Y"}}{% else %}today{% endif %}

	{% endif %}

Tags

		{% for tag in tag_list %}

{{tag.name}}

		{% endfor %}

{% if item.entry.sub_type == "snippet" %}

		Code

{{item.item_code|safe}}

{% endif %}

{% if item.entry.sub_type == "package" %}

		Files

			{% if preview %}
			Links to the ZIP file contents will appear here
			{% else %}

				{% for file in package_files %}

{{file}}

				{% endfor %}

			{% endif %}

{% endif %}

		More information

			{{item.description_html|safe}}

{% if not preview %}

	{% get_comment_count for item as comment_count %}

		Comments ({{comment_count}})

			{% render_comment_list for item %}

{% endif %}

{% if extra_html %}

	{{extra_html|safe}}

{% endif %}
{% endblock %}


text:
<?php declare(strict_types=1);

namespace Bartlett\CompatInfoDb\Infrastructure\Persistence\Doctrine\Hydrator;

use Bartlett\CompatInfoDb\Domain\ValueObject\IniEntry as Domain;
use Bartlett\CompatInfoDb\Infrastructure\Persistence\Doctrine\Entity\IniEntry as Entity;

/**
 * @since Release 3.0.0
 * @author Laurent Laville
 */
final class IniEntryHydrator implements HydratorInterface
{
    use HydrationArraysTrait;

    /**
     * {@inheritDoc}
     */
    public function extract(object $object): array
    {
        if (!$object instanceof Entity) {
            return [];
        }

        return [
            'name' => $object->getName(),
            'ext_min' => $object->getExtMin(),
            'ext_max' => $object->getExtMax(),
            'php_min' => $object->getPhpMin(),
            'php_max' => $object->getPhpMax(),
        ];
    }

    /**
     * {@inheritDoc}
     */
    public function hydrate(array $data, string $class = Entity::class): object
    {
        $object = new $class();

        if (!$object instanceof Entity) {
            $object = new Entity();
        }

        $object->setName($data['name']);
        $object->setExtMin($data['ext_min']);
        $object->setExtMax($data['ext_max'] ?? null);
        $object->setPhpMin($data['php_min']);
        $object->setPhpMax($data['php_max'] ?? null);

        $dependencies = (new DependencyHydrator())->hydrateArrays($data['dependencies'] ?? []);
        $object->addDependencies($dependencies);

        return $object;
    }

    /**
     * @param Entity $entity
     * @return Domain
     */
    public function toDomain(Entity $entity): Domain
    {
        $hydrator = new DependencyHydrator();
        $dependencies = [];
        foreach ($entity->getDependencies() as $dependencyEntity) {
            $dependencies[] = $hydrator->toDomain($dependencyEntity);
        }

        return new Domain(
            $entity->getName(),
            $entity->getExtMin(),
            $entity->getExtMax(),
            $entity->getPhpMin(),
            $entity->getPhpMax(),
            $dependencies
        );
    }
}


text:
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/sharing/click_to_call/click_to_call_context_menu_observer.h"

#include <memory>
#include <string>
#include <vector>

#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/renderer_context_menu/mock_render_view_context_menu.h"
#include "chrome/browser/sharing/click_to_call/click_to_call_utils.h"
#include "chrome/browser/sharing/fake_device_info.h"
#include "chrome/browser/sharing/features.h"
#include "chrome/browser/sharing/mock_sharing_service.h"
#include "chrome/browser/sharing/sharing_constants.h"
#include "chrome/browser/sharing/sharing_service_factory.h"
#include "components/sync_device_info/device_info.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/test_renderer_host.h"
#include "content/public/test/web_contents_tester.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"

using ::testing::_;
using ::testing::ByMove;
using ::testing::Eq;
using ::testing::NiceMock;
using ::testing::Property;
using ::testing::Return;

using SharingMessage = chrome_browser_sharing::SharingMessage;

namespace {

const char kPhoneNumber[] = "+9876543210";

class ClickToCallContextMenuObserverTest : public testing::Test {
 public:
  ClickToCallContextMenuObserverTest() = default;

  ClickToCallContextMenuObserverTest(
      const ClickToCallContextMenuObserverTest&) = delete;
  ClickToCallContextMenuObserverTest& operator=(
      const ClickToCallContextMenuObserverTest&) = delete;

  ~ClickToCallContextMenuObserverTest() override = default;

  void SetUp() override {
    web_contents_ = content::WebContentsTester::CreateTestWebContents(
        menu_.GetBrowserContext(), nullptr);
    menu_.set_web_contents(web_contents_.get());
    SharingServiceFactory::GetInstance()->SetTestingFactory(
        menu_.GetBrowserContext(),
        base::BindRepeating([](content::BrowserContext* context)
                                -> std::unique_ptr<KeyedService> {
          return std::make_unique<NiceMock<MockSharingService>>();
        }));
    observer_ = std::make_unique<ClickToCallContextMenuObserver>(&menu_);
    menu_.SetObserver(observer_.get());
  }

  void BuildMenu(const std::string& phone_number) {
    observer_->BuildMenu(phone_number, /*selection_text=*/std::string(),
                         SharingClickToCallEntryPoint::kRightClickLink);
    sharing_message.mutable_click_to_call_message()->set_phone_number(
        phone_number);
  }

  std::vector<std::unique_ptr<syncer::DeviceInfo>> CreateFakeDevices(
      int count) {
    std::vector<std::unique_ptr<syncer::DeviceInfo>> devices;
    for (int i = 0; i < count; i++) {
      devices.emplace_back(CreateFakeDeviceInfo(
          base::StrCat({"guid", base::NumberToString(i)}), "name"));
    }
    return devices;
  }

 protected:
  NiceMock<MockSharingService>* service() {
    return static_cast<NiceMock<MockSharingService>*>(
        SharingServiceFactory::GetForBrowserContext(menu_.GetBrowserContext()));
  }

  content::BrowserTaskEnvironment task_environment_;
  content::RenderViewHostTestEnabler test_render_host_factories_;
  MockRenderViewContextMenu menu_{/* incognito= */ false};
  std::unique_ptr<content::WebContents> web_contents_;
  std::unique_ptr<ClickToCallContextMenuObserver> observer_;
  SharingMessage sharing_message;
};

}  // namespace

MATCHER_P(ProtoEquals, message, "") {
  std::string expected_serialized, actual_serialized;
  message.SerializeToString(&expected_serialized);
  arg.SerializeToString(&actual_serialized);
  return expected_serialized == actual_serialized;
}

TEST_F(ClickToCallContextMenuObserverTest, NoDevices_DoNotShowMenu) {
  auto devices = CreateFakeDevices(0);

  EXPECT_CALL(*service(), GetDeviceCandidates(_))
      .WillOnce(Return(ByMove(std::move(devices))));

  BuildMenu(kPhoneNumber);

  EXPECT_EQ(0U, menu_.GetMenuSize());
}

TEST_F(ClickToCallContextMenuObserverTest, SingleDevice_ShowMenu) {
  auto devices = CreateFakeDevices(1);
  auto guid = devices[0]->guid();

  EXPECT_CALL(*service(), GetDeviceCandidates(_))
      .WillOnce(Return(ByMove(std::move(devices))));

  BuildMenu(kPhoneNumber);
  ASSERT_EQ(1U, menu_.GetMenuSize());

  MockRenderViewContextMenu::MockMenuItem item;
  ASSERT_TRUE(menu_.GetMenuItem(0, &item));
  EXPECT_EQ(IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_SINGLE_DEVICE,
            item.command_id);

  // Emulate click on the device.
  EXPECT_CALL(*service(),
              SendMessageToDevice(Property(&syncer::DeviceInfo::guid, guid),
                                  Eq(kSharingMessageTTL),
                                  ProtoEquals(sharing_message), _))
      .Times(1);
  menu_.ExecuteCommand(IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_SINGLE_DEVICE,
                       0);
}

TEST_F(ClickToCallContextMenuObserverTest, MultipleDevices_ShowMenu) {
  constexpr int device_count = 3;
  auto devices = CreateFakeDevices(device_count);
  std::vector<std::string> guids;
  for (auto& device : devices)
    guids.push_back(device->guid());

  EXPECT_CALL(*service(), GetDeviceCandidates(_))
      .WillOnce(Return(ByMove(std::move(devices))));

  BuildMenu(kPhoneNumber);
  ASSERT_EQ(device_count + 1U, menu_.GetMenuSize());

  // Assert item ordering.
  MockRenderViewContextMenu::MockMenuItem item;
  ASSERT_TRUE(menu_.GetMenuItem(0, &item));
  EXPECT_EQ(IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_MULTIPLE_DEVICES,
            item.command_id);

  for (int i = 0; i < device_count; i++) {
    ASSERT_TRUE(menu_.GetMenuItem(i + 1, &item));
    EXPECT_EQ(kSubMenuFirstDeviceCommandId + i, item.command_id);
  }

  // Emulate clicks on all commands to check for commands with no device
  // assigned.
  for (int i = 0; i < kMaxDevicesShown; i++) {
    if (i < device_count) {
      EXPECT_CALL(*service(),
                  SendMessageToDevice(
                      Property(&syncer::DeviceInfo::guid, guids[i]),
                      Eq(kSharingMessageTTL), ProtoEquals(sharing_message), _))
          .Times(1);
    } else {
      EXPECT_CALL(*service(), SendMessageToDevice(_, _, _, _)).Times(0);
    }
    observer_->sub_menu_delegate_.ExecuteCommand(
        kSubMenuFirstDeviceCommandId + i, 0);
  }
}

TEST_F(ClickToCallContextMenuObserverTest,
       MultipleDevices_MoreThanMax_ShowMenu) {
  int device_count = kMaxDevicesShown + 1;
  auto devices = CreateFakeDevices(device_count);
  std::vector<std::string> guids;
  for (auto& device : devices)
    guids.push_back(device->guid());

  EXPECT_CALL(*service(), GetDeviceCandidates(_))
      .WillOnce(Return(ByMove(std::move(devices))));

  BuildMenu(kPhoneNumber);
  ASSERT_EQ(kMaxDevicesShown + 1U, menu_.GetMenuSize());

  // Assert item ordering.
  MockRenderViewContextMenu::MockMenuItem item;
  ASSERT_TRUE(menu_.GetMenuItem(0, &item));
  EXPECT_EQ(IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_MULTIPLE_DEVICES,
            item.command_id);

  for (int i = 0; i < kMaxDevicesShown; i++) {
    ASSERT_TRUE(menu_.GetMenuItem(i + 1, &item));
    EXPECT_EQ(kSubMenuFirstDeviceCommandId + i, item.command_id);
  }

  // Emulate clicks on all device commands to check for commands outside valid
  // range too.
  for (int i = 0; i < device_count; i++) {
    if (i < kMaxDevicesShown) {
      EXPECT_CALL(*service(),
                  SendMessageToDevice(
                      Property(&syncer::DeviceInfo::guid, guids[i]),
                      Eq(kSharingMessageTTL), ProtoEquals(sharing_message), _))
          .Times(1);
    } else {
      EXPECT_CALL(*service(), SendMessageToDevice(_, _, _, _)).Times(0);
    }
    observer_->sub_menu_delegate_.ExecuteCommand(
        kSubMenuFirstDeviceCommandId + i, 0);
  }
}


text:
package org.apache.commons.math3.ode.sampling;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.apache.commons.math3.exception.MaxCountExceededException;
import org.apache.commons.math3.util.FastMath;
import org.junit.Assert;
import org.junit.Test;

public class DummyStepInterpolatorTest {

  @Test
  public void testNoReset() throws MaxCountExceededException {

    double[]   y    =   { 0.0, 1.0, -2.0 };
    DummyStepInterpolator interpolator = new DummyStepInterpolator(y, new double[y.length], true);
    interpolator.storeTime(0);
    interpolator.shift();
    interpolator.storeTime(1);

    double[] result = interpolator.getInterpolatedState();
    for (int i = 0; i < result.length; ++i) {
      Assert.assertTrue(FastMath.abs(result[i] - y[i]) < 1.0e-10);
    }

  }

  @Test
  public void testFixedState() throws MaxCountExceededException {

    double[]   y    =   { 1.0, 3.0, -4.0 };
    DummyStepInterpolator interpolator = new DummyStepInterpolator(y, new double[y.length], true);
    interpolator.storeTime(0);
    interpolator.shift();
    interpolator.storeTime(1);

    interpolator.setInterpolatedTime(0.1);
    double[] result = interpolator.getInterpolatedState();
    for (int i = 0; i < result.length; ++i) {
        Assert.assertTrue(FastMath.abs(result[i] - y[i]) < 1.0e-10);
    }

    interpolator.setInterpolatedTime(0.5);
    result = interpolator.getInterpolatedState();
    for (int i = 0; i < result.length; ++i) {
        Assert.assertTrue(FastMath.abs(result[i] - y[i]) < 1.0e-10);
    }

  }

  @Test
  public void testSerialization()
  throws IOException, ClassNotFoundException, MaxCountExceededException {

    double[]   y    =   { 0.0, 1.0, -2.0 };
    DummyStepInterpolator interpolator = new DummyStepInterpolator(y, new double[y.length], true);
    interpolator.storeTime(0);
    interpolator.shift();
    interpolator.storeTime(1);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream    oos = new ObjectOutputStream(bos);
    oos.writeObject(interpolator);

    Assert.assertTrue(bos.size () > 300);
    Assert.assertTrue(bos.size () < 500);

    ByteArrayInputStream  bis = new ByteArrayInputStream(bos.toByteArray());
    ObjectInputStream     ois = new ObjectInputStream(bis);
    DummyStepInterpolator dsi = (DummyStepInterpolator) ois.readObject();

    dsi.setInterpolatedTime(0.5);
    double[] result = dsi.getInterpolatedState();
    for (int i = 0; i < result.length; ++i) {
        Assert.assertTrue(FastMath.abs(result[i] - y[i]) < 1.0e-10);
    }

  }

  @Test
  public void testImpossibleSerialization()
  throws IOException {

    double[] y = { 0.0, 1.0, -2.0 };
    AbstractStepInterpolator interpolator = new BadStepInterpolator(y, true);
    interpolator.storeTime(0);
    interpolator.shift();
    interpolator.storeTime(1);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream    oos = new ObjectOutputStream(bos);
    try {
        oos.writeObject(interpolator);
        Assert.fail("an exception should have been thrown");
    } catch (LocalException le) {
        // expected behavior
    }
  }

  private static class BadStepInterpolator extends DummyStepInterpolator {
      @SuppressWarnings("unused")
      public BadStepInterpolator() {
      }
      public BadStepInterpolator(double[] y, boolean forward) {
          super(y, new double[y.length], forward);
      }
      @Override
      protected void doFinalize() {
          throw new LocalException();
      }
  }

  private static class LocalException extends RuntimeException {
    private static final long serialVersionUID = 1L;
  }

}


text:
using System;

namespace Microsoft.PowerShell.Security
{
    public class MyClass
    {
        public MyClass()
        {
        }
    }
}


text:
from sqlalchemy import *
from migrate import *

from migrate.changeset import schema
pre_meta = MetaData()
post_meta = MetaData()
search = Table('search', post_meta,
    Column('id', Integer, primary_key=True, nullable=False),
    Column('user_id', Integer),
    Column('frequency', String(length=32)),
    Column('description', String(length=255)),
    Column('start_time', DateTime),
)

def upgrade(migrate_engine):
    # Upgrade operations go here. Don't create your own engine; bind
    # migrate_engine to your metadata
    pre_meta.bind = migrate_engine
    post_meta.bind = migrate_engine
    post_meta.tables['search'].columns['user_id'].create()

def downgrade(migrate_engine):
    # Operations to reverse the above upgrade go here.
    pre_meta.bind = migrate_engine
    post_meta.bind = migrate_engine
    post_meta.tables['search'].columns['user_id'].drop()


text: An implementation of an Ordinary Least-Squares Linear Regression model.


text:
Elastica: elasticsearch PHP Client
==================================

[![Build Status](https://secure.travis-ci.org/ruflin/Elastica.png?branch=master)](http://travis-ci.org/ruflin/Elastica)

Documentation
---------------------
Check out the [Elastica documentation](http://Elastica.io/) to find out how Elastica works. If you have questions, don't hesitate to ask them in the [Elastica google group](https://groups.google.com/group/elastica-php-client). Issues should go to the [issue tracker from github](https://github.com/ruflin/Elastica/issues).

About
---------------------
PHP client for the distributed search engine [elasticsearch](http://www.elasticsearch.com/) which is
based on [Lucene](http://lucene.apache.org/java/docs/index.html) and can be an alternative to [solr](http://lucene.apache.org/solr/).
The client naming and structure is consistent with [Zend Framework](http://framework.zend.com/)
and other PHP frameworks. This makes it easy to use the client in combination with Zend Framework.

Changes
-------
For changes in the API please check the file [changes.txt](https://github.com/ruflin/Elastica/blob/master/changes.txt)

Versions
--------
The version numbers are consistent with elasticsearch. The version number 0.16.0.0 means it is the first release for elasticsearch version 0.16.0. The next release is called 0.16.0.1. As soon as the elasticsearch is updated and the client is updated, also the next version is called 0.16.1.0. Like this it should be always clear to which versions the Elastica client is compatible.

Compatibility
-------------
At the moment the client should be backward compatible to PHP 5.2. That's the reason why
the client was not directly built with namespaces and other nice PHP 5.3 features.

File indexing
-------------
File upload is supported but the mapper attachement plugin has to be installed

	./bin/plugin install mapper-attachments

Contributing
------------
Help is very welcomed, but code contributions must be done in respect of [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md).

See [Coding guidelines](https://github.com/ruflin/Elastica/wiki/Coding-guidelines) for tips on how to do so.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class a_vcard.android.text.SpannableStringBuilder
</TITLE>

<META NAME="date" CONTENT="2011-09-25">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
a_vcard.android.text.SpannableStringBuilder

Packages that use SpannableStringBuilder

a_vcard.android.text

Uses of SpannableStringBuilder in a_vcard.android.text

Methods in a_vcard.android.text that return SpannableStringBuilder

 SpannableStringBuilder
SpannableStringBuilder.append(char text)

 SpannableStringBuilder
SpannableStringBuilder.append(java.lang.CharSequence text)

 SpannableStringBuilder
SpannableStringBuilder.append(java.lang.CharSequence text,
       int start,
       int end)

 SpannableStringBuilder
SpannableStringBuilder.delete(int start,
       int end)

 SpannableStringBuilder
SpannableStringBuilder.insert(int where,
       java.lang.CharSequence tb)

 SpannableStringBuilder
SpannableStringBuilder.insert(int where,
       java.lang.CharSequence tb,
       int start,
       int end)

 SpannableStringBuilder
SpannableStringBuilder.replace(int start,
        int end,
        java.lang.CharSequence tb)

 SpannableStringBuilder
SpannableStringBuilder.replace(int start,
        int end,
        java.lang.CharSequence tb,
        int tbstart,
        int tbend)

static SpannableStringBuilder
SpannableStringBuilder.valueOf(java.lang.CharSequence source)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
<component name="libraryTable">
  <library name="beta-1.2.5">
    <CLASSES>
      <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.crashlytics.sdk.android/beta/1.2.5/res" />
      <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.crashlytics.sdk.android/beta/1.2.5/jars/classes.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>