public void SmokeTest()
        {
            var adam = new Employee { Name = "Adam", Age = 50, Salary = 125 };
            var alice = new Employee { Name = "Alice", Age = 25, Salary = 100 };
            var bob = new Employee { Name = "Bob", Age = 30, Salary = 75 };
            var carol = new Employee { Name = "Carol", Age = 35, Salary = 100 };
            var xavier = new Employee { Name = "Xavier", Age = 35, Salary = 100 };

            var employees = new List<Employee> { adam, alice, bob, carol, xavier };

            employees.Sort(OrderedComparer<Employee>.OrderBy(x => x.Name));
            Assert.True(employees.SequenceEqual(new[] { adam, alice, bob, carol, xavier }));

            employees.Sort(OrderedComparer<Employee>
                .OrderByDescending(x => x.Age)
                .ThenBy(x => x.Name)
            );
            Assert.True(employees.SequenceEqual(new[] { adam, carol, xavier, bob, alice }));

            employees.Sort(OrderedComparer<Employee>
                .OrderByDescending(x => x.Salary)
                .ThenBy(x => x.Name, StringComparer.OrdinalIgnoreCase)
            );
            Assert.True(employees.SequenceEqual(new[] { adam, alice, carol, xavier, bob }));

            employees.Sort(OrderedComparer<Employee>
                .OrderByDescending(x => x.Age)
                .ThenByDescending(x => x.Salary)
                .ThenBy(x => x.Name)
            );
            Assert.True(employees.SequenceEqual(new[] { adam, carol, xavier, bob, alice }));
        }
        /// <summary>
        /// Runs the specified test specification.
        /// </summary>
        /// <param name="specification">The test specification to run.</param>
        /// <returns>
        /// The result of running the test specification.
        /// </returns>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="specification"/> is <c>null</c>.</exception>
        public EventCentricAggregateFactoryTestResult Run(EventCentricAggregateFactoryTestSpecification specification)
        {
            if (specification == null) throw new ArgumentNullException("specification");
            var sut = specification.SutFactory();
            sut.Initialize(specification.Givens);
            IAggregateRootEntity factoryResult = null;
            var result = Catch.Exception(() => factoryResult = specification.When(sut));
            if (result.HasValue)
            {
                return specification.Fail(result.Value);
            }
#if NET20
            var actualEvents = new List<object>(factoryResult.GetChanges()).ToArray();
            if (!actualEvents.SequenceEqual(specification.Thens, new WrappedEventComparerEqualityComparer(_comparer)))
            {
                return specification.Fail(actualEvents);
            }
#else
            var actualEvents = factoryResult.GetChanges().ToArray();
            if (!actualEvents.SequenceEqual(specification.Thens, new WrappedEventComparerEqualityComparer(_comparer)))
            {
                return specification.Fail(actualEvents);
            }
#endif
            return specification.Pass();
        }
        public void ChainOntoRegularIComparables()
        {
            var items = new List<string> { "aaa", "AAA", "abb", "aaaa" };
            var comparer = StringComparer.OrdinalIgnoreCase;

            items.Sort(comparer);
            Assert.True(items.SequenceEqual(new[] { "AAA", "aaa", "aaaa", "abb" }, StringComparer.OrdinalIgnoreCase));

            items.Sort(comparer.ThenByDescending(x => x, StringComparer.Ordinal));
            Assert.True(items.SequenceEqual(new[] { "aaa", "AAA", "aaaa", "abb" }, StringComparer.Ordinal));
        }
Example #4
0
        public static void DoTestDescending()
        {
            List<int> numbers = new List<int> { 23, 42, 4, 16, 8, 15, 3, 9, 55, 0, 34, 12, 2, 46, 25 };
            numbers.PigeonHoleSortDescending();

            Debug.Assert(numbers.SequenceEqual(numbers.OrderByDescending(i => i)), "Wrong PigeonHole descending");
        }
Example #5
0
        /// <summary>
        /// Devuelve una Lista de Listas de Tuplas(Doule,Doule) que contiene el historial de configuraciones de los pesos.
        /// El algoritmo tiene como condicion de Fin que se estabilicen los pesos, es decir que termina cuando la anteultima y ultima configuracion son iguales.
        /// </summary>
        /// <param name="Pesos">Lista de tuplas(double,double) que representa la configuracion de pesos iniciales.</param>
        /// <param name="Patrones">Lista de tuplas(double,double) que representa los patrones de entrada.</param>
        public List<List<Tuple<Double, Double>>> SOMAlgorithm(List<Tuple<Double, Double>> Pesos, List<Tuple<Double, Double>> Patrones)
        {
            this.HistorialActualizacion = new List<List<Tuple<Double, Double>>>();
            this.HistorialDistancias = new List<List<Double>>();
            var UltimaConfig = new List<Tuple<Double, Double>>();
            var AnteUltimaConfig = new List<Tuple<Double, Double>>();
            int i = 0;

                //foreach (var Patron in Patrones)
                do
                {
                    var Patron = Patrones[i % 5];

                    var IxGanador = FuncionActivacion(Pesos, Patron);
                    Pesos = ActualizarPesos(Pesos, Patron, Patrones.IndexOf(Patron)+1, IxGanador);

                    HistorialActualizacion.Add(Pesos);//Se guardan las configuraciones de pesos parciales. La ultima será la final.

                    //Print pesos
                    ////Console.WriteLine();
                    ////Console.WriteLine("Nuevos Pesos:");
                    //Pesos.ForEach(delegate(Tuple<Double, Double> peso) { //Console.WriteLine(peso.Item1 + "; " + peso.Item2); });
                    //Console.WriteLine();

                    i++;
                    UltimaConfig = HistorialActualizacion.Last();

                    if (i>=2)
                    {
                        AnteUltimaConfig = HistorialActualizacion.ElementAt(HistorialActualizacion.IndexOf(UltimaConfig)-1) ;
                    }

                } while (!UltimaConfig.SequenceEqual(AnteUltimaConfig));
            return HistorialActualizacion;
        }
Example #6
0
        static public bool TestCompleteSequence()
        {
            var ledRed = Light.Leds[Color.Red];
            ledRed.RunSequence();
            var ledYellow = Light.Leds[Color.Yellow];
            ledYellow.RunSequence(false);
            var ledGreen = Light.Leds[Color.Green];
            ledGreen.RunSequence(false);
            ledYellow.RunSequence(false);
            ledRed.RunSequence(false);
            var expectedSequence = new List<object>();
            expectedSequence.Add(new Tuple<Color, string>(Color.Red, "High"));
            expectedSequence.Add(new Tuple<Color, string>(Color.Red, "3000ms"));
            expectedSequence.Add(new Tuple<Color, string>(Color.Red, "Low"));
            expectedSequence.Add(new Tuple<Color, string>(Color.Yellow, "High"));
            expectedSequence.Add(new Tuple<Color, string>(Color.Yellow, "3000ms"));
            expectedSequence.Add(new Tuple<Color, string>(Color.Yellow, "Low"));
            expectedSequence.Add(new Tuple<Color, string>(Color.Green, "High"));
            expectedSequence.Add(new Tuple<Color, string>(Color.Green, "3000ms"));
            expectedSequence.Add(new Tuple<Color, string>(Color.Green, "Low"));
            expectedSequence.Add(new Tuple<Color, string>(Color.Yellow, "High"));
            expectedSequence.Add(new Tuple<Color, string>(Color.Yellow, "3000ms"));
            expectedSequence.Add(new Tuple<Color, string>(Color.Yellow, "Low"));
            expectedSequence.Add(new Tuple<Color, string>(Color.Red, "High"));
            expectedSequence.Add(new Tuple<Color, string>(Color.Red, "3000ms"));
            expectedSequence.Add(new Tuple<Color, string>(Color.Red, "Low"));

            return (expectedSequence.SequenceEqual(Light.Sequence));
        }
Example #7
0
    static int[] FindLoop(int[] line)
    {
        for (int i = 0; i < line.Length; i++)
        {
            int nextOccurrence = Array.IndexOf(line, line[i], i + 1);

            if (nextOccurrence != -1)
            {
                List<int> testRange = new List<int>(),
                       compareRange = new List<int>();

                for (int j = i; j < nextOccurrence; j++)
                    testRange.Add(line[j]);

                for (int j = 0; j < testRange.Count; j++)
                {
                    if (j >= line.Length)
                    {
                        compareRange.Clear();
                        break;
                    }
                    compareRange.Add(line[j + nextOccurrence]);
                }
                if (testRange.SequenceEqual(compareRange))
                    return testRange.ToArray();
            }
        }
        return new int[0];
    }
Example #8
0
        public static void DoTestDescending()
        {
            List<int> numbers = new List<int> { 23, 42, 4, 16, 8, 15, 3, 9, 55, 0, 34, 12, 2, 46, 25 };
            numbers.CombSortDescending(Comparer<int>.Default);

            Debug.Assert(numbers.SequenceEqual(numbers.OrderByDescending(i => i)), "Wrong CombSort descending");
        }
        public static void TestInvoker()
        {
            var range = Arrays.Range(0, 1, 100);
            var list = new List<int>();
            IAsyncResult result = null;

            using (var sti = new SingleThreadedInvoker())
            {
                foreach (int i in range)
                {
                    int j = i;
                    if (j % 2 == 0)
                        result = sti.BeginInvoke(new Action(() =>
                        {
                            list.Add(j);
                        }), new object[0]);
                    else
                        sti.Invoke(new Action(() =>
                        {
                            list.Add(j);
                        }), new object[0]);
                }

                // wait for all to finish
                sti.EndInvoke(result);
            }

            if (!list.SequenceEqual(range))
                throw new Exception("SingleThreadedInvoker failed!");
        }
Example #10
0
 bool BibTeXCheck(){
     if(!aux.ContainsKey(".aux") || aux[".aux"] == null) return false;
     var bibcite = new System.Text.RegularExpressions.Regex("\\\\bibcite\\{(.*?)\\}");
     var citation = new System.Text.RegularExpressions.Regex("\\\\citation\\{(.*?)\\}");
     var bibs = new List<string>();
     var cits = new List<string>();
     bool existbibdata = false;
     Encoding[] encs = KanjiEncoding.GuessKajiEncoding(aux[".aux"]);
     Encoding enc;
     if(encs.Length == 0) enc = Encoding.GetEncoding("shift_jis");
     else enc = encs[0];
     using(var fs = new StringReader(enc.GetString(aux[".aux"]))) {
         while(true) {
             string line = fs.ReadLine();
             if(line == null) break;
             if(!existbibdata && line.IndexOf("\\bibdata{") != -1) existbibdata = true;
             var m = bibcite.Match(line);
             if(m.Success) bibs.Add(m.Groups[1].Value);
             m = citation.Match(line);
             if(m.Success) cits.Add(m.Groups[1].Value);
         }
     }
     if(!existbibdata)return false;
     cits.Sort(); cits = new List<string>(cits.Distinct());
     bibs.Sort(); bibs = new List<string>(bibs.Distinct());
     return !(cits.SequenceEqual(bibs));
 }
Example #11
0
        /// <summary>
        /// Tests the ReplaySubject with concurrent subscribers.
        /// </summary>
        public static void ConcurrentSubscribers()
        {
            var N = int.MaxValue;
            var M = int.MaxValue;

            var r = new ReplaySubject<int>(4);

            var rnd = new Random();
            var ts = new List<Task>();

            for (var i = 0; i < 16; i++)
            {
                var rnd2 = new Random(rnd.Next());

                ts.Add(Task.Factory.StartNew(async () =>
                {
                    var n = rnd2.Next(10, 1000);

                    for (var j = 0; j < M; j++)
                    {
                        var xs = new List<int>();
                        await r.Take(n).Scan((x1, x2) =>
                        {
                            if (x2 - x1 != 1)
                                Debugger.Break();

                            if (x2 == 0)
                                Debugger.Break();

                            return x2;
                        }).ForEachAsync(xs.Add);

                        var f = xs.First();
                        if (!xs.SequenceEqual(Enumerable.Range(f, xs.Count)))
                        {
                            Console.WriteLine("FAIL!");
                            Debugger.Break();
                        }
                        else
                        {
                            Console.Write(".");
                        }

                        if (j % 1000 == 0)
                        {
                            await Task.Delay(50);
                        }
                    }
                }));
            }

            for (var i = 0; i < N; i++)
            {
                r.OnNext(i);
            }

            Console.WriteLine("Done!");

            Task.WaitAll(ts.ToArray());
        }
Example #12
0
        public static void DoTestDescending()
        {
            List<int> numbers = new List<int> { 84, 69, 76, 86, 94, 91, 77, 31, 44, 55, 20 };
            numbers.GnomeSortDescending(Comparer<int>.Default);

            Debug.Assert(numbers.SequenceEqual(numbers.OrderByDescending(i => i)), "Wrong GnomeSort descending");
        }
Example #13
0
        public static void DoTestAscending()
        {
            List<int> numbers = new List<int> { 54, 26, 93, 17, 77, 31, 44, 55, 20 };
            numbers.GnomeSortAscending(Comparer<int>.Default);

            Debug.Assert(numbers.SequenceEqual(numbers.OrderBy(i => i)), "Wrong GnomeSort ascending");
        }
Example #14
0
        public override bool Equals(RelationshipDescriptor other)
        {
            AnyOfRelationshipDescriptor anyRel = other as AnyOfRelationshipDescriptor;

            return(anyRel != null &&
                   (any_of?.SequenceEqual(anyRel.any_of) ?? anyRel.any_of == null));
        }
Example #15
0
        /// <summary>
        /// Tests the Replay operator with different schedulers, supporting ISchedulerLongRunning and otherwise.
        /// Stresses the ScheduledObserver implementation with its counting logic.
        /// </summary>
        public static void DifferentSchedulers()
        {
            while (true)
            {
                for (int i = 100; i <= 10000; i *= 10)
                {
                    foreach (var s in new IScheduler[] { Scheduler.Default, TaskPoolScheduler.Default, ThreadPoolScheduler.Instance })
                    {
                        foreach (var b in new[] { true, false })
                        {
                            var t = b ? s : s.DisableOptimizations();

                            var e = new ManualResetEvent(false);
                            var xs = Observable.Range(0, i, TaskPoolScheduler.Default.DisableOptimizations()).Do(_ => { }, () => e.Set());

                            var ys = xs.Replay(t);

                            var f = new ManualResetEvent(false);
                            var r = new List<int>();
                            ys.Subscribe(r.Add, () => f.Set());

                            ys.Connect();
                            
                            e.WaitOne();
                            f.WaitOne();

                            if (!r.SequenceEqual(Enumerable.Range(0, i)))
                                throw new Exception();

                            Console.Write(".");
                        }
                    }
                }
            }
        }
        public async Task Notifier_should_send_notifications_within_specified_time_span()
        {
            var minimumChecks = 3;
            var expectedEventTimeline = new List<string>();
            for (var i = 0; i < minimumChecks; ++i)
                expectedEventTimeline.AddRange(new[] { "updateHealth_start", "delay_start", "update_finish", "update_finish" });

            var countdown = new AsyncCountdown("notifications", minimumChecks);
            var endpointId = Guid.NewGuid();
            var interval = TimeSpan.FromMilliseconds(300);

            SetupHealthCheckInterval(interval);

            SetupEndpointRegistration(endpointId);

            _mockClient
                .Setup(c => c.SendHealthUpdateAsync(endpointId, AuthenticationToken, It.IsAny<HealthUpdate>(), It.IsAny<CancellationToken>()))
                .Returns(() => _awaitableFactory.Return().WithDelay(TimeSpan.FromMilliseconds(100)).WithTimeline("updateHealth").WithCountdown(countdown).RunAsync());

            _mockTimeCoordinator
                .Setup(c => c.Delay(interval, It.IsAny<CancellationToken>()))
                .Returns(() => _awaitableFactory.Return().WithDelay(TimeSpan.FromMilliseconds(50)).WithTimeline("delay").RunAsync());

            using (CreateNotifier())
                await countdown.WaitAsync(TestMaxTime);

            var actualEventTimeline = _awaitableFactory.GetOrderedTimelineEvents()
                .Select(eventName => (eventName == "updateHealth_finish" || eventName == "delay_finish") ? "update_finish" : eventName)
                .Take(minimumChecks * 4)
                .ToArray();

            Assert.True(expectedEventTimeline.SequenceEqual(actualEventTimeline), $"Expected:\n{string.Join(",", expectedEventTimeline)}\nGot:\n{string.Join(",", actualEventTimeline)}");
        }
        public void CustomComparerTest()
        {
            var items = new List<string> { "aaa", "AAA", "abb", "aaaa" };

            items.Sort(OrderedComparer<string>.OrderBy(x => x, StringComparer.Ordinal));
            Assert.True(items.SequenceEqual(new[] { "AAA", "aaa", "aaaa", "abb" }));

            items.Sort(OrderedComparer<string>.OrderByDescending(x => x.Length).ThenBy(x => x, StringComparer.Ordinal));
            Assert.True(items.SequenceEqual(new[] { "aaaa", "AAA", "aaa", "abb" }));

            items.Sort(OrderedComparer<string>.OrderBy(x => x.Length).ThenBy(x => x, StringComparer.Ordinal));
            Assert.True(items.SequenceEqual(new[] { "AAA", "aaa", "abb", "aaaa" }));

            items.Sort(OrderedComparer<string>.OrderBy(x => x.Length).ThenBy(x => x, StringComparer.OrdinalIgnoreCase));
            Assert.True(items.SequenceEqual(new[] { "AAA", "AAA", "abb", "aaaa" }, StringComparer.OrdinalIgnoreCase));
        }
Example #18
0
        public void ShouldReturnInnerElements()
        {
            var innerList = new List<int> { 1, 2, 3 };

            var list = new LazyList<int>(() => innerList);

            Assert.True(innerList.SequenceEqual(list));
        }
        public void BindTo_should_set_list_of_items()
        {
            var items = new List<string> { "1", "2", "3"};

            builder.BindTo(items);

            Assert.True(items.SequenceEqual(AutoComplete.Items));
        }
Example #20
0
        public static void MemberNames_can_be_set_through_two_args_constructor()
        {
            var validationResult = new ValidationResult("SomeErrorMessage", null);
            AssertEx.Empty(validationResult.MemberNames);

            var memberNames = new List<string>() { "firstMember", "secondMember" };
            validationResult = new ValidationResult("SomeErrorMessage", memberNames);
            Assert.True(memberNames.SequenceEqual(validationResult.MemberNames));
        }
 public static void Can_get_ThisKeyMembers_and_OtherKeyMembers()
 {
     var listOfThisKeys = new List<string>() { "ThisKey1", "ThisKey2", "ThisKey3" };
     var listOfOtherKeys = new List<string>() { "OtherKey1", "OtherKey2" };
     // doesn't matter how many spaces are between keys, but they must be separated by a comma
     var attribute = new AssociationAttribute("Name", "ThisKey1,  ThisKey2, ThisKey3", "OtherKey1,  OtherKey2");
     Assert.True(listOfThisKeys.SequenceEqual(attribute.ThisKeyMembers));
     Assert.True(listOfOtherKeys.SequenceEqual(attribute.OtherKeyMembers));
 }
Example #22
0
        /// <summary>
        /// Returns true if MainWindow should be shown afterwards.
        /// </summary>
        public static async Task <bool> ProcessArguments(IEnumerable <string> arguments, TimeSpan extraDelay = default(TimeSpan))
        {
            var showMainWindow = false;

            var list = arguments.ToList();

            if (_previousArguments?.SequenceEqual(list) == true)
            {
                return(false);
            }

            _previousArguments = list;

            var remote = (await list.Select(async x => Tuple.Create(x,
                                                                    ContentInstallationManager.IsRemoteSource(x) || ContentInstallationManager.IsAdditionalContent(x) ? x :
                                                                    await ContentInstallationManager.IsRemoteSourceFlexible(x))
                                            ).WhenAll()).Where(x => x.Item2 != null).ToList();

            if (remote.Any())
            {
                list = list.ApartFrom(remote.Select(x => x.Item1)).ToList();
                if ((await remote.Select(x => ContentInstallationManager.Instance.InstallAsync(x.Item2, new ContentInstallationParams {
                    AllowExecutables = true
                })).WhenAll()).All(x => !x))
                {
                    await Task.Delay(ContentInstallationManager.OptionFailedDelay);
                }
            }

            foreach (var arg in list)
            {
                var result = await ProcessArgument(arg);

                if (extraDelay != TimeSpan.Zero)
                {
                    await Task.Delay(extraDelay);
                }

                if (result == ArgumentHandleResult.FailedShow)
                {
                    NonfatalError.Notify(AppStrings.Main_CannotProcessArgument, AppStrings.Main_CannotProcessArgument_Commentary);
                }

                if (result == ArgumentHandleResult.SuccessfulShow || result == ArgumentHandleResult.FailedShow)
                {
                    showMainWindow = true;
                }
            }

            _previousArguments = null;
            return(showMainWindow);
        }
Example #23
0
        public void Explicit_List_Cast()
        {
            //arrange
            List<int> expected = new List<int>() { 1, 2, 3 };
            SetType<IntegerType> actualType = SetType<IntegerType>.From(expected);

            //act
            CassandraObject actual = actualType;
            var actualValues = actual.GetValue<List<object>>();

            //assert
            Assert.True(expected.SequenceEqual(actualValues.Select(Convert.ToInt32)));
        }
        private static readonly Dictionary <string, List <string> > LastThings = new Dictionary <string, List <string> >(); //as reddit calls them "things"


        public static async Task <List <AnimeWallpaperData> > GetAllWallpapers(int page)
        {
            //if we have different set we are clearing previously fetched data
            var allSubsCount = Enum.GetValues(typeof(WallpaperSources)).Length;
            var currentSubs  = Settings.EnabledWallpaperSources.OrderBy(source => (int)source).ToList();

            if (!_previousSourceSet?.SequenceEqual(currentSubs) ?? false)
            {
                Cache.Clear();
                LastThings.Clear();
                page = 0;
                ViewModelLocator.Wallpapers.CurrentPage = 0;
            }
            if (page > LastThings.Count)
            {
                page = 0;
                ViewModelLocator.Wallpapers.CurrentPage = 0;
            }
            _itemsToPull       = BaseItemsToPull + (allSubsCount - currentSubs.Count);
            _previousSourceSet = currentSubs;
            if (Cache.ContainsKey(page))
            {
                return(Cache[page]);
            }

            var tasks = new List <Task <List <AnimeWallpaperData> > >();

            lock (LastThings)
            {
                currentSubs.ForEach(
                    s =>
                    tasks.Add(
                        new AnimeWallpapersQuery(s.ToString(), page == 0 ? null : LastThings[s.ToString()][page - 1], page,
                                                 s).GetWallpapers()));
            }
            await Task.WhenAll(tasks);

            var output = new List <AnimeWallpaperData>();

            foreach (var task in tasks)
            {
                output.AddRange(task.Result);
            }
            output =
                output.Where(data => !data.FileUrl.Contains(".gif"))
                .Distinct()
                .OrderByDescending(data => data.DateTime)
                .ToList();
            Cache.Add(page, output);
            return(output);
        }
        public void Create_NullCoalescingAction()
        {
            var xs = Observable.Create<int>(o =>
            {
                o.OnNext(42);
                return default(Action);
            });

            var lst = new List<int>();
            var d = xs.Subscribe(lst.Add);
            d.Dispose();

            Assert.IsTrue(lst.SequenceEqual(new[] {42}));
        }
Example #26
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var username = "";
            var password = "";
            var list = new List<string>();
            DA.GetDataList(0, list);
            DA.GetData(1, ref username);
            DA.GetData(2, ref password);


            if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password))
            {
                BimServer.Username = username;
                BimServer.Password = password;
            }


            if (list.SequenceEqual(BimVisualiserData.Instance.URIList))
            {
                BimVisualiserData.Instance.URIList = list;
            }
            // New data feeded, need to recompute
            else
            {
                _returnValue = "";
                BimVisualiserData.Instance.Selected = -1;
                BimVisualiserData.Instance.URIList = list;
                BimVisualiserData.Instance.NameList = new List<string>();
            }


            if (BimVisualiserData.Instance.NameList.Count == 0)
            {
                foreach (var uri in BimVisualiserData.Instance.URIList)
                {
                    var client = new BimServer();
                    client.Login();
                    var name = GetProjectName(client, uri);
                    BimVisualiserData.Instance.NameList.Add(name);
                }

                m_attributes.ExpireLayout();
            }


            DA.SetData(0, _returnValue);
        }
        public void Should_be_able_to_enumerate_keys()
        {
            // Given
            dynamic parameters = new DynamicDictionary();

            parameters["test"] = "10";
            parameters["rest"] = "20";

            // When
            var names = new List<string>();
            foreach (var name in parameters) {
                names.Add(name);
            }

            // Then
            Assert.True(names.SequenceEqual(new[] { "test", "rest" }));
        }
        public void AddShouldInsertNewItem()
        {
            // arrange
            var expectedProperties = new[] { "Count", "Item[]" };
            var actualProperties = new List<string>();
            var target = new ObservableKeyedCollection<string, int>( i => i.ToString() );

            target.PropertyChanged += ( s, e ) => actualProperties.Add( e.PropertyName );

            // act
            target.Add( 1 );

            // assert
            Assert.Equal( 1, target.Count );
            Assert.Equal( 1, target[0] );
            Assert.True( actualProperties.SequenceEqual( expectedProperties ) );
        }
        public void GetAllReturnsAllStrategies()
        {
            // Arrange:
            var cooperationStrategyRepository = new CooperationStrategyRepository();

            // Act:
            var strategies = cooperationStrategyRepository.GetAll();

            // Assert
            var allStrategies = new List<CooperationStrategy>
                                    {
                                        new NaiveCooperationStrategy(),
                                        new EvilCooperationStrategy(),
                                        new TitForTatCooperationStrategy(),
                                    };
            Assert.True(allStrategies.SequenceEqual(strategies));
        }
        public void ShouldUnselectValueInCollectionOnClear()
        {
            // arrange
            var target = new SelectableItemCollection<string>( new[] { "1", "2", "3" } );
            var expectedProperties = new[] { "Count", "Item[]" };
            var actualProperties = new List<string>();

            target.SelectedValues.Add( "2" );
            ( (INotifyPropertyChanged) target.SelectedValues ).PropertyChanged += ( s, e ) => actualProperties.Add( e.PropertyName );

            // act
            target.SelectedValues.Clear();

            // assert
            Assert.Equal( 0, target.SelectedItems.Count );
            Assert.True( actualProperties.SequenceEqual( expectedProperties ) );
        }
Example #31
0
        static void Main()
        {
            var list = new List<string>();

            while (true)
            {
                var _ = new List<string>();
                var url = new List<string>();

                var xmlReader = XmlReader.Create("http://rssblog.ameba.jp/asakuramomoblog/rss20.xml");
                while (xmlReader.Read())
                {
                    if (xmlReader.NodeType != XmlNodeType.Element) continue;
                    switch (xmlReader.LocalName)
                    {
                        case "title":
                            _.Add(xmlReader.ReadString());
                            break;
                        case "link":
                            url.Add(xmlReader.ReadString());
                            break;
                    }
                }

                if (!list.SequenceEqual(_))
                {
                    if (list.Count != 0)
                    {
                        var sw = new System.IO.StreamWriter("mocho.log", false, Encoding.UTF8);
                        sw.Write("麻倉ももオフィシャルブログ「もちょっとおしゃべり」が更新されました!\n『" + _[1] + "』" + url[4]);
                        sw.Close();

                        Process.Start(new ProcessStartInfo("python", "./tw.py"));
                    }
                }
                list.Clear();
                list.AddRange(_);

                Console.WriteLine(string.Join("\n", list) + "\n");

                Thread.Sleep(10 * 60 * 1000);
            }
        }
Example #32
0
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter a series of numbers separated by a hyphen");
            var numbers = Console.ReadLine();
            var numbersList = new List<int>();
            numbersList = numbers.Split('-').Select(Int32.Parse).ToList();
            var sortedNumbers = new List<int>(numbersList);
            sortedNumbers.Sort();

            if (numbersList.SequenceEqual(sortedNumbers))
            {
                Console.WriteLine("Consecutive");
            }
            else
            {
                Console.WriteLine("Not consecutive");
            }
            Console.ReadKey();
        }
Example #33
0
        public static SyntaxTokenList Organize(SyntaxTokenList modifiers)
        {
            if (modifiers.Count > 1 && !modifiers.SpansPreprocessorDirective())
            {
                var initialList = new List<SyntaxToken>(modifiers);
                var leadingTrivia = initialList.First().LeadingTrivia;
                initialList[0] = initialList[0].WithLeadingTrivia(SpecializedCollections.EmptyEnumerable<SyntaxTrivia>());

                var finalList = initialList.OrderBy(new Comparer()).ToList();
                if (!initialList.SequenceEqual(finalList))
                {
                    finalList[0] = finalList[0].WithLeadingTrivia(leadingTrivia);

                    return finalList.ToSyntaxTokenList();
                }
            }

            return modifiers;
        }
        public async Task <(List <Key>, bool)> WaitForStateKeypressAsync(List <Key> PreviousPressedKeys, int PollRate = 30)
        {
            await Task.Delay(PollRate).ConfigureAwait(false);

            KeyboardState State = GetKeyboardState();
            List <Key>    CurrentPressedKeys = State.PressedKeys;

            if (CurrentPressedKeys.Contains(MonitoredKey))
            {
                Debug.WriteLine("Contained!");
                if (!(PreviousPressedKeys?.SequenceEqual(CurrentPressedKeys) ?? CurrentPressedKeys == null))
                {
                    //Ensures value is only returned if sequence is different from last attempt (only called once per keypress of monitored key)
                    //PressedKeys contains keys that are currently down, held and up; we only want down.
                    return(CurrentPressedKeys, true);
                }
            }
            return(null, false);
        }
Example #35
0
 /// <nodoc/>
 public bool Equals(CacheId other) => other != null && m_hierarchicalIds.SequenceEqual <string>(other.HierarchicalIds);
            public async Task Processes_Ranges_And_Waits_Until_Next_Range_Is_Available()
            {
                var mockWaitStategy = new Mock <IWaitStrategy>();

                Service.WaitForBlockStrategy = mockWaitStategy.Object;

                var waits = new List <uint>();
                var cancellationSource = new CancellationTokenSource();

                var range1    = new BlockRange(0, 9);
                var nullRange = new BlockRange?();
                var range2    = new BlockRange(10, 19);

                var rangeQueue = new Queue <BlockRange?>();

                //initial range to process
                rangeQueue.Enqueue(range1);

                //simulate being up to date for 3 iterations
                rangeQueue.Enqueue(nullRange);
                rangeQueue.Enqueue(nullRange);
                rangeQueue.Enqueue(nullRange);

                //simulate new range becoming available
                rangeQueue.Enqueue(range2);

                //get next range from queue
                MockProgressService
                .Setup(s => s.GetNextBlockRangeToProcessAsync(MaxBlocksPerBatch))
                .ReturnsAsync(() => rangeQueue.Dequeue());

                //process range 1
                MockProcessor
                .Setup(p => p.ProcessAsync(range1, It.IsAny <CancellationToken>()))
                .Returns(Task.CompletedTask);

                //when range is null expect wait strategy to be invoked
                mockWaitStategy
                .Setup(s => s.Apply(It.IsAny <uint>()))
                .Callback <uint>((attemptCount) => waits.Add(attemptCount))
                .Returns(Task.CompletedTask);

                //process range 2
                MockProcessor
                .Setup(p => p.ProcessAsync(range2, It.IsAny <CancellationToken>()))
                .Returns(Task.CompletedTask);

                //update progress range 1
                MockProgressService
                .Setup(s => s.SaveLastBlockProcessedAsync(range1.To))
                .Returns(Task.CompletedTask);

                //update progress range 2
                MockProgressService
                .Setup(s => s.SaveLastBlockProcessedAsync(range2.To))
                .Returns(Task.CompletedTask);

                //short circuit callback used to exit process
                var shortCircuit = new Action <LogBatchProcessedArgs>((args) =>
                {
                    if (args.LastRangeProcessed.Equals(range2))
                    {
                        cancellationSource.Cancel();
                    }
                });

                var blocksProcessed = await Service.ProcessContinuallyAsync(
                    cancellationSource.Token, shortCircuit);

                Assert.Equal(20, blocksProcessed);
                Assert.Equal(3, waits.Count);
                //wait strategy is sent an attempt count so it can adjust wait time accordingly
                Assert.True(waits.SequenceEqual(new uint[] { 1, 2, 3 }));

                MockProcessor.Verify();
                MockProgressService.Verify();
            }
Example #37
0
        /// <summary>
        /// Returns true if MainWindow should be shown afterwards.
        /// </summary>
        public static async Task <ShowMainWindow> ProcessArguments([CanBeNull] IEnumerable <string> arguments, bool fullPathsOnly,
                                                                   TimeSpan extraDelay = default(TimeSpan))
        {
            if (arguments == null)
            {
                return(ShowMainWindow.No);
            }

            var list = arguments.Select(FixProxiedRequest).ToList();

            if (_previousArguments?.SequenceEqual(list) == true)
            {
                return(ShowMainWindow.No);
            }
            if (list.Count == 0)
            {
                return(ShowMainWindow.Immediately);
            }

            try {
                // Why it’s here?
                _previousArguments = list;

                using (BringNewWindowsInFront()) {
                    var contentToInstall = (await list.Where(x => !IsCustomUriScheme(x))
                                            .Select(async x => Tuple.Create(x,
                                                                            ContentInstallationManager.IsRemoteSource(x) || ContentInstallationManager.IsAdditionalContent(x, fullPathsOnly) ? x :
                                                                            await ContentInstallationManager.IsRemoteSourceFlexible(x))
                                                    ).WhenAll()).Where(x => x.Item2 != null).ToList();
                    if (contentToInstall.Any())
                    {
                        list = list.ApartFrom(contentToInstall.Select(x => x.Item1)).ToList();
                        if ((await contentToInstall.Select(x => ContentInstallationManager.Instance.InstallAsync(x.Item2,
                                                                                                                 new ContentInstallationParams(true))).WhenAll()).All(x => !x))
                        {
                            // TODO
                            await Task.Delay(2000);
                        }
                    }

                    var showMainWindow = false;
                    foreach (var arg in list)
                    {
                        var result = await ProcessArgument(arg);

                        if (extraDelay != TimeSpan.Zero)
                        {
                            await Task.Delay(extraDelay);
                        }

                        if (result == ArgumentHandleResult.FailedShow)
                        {
                            NonfatalError.Notify(string.Format(AppStrings.Main_CannotProcessArgument, arg), AppStrings.Main_CannotProcessArgument_Commentary);
                        }

                        if (result == ArgumentHandleResult.SuccessfulShow || result == ArgumentHandleResult.FailedShow)
                        {
                            showMainWindow = true;
                        }
                    }

                    return(showMainWindow ? ShowMainWindow.Yes : ShowMainWindow.No);
                }
            } finally {
                _previousArguments = null;
            }
        }
        /////////////////
        // Advanced    //
        /////////////////
        private static void VertexStreamsArea(Material material, List <ParticleSystemRenderer> renderers, ShaderTemplate shaderTemplate)
        {
            bool useLighting, isPBS;

            useLighting = shaderTemplate != ShaderTemplate.Unlit ? true : false;
            isPBS       = shaderTemplate == ShaderTemplate.PhysicallyBased ? true : false;
            EditorGUILayout.Space();
            // Display list of streams required to make this shader work
            bool useNormalMap        = false;
            bool useFlipbookBlending = Properties.flipbook.GetValue(material);

            if (useLighting)
            {
                useNormalMap = Properties.normalMap.GetValue(material) != null;
            }
            bool useHeightMap = false;

            if (isPBS)
            {
                useHeightMap = Properties.heightMap.GetValue(material) != null;
            }
            bool useDetailNormalMap = false;

            if (isPBS)
            {
                useDetailNormalMap = Properties.detailNormalMap.GetValue(material) != null && isPBS;
            }
            bool useAnisotropicSpecular = false;

            if (useLighting)
            {
                useAnisotropicSpecular = Properties.specular.GetValue(material) != Specular.Anisotropic && isPBS;
            }

            // Build the list of expected vertex streams
            List <ParticleSystemVertexStream> streams = new List <ParticleSystemVertexStream>();
            List <string> streamList = new List <string>();

            streams.Add(ParticleSystemVertexStream.Position);
            streamList.Add(EditorHelper.EditorStyles.streamPositionText);

            if (useLighting)
            {
                streams.Add(ParticleSystemVertexStream.Normal);
                streamList.Add(EditorHelper.EditorStyles.streamNormalText);
                if (useNormalMap || useDetailNormalMap || useDetailNormalMap || useHeightMap)
                {
                    streams.Add(ParticleSystemVertexStream.Tangent);
                    streamList.Add(EditorHelper.EditorStyles.streamTangentText);
                }
            }

            streams.Add(ParticleSystemVertexStream.Color);
            streamList.Add(EditorHelper.EditorStyles.streamColorText);
            streams.Add(ParticleSystemVertexStream.UV);
            streamList.Add(EditorHelper.EditorStyles.streamUVText);

            if (useFlipbookBlending)
            {
                streams.Add(ParticleSystemVertexStream.UV2);
                streamList.Add(EditorHelper.EditorStyles.streamUV2Text);
                streams.Add(ParticleSystemVertexStream.AnimBlend);
                streamList.Add(EditorHelper.EditorStyles.streamAnimBlendText);
            }

            vertexStreamList = new ReorderableList(streamList, typeof(string), false, true, false, false);

            vertexStreamList.drawHeaderCallback = (Rect rect) => {
                EditorGUI.LabelField(rect, "Vertex Streams");
            };

            vertexStreamList.DoLayoutList();

            // Display a warning if any renderers have incorrect vertex streams
            string Warnings = "";
            List <ParticleSystemVertexStream> rendererStreams = new List <ParticleSystemVertexStream>();

            foreach (ParticleSystemRenderer renderer in renderers)
            {
                renderer.GetActiveVertexStreams(rendererStreams);
                if (!rendererStreams.SequenceEqual(streams))
                {
                    Warnings += "-" + renderer.name + "\n";
                }
            }

            if (!string.IsNullOrEmpty(Warnings))
            {
                EditorGUILayout.HelpBox(
                    "The following Particle System Renderers are using this material with incorrect Vertex Streams:\n" +
                    Warnings, MessageType.Error, true);
                // Set the streams on all systems using this material
                if (GUILayout.Button(EditorHelper.EditorStyles.streamApplyToAllSystemsText, EditorStyles.miniButton, GUILayout.ExpandWidth(true)))
                {
                    Undo.RecordObjects(renderers.Where(r => r != null).ToArray(), EditorHelper.EditorStyles.undoApplyCustomVertexStreams);

                    foreach (ParticleSystemRenderer renderer in renderers)
                    {
                        renderer.SetActiveVertexStreams(streams);
                    }
                }
            }
        }
Example #39
0
        public static async Task Execute(ISession session, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            // Refresh inventory so that the player stats are fresh
            await session.Inventory.RefreshCachedInventory();

            var playerStats = (await session.Inventory.GetPlayerStats())?.FirstOrDefault();

            if (playerStats == null)
            {
                return;
            }

            var kmWalked = playerStats.KmWalked;

            var incubators = (await session.Inventory.GetEggIncubators())
                             .Where(x => x.UsesRemaining > 0 || x.ItemId == ItemId.ItemIncubatorBasicUnlimited)
                             .OrderByDescending(x => x.ItemId == ItemId.ItemIncubatorBasicUnlimited)
                             .ToList();

            var unusedEggs = (await session.Inventory.GetEggs())
                             .Where(x => string.IsNullOrEmpty(x.EggIncubatorId))
                             .OrderBy(x => x.EggKmWalkedTarget - x.EggKmWalkedStart)
                             .ToList();

            var rememberedIncubatorsFilePath = Path.Combine(session.LogicSettings.ProfilePath, "temp", "incubators.json");
            var rememberedIncubators         = GetRememberedIncubators(rememberedIncubatorsFilePath);
            var pokemons = (await session.Inventory.GetPokemons()).ToList();

            // Check if eggs in remembered incubator usages have since hatched
            // (instead of calling session.Client.Inventory.GetHatchedEgg(), which doesn't seem to work properly)
            foreach (var incubator in rememberedIncubators)
            {
                var hatched = pokemons.FirstOrDefault(x => !x.IsEgg && x.Id == incubator.PokemonId);
                if (hatched == null)
                {
                    continue;
                }

                var pokemonSettings = await session.Inventory.GetPokemonSettings();

                var pokemonFamilies = await session.Inventory.GetPokemonFamilies();

                var setting =
                    pokemonSettings.FirstOrDefault(q => q.PokemonId == hatched?.PokemonId);
                var family = pokemonFamilies.FirstOrDefault(q => setting != null && q.FamilyId == setting.FamilyId);
                if (family != null && setting != null)
                {
                    session.EventDispatcher.Send(new EggHatchedEvent
                    {
                        Id            = hatched.Id,
                        PokemonId     = hatched.PokemonId,
                        Level         = PokemonInfo.GetLevel(hatched),
                        Cp            = hatched.Cp,
                        MaxCp         = (int)PokemonInfo.GetMaxCpAtTrainerLevel(hatched, session.Runtime.CurrentLevel),
                        Perfection    = Math.Round(hatched.CalculatePokemonPerfection(), 2),
                        Move1         = hatched.Move1,
                        Move2         = hatched.Move2,
                        Candy         = family.Candy_,
                        Family        = family.FamilyId,
                        Type1         = setting.Type,
                        Type2         = setting.Type2,
                        Stats         = setting.Stats,
                        Stamina       = hatched.Stamina,
                        MaxStamina    = hatched.StaminaMax,
                        PossibleCp    = (int)PokemonInfo.GetMaxCpAtTrainerLevel(hatched, 40),
                        CandyToEvolve = setting.CandyToEvolve
                    });
                }
            }

            var newRememberedIncubators = new List <IncubatorUsage>();

            foreach (var incubator in incubators.Where(x => x.ItemId == ItemId.ItemIncubatorBasicUnlimited || !session.LogicSettings.UseOnlyUnlimitedIncubator))
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (incubator.PokemonId == 0)
                {
                    // Unlimited incubators prefer short eggs, limited incubators prefer long eggs
                    var egg = (incubator.ItemId == ItemId.ItemIncubatorBasicUnlimited && !session.LogicSettings.AlwaysPrefferLongDistanceEgg)
                        ? unusedEggs.FirstOrDefault()
                        : unusedEggs.LastOrDefault();

                    if (egg == null)
                    {
                        continue;
                    }

                    var response = await session.Client.Inventory.UseItemEggIncubator(incubator.Id, egg.Id);

                    unusedEggs.Remove(egg);

                    newRememberedIncubators.Add(new IncubatorUsage {
                        IncubatorId = incubator.Id, PokemonId = egg.Id
                    });

                    session.EventDispatcher.Send(new EggIncubatorStatusEvent
                    {
                        IncubatorId = incubator.Id,
                        WasAddedNow = true,
                        PokemonId   = egg.Id,
                        KmToWalk    = egg.EggKmWalkedTarget,
                        KmRemaining = response.EggIncubator.TargetKmWalked - kmWalked
                    });
                }
                else
                {
                    newRememberedIncubators.Add(new IncubatorUsage
                    {
                        IncubatorId = incubator.Id,
                        PokemonId   = incubator.PokemonId
                    });

                    session.EventDispatcher.Send(new EggIncubatorStatusEvent
                    {
                        IncubatorId = incubator.Id,
                        PokemonId   = incubator.PokemonId,
                        KmToWalk    = incubator.TargetKmWalked - incubator.StartKmWalked,
                        KmRemaining = incubator.TargetKmWalked - kmWalked
                    });
                }
            }

            if (!newRememberedIncubators.SequenceEqual(rememberedIncubators))
            {
                SaveRememberedIncubators(newRememberedIncubators, rememberedIncubatorsFilePath);
            }
        }
Example #40
0
        private static void Game_OnIngameUpdate(EventArgs args)
        {
            if (!Game.IsInGame || Game.IsPaused)
            {
                return;
            }

            // auto farm units
            for (var i = AutoFarmUnits.Count - 1; i >= 0; --i)
            {
                var entry = AutoFarmUnits[i];
                if (!entry.IsValid)
                {
                    entry.RemoveEffects();
                    AutoFarmUnits.RemoveAt(i);
                    continue;
                }
                if (!entry.LastHit() && FarmMenu.IsMovingActive)
                {
                    MoveToMouse(entry);
                }
            }

            // currently pressed
            if (!_farmPressed)
            {
                return;
            }

            var player = ObjectManager.LocalPlayer;

            if (player == null)
            {
                return;
            }

            var selection = player.Selection.Where(x => x is Unit).Cast <Unit>().ToList();

            if (!selection.Any())
            {
                return;
            }

            if (!_oldSelection.SequenceEqual(selection))
            {
                foreach (var unit in _oldSelection)
                {
                    FarmUnit farmer;
                    if (FarmUnits.TryGetValue(unit, out farmer))
                    {
                        farmer.RemoveEffects();
                    }
                }
                foreach (var unit in selection)
                {
                    FarmUnit farmer;
                    if (FarmUnits.TryGetValue(unit, out farmer))
                    {
                        farmer.AddEffects();
                    }
                }
                _oldSelection = selection;
            }

            foreach (var unit in selection)
            {
                if (!unit.IsAlive || !unit.IsControllable)
                {
                    continue;
                }

                FarmUnit farmer;
                if (!FarmUnits.TryGetValue(unit, out farmer))
                {
                    farmer = CreateFarmer(unit);
                    FarmUnits.Add(unit, farmer);

                    farmer.AddEffects();
                }
                AutoFarmUnits.Remove(farmer);
                if (!farmer.LastHit() && FarmMenu.IsMovingActive)
                {
                    MoveToMouse(farmer);
                }
            }
        }
Example #41
0
        public static void Run(TestHelper helper)
        {
            Communicator?communicator = helper.Communicator;

            TestHelper.Assert(communicator != null);
            bool       ice1      = helper.Protocol == Protocol.Ice1;
            string     transport = helper.Transport;
            TextWriter output    = helper.Output;

            output.Write("testing proxy endpoint information... ");
            output.Flush();
            {
                string ice1Prx = @"test -t:tcp -h tcphost -p 10000 -t 1200 -z
                    --sourceAddress 10.10.10.10: udp -h udphost -p 10001 --interface eth0 --ttl 5
                    --sourceAddress 10.10.10.10:opaque -e 1.8 -t 100 -v ABCD";

                string ice2Prx = "ice+tcp://tcphost:10000/test?source-address=10.10.10.10" +
                                 "&alt-endpoint=ice+universal://unihost:10000?transport=100$option=ABCD";

                var p1 = IObjectPrx.Parse(ice1 ? ice1Prx : ice2Prx, communicator);

                IReadOnlyList <Endpoint> endps = p1.Endpoints;

                Endpoint tcpEndpoint = endps[0];
                TestHelper.Assert(tcpEndpoint.Transport == Transport.TCP && !tcpEndpoint.IsSecure);
                TestHelper.Assert(tcpEndpoint.Host == "tcphost");
                TestHelper.Assert(tcpEndpoint.Port == 10000);
                TestHelper.Assert(tcpEndpoint["source-address"] == "10.10.10.10");
                if (ice1)
                {
                    TestHelper.Assert(tcpEndpoint["timeout"] == "1200");
                    TestHelper.Assert(tcpEndpoint["compress"] == "true");
                }
                TestHelper.Assert(!tcpEndpoint.IsDatagram);

                if (ice1)
                {
                    Endpoint udpEndpoint = endps[1];
                    TestHelper.Assert(udpEndpoint.Host == "udphost");
                    TestHelper.Assert(udpEndpoint.Port == 10001);
                    TestHelper.Assert(udpEndpoint["interface"] == "eth0");
                    TestHelper.Assert(udpEndpoint["ttl"] == "5");
                    TestHelper.Assert(udpEndpoint["source-address"] == "10.10.10.10");
                    TestHelper.Assert(udpEndpoint["timeout"] == null);
                    TestHelper.Assert(udpEndpoint["compress"] == null);
                    TestHelper.Assert(!udpEndpoint.IsSecure);
                    TestHelper.Assert(udpEndpoint.IsDatagram);
                    TestHelper.Assert(udpEndpoint.Transport == Transport.UDP);

                    Endpoint opaqueEndpoint = endps[2];
                    TestHelper.Assert(opaqueEndpoint["value"] == "ABCD");
                    TestHelper.Assert(opaqueEndpoint["value-encoding"] == "1.8");
                }
                else
                {
                    Endpoint universalEndpoint = endps[1];
                    TestHelper.Assert(universalEndpoint.Transport == (Transport)100);
                    TestHelper.Assert(universalEndpoint["option"] == "ABCD");
                }
            }
            output.WriteLine("ok");

            ObjectAdapter adapter;

            output.Write("test object adapter endpoint information... ");
            output.Flush();
            {
                communicator.SetProperty("TestAdapter.Endpoints", "tcp -h \"" + helper.Host +
                                         "\" -t 15000:udp -h \"" + helper.Host + "\"");
                adapter = communicator.CreateObjectAdapter("TestAdapter");

                IReadOnlyList <Endpoint> endpoints = adapter.GetEndpoints();
                TestHelper.Assert(endpoints.Count == 2);
                IReadOnlyList <Endpoint> publishedEndpoints = adapter.PublishedEndpoints;
                TestHelper.Assert(endpoints.SequenceEqual(publishedEndpoints));

                Endpoint tcpEndpoint = endpoints[0];
                TestHelper.Assert(tcpEndpoint != null);
                TestHelper.Assert(tcpEndpoint.Transport == Transport.TCP ||
                                  tcpEndpoint.Transport == Transport.SSL ||
                                  tcpEndpoint.Transport == Transport.WS ||
                                  tcpEndpoint.Transport == Transport.WSS);

                TestHelper.Assert(tcpEndpoint.Host == helper.Host);
                TestHelper.Assert(tcpEndpoint.Port > 0);
                TestHelper.Assert(tcpEndpoint["timeout"] is string value && int.Parse(value) == 15000);

                Endpoint udpEndpoint = endpoints[1];
                TestHelper.Assert(udpEndpoint.Host == helper.Host);
                TestHelper.Assert(udpEndpoint.IsDatagram);
                TestHelper.Assert(udpEndpoint.Port > 0);

                endpoints = new List <Endpoint> {
                    endpoints[0]
                };

                adapter.SetPublishedEndpoints(endpoints);
                publishedEndpoints = adapter.PublishedEndpoints;
                TestHelper.Assert(endpoints.SequenceEqual(publishedEndpoints));

                adapter.Dispose();

                int port = helper.BasePort + 1;
                communicator.SetProperty("TestAdapter.Endpoints",
                                         ice1 ? $"{transport} -h 0.0.0.0 -p {port}" : $"ice+{transport}://0.0.0.0:{port}");
                communicator.SetProperty("TestAdapter.PublishedEndpoints", helper.GetTestEndpoint(1));
                adapter = communicator.CreateObjectAdapter("TestAdapter");

                endpoints = adapter.GetEndpoints();
                TestHelper.Assert(endpoints.Count >= 1);
                publishedEndpoints = adapter.PublishedEndpoints;
                TestHelper.Assert(publishedEndpoints.Count == 1);

                foreach (Endpoint endpoint in endpoints)
                {
                    TestHelper.Assert(endpoint.Port == port);
                }

                tcpEndpoint = publishedEndpoints[0];
                TestHelper.Assert(tcpEndpoint.Host == "127.0.0.1");
                TestHelper.Assert(tcpEndpoint.Port == port);

                adapter.Dispose();
            }
            output.WriteLine("ok");

            int endpointPort = helper.BasePort + 0;

            ITestIntfPrx testIntf;

            if (ice1)
            {
                testIntf = ITestIntfPrx.Parse("test:" + helper.GetTestEndpoint(0) + ":" +
                                              helper.GetTestEndpoint(0, "udp"), communicator);
            }
            else
            {
                testIntf = ITestIntfPrx.Parse(helper.GetTestProxy("test", 0), communicator);
            }

            string defaultHost = helper.Host;

            output.Write("test connection endpoint information... ");
            output.Flush();
            {
                Endpoint tcpEndpoint = testIntf.GetConnection() !.Endpoint;
                TestHelper.Assert(tcpEndpoint.Port == endpointPort);

                TestHelper.Assert(tcpEndpoint["compress"] == null);
                TestHelper.Assert(tcpEndpoint.Host == defaultHost);

                Dictionary <string, string> ctx = testIntf.GetEndpointInfoAsContext();
                TestHelper.Assert(ctx["host"] == tcpEndpoint.Host);
                TestHelper.Assert(ctx["compress"] == "false");
                int port = int.Parse(ctx["port"]);
                TestHelper.Assert(port > 0);

                if (ice1)
                {
                    Endpoint udpEndpoint =
                        testIntf.Clone(invocationMode: InvocationMode.Datagram).GetConnection() !.Endpoint;
                    TestHelper.Assert(udpEndpoint.Port == endpointPort);
                    TestHelper.Assert(udpEndpoint.Host == defaultHost);
                }
            }
            output.WriteLine("ok");

            output.Write("testing connection information... ");
            output.Flush();
            {
                var connection = (IPConnection)testIntf.GetConnection() !;

                TestHelper.Assert(!connection.IsIncoming);
                TestHelper.Assert(connection.Adapter == null);
                TestHelper.Assert(connection.RemoteEndpoint !.Port == endpointPort);
                TestHelper.Assert(connection.LocalEndpoint !.Port > 0);
                if (defaultHost.Equals("127.0.0.1"))
                {
                    TestHelper.Assert(connection.LocalEndpoint !.Address.ToString() == defaultHost);
                    TestHelper.Assert(connection.RemoteEndpoint !.Address.ToString() == defaultHost);
                }

                if (connection.Endpoint.IsSecure)
                {
                    TestHelper.Assert(((TcpConnection)connection).IsEncrypted);
                    // WSS tests run client authentication disabled for compatibility with web browser testing.
                    if (connection.Endpoint.Transport == Transport.SSL)
                    {
                        TestHelper.Assert(((TcpConnection)connection).IsMutuallyAuthenticated);
                        TestHelper.Assert(((TcpConnection)connection).LocalCertificate != null);
                    }
                    else
                    {
                        TestHelper.Assert(!((TcpConnection)connection).IsMutuallyAuthenticated);
                        TestHelper.Assert(((TcpConnection)connection).LocalCertificate == null);
                    }
                    TestHelper.Assert(((TcpConnection)connection).IsSigned);

                    TestHelper.Assert(((TcpConnection)connection).RemoteCertificate != null);
                    TestHelper.Assert(((TcpConnection)connection).NegotiatedApplicationProtocol != null);
                    TestHelper.Assert(((TcpConnection)connection).NegotiatedCipherSuite != null);
                    TestHelper.Assert(((TcpConnection)connection).SslProtocol == SslProtocols.Tls12 ||
                                      ((TcpConnection)connection).SslProtocol == SslProtocols.Tls13);
                }
                else
                {
                    TestHelper.Assert(!((TcpConnection)connection).IsEncrypted);
                    TestHelper.Assert(!((TcpConnection)connection).IsMutuallyAuthenticated);
                    TestHelper.Assert(!((TcpConnection)connection).IsSigned);
                    TestHelper.Assert(((TcpConnection)connection).LocalCertificate == null);
                    TestHelper.Assert(((TcpConnection)connection).RemoteCertificate == null);
                    TestHelper.Assert(((TcpConnection)connection).NegotiatedApplicationProtocol == null);
                    TestHelper.Assert(((TcpConnection)connection).NegotiatedCipherSuite == null);
                    TestHelper.Assert(((TcpConnection)connection).SslProtocol == null);
                }

                Dictionary <string, string> ctx = testIntf.GetConnectionInfoAsContext();
                TestHelper.Assert(ctx["incoming"].Equals("true"));
                TestHelper.Assert(ctx["adapterName"].Equals("TestAdapter"));
                TestHelper.Assert(ctx["remoteAddress"].Equals(connection.LocalEndpoint !.Address.ToString()));
                TestHelper.Assert(ctx["localAddress"].Equals(connection.RemoteEndpoint !.Address.ToString()));
                TestHelper.Assert(ctx["remotePort"].Equals(connection.LocalEndpoint !.Port.ToString()));
                TestHelper.Assert(ctx["localPort"].Equals(connection.RemoteEndpoint !.Port.ToString()));

                if ((connection as WSConnection)?.Headers is IReadOnlyDictionary <string, string> headers)
                {
                    TestHelper.Assert(headers["Upgrade"].Equals("websocket"));
                    TestHelper.Assert(headers["Connection"].Equals("Upgrade"));
                    TestHelper.Assert(headers["Sec-WebSocket-Protocol"].Equals("ice.zeroc.com"));
                    TestHelper.Assert(headers["Sec-WebSocket-Accept"] != null);

                    TestHelper.Assert(ctx["ws.Upgrade"].Equals("websocket"));
                    TestHelper.Assert(ctx["ws.Connection"].Equals("Upgrade"));
                    TestHelper.Assert(ctx["ws.Sec-WebSocket-Protocol"].Equals("ice.zeroc.com"));
                    TestHelper.Assert(ctx["ws.Sec-WebSocket-Version"].Equals("13"));
                    TestHelper.Assert(ctx["ws.Sec-WebSocket-Key"] != null);
                }

                if (ice1)
                {
                    connection = (IPConnection)testIntf.Clone(invocationMode: InvocationMode.Datagram).GetConnection() !;

                    var udpConnection = connection as UdpConnection;
                    TestHelper.Assert(udpConnection != null);
                    TestHelper.Assert(!udpConnection.IsIncoming);
                    TestHelper.Assert(udpConnection.Adapter == null);
                    TestHelper.Assert(udpConnection.LocalEndpoint?.Port > 0);
                    TestHelper.Assert(udpConnection.RemoteEndpoint?.Port == endpointPort);

                    if (defaultHost == "127.0.0.1")
                    {
                        TestHelper.Assert(udpConnection.RemoteEndpoint.Address.ToString().Equals(defaultHost));
                        TestHelper.Assert(udpConnection.LocalEndpoint.Address.ToString().Equals(defaultHost));
                    }
                }
            }
            output.WriteLine("ok");

            testIntf.Shutdown();

            communicator.ShutdownAsync();
            communicator.WaitForShutdownAsync();
        }
        public void GenerateMesh(Mesh mesh, Track track)
        {
            //This function is optimized.
            //There are some places where simpler, more fluent language constructs are avoided in the interest of performance.

            if (railMesh == null && capMesh == null && !tieMesh)
            {
                //no results case
                mesh.Clear();
                return;
            }


            //build the rails (rails are built by bridging each set of points we render)
            List <Vector3> allVerts   = new List <Vector3>();
            List <Vector3> allNormals = new List <Vector3>();
            List <Vector2> allUVs     = new List <Vector2>();
            List <int>     allTris    = new List <int>();

            if (railMesh != null)
            {
                //Rail mesh should consist of a straight piece of track along z from -.5 to .5.
                int vertOffset = allVerts.Count;

                SimpleTransform lastStep = null;
                var             steps    = GetSteps(track);

                var vertCount = (steps.Length - 1) * railMesh.verts.Count;
                var triCount  = (steps.Length - 1) * railMesh.tris.Count;
                allVerts.EnsureSpace(vertCount);
                allNormals.EnsureSpace(vertCount);
                allUVs.EnsureSpace(vertCount);
                allTris.EnsureSpace(triCount);

                foreach (float step in steps)
                {
                    //Note: we could use Curve.GetIntervals, but it's better to have more steps along curves
                    //which tends to happen (a little bit) automatically if we use the mathematical fraction.
                    SimpleTransform curStep = track.Curve.GetPointAt(step);

                    if (lastStep != null)
                    {
                        //bridge between two steps
                        int pInitial = allVerts.Count;
                        int j        = 0;
                        foreach (Vertex vert in railMesh.verts)
                        {
                            Vector3 pos = vert.pos;
                            if (pos.z < 0)
                            {
                                //this vert falls on the prev side
                                pos.z += .5f;                        //the model has data one unit wide, offset that
                                Vector3 p = lastStep * pos;
                                allVerts.Add(p);
                                allNormals.Add(lastStep.rotation * vert.normal);
                                allUVs.Add(vert.uv);
                            }
                            else
                            {
                                //this vert falls on the next side
                                pos.z -= .5f;                        //the model has data one unit wide, offset that
                                Vector3 p = curStep * pos;
                                allVerts.Add(p);
                                allNormals.Add(curStep.rotation * vert.normal);
                                allUVs.Add(vert.uv);
                            }

                            j++;
                        }

                        foreach (int idx in railMesh.tris)
                        {
                            allTris.Add(idx + pInitial + vertOffset);
                        }
                    }

                    lastStep = curStep;
                }
            }

            if (capMesh != null && (!track.NextTrack || !track.PrevTrack || track.forceEndCaps))
            {
                //Cap mesh should consist of faces in +z or -z
                //No faces may cross 0

                List <Vector3> verts   = new List <Vector3>();
                List <Vector3> normals = new List <Vector3>();
                List <Vector2> uvs     = new List <Vector2>();
                List <int>     tris    = new List <int>();

                SimpleTransform firstStep = new SimpleTransform(), lastStep = track.Curve.GetPointAt(1);

                var caps     = (track.PrevTrack ? 0 : 1) + (track.NextTrack ? 0 : 1);
                //We assume that the start and end caps have the same number of verts/tris, if not this will run a little slower or use more memory.
                var vertCount = caps * capMesh.verts.Count / 2;
                var triCount = caps * capMesh.tris.Count / 2;
                allVerts.EnsureSpace(vertCount);
                allNormals.EnsureSpace(vertCount);
                allUVs.EnsureSpace(vertCount);
                allTris.EnsureSpace(triCount);

                for (int triIdx = 0; triIdx < capMesh.tris.Count; triIdx += 3)
                {
                    //grab the first vert in the face to see what side the face is on
                    Vector3 pos0 = capMesh.verts[capMesh.tris[triIdx + 0]].pos;

                    float           offset;  //how much to offset Z to zero out the tri
                    SimpleTransform trans;

                    if (pos0.z < 0)
                    {
                        //this tri falls on the start side
                        if (track.PrevTrack && !track.forceEndCaps)
                        {
                            continue;                                                         //can't see this cap
                        }
                        offset = .5f;
                        trans  = firstStep;
                    }
                    else
                    {
                        //this tri falls on the end side
                        if (track.NextTrack && !track.forceEndCaps)
                        {
                            continue;                                                         //can't see this cap
                        }
                        offset = -.5f;
                        trans  = lastStep;
                    }

                    //Copy each vert from this face
                    for (int i = 0; i < 3; ++i)
                    {
                        int idx = capMesh.tris[triIdx + i];

                        Vertex  v    = capMesh.verts[idx];
                        Vector3 vPos = v.pos;
                        vPos.z += offset;

                        tris.Add(verts.Count);
                        verts.Add(trans * vPos);
                        normals.Add(trans.rotation * v.normal);
                        uvs.Add(v.uv);
                    }
                }

                //Add intermediate results to the final mesh
                int vertOffset = allVerts.Count;
                allVerts.AddRange(verts);
                allNormals.AddRange(normals);
                allUVs.AddRange(uvs);
                foreach (var vertIdx in tris)
                {
                    allTris.Add(vertIdx + vertOffset);
                }
            }

            if (tieMesh)
            {
                //Tie mesh should consist of some polygons we can throw in at intervals to tie the track together.

                var trackLength = track.Length;

                var numTies = Mathf.Floor(trackLength / track.tieInterval);
                // Give the number of ties a reasonable limit.
                if (track.tieInterval <= 0)
                {
                    numTies = 0;
                }
                if (numTies > MaxTiesCount)
                {
                    numTies = MaxTiesCount;
                }

                // Space ties evenly along the length (results in a slightly higher tie interval than requested)
                var effectiveInterval = trackLength / numTies;

                var offset = .5f * effectiveInterval;

                var tieVerts   = tieMesh.vertices;
                var tieNormals = tieMesh.normals;
                var uvTris     = tieMesh.uv;
                var tieTris    = tieMesh.triangles;

                var vertCount = (int)numTies * tieVerts.Length;
                var triCount  = (int)numTies * tieTris.Length;
                allVerts.EnsureSpace(vertCount);
                allNormals.EnsureSpace(vertCount);
                allUVs.EnsureSpace(vertCount);
                allTris.EnsureSpace(triCount);

                var intervalIter = track.Curve.GetIntervals(offset, effectiveInterval).GetEnumerator();
                for (int i = 0; i < numTies; i++)
                {
                    if (!intervalIter.MoveNext())
                    {
                        Debug.LogWarning("Tie count didn't match up", track);
                        break;
                    }

                    var tiePos   = intervalIter.Current;
                    int pInitial = allVerts.Count;

                    //allVerts.AddRange(from vPos in tieMesh.vertices select tiePos * vPos);
                    for (int j = 0; j < tieVerts.Length; ++j)
                    {
                        allVerts.Add(tiePos * tieVerts[j]);
                    }

                    //allNormals.AddRange(from normal in tieMesh.normals select tiePos.rotation * normal);
                    for (int j = 0; j < tieNormals.Length; ++j)
                    {
                        allNormals.Add(tiePos.rotation * tieNormals[j]);
                    }

                    //allUVs.AddRange(tieMesh.uv);
                    for (int j = 0; j < uvTris.Length; ++j)
                    {
                        allUVs.Add(uvTris[j]);
                    }

                    //allTris.AddRange(from idx in tieMesh.triangles select idx + pInitial);
                    for (int j = 0; j < tieTris.Length; ++j)
                    {
                        allTris.Add(pInitial + tieTris[j]);
                    }
                }
            }

                #if UNITY_EDITOR
            if (!Application.isPlaying)
            {
                //If the mesh hasn't changed, don't modify it while editing. This will avoid marking the scene as changed when it hasn't.
                //During play mode, don't worry about it. It's stupid to burn CPU to avoid a no-op at this point.

                if (
                    allVerts.SequenceEqual(mesh.vertices) &&
                    allNormals.SequenceEqual(mesh.normals) &&
                    allUVs.SequenceEqual(mesh.uv) &&
                    allTris.SequenceEqual(mesh.triangles)
                    )
                {
                    //turns out, we didn't need to do anything after all
                    return;
                }
            }
                #endif

            mesh.Clear();
            mesh.vertices  = allVerts.ToArray();
            mesh.normals   = allNormals.ToArray();
            mesh.uv        = allUVs.ToArray();
            mesh.triangles = allTris.ToArray();
        }
Example #43
0
 public bool Equals(List <string> x, List <string> y)
 {
     return(x.SequenceEqual(y));     // Use this if { "a", "b" } != { "a", "b" }
     //return x.Count == y.Count && x.Count == x.Intersect(y).Count();  // Use this if { "a", "b" } == { "a", "b" }
 }
 public bool Equals(List <T> x, List <T> y)
 {
     return(x.SequenceEqual(y));
 }
Example #45
0
 public bool Equals(SpriteAnimationClipMaterials other)
 {
     return(Value?.SequenceEqual(other.Value) ?? false);
 }
 /// <inheritdoc />
 public override bool Equals(object obj)
 {
     return(obj is GridPolygon other && points.SequenceEqual(other.GetPoints()));
 }