public async Task SingleShouldReturnElement()
        {
            var sequence = new[] {10}.ToAsync();
            Assert.AreEqual(10,await sequence.Single());

            var sequence2 = new int[] {}.ToAsync();
            try
            {
                await sequence2.Single();
                Assert.Fail("No exception thrown");
            }
            catch (InvalidOperationException)
            {
            }

            var sequence3 = new int[] {10,11 }.ToAsync();
            try
            {
                await sequence3.Single();
                Assert.Fail("No exception thrown");
            }
            catch (InvalidOperationException)
            {  
            }
        }
Esempio n. 2
0
            public override object GetIndex(Func<object> proceed, object self, System.Collections.Generic.IEnumerable<object> keys) {
                if (keys.Count() == 1) {
                    var key = System.Convert.ToString(keys.Single());

                    return GetMember(proceed, null, key);
                }
                return proceed();
            }
        public void Collide()
        {
            if (!this._movingItem1.IsExtant || !this._movingItem2.IsExtant)
                return;

            var items = new[] { this._movingItem1, this._movingItem2 };
            var shot = items.OfType<Shot>().FirstOrDefault();
            if (shot != null)
                {
                var otherItem = items.Single(item => item != shot);
                if (InteractionInvolvingShot(this._world, shot, otherItem))
                    return;
                }

            var mine = items.OfType<Mine>().FirstOrDefault();
            if (mine != null)
                {
                var otherItem = items.Single(item => item != mine);
                mine.SteppedOnBy(otherItem);
                return;
                }

            var player = items.OfType<Player>().SingleOrDefault();
            if (player != null)
                {
                var monster = items.Single(item => item != player) as Monster.Monster;
                if (monster != null)
                    {
                    int monsterEnergy = monster.InstantlyExpire();
                    player.ReduceEnergy(monsterEnergy);
                    this._world.AddBang(monster.Position, BangType.Long);
                    this._world.Game.SoundPlayer.Play(GameSound.PlayerCollidesWithMonster);
                    return;
                    }
                }

            var moveableObject = items.FirstOrDefault(item => item.Solidity == ObjectSolidity.Moveable);
            var movingObject = items.FirstOrDefault(item => item != moveableObject && (item.Capability == ObjectCapability.CanPushOthers || item.Capability == ObjectCapability.CanPushOrCauseBounceBack));
            if (moveableObject != null && movingObject != null)
                {
                if (PushOrBounceObject(moveableObject, movingObject))
                    return;
                }
        }
Esempio n. 4
0
        public void FindLabelNotInSet()
        {
            const LabelEnumeration label = LabelEnumeration.Competition;
            const LabelEnumeration otherLabel = LabelEnumeration.Trash;
            var labels = new []{ label, otherLabel};

            var findLabel = labels.Single(x => (x & LabelEnumeration.Trash) != LabelEnumeration.Trash);

            Assert.AreEqual(findLabel, label);
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            var receiveThread = new Thread(new ThreadStart(UdpListener));
            receiveThread.Start();

            CreateUdpClient();

            var cmd = "";

            var dimmerMap = new[] {
                                new { value = "0", level = 0 },
                                new { value = "1", level = 3 },
                                new { value = "2", level = 7 },
                                new { value = "3", level = 10 },
                                new { value = "4", level = 14 },
                                new { value = "5", level = 18 },
                                new { value = "6", level = 21 },
                                new { value = "7", level = 25 },
                                new { value = "8", level = 28 },
                                new { value = "9", level = 32 }};

            if (args.Contains("register"))
            {
                cmd = "000,!F*p\n";
                SendCmd(cmd);
                Thread.Sleep(60000);
            }

            var cmdLampOff = "001,!R1D1F0\n";
            SendCmd(cmdLampOff);

            var r = new Regex("[0-9]{1}");

            var s = Console.ReadLine();
            if (s.Length > 1)
            {
                s = s.Substring(0, 1);
            }

            while (r.IsMatch(s))
            {
                if (s == "0")
                    cmd = cmdLampOff;
                else
                {
                    var level = dimmerMap.Single(dm => dm.value == s).level;

                    cmd = $"001,!R1D1FdP{level}\n";
                }
                SendCmd(cmd);
                s = Console.ReadLine();

            }
        }
            public override object GetIndex(Func<object> proceed, object self, System.Collections.Generic.IEnumerable<object> keys) {
                if (keys.Count() == 1) {
                    var key = System.Convert.ToString(keys.Single());

                    // the zone name is in reference of Layout, e.g. /AsideSecond
                    if(_layoutShape != null && key.StartsWith("/")) {
                        key = key.Substring(1);
                        _parent = _layoutShape;
                    }

                    return GetMember(proceed, null, key);
                }
                return proceed();
            }
 /// <summary>
 /// Calculates area of right trangle square
 /// </summary>
 /// <param name="side1Length">length of first side</param>
 /// <param name="side2Length">length of second side</param>
 /// <param name="side3Length">length of third side</param>
 public static Double Area(Double side1Length, Double side2Length, Double side3Length)
 {
     var sidesLength = new[] { side1Length, side2Length, side3Length };
     var hypotenuse = sidesLength.Max();
     try
     {
         sidesLength.Single(l => DoubleEquals(l, hypotenuse));//checks if there is only one side with maximum length
     }
     catch (System.InvalidOperationException)
     {
         throw new ArgumentException("Wrong sides length");
     }
     if (!DoubleEquals(hypotenuse, Math.Sqrt(sidesLength.Where(l => l != hypotenuse).Select(l => Math.Pow(l, 2)).Sum())))//checks Pythagorean theorem
         throw new ArgumentException("Wrong sides length, does not satisfy the Pythagorean theorem");
     return 0.5 * sidesLength.Where(l => !DoubleEquals(l, hypotenuse)).Aggregate((cathetus1, cathetus2) => cathetus1 * cathetus2);
 }
Esempio n. 8
0
        public void UserStoreInterface_FindByIdAsync_DelegatesToDataDependency(int userId, bool expectFound)
        {
            var entities = new Mock<IWriteEntities>(MockBehavior.Strict);
            var instance = new SecurityStore(entities.Object) as IUserStore<User, int>;
            var data = new[] { new FakeUser(1), new FakeUser(2), new FakeUser(3) }.AsQueryable();
            var dbSet = new Mock<DbSet<User>>(MockBehavior.Strict).SetupDataAsync(data);
            entities.Setup(x => x.Get<User>()).Returns(dbSet.Object);
            Expression<Func<IQueryable<User>, bool>> expectedData = x => ReferenceEquals(x, dbSet.Object);
            entities.Setup(x => x.EagerLoad(It.Is(expectedData), It.IsAny<Expression<Func<User, object>>>())).Returns(dbSet.Object);

            var result = instance.FindByIdAsync(userId).Result;

            (result != null).ShouldEqual(expectFound);
            if (expectFound)
                result.ShouldEqual(data.Single(x => userId.Equals(x.Id)));
            entities.Verify(x => x.Get<User>(), Times.Once);
        }
Esempio n. 9
0
            public override object GetIndex(Func<object> proceed, object self, System.Collections.Generic.IEnumerable<object> keys) {
                if (keys.Count() == 1) {

                    // Here's the new bit
                    var key = System.Convert.ToString(keys.Single());

                    // Check for the proxy symbol
                    if (key.Contains("@")) {
                        // Find the proxy!
                        var split = key.Split('@');
                        // Access the proxy shape
                        return _Proxies[split[0]]()
                            // Find the right zone on it
                            .Zones[split[1]];
                    }
                    else {
                        // Otherwise, defer to the ZonesBehavior activator, which we made available
                        // This will always return a ZoneOnDemandBehavior for the local shape
                        return _zonesActivator()[key];
                    }
                }
                return proceed();
            }
Esempio n. 10
0
 public void Single()
 {
     var ints1 = new[] { 1 };
     var int1 = ints1.Single();
     AssertEquals(int1, 1);
 }
Esempio n. 11
0
 public void SingleThrowsWhenContainsMany()
 {
     var ints1 = new[] { 1, 2 };
     try
     {
         var int1 = ints1.Single();
         AssertTrue(false);
     }
     catch (Exception e)
     {
         AssertTrue(true);
     }
 }
Esempio n. 12
0
 public void TestSinglePredicateTooMany() {
     Func<int> f = () => {
         var a = new[] { 1, 2, 3 };
         try {
             return a.Single(x => x >= 0);
         } catch {
             return -1;
         }
     };
     this.Test(f, -1);
 }
Esempio n. 13
0
        public SearchWindow(MainWindow window)
        {
            this.Owner = window;
            InitializeComponent();

            m_window = window;
            this.Style = window.Style;
            window.StyleChanged += (o, e) => this.Style = this.Owner.Style;
            window.Implementation.ProtocolChanged += new EventHandler(Implementation_ProtocolChanged);

            if (window.CurrentProtocol != null && window.CurrentProtocol.OpcodesEnumType != null)
                this.UpdateOpcodeNames();

            var modeRadioButtons = new[]
            {
                ui_rbBinaryContents,
                ui_rbOpcodes,
                ui_rbPacketContents,
                ui_rbParserOutput,
                ui_rbTextContents
            };

            // Load Recent Searches, must be first
            var recentSearches = Configuration.GetValue("Searches", new List<string>());
            int delta = recentSearches.Count - s_nRecentSearches;
            if (delta > 0)
                recentSearches.RemoveRange(s_nRecentSearches, delta);

            m_recentSearches = new ObservableCollection<string>(recentSearches);

            // Load Search Mode
            var mode = Configuration.GetValue("Mode", SearchMode.Opcodes);
            if (!Enum.IsDefined(typeof(SearchMode), mode))
                mode = SearchMode.Opcodes;

            var modeString = mode.ToString();
            modeRadioButtons.Single(button => (string)button.Tag == modeString).IsChecked = true;

            // Load Misc Options
            ui_cbMatchCase.IsChecked = Configuration.GetValue("CaseSensitive", false);
            ui_cbRegex.IsChecked = Configuration.GetValue("Regex", false);
            ui_cbAllowSpecialChars.IsChecked = Configuration.GetValue("Chars", false);
        }
Esempio n. 14
0
 public void TestSingleCollectionTooMany() {
     Func<int> f = () => {
         var a = new[] { 1, 2 };
         try {
             return a.Single();
         } catch {
             return -1;
         }
     };
     this.Test(f, -1);
 }
Esempio n. 15
0
 public void TestSinglePredicateOnly1() {
     Func<int> f = () => {
         var a = new[] { 1, 2, 3 };
         return a.Single(x => x == 2);
     };
     this.Test(f, 2);
 }
Esempio n. 16
0
        public void OutOfFrameByteTest()
        {
            AsyncPump.Run(
                async () =>
                {
                    var first = this.GetRandomByteExcept(0xFE);
                    var second = this.GetRandomByteExcept(0xFE);

                    var prefix = new[] { this.GetRandomByteExcept() };
                    var third = this.GetRandomByteExcept(0xFE);
                    var postfix = new[] { this.GetRandomByteExcept() };

                    using (var asyncStream = new MemoryStream())
                    {
                        var writer = new S101Writer(asyncStream.WriteAsync);

                        try
                        {
                            await writer.WriteOutOfFrameByteAsync(first, CancellationToken.None);
                            await writer.WriteMessageAsync(KeepAliveRequestMessage, CancellationToken.None);
                            await writer.WriteOutOfFrameByteAsync(second, CancellationToken.None);

                            using (var encodingStream = await writer.WriteMessageAsync(EmberDataMessage, CancellationToken.None))
                            {
                                await encodingStream.WriteAsync(prefix, 0, prefix.Length, CancellationToken.None);
                                await writer.WriteOutOfFrameByteAsync(third, CancellationToken.None);
                                await encodingStream.WriteAsync(postfix, 0, postfix.Length, CancellationToken.None);
                                await encodingStream.DisposeAsync(CancellationToken.None);
                            }
                        }
                        finally
                        {
                            await writer.DisposeAsync(CancellationToken.None);
                        }

                        asyncStream.Position = 0;
                        var reader = new S101Reader(asyncStream.ReadAsync);
                        var firstTask = WaitForOutOfFrameByte(reader);
                        Assert.IsTrue(await reader.ReadAsync(CancellationToken.None));
                        Assert.AreEqual(0x00, reader.Message.Slot);
                        Assert.IsInstanceOfType(reader.Message.Command, typeof(KeepAliveRequest));
                        Assert.AreEqual(first, await firstTask);
                        var secondTask = WaitForOutOfFrameByte(reader);
                        Assert.IsTrue(await reader.ReadAsync(CancellationToken.None));
                        Assert.AreEqual(0x00, reader.Message.Slot);
                        Assert.IsInstanceOfType(reader.Message.Command, typeof(EmberData));
                        Assert.AreEqual(second, await secondTask);
                        var thirdTask = WaitForOutOfFrameByte(reader);

                        using (var payloadStream = new MemoryStream())
                        {
                            await reader.Payload.CopyToAsync(payloadStream);
                            var payload = payloadStream.ToArray();
                            Assert.AreEqual(2, payload.Length);
                            Assert.AreEqual(prefix.Single(), payload[0]);
                            Assert.AreEqual(postfix.Single(), payload[1]);
                        }

                        Assert.AreEqual(third, await thirdTask);
                    }
                });
        }
Esempio n. 17
0
 public void TestSingleCollectionOnly1() {
     Func<int> f = () => {
         var a = new[] { 1 };
         return a.Single();
     };
     this.Test(f, 1);
 }
 public void SingleElementSequenceWithoutPredicate()
 {
     IEnumerableWithCount<int> source = new[]{ 5 }.AsEnumerableWithCount();
     Assert.AreEqual(5, source.Single());
 }
 public void MultipleElementSequenceWithoutPredicate()
 {
     IEnumerableWithCount<int> source = new[]{ 5, 10 }.AsEnumerableWithCount();
     Assert.Throws<InvalidOperationException>(() => source.Single());
 }
        public void Handler_ReturnsNonNullRemoteMembership_WhenFound_ByUserId()
        {
            var userId = FakeData.Id();
            var otherUserId = FakeData.Id(userId);
            var loginProvider = FakeData.String();
            var providerKey = FakeData.String();
            var userLoginInfo = new UserLoginInfo(loginProvider, providerKey);
            var remoteMemberships = new[]
            {
                new ProxiedRemoteMembership(loginProvider, providerKey)
                    { UserId = otherUserId, },
                new ProxiedRemoteMembership(FakeData.String(), FakeData.String())
                    { UserId = userId, },
                new ProxiedRemoteMembership(loginProvider, providerKey)
                    { UserId = userId, },
            };
            var data = remoteMemberships.AsQueryable();
            var query = new RemoteMembershipByUser(userId, userLoginInfo);
            var dbSet = new Mock<DbSet<RemoteMembership>>(MockBehavior.Strict).SetupDataAsync(data);
            var entities = new Mock<IReadEntities>(MockBehavior.Strict);
            var entitySet = new EntitySet<RemoteMembership>(dbSet.Object, entities.Object);
            entities.Setup(x => x.Query<RemoteMembership>()).Returns(entitySet);
            var handler = new HandleRemoteMembershipByUserQuery(entities.Object);

            RemoteMembership result = handler.Handle(query).Result;

            result.ShouldNotBeNull();
            Func<ProxiedRemoteMembership, bool> expectedRemoteMembership =
                x => x.UserId == userId &&
                    x.LoginProvider == loginProvider &&
                    x.ProviderKey == providerKey;
            result.ShouldEqual(remoteMemberships.Single(expectedRemoteMembership));
            entities.Verify(x => x.Query<RemoteMembership>(), Times.Once);
        }
		public void Step2_ChooseCount(
			AeroNavigationBar.HistoryInfo History,
			LinkImages Source
			)
		{
			History.AddFrame(
				delegate
				{
					this.Title.Text = "How many images are you willing to compare from '" + Source.Text + "'";

					var UserDefinedValues_extremly_better = new ComparisionValue { Name = "extremly better", Value = 9 };
					var UserDefinedValues_much_better = new ComparisionValue { Name = "much better", Value = 7 };
					var UserDefinedValues_better = new ComparisionValue { Name = "better", Value = 5 };
					var UserDefinedValues_slightly_better = new ComparisionValue { Name = "slightly better", Value = 3 };

					var DefinedValues = new[] 
					{
						UserDefinedValues_extremly_better,
						UserDefinedValues_much_better,
						UserDefinedValues_better,
						UserDefinedValues_slightly_better,
						new ComparisionValue { Name = "equal", Value =1 },
						new ComparisionValue { Name = "slightly worse", InverseOf = UserDefinedValues_slightly_better },
						new ComparisionValue { Name = "worse", InverseOf = UserDefinedValues_better },
						new ComparisionValue { Name = "much worse", InverseOf = UserDefinedValues_much_better },
						new ComparisionValue { Name = "extremly worse", InverseOf = UserDefinedValues_extremly_better },
					};

					Action<int> Handler =
						XNumber =>
						{
							var Selection = Source.Select((k, i) => new { k, i }).Where(k => k.i < XNumber).ToArray(k => k.k);

							var Matrix = Enumerable.Range(0, Selection.Length).SelectMany(
								x => Enumerable.Range(0, Selection.Length).Select(
									y =>
									{
										var n = new ComparisionInfo
										{
											X = x,
											Y = y,
										};

										if (n.X == n.Y)
										{
											n.Value = DefinedValues.Single(k => k.Value == 1);
										}

										if (n.X > n.Y)
											n.WaitingForUser = true;

										return n;
									}
								)
							).Randomize().ToArray();

							if (XNumber == 6)
							{
								Action<int, int, double> set =
									(x, y, value) =>
									{
										Matrix.Single(k => k.X == x && k.Y == y).Value = DefinedValues.Single(k => k.GetCurrentValue() == value);
										Matrix.Single(k => k.X == y && k.Y == x).Value = DefinedValues.Single(k => k.GetCurrentValue() == 1.0 / value);
									};

								set(0, 1, 3);
								set(2, 0, 3);
								set(3, 0, 5);
								set(0, 4, 3);
								set(5, 0, 3);


								set(2, 1, 7);
								set(3, 1, 9);
								set(4, 1, 1);
								set(5, 1, 7);

								set(3, 2, 3);
								set(2, 4, 5);
								set(5, 2, 1);

								set(3, 4, 9);
								set(3, 5, 3);

								set(5, 4, 9);

							}

							// we need to have the matrix now

							Step3_Compare(History, Selection, Matrix, DefinedValues);


						};

					#region Options
					var Options = Enumerable.Range(3, Source.Images.Count - 2).Select(
						(XNumber, Index) =>
						{
							var o7 = new TextButtonControl
							{
								Text = "I can only handle " + XNumber + "  images from '" + Source.Text + "'",
								Width = 400,
								Height = 40,
							}.AttachContainerTo(this).MoveContainerTo(100, 100 + 40 * Index);

							o7.Content.FontSize = 20;

							var o7bg = o7.Background.ToAnimatedOpacity();


							o7.Background.Fill = Brushes.White;
							o7bg.Opacity = 0;

							o7.Overlay.MouseEnter +=
								delegate { o7bg.Opacity = 1; };


							o7.Overlay.MouseLeave +=
								delegate { o7bg.Opacity = 0; };


							o7.Click +=
								delegate
								{
									Handler(XNumber);
								};

							return o7;
						}
					).ToArray();
					#endregion

					return delegate
					{
						this.Title.Text = "...";
						Options.ForEach(k => k.OrphanizeContainer());
					};
				}
			);
		}
Esempio n. 22
0
        private IInteraction BuildInteraction(StaticItem thisGameItem, StaticItem thatGameItem)
        {
            IInteraction result;
            var items = new[] { thisGameItem, thatGameItem };
            var staticItem = items.FirstOrDefault(item => !(item is MovingItem));
            if (staticItem != null)
                {
                var otherItem = items.Single(item => item != staticItem);
                var movingItem = otherItem as MovingItem;
                if (otherItem is MovingItem)
                    result = new InteractionWithStaticItems(this, staticItem, movingItem);
                else
                    result = new StaticItemAndStaticItemInteraction(this, staticItem, otherItem);
                }
            else
                {
                result = new InteractionWithMovingItems(this, (MovingItem) thisGameItem, (MovingItem) thatGameItem);
                }

            //var shot = items.OfType<Shot>().FirstOrDefault();
            //if (shot != null)
            //    {
            //    var otherItem = items.Single(item => item != shot);
            //    var movingItem = otherItem as MovingItem;
            //    result = movingItem != null
            //        ? (IInteraction) new ShotAndMovingItemInteraction(this, shot, movingItem)
            //        : new ShotAndStaticItemInteraction(this, shot, otherItem);
            //    }
            //else
            //    {
            //    var movingItem = items.OfType<MovingItem>().FirstOrDefault();
            //    if (movingItem != null)
            //        {
            //        var otherItem = items.Single(item => item != movingItem);
            //        var otherMovingItem = otherItem as MovingItem;
            //        result = otherMovingItem != null
            //            ? (IInteraction) new MovingItemAndMovingItemInteraction(this, movingItem, otherMovingItem)
            //            : new MovingItemAndStaticItemInteraction(this, movingItem, otherItem);
            //        }
            //    else
            //        result = new StaticItemAndStaticItemInteraction(this, thisGameItem, thatGameItem);
            //    }
            return result;
        }
        private static bool InteractionInvolvingShot(World world, Shot shot, MovingItem movingItem)
        {
            if (movingItem is Player)
                {
                movingItem.ReduceEnergy(shot.Energy);
                if (movingItem.IsAlive())
                    world.Game.SoundPlayer.Play(GameSound.PlayerInjured);
                world.ConvertShotToBang(shot);
                return true;
                }

            var monster = movingItem as Monster.Monster;
            if (monster != null)
                {
                var result = ShotHitsMonster(world, shot, monster);
                return result;
                }

            var items = new[] { shot, movingItem };
            var explosion = items.OfType<Explosion>().FirstOrDefault();
            if (explosion != null)
                {
                var otherItem = items.Single(item => item != explosion);
                if (otherItem is Shot)
                    {
                    shot.ReduceEnergy(explosion.Energy);
                    return true;
                    }
                }

            var standardShot1 = shot as StandardShot;
            var standardShot2 = movingItem as StandardShot;
            if (standardShot1 != null && standardShot2 != null)
                {
                var result = ShotHitsShot(world, standardShot1, standardShot2);
                return result;
                }

            return false;
        }
Esempio n. 24
0
        public void UserLoginStoreInterface_FindAsync_DelegatesToDataDependency(string provider, string key, bool expectFound)
        {
            var entities = new Mock<IWriteEntities>(MockBehavior.Strict);
            var instance = new SecurityStore(entities.Object) as IUserLoginStore<User, int>;
            var data = new[]
            {
                new User { Name = "user1" },
            }.AsQueryable();
            data.Single().RemoteMemberships.Add(new RemoteMembership
            {
                Id = { LoginProvider = Guid.NewGuid().ToString(), ProviderKey = Guid.NewGuid().ToString() }
            });
            data.Single().RemoteMemberships.Add(new RemoteMembership
            {
                Id = { LoginProvider = "provider1", ProviderKey = "key1" }
            });
            data.Single().RemoteMemberships.Add(new RemoteMembership
            {
                Id = { LoginProvider = Guid.NewGuid().ToString(), ProviderKey = Guid.NewGuid().ToString() }
            });
            var dbSet = new Mock<DbSet<User>>(MockBehavior.Strict).SetupDataAsync(data);
            entities.Setup(x => x.Get<User>()).Returns(dbSet.Object);
            Expression<Func<IQueryable<User>, bool>> expectedData = x => ReferenceEquals(x, dbSet.Object);
            entities.Setup(x => x.EagerLoad(It.Is(expectedData), It.IsAny<Expression<Func<User, object>>>())).Returns(dbSet.Object);

            var result = instance.FindAsync(new UserLoginInfo(provider, key)).Result;

            (result != null).ShouldEqual(expectFound);
            if (expectFound)
                result.ShouldEqual(data.Single());
            entities.Verify(x => x.Get<User>(), Times.Once);
        }