private List<DynamicSoundGroup> ScanForGroups() {
        var groups = new List<DynamicSoundGroup>();

        for (var i = 0; i < _creator.transform.childCount; i++) {
            var aChild = _creator.transform.GetChild(i);

            var grp = aChild.GetComponent<DynamicSoundGroup>();
            if (grp == null) {
                continue;
            }

            grp.groupVariations = VariationsForGroup(aChild.transform);

            groups.Add(grp);
        }

        if (_creator.groupByBus) {
            groups.Sort(delegate(DynamicSoundGroup g1, DynamicSoundGroup g2) {
                // ReSharper disable once ConvertIfStatementToReturnStatement
                if (g1.busIndex == g2.busIndex) {
                    return g1.name.CompareTo(g2.name);
                }

                return g1.busIndex.CompareTo(g2.busIndex);
            });
        } else {
            groups.Sort(delegate(DynamicSoundGroup g1, DynamicSoundGroup g2) {
                return g1.name.CompareTo(g2.name);
            });
        }

        return groups;
    }
Example #2
0
 public KdTree(List<Point3d> Points)
 {
     this.points = new List<Point3d>();
     double x1, x2, y1, y2, z1, z2;
     Points.Sort(CompareDinos_X);
     x1 = Points[0].X; x2 = Points[Points.Count - 1].X;
     Points.Sort(CompareDinos_Y);
     y1 = Points[0].Y; y2 = Points[Points.Count - 1].Y;
     Points.Sort(CompareDinos_Z);
     z1 = Points[0].Z; z2 = Points[Points.Count - 1].Z;
     if ((x2 - x1) > (y2 - y1)) { side = 1; } else { side = 2; }
     for (int i = 0; i < Points.Count; i++)
     {
         Point3d p = Points[i];
         if (p.X != x1 && p.X != x2 && p.Y != y1 && p.Y != y2)
         {
             this.points.Add(p);
         }
     }
     Point3d p1, p2, p3, p4;
     p1 = new Point3d(x1, y1, 0);
     p2 = new Point3d(x2, y1, 0);
     p3 = new Point3d(x2, y2, 0);
     p4 = new Point3d(x1, y2, 0);
     this.Counter = new Polyline();
     this.Counter.Add(p1);
     this.Counter.Add(p2);
     this.Counter.Add(p3);
     this.Counter.Add(p4);
     this.Counter.Add(p1);
 }
Example #3
0
        void SortNumbers(List<int> numbers)
        {
            numbers.Sort((x, y) => y - x);

            // vs..
            numbers.Sort(delegate(int x, int y) { return y - x; });
        }
Example #4
0
        static void Main(string[] args)
        {
            string setosa = "Iris-setosa";
            var reader = new StreamReader(File.OpenRead(@"E:\Projects\C#\Console\OneRule\OneRule\Resources\iris.data"));
            List<Node> listIrisData = new List<Node>();

            while(!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                var values = line.Split(',');

                Node node = new Node();
                node.width1 = Convert.ToDouble(values[0]);
                node.height1 = Convert.ToDouble(values[1]);
                node.width2 = Convert.ToDouble(values[2]);
                node.height2 = Convert.ToDouble(values[3]);
                node.class_ = values[4];

                listIrisData.Add(node);
                listIrisData.Sort((s1,s2)=> s1.height1.CompareTo(s2.height1));
                listIrisData.Sort((s3, s4) => s3.height2.CompareTo(s4.height2));

            }

            foreach (Node value in listIrisData)
            {
                Console.WriteLine(value.toString());
                if (value.Equals(setosa))
                    Console.WriteLine("Setosa;;;;;;;;;;;;");
            }

            Console.WriteLine();
            Console.ReadKey();
        }
Example #5
0
        // Imprime um relatório com a carga dos nós
        public void printNodesLoad()
        {
            // Imprimir relatório de cargas.
            nodeList.Sort ();
            List<Node> weirdNodes = new List<Node> ();
            List<Node> overloadedNodes = new List<Node> ();

            // Todos os nós.
            Console.WriteLine ("### LOAD REPORT ###");
            foreach (Node n in nodeList)
            {
                if (n.State.Equals ("DOWN*"))
                    continue;
                Console.WriteLine ("{0}:{1:F2}", n.Hostname, n.Load);
                if (n.isOverloaded ())
                    overloadedNodes.Add (n);
                else if (!n.State.Equals ("IDLE") && n.Load < 2.00)
                    weirdNodes.Add (n);
            }

            // Nós sobrecarregados.
            Console.WriteLine ("### OVERLOADED NODES ###");
            overloadedNodes.Sort ();
            foreach (Node n in overloadedNodes) {
                Console.WriteLine ("{0}:{1:F2}", n.Hostname, n.Load);
            }

            // Nós estranhos.
            Console.WriteLine ("### WEIRD NODES ###");
            overloadedNodes.Sort ();
            foreach (Node n in weirdNodes) {
                Console.WriteLine ("{0}:{1:F2}", n.Hostname, n.Load);
            }
        }
Example #6
0
        static void Main()
        {
            var graham = new Racer(7, "Graham", "Hill", "UK", 14);
            var emerson = new Racer(13, "Emerson", "Fittipaldi", "Brazil", 14);
            var mario = new Racer(16, "Mario", "Andretti", "USA", 12);

            var racers = new List<Racer>(20) { graham, emerson, mario };

            racers.Add(new Racer(24, "Michael", "Schumacher", "Germany", 91));
            racers.Add(new Racer(27, "Mika", "Hakkinen", "Finland", 20));
            racers.Add(new Racer(17, "Jack", "ss", "Austria", 22));

            racers.AddRange(new Racer[] {
               new Racer(14, "Niki", "Lauda", "Austria", 25),
               new Racer(21, "Alain", "Prost", "France", 51)});

            var racers2 = new List<Racer>(new Racer[] {
               new Racer(12, "Jochen", "Rindt", "Austria", 6),
               new Racer(14, "Jack", "dd", "Austria", 63),
               new Racer(22, "Ayrton", "Senna", "Brazil", 41) });

            //这个比较实用
            racers.ForEach(r=>Console.WriteLine("{0:A}",r));
            racers.ForEach(r => Console.WriteLine("{0}", r.FirstName));
            racers.ForEach(ActionHandler);
            //排序
            Console.WriteLine("-----------Order---------");
            racers.Sort(new RacerComparer(CompareType.Country));
            racers.ForEach(ActionHandler);
            Console.WriteLine("-----------OverLoad Order---------");
            racers.Sort((r1, r2) => r2.Wins.CompareTo(r1.Wins));
            racers.ForEach(r=>Console.WriteLine("{0}",r.Wins));
            Console.ReadKey();

        }
        public void SetItems(List<SpotObject> spots)
        {
            // If items have something, clear.
            this.Items.Clear();

            // Sorting spots
            spots.Sort((s1, s2) =>
            {
                return s1.SpotName.CompareTo(s2.SpotName);
            });
            spots.Sort((s1, s2) =>
            {
                return s1.SpotDistance.CompareTo(s2.SpotDistance);
            });

            // Convert jarray spots to spot view items and set to view model
            foreach (SpotObject spot in spots)
            {
                // Set new spot view item
                SpotViewItem spotViewItem = new SpotViewItem(spot);

                if (spot.IsPrivate)
                    spotViewItem.IsPrivateImage = FileObjectViewModel.IS_PRIVATE_IMAGE_URI;
                else
                    spotViewItem.IsPrivateImage = FileObjectViewModel.TRANSPARENT_IMAGE_URI;

                this.Items.Add(spotViewItem);
            }
        }
Example #8
0
        static void Main(string[] args)
        {
            List<Duck> ducks = new List<Duck>() {
                new Duck() { Kind = KindOfDuck.Mallard, Size = 17 },
                new Duck() { Kind = KindOfDuck.Muscovy, Size = 18 },
                new Duck() { Kind = KindOfDuck.Decoy, Size = 14 },
                new Duck() { Kind = KindOfDuck.Muscovy, Size = 11 },
                new Duck() { Kind = KindOfDuck.Mallard, Size = 14 },
                new Duck() { Kind = KindOfDuck.Decoy, Size = 13 },
            };

            DuckComparerBySize sizeComparer = new DuckComparerBySize();
            ducks.Sort(sizeComparer);
            PrintDucks(ducks);

            DuckComparerByKind kindComparer = new DuckComparerByKind();
            ducks.Sort(kindComparer);
            PrintDucks(ducks);

            DuckComparer comparer = new DuckComparer();

            comparer.SortBy = SortCriteria.KindThenSize;
            ducks.Sort(comparer);
            PrintDucks(ducks);

            comparer.SortBy = SortCriteria.SizeThenKind;
            ducks.Sort(comparer);
            PrintDucks(ducks);

            // This keeps the output from disappearing before you can read it
            Console.ReadKey();

        }
Example #9
0
        /// <summary>
        /// 取授权登录URL
        /// </summary>
        /// <returns>登录URL</returns>
        public string GetAuthUrl() {
            List<UrlParameter> param = new List<UrlParameter>();
            param.Add(new UrlParameter("oauth_callback", config.RedirectUrl.UrlEncode2()));
            param.Add(new UrlParameter("oauth_consumer_key", config.AppKey));
            param.Add(new UrlParameter("oauth_nonce", OAuthCommon.GetGUID32()));
            param.Add(new UrlParameter("oauth_signature_method", "HMAC-SHA1"));
            param.Add(new UrlParameter("oauth_timestamp", OAuthCommon.GetTimestamp()));
            param.Add(new UrlParameter("oauth_version", "1.0"));
            param.Sort(new UrlParameterCompre());

            StringBuilder sbSign = new StringBuilder().Append("GET&")
                .Append(request_token.UrlEncode2())
                .Append("&")
                .Append(OAuthCommon.GetUrlParameter(param).UrlEncode2());

            param.Add(new UrlParameter("oauth_signature", OAuthCommon.GetHMACSHA1(config.AppSecret, "", sbSign.ToString()).UrlEncode2()));
            param.Sort(new UrlParameterCompre());

            string data = HttpHelper.SendGet(new StringBuilder().Append(request_token).Append("?").Append(OAuthCommon.GetUrlParameter(param)).ToString());

            string token = data.GetMatchingValues("oauth_token=(.+?)&", "oauth_token=", "&").FirstOrDefault() ?? "";
            string tokenSecret = data.GetMatchingValues("oauth_token_secret=(.+?)&", "oauth_token_secret=", "&").FirstOrDefault() ?? "";
            Session2.Set("oauth_token", token);
            Session2.Set("oauth_token_secret", tokenSecret);
            return authorize + "?oauth_token=" + token;
        }
        static void Main(string[] args)
        {
            List<Aluno> alunos = new List<Aluno>();
            
            Aluno aluno1 = new Aluno("Rafael", 1.80);

            Aluno aluno2 = new Aluno("Osni", 1.75);

            Aluno aluno3 = new Aluno("David", 1.86);

            alunos.Add(aluno1);
            alunos.Add(aluno2);
            alunos.Add(aluno3);

            MostrarAlunos(alunos);

            Console.WriteLine("----------------------------");

            Console.ReadKey();

            alunos.Sort(Aluno.ComparaPorAlturaAsc);

            MostrarAlunos(alunos);

            Console.WriteLine("----------------------------");

            alunos.Sort(Aluno.ComparaPorAlturaDesc);

            MostrarAlunos(alunos);

            Console.WriteLine("----------------------------");

            Console.ReadKey();
        }
        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 }));
        }
Example #12
0
        public void RunProgram()
        {
            //results = new List<QuoteResult>()
            //{
            //    new QuoteResult { Id = 1, AnnualAnnuity = 4000f, AssumedBonusRate = 2f },
            //    new QuoteResult { Id = 2, AnnualAnnuity = 3879f, AssumedBonusRate = 3f },
            //    new QuoteResult { Id = 3, AnnualAnnuity = null, AssumedBonusRate = null },
            //    new QuoteResult { Id = 4, AnnualAnnuity = 4823f, AssumedBonusRate = null },
            //    new QuoteResult { Id = 5, AnnualAnnuity = null, AssumedBonusRate = 0f },
            //    new QuoteResult { Id = 6, AnnualAnnuity = 2934f, AssumedBonusRate = 4f },
            //    new QuoteResult { Id = 7, AnnualAnnuity = 4000f, AssumedBonusRate = 3f },
            //    new QuoteResult { Id = 8, AnnualAnnuity = 3259f, AssumedBonusRate = 2f },
            //    new QuoteResult { Id = 9, AnnualAnnuity = 4100f, AssumedBonusRate = 3f }
            //};
            results = new List<QuoteResult>()
            {
                new QuoteResult { Id = 8, AnnualAnnuity = 1045.92f, AssumedBonusRate = null },
                new QuoteResult { Id = 4, AnnualAnnuity = 1046.64f, AssumedBonusRate = null },
                new QuoteResult { Id = 7, AnnualAnnuity = 1070f, AssumedBonusRate = null }
            };
            PrintResults(":");

            results.Sort(new AnnualAnnuityComparer { Direction = SortDirection.Descending });
            PrintResults("sorted by Annual Annuity descending:");

            results.Sort(new AnnualAnnuityComparer { Direction = SortDirection.Ascending });
            PrintResults("sorted by Annual Annuity ascending:");

            results.Sort(new AssumedBonusRateComparer { Direction = SortDirection.Descending });
            PrintResults("sorted by Assumed Bonus Rate descending");

            results.Sort(new AssumedBonusRateComparer { Direction = SortDirection.Ascending });
            PrintResults("sorted by Assumed Bonus Rate ascending");
        }
Example #13
0
        /// <summary>
        /// 同类型管子套料程序,返回已使用的母材列表(贪心算法);
        /// List<PipeBase> mPipeBaseList 初始母材列表;
        /// List<PipePart> mPipePartList 零件列表;
        /// List<PipeBase> mUsedPipeBaseList (返回)
        /// 已使用母材列表;
        /// </summary>
        /// <param name="mPipeBaseList"></param>
        /// <param name="mPipePartList"></param>
        /// <param name="mUsedPipeBaseList"></param>
        public void PipeNesting(List<PipeBase> mPipeBaseList, List<PipePart> mPipePartList, List<PipeBase> mUsedPipeBaseList)
        {
            //排序,仓库管路按照升序排列,零件长度按照降序排列
            mPipeBaseList.Sort(delegate(PipeBase a, PipeBase b) { return a.Length.CompareTo(b.Length); });
            mPipePartList.Sort(delegate(PipePart a, PipePart b) { return b.Length.CompareTo(a.Length); });

            int i, j;
            for (i = 0; i < mPipePartList.Count; i++)
            {
                for (j = 0; j < mPipeBaseList.Count; j++)
                {
                    //如果管路类型相同,且零件长度短于母材长度,则将其排入此母材的加工序列
                    if ((mPipePartList[i].PipeType == mPipeBaseList[j].PipeType) && (mPipePartList[i].Length <= mPipeBaseList[j].Length))
                    {
                        mPipePartList[i].NestedBasePipe = mPipeBaseList[j].ID;
                        mPipePartList[i].Nested = true;
                        mPipePartList[i].Dispatch_date = DateTime.Now.ToString("yyyy-mm-dd");
                        mPipeBaseList[j].ContainsID.Add(mPipePartList[i].ID);
                        mPipeBaseList[j].ContainsPipe.Add(mPipePartList[i]);
                        mPipeBaseList[j].Length = mPipeBaseList[j].Length - mPipePartList[i].Length;
                        //重新按长度对母材库进行升序排列
                        mPipeBaseList.Sort(delegate(PipeBase a, PipeBase b) { return a.Length.CompareTo(b.Length); });
                        //已将当前管路零件套料完毕,跳出循环,继续下一根零件的套料
                        break;
                    }
                }
            }

            //获取已被使用的母材列表
            for (i = 0; i < mPipeBaseList.Count; i++)
                if (mPipeBaseList[i].ContainsID.Count > 0)
                    mUsedPipeBaseList.Add(mPipeBaseList[i]);

            return;
        }
Example #14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Cache["voc"]==null){
                var rootPath = Server.MapPath("~");
                var fileName = Path.Combine(rootPath, "voc.txt");
                FileStream Stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                var lines = File.ReadAllLines(fileName);
                var li = new List<vocline>();

                foreach (string line in lines)
                {
                    var words = line.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
                    var l = new vocline();
                    l.word = words[0];
                    l.file = words[2];
                    l.pars = "";
                    for (int i = 3; i < words.Length; i++)
                    {
                        l.pars += words[i] + " " ;
                    }
                    li.Add(l);
                }

                li.Sort(
                    (x, y) => string.Compare(x.word, y.word)
                );

                li.Sort();
                Cache["voc"] = li;
            }
        }
Example #15
0
        static void Main(string[] args)
        {
            List<Duck> ducks = new List<Duck>()
            {
                new Duck() { Kind = KindOfDuck.Mallard, Size = 17 },
                new Duck() { Kind = KindOfDuck.Muscovy, Size = 18 },
                new Duck() { Kind = KindOfDuck.Decoy, Size = 14 },
                new Duck() { Kind = KindOfDuck.Muscovy, Size = 11 },
                new Duck() { Kind = KindOfDuck.Mallard, Size = 14 },
                new Duck() { Kind = KindOfDuck.Decoy, Size = 13 },
            };

            //ducks.Sort();

            DuckComparerBySize compareBySize = new DuckComparerBySize();
            DuckComparerByKind compareByKind = new DuckComparerByKind();

            ducks.Sort(compareBySize);
            Console.WriteLine("Sort by size:");
            PrintDucks(ducks);

            ducks.Sort(compareByKind);
            Console.WriteLine("Sort by kind:");
            PrintDucks(ducks);

            Console.ReadKey();
        }
Example #16
0
        private void OnMusicListColumnClick(object sender, ColumnClickEventArgs e)
        {
            if (MusicList.ListViewItemSorter == null)
            {
                MusicList.ListViewItemSorter = new ListViewColumnSorter();
            }

            var sorter      = MusicList.ListViewItemSorter as ListViewColumnSorter;
            var chartSorter = new ChartSorter();

            chartSorter.SortType = (ChartSortType)e.Column;
            if (e.Column != sorter.SortColumn)
            {
                sorter.SortColumn = e.Column;
                chartSorter.Order = sorter.Order = SortOrder.Ascending;
            }
            else
            {
                chartSorter.Order = sorter.Order = sorter.Order == SortOrder.Descending || sorter.Order == SortOrder.None ?
                                                   SortOrder.Ascending :
                                                   SortOrder.Descending;
            }

            MusicList.Sort();
            charts?.Sort(chartSorter);
        }
Example #17
0
        public Form1()
        {
            InitializeComponent();                  // Initialize form components

            dataBase = new MySQLConnection();       // Create database connection

            fillStates();                           // Fill state drop box

            // Populate Categories Lists
            string qStr = "SELECT name FROM Categories";
            List<string> qResults = new List<string>();                 // Query must return list, even if we know there will only be one item
            qResults = dataBase.SQLSELECTExec(qStr, "name");
            qResults.Sort();                                            // Sort query list
            qResults = qResults.Distinct().ToList();
            foreach(string item in qResults)
            {
                listBoxCategoryDem.Items.Add(item);
                listBoxCategorySearch.Items.Add(item);
            }

            // Populate Attributes List
            qStr = "SELECT DISTINCT name FROM Attributes";
            qResults = dataBase.SQLSELECTExec(qStr, "name");
            qResults.Sort();
            listBoxAttributes.Items.AddRange(qResults.ToArray());
        }
        public ActionResult GetDataTables2(DataTable dataTable) {
            List<List<string>> table = new List<List<string>>();

            List<int> column1 = new List<int>();
            for (int i = dataTable.iDisplayStart; i < dataTable.iDisplayStart + dataTable.iDisplayLength; i++) {
                column1.Add(i);
            }

            foreach (var sortDir in dataTable.sSortDirs) {
                if (sortDir == DataTableSortDirection.Ascending) {
                    column1.Sort();
                } else {
                    column1.Sort(delegate(int a, int b) {
                        if (a > b) return -1;
                        if (a < b) return 1;
                        return 0;
                    });
                }
            }

            for (int i = 0; i < column1.Count; i++) {
                table.Add(new List<string> { column1[i].ToString(), "ÄÖÜäöü" + i });
            }

            var result = new DataTableResult(dataTable, table.Count, table.Count, table);
            result.ContentEncoding = Encoding.UTF8;
            return result;
        }
Example #19
0
        public static List<LichSuKien> get_LichSuKienSearching(bool status, string symbol, int type, DateTime fromDate, DateTime toDate, int PageIndex, int PageCount, out int totalItem)
        {

            var redis = BLFACTORY.RedisClient;
            var ret = new List<LichSuKien>();
            var keylist = redis.ContainsKey(RedisKey.KeyLichSuKien) ? redis.Get<List<string>>(RedisKey.KeyLichSuKien) : new List<string>();
            if(status && int.Parse(fromDate.ToString("yyyyMMdd")) < int.Parse(DateTime.Now.ToString("yyyyMMdd")))
            {
                fromDate = DateTime.Now;
            }
            if (!status && int.Parse(toDate.ToString("yyyyMMdd")) > int.Parse(DateTime.Now.ToString("yyyyMMdd")))
            {
                toDate = DateTime.Now;
            }
            keylist = keylist.FindAll(sKey => ((Convert.ToInt32(fromDate.ToString("yyyyMMdd")) < int.Parse("20000101") || Convert.ToInt32(sKey.Substring(0, 8)) >= Convert.ToInt32(fromDate.ToString("yyyyMMdd")))) && (Convert.ToInt32(toDate.ToString("yyyyMMdd")) < int.Parse("20000101") || Convert.ToInt32(sKey.Substring(0, 8)) <= Convert.ToInt32(toDate.ToString("yyyyMMdd"))) && (type == 0 || ("," + sKey.Substring(9, sKey.LastIndexOf(":") - 9) + ",").Contains("," + type.ToString() + ",")));
            var keys = new List<string>();
            foreach (var hKey in keylist)
            {
                var key = string.Format(RedisKey.KeyLichSuKienObject, hKey.Substring(hKey.LastIndexOf(":") + 1));
                if (!keys.Contains(key)) keys.Add(key);
            }
            var objs = keys.Count > 0 ? redis.GetAll<LichSuKien>(keys) : new Dictionary<string, LichSuKien>();
            ret = objs.Values.ToList().FindAll(s => s != null && (symbol == "" || stringContainSymbol(s.MaCK, symbol)) && double.Parse(s.PostDate.ToString("yyyyMMddHHmm")) <= double.Parse(DateTime.Now.ToString("yyyyMMddHHmm")));
            if (status)
                ret.Sort("EventDate asc");
            else
                ret.Sort("EventDate desc");
            totalItem = ret.Count;
            ret = ret.GetPaging(PageIndex, PageCount);
            return ret;
        }
Example #20
0
        static void Main(string[] args)
        {
            const int NumberOfAnimals = 10;
            List<Animal> animals = new List<Animal>();

            Random r = new Random();
            for (int index = 0; index < NumberOfAnimals; index++)
            {
                var animalShouldBeCat = (r.Next(2) == 0);
                uint nextWeight = (uint)r.Next(10, 40);
                Animal nextAnimal = animalShouldBeCat ? (Animal)(new Cat(nextWeight, "John")) : (Animal)(new Dog(nextWeight, "Dave"));
                animals.Add(nextAnimal);
            }

            foreach (Animal animal in animals)
            {
                Console.WriteLine(animal);
            }

            Console.WriteLine();
            Console.WriteLine("/// SORTING ANIMALS BY NAME...");
            animals.Sort(new AnimalComparator(AnimalComparisonType.Name));
            foreach (Animal animal in animals)
            {
                Console.WriteLine(animal);
            }

            Console.WriteLine();
            Console.WriteLine("/// SORTING ANIMALS BY WEIGHT...");
            animals.Sort(new AnimalComparator(AnimalComparisonType.Weight));
            foreach (Animal animal in animals)
            {
                Console.WriteLine(animal);
            }
        }
Example #21
0
        /// <summary>
        /// 取授权登录URL
        /// </summary>
        /// <returns>登录URL</returns>
        public string GetAuthUrl() {
            List<UrlParameter> param = new List<UrlParameter>();
            param.Add(new UrlParameter("oauth_consumer_key", config.AppKey));
            param.Add(new UrlParameter("oauth_nonce", OAuthCommon.GetGUID32()));
            param.Add(new UrlParameter("oauth_signature_method", "HMAC-SHA1"));
            param.Add(new UrlParameter("oauth_timestamp", OAuthCommon.GetTimestamp()));
            param.Add(new UrlParameter("oauth_version", "1.0"));
            param.Sort(new UrlParameterCompre());

            StringBuilder sbSign = new StringBuilder().Append("GET&")
                .Append(request_token.UrlEncode2())
                .Append("&")
                .Append(OAuthCommon.GetUrlParameter(param).UrlEncode2());
            
            param.Add(new UrlParameter("oauth_signature", OAuthCommon.GetHMACSHA1(config.AppSecret, "", sbSign.ToString()).UrlEncode2()));
            param.Sort(new UrlParameterCompre());
            string data = HttpHelper.SendGet(new StringBuilder().Append(request_token).Append("?").Append(OAuthCommon.GetUrlParameter(param)).ToString());

            int intOTS = data.IndexOf("oauth_token=");
            int intOTSS = data.IndexOf("&oauth_token_secret=");
            string oauth_token = data.Substring(intOTS + 12, intOTSS - (intOTS + 12));
            string oauth_token_secret = data.Substring((intOTSS + 20), data.Length - (intOTSS + 20));
            Session2.Set("oauth_token", oauth_token);
            Session2.Set("oauth_token_secret", oauth_token_secret);
            return (authorize + "?oauth_token=" + oauth_token + "&oauth_callback=" + config.RedirectUrl);
        }
Example #22
0
        static void Main(string[] args)
        {
            int i = 0;

            List<Person> persons = new List<Person>();
            persons.Add(new Person("Ole", 23));
            persons.Add(new Person("Pelle", 12));
            persons.Add(new Person("Rikke", 34));
            persons.Add(new Person("Stine", 78));
            persons.Add(new Person("Thor", 45));
            persons.Add(new Person("Thor", 11));
            persons.Add(new Person("Rikke", 89));

            //int[] myArray = { 2, 3, 4, 5, 6, 3 };
            //Array.Sort<int>(myArray);
            //Array.Reverse(myArray);

            Console.WriteLine("List of persons");
            Print(persons);

            //persons.Sort();
            //Console.WriteLine("Sorted by natural order");
            // Print(persons);

            Console.WriteLine("Sorted by Name");
            persons.Sort(new NameComparator()); //Her bruges en IComparer
            Print(persons);
            Console.WriteLine("Sorted by age");
            persons.Sort(Person.GetAgeComparer());
            Print(persons);
            Console.Read();
        }
Example #23
0
        /// <summary>
        /// Shows how to pass delegates to the List Sort method.
        /// </summary>
        public static void SortingExamples()
        {
            // Make a list for demonstration purposes
            List<String> list = new List<String>();
            list.Add("hello");
            list.Add("long string");
            list.Add("a");
            list.Add("another long string");

            // The Sort method can take a delegate as a parameter.  This delegate should
            // take two list elements x and y and return negative (if x is smaller than y),
            // positive (if x is larger than y), and zero (if x and y are equal).

            // This sorts in the usual fashion.  We pass in an existing method.
            list.Sort(String.Compare);
            Console.WriteLine(String.Join(", ", list));

            // This sorts in reverse order.  We pass in a lambda.
            list.Sort((x, y) => -String.Compare(x, y));
            Console.WriteLine(String.Join(", ", list));

            // Another way of doing the same way.
            list.Sort(OppCompare);
            Console.WriteLine(String.Join(", ", list));

            // This sorts by length.  We pass in a lambda.
            list.Sort((x, y) => x.Length - y.Length);
            Console.WriteLine(String.Join(", ", list));
        }
    /**
     * main.
     *
     * @param args
     */
    public static void main(string[] args)
    {
        int nbTests = (args != null && args.Length >= 1) ? int.Parse(args[0]) : NB_TESTS;
        int nbOfExclusionMinMax = (args != null && args.Length >= 2) ? int.Parse(args[1]) : NB_OF_EXCLUSION_MIN_MAX;

        List<long> executionTimes = new List<long>(nbTests);

        for (int i = nbTests; i != 0; i--)
            executionTimes.Add(FileTest.testWriteFile());
        executionTimes.Sort();
        Console.WriteLine("[FileTest], Write " + NB_FILE_TESTS + " file(s) with " + IO_MAX + " lines,, average time,"
                + averageTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax) + ", min time," + executionTimes[0] + ", max time," + executionTimes[executionTimes.Count - 1]
                + ", relative deviation time," + relativeDeviationTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax));
        executionTimes.Clear();

        for (int i = nbTests; i != 0; i--)
            executionTimes.Add(FileTest.testWriteFileWithFlush());
        executionTimes.Sort();
        Console.WriteLine("[FileTest], Write with flush " + NB_FILE_TESTS + " file(s) with " + IO_MAX + " lines,, average time,"
                + averageTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax) + ", min time," + executionTimes[0] + ", max time," + executionTimes[executionTimes.Count - 1]
                + ", relative deviation time," + relativeDeviationTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax));
        executionTimes.Clear();

        //Write File before read
        try
        {
            String textLine =
                "abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefgh\n";
            String textLine2 =
              "1234567890\n";
            StreamWriter streamWriter = new StreamWriter(FILE_NAME);
            for (int i = IO_MAX; i != 0; i--)
            {
                if ((i % 2) == 0)
                {
                    streamWriter.Write(textLine);
                }
                else
                {
                    streamWriter.Write(textLine2);
                }
            }
            streamWriter.Close();
        }
        catch (IOException e)
        {
            //
        }

        for (int i = nbTests; i != 0; i--)
            executionTimes.Add(FileTest.testReadFile());
        executionTimes.Sort();
        Console.WriteLine("[FileTest], Read " + NB_FILE_TESTS + " file(s) with " + IO_MAX + " lines,, average time,"
                + averageTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax) + ", min time," + executionTimes[0] + ", max time," + executionTimes[executionTimes.Count - 1]
                + ", relative deviation time," + relativeDeviationTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax));
        executionTimes.Clear();

        // Delete the file after
        File.Delete(FILE_NAME);
    }
Example #25
0
        public static List<LineSegment> KruskalTree(List<LineSegment> segments, KruskalType type= KruskalType.Minimum) {
            var nodes = new Dictionary<Point, Node>();
            var mst = new List<LineSegment>();
            switch (type) {
                // note that the compare functions are the reverse of what you'd expect
                // because (see below) we traverse the lineSegments in reverse order for speed
                case KruskalType.Maximum:
                    segments.Sort(LineSegment.CompareLengths);
                    break;
                default:
                    segments.Sort(LineSegment.CompareLengthsMax);
                    break;
            }
            for (int i = segments.Count; --i > -1; ) {
                var segment = segments[i];
                Node rootOfSet0 = null;
                Node node0;
                if (!nodes.ContainsKey(segment.P0)) {
                    node0 = new Node();
                    // intialize the node:
                    rootOfSet0 = node0.Parent = node0;
                    node0.TreeSize = 1;

                    nodes[segment.P0] = node0;
                } else {
                    node0 = nodes[segment.P0];
                    rootOfSet0 = Node.Find(node0);
                }
                Node node1;
                Node rootOfSet1;
                if (!nodes.ContainsKey(segment.P1)) {
                    node1 = new Node();
                    // intialize the node:
                    rootOfSet1 = node1.Parent = node1;
                    node1.TreeSize = 1;
                    nodes[segment.P1] = node1;
                } else {
                    node1 = nodes[segment.P1];
                    rootOfSet1 = Node.Find(node1);
                }

                if (rootOfSet0 != rootOfSet1) { // nodes not in same set
                    mst.Add(segment);

                    // merge the two sets:
                    var treeSize0 = rootOfSet0.TreeSize;
                    var treeSize1 = rootOfSet1.TreeSize;
                    if (treeSize0 >= treeSize1) {
                        // set0 absorbs set1:
                        rootOfSet1.Parent = rootOfSet0;
                        rootOfSet0.TreeSize += treeSize1;
                    } else {
                        // set1 absorbs set0:
                        rootOfSet0.Parent = rootOfSet1;
                        rootOfSet1.TreeSize += treeSize0;
                    }
                }
            }
            return mst;
        }
Example #26
0
        static void Main(string[] args)
        {
            string[] input = Console.ReadLine().Split('\\');

            List<char> left = input[0].ToCharArray().ToList();
            List<char> right = input[1].ToCharArray().ToList();
            string command = input[2];

            List<char> result = new List<char>();

            switch (command)
            {
                case "join":

                    foreach (char element in right)
                    {
                        result.AddRange(left.FindAll(c => c == element));
                    }

                    result.Sort();

                    Console.WriteLine(String.Join("", result.Distinct()));

                    break;

                case "right exclude":

                    result = left;

                    foreach (char element in right)
                    {
                        result.RemoveAll(c => c == element);
                    }

                    result.Sort();

                    Console.WriteLine(String.Join("", result.Distinct()));

                    break;

                case "left exclude":

                    result = right;

                    foreach (char element in left)
                    {
                        result.RemoveAll(c => c == element);
                    }

                    result.Sort();

                    Console.WriteLine(String.Join("", result.Distinct()));

                    break;

                default:
                    break;
            }
        }
        public static void Test3()
        {
            IList<SemanticVersion> versions = new List<SemanticVersion>();

            versions.Add(SemanticVersion.Parse("1.0.0"));
            versions.Add(SemanticVersion.Parse("1.5.0"));
            versions.Add(SemanticVersion.Parse("1.8.0"));
            versions.Add(SemanticVersion.Parse("2.0.0"));
            versions.Add(SemanticVersion.Parse("2.2.0"));
            versions.Add(SemanticVersion.Parse("2.5.0"));
            versions.Add(SemanticVersion.Parse("2.5.1"));
            versions.Add(SemanticVersion.Parse("2.6.0"));
            versions.Add(SemanticVersion.Parse("2.6.7"));
            versions.Add(SemanticVersion.Parse("2.8.0"));
            versions.Add(SemanticVersion.Parse("2.8.1"));
            versions.Add(SemanticVersion.Parse("3.0.0"));
            versions.Add(SemanticVersion.Parse("3.5.0"));
            versions.Add(SemanticVersion.Parse("3.6.0"));
            versions.Add(SemanticVersion.Parse("3.7.0"));
            versions.Add(SemanticVersion.Parse("4.0.0"));
            versions.Add(SemanticVersion.Parse("4.1.0"));
            versions.Add(SemanticVersion.Parse("4.1.2"));
            versions.Add(SemanticVersion.Parse("4.5.0"));
            versions.Add(SemanticVersion.Parse("5.0.0"));

            SemanticVersion current = SemanticVersion.Parse("2.5.0");

            List<SemanticVersion> lineup = new List<SemanticVersion>();

            lineup.AddRange(versions.Where(Includes(current, SemanticVersionSpan.MaxMinor)));

            DeDup(lineup);

            Trim(lineup);

            lineup.Sort(SemanticVersionRange.DefaultComparer);

            Print(lineup);

            lineup.AddRange(versions.Where(Includes(current, SemanticVersionSpan.FromMajor(-1))));

            DeDup(lineup);

            Trim(lineup);

            lineup.Sort(SemanticVersionRange.DefaultComparer);

            Print(lineup);

            lineup.AddRange(versions.Where(Includes(current, SemanticVersionSpan.FromMajor(1))));

            DeDup(lineup);

            Trim(lineup);

            lineup.Sort(SemanticVersionRange.DefaultComparer);

            Print(lineup);
        }
 public void Reduce(string key, IEnumerable<string> values, IReducerCollector collector, bool isrereduce)
 {
     var tmp = new List<string>(values);
     if (_comparer != null)
         tmp.Sort(_comparer);
     else
         tmp.Sort();
     collector.Collect(key, string.Join(_separator, tmp.ToArray()));
 }
Example #29
0
	public List<LineSegment> kruskal(List<LineSegment> lineSegments,string type="minimum"){
		Dictionary<Vector2 ,Node> nodes=new Dictionary<Vector2, Node>();
		List<LineSegment> mst=new List<LineSegment>();
		List<Node> nodePool=new List<Node>();
		switch(type){
		case "maximum":
			lineSegments.Sort(LineSegment.compareLengths);

			break;
		default:
			lineSegments.Sort(LineSegment.compareLengths_MAX);
			break;
		}
		for(int i=lineSegments.Count;i>-1;i--){
			LineSegment lineSegment=lineSegments[i];
			Node node0;
			nodes.TryGetValue(lineSegment.p0,out node0);
			Node rootOfSet0;
			if(node0==null){
				node0=nodePool.Count>0?nodePool[nodePool.Count-1]:new Node();
				nodePool.RemoveAt(nodePool.Count-1);
				rootOfSet0=node0.parent=node0;
				node0.treeSize=1;
				nodes[lineSegment.p0]=node0;
			}else{
				rootOfSet0=find(node0);
			}

			Node node1=nodes[lineSegment.p1];
			Node rootOfSet1;
			if(node1==null){
			node1=nodePool.Count>0?nodePool[nodePool.Count-1]:new Node();
				rootOfSet1=node1.parent=node1;
				node1.treeSize=1;
				nodes[lineSegment.p1]=node1;
			}

			if(rootOfSet0!=rootOfSet1){
				mst.Add(lineSegment);
				int treeSize0=rootOfSet0.treeSize;
				int treeSize1=rootOfSet1.treeSize;
				if(treeSize0>=treeSize1){
					rootOfSet1.parent=rootOfSet0;
					rootOfSet0.treeSize+=treeSize1;
				}else{
					rootOfSet0.parent=rootOfSet1;
					rootOfSet1.treeSize+=treeSize0;
				}
			}
		}
		foreach(Node node in nodes){
			nodePool.Add(node);
		}
		return mst;
	}
    /**
     * main.
     *
     * @param args
     */
    public static void main(string[] args)
    {
        int nbTests = (args != null && args.Length >= 1) ? int.Parse(args[0]) : NB_TESTS;
        int nbOfExclusionMinMax = (args != null && args.Length >= 2) ? int.Parse(args[1]) : NB_OF_EXCLUSION_MIN_MAX;

        List<long> executionTimes = new List<long>(nbTests);

        for (int i = nbTests; i != 0; i--)
            executionTimes.Add(TrigoTest.testSin());
        executionTimes.Sort();
        Console.WriteLine("[TrigoTest], Calculation of Sin " + NB_ARITHMETIC_TESTS + " while (i < " + TRIG_MAX + ") {sine = Math.Sin(i)     i++ },, average time,"
                + averageTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax) + ", min time," + executionTimes[0] + ", max time," + executionTimes[executionTimes.Count - 1]
                + ", relative deviation time," + relativeDeviationTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax));
        executionTimes.Clear();

        for (int i = nbTests; i != 0; i--)
            executionTimes.Add(TrigoTest.testCos());
        executionTimes.Sort();
        Console.WriteLine("[TrigoTest], Calculation of Cos " + NB_ARITHMETIC_TESTS + " while (i < " + TRIG_MAX + ") {cosine = Math.Cos(i)     i++ },, average time,"
                + averageTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax) + ", min time," + executionTimes[0] + ", max time," + executionTimes[executionTimes.Count - 1]
                + ", relative deviation time," + relativeDeviationTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax));
        executionTimes.Clear();

        for (int i = nbTests; i != 0; i--)
            executionTimes.Add(TrigoTest.testTan());
        executionTimes.Sort();
        Console.WriteLine("[TrigoTest], Calculation of Tan " + NB_ARITHMETIC_TESTS + " while (i < " + TRIG_MAX + ") {tan = Math.Tan(i)     i++ },, average time,"
                + averageTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax) + ", min time," + executionTimes[0] + ", max time," + executionTimes[executionTimes.Count - 1]
                + ", relative deviation time," + relativeDeviationTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax));
        executionTimes.Clear();

        for (int i = nbTests; i != 0; i--)
            executionTimes.Add(TrigoTest.testLog());
        executionTimes.Sort();
        Console.WriteLine("[TrigoTest], Calculation of Log " + NB_ARITHMETIC_TESTS + " while (i < " + TRIG_MAX + ") {log = Math.Log(i)     i++ },, average time,"
                + averageTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax) + ", min time," + executionTimes[0] + ", max time," + executionTimes[executionTimes.Count - 1]
                + ", relative deviation time," + relativeDeviationTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax));
        executionTimes.Clear();

        for (int i = nbTests; i != 0; i--)
            executionTimes.Add(TrigoTest.testExp());
        executionTimes.Sort();
        Console.WriteLine("[TrigoTest], Calculation of Exp " + NB_ARITHMETIC_TESTS + " while (i < " + TRIG_MAX + ") {exp = Math.Exp(i)     i++ },, average time,"
                + averageTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax) + ", min time," + executionTimes[0] + ", max time," + executionTimes[executionTimes.Count - 1]
                + ", relative deviation time," + relativeDeviationTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax));
        executionTimes.Clear();

        for (int i = nbTests; i != 0; i--)
            executionTimes.Add(TrigoTest.testSqrt());
        executionTimes.Sort();
        Console.WriteLine("[TrigoTest], Calculation of Sqrt " + NB_ARITHMETIC_TESTS + " while (i < " + TRIG_MAX + ") {sqrt = Math.Sqrt(i)     i++ },, average time,"
                + averageTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax) + ", min time," + executionTimes[0] + ", max time," + executionTimes[executionTimes.Count - 1]
                + ", relative deviation time," + relativeDeviationTimeWithoutMinMax(executionTimes, nbOfExclusionMinMax));
        executionTimes.Clear();
    }
        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));
        }
        private static IEnumerable <FoodTruckLocation> CalculateDistancesToFoodTrucks(
            string latitude, string longitude, List <FoodTruckLocation> foodTruckLocations)
        {
            foreach (var foodTruckLocation in foodTruckLocations)
            {
                try
                {
                    var sCoord = new GeoCoordinate(double.Parse(latitude), double.Parse(longitude));
                    var eCoord = new GeoCoordinate(double.Parse(foodTruckLocation.Latitude), double.Parse(foodTruckLocation.Longitude));

                    foodTruckLocation.DistanceFromCurrentLocation = sCoord.GetDistanceTo(eCoord);
                }
                catch
                {
                    continue;
                }
            }

            foodTruckLocations?.Sort(delegate(FoodTruckLocation one, FoodTruckLocation two)
            {
                return(one.DistanceFromCurrentLocation.CompareTo(two.DistanceFromCurrentLocation));
            });

            return(foodTruckLocations.Take(5));
        }
Example #33
0
 void OnEnable()
 {
     // TODO: optimize, to avoid sorting all objects each validation
     // sort ascending by drop chance, for easier loot spawning
     lootTable?.Sort((x, y) => y.dropChance.CompareTo(x.dropChance));
     lootTable?.Reverse();
 }
Example #34
0
        public void SetUp()
        {
            if (SqlTestHelpers.ConnectionString(null) == null)
            {
                return;
            }
            SqlTestHelpers.WithNewDb("LogTest", conn =>
            {
                var tableFactory = new SqlTableManager(SqlTestHelpers.ConnectionString("LogTest"), "log");
                var export       = new DataExtract <School>(Spec, tableFactory);
                export.Run(new[] { School });

                tableFactory = new SqlTableManager(SqlTestHelpers.ConnectionString("LogTest"), "log");
                tableFactory.WriteLog("Explicit logging from the outside A");
                export = new DataExtract <School>(Spec, tableFactory);
                export.Run(new[] { School });
                tableFactory.WriteLog("Explicit logging from the outside B");

                tableFactory = new SqlTableManager(SqlTestHelpers.ConnectionString("LogTest"), "log");
                tableFactory.WriteLog("Explicit logging from the outside C");

                _logRows   = SqlTestHelpers.SimpleQuery(conn, "SELECT * FROM log").Rows.Select(_ => new logEntry(_)).ToList();
                var lookup = _logRows.ToLookup(_ => _.SessionId, _ => _);
                _log1      = lookup.FirstOrDefault(_ => _.Count() == 3)?.ToList();
                _log2      = lookup.FirstOrDefault(_ => _.Count() == 6)?.ToList();
                _log3      = lookup.FirstOrDefault(_ => _.Count() == 1)?.ToList();
                _log1?.Sort((x, y) => x.SeqId.CompareTo(y.SeqId));
                _log2?.Sort((x, y) => x.SeqId.CompareTo(y.SeqId));
                _log3?.Sort((x, y) => x.SeqId.CompareTo(y.SeqId));
            });
        }
Example #35
0
        private static void AlphabetizeNewlineList(string filePath, Op operation)
        {
            List <string> preLines   = new List <string>();
            List <string> postLines  = new List <string>();
            List <string> alphaLines = null;

            using (StreamReader reader = new StreamReader(filePath))
            {
                bool preAlpha = true;
                // get each line until end of file
                while (reader.Peek() >= 0)
                {
                    string line = reader.ReadLine();
                    if (line.Equals(ALPHA_START))
                    {
                        alphaLines = InAlphaNewlineLines(reader);
                        preAlpha   = false;
                    }
                    else if (preAlpha)
                    {
                        preLines.Add(line);
                    }
                    else
                    {
                        postLines.Add(line);
                    }
                }
            }

            alphaLines?.Sort();
            ReplaceAlphaNewlineLines(filePath, preLines, alphaLines, postLines);
        }
        /// <summary>
        /// Sorts the keys.
        /// </summary>
        /// <param name="keys">The keys.</param>
        /// <returns></returns>
        public List <string> SortKeys(List <string> keys)
        {
            keys?.Sort((code1, code2) =>
            {
                if (string.IsNullOrEmpty(code1) || code1.Equals(this.NullValueKey))
                {
                    return(-1);
                }

                if (string.IsNullOrEmpty(code2) || code2.Equals(this.NullValueKey))
                {
                    return(1);
                }

                var possibleValue1 = this.PossibleValueForKey(code1);
                var value1         = possibleValue1.TitleLabelField.StringValue;

                var possibleValue2 = this.PossibleValueForKey(code2);
                var value2         = possibleValue2.TitleLabelField.StringValue;

                return(string.Compare(value1, value2, StringComparison.Ordinal));
            });

            return(keys);
        }
Example #37
0
        public List <StudioVersion> GetInstalledStudioVersions()
        {
            if (_installedVersions != null)
            {
                return(_installedVersions);
            }

            var studioVersionService    = new StudioVersionService();
            var installedStudioVersions = studioVersionService.GetInstalledStudioVersions();

            _logger.Info("Installed Trados Studio Versions");

            _installedVersions = installedStudioVersions
                                 ?.Select(v => new StudioVersion(v)).ToList();

            if (installedStudioVersions != null)
            {
                foreach (var studioVersion in installedStudioVersions)
                {
                    _logger.Info(
                        $"Installed Version:{studioVersion.Version} Public version: {studioVersion.PublicVersion}");
                }
            }
            else
            {
                _logger.Info("Cannot find any Trados Version installed on the machine");
            }

            _installedVersions?.Sort((item1, item2) =>
                                     item1.ExecutableVersion.Major <item2.ExecutableVersion.Major ? 1 :
                                                                    item1.ExecutableVersion.Major> item2.ExecutableVersion.Major ? -1 : 0);

            return(_installedVersions);
        }
Example #38
0
        static string GetLatestProfilesBackupFile()
        {
            List <string> files = Directory.GetFiles(Program.ExeFolder, ProfilesName + ".*", SearchOption.TopDirectoryOnly).ToList();

            files?.Sort();
            return(files?.Where(str => str.ToUpper().Contains("XML") == false).FirstOrDefault());
        }
Example #39
0
        void updateMusicAssets()
        {
            Log.Debug("Load Content");

            if (allAssets?.Count == 0 && ContentClient.Shared.AvContent.Count > 0)
            {
                allAssets = ContentClient.Shared.AvContent [UserRoles.General].Where(m => m.HasId && m.HasRemoteAssetUri)
                            .Select(s => AssetPersistenceManager.Shared.GetMusicAsset(s))
                            .ToList();
            }
            else
            {
                var newAssets = ContentClient.Shared.AvContent [UserRoles.General].Where(m => m.HasId && m.HasRemoteAssetUri && !allAssets.Any(ma => ma.Id == m.Id))
                                .Select(s => AssetPersistenceManager.Shared.GetMusicAsset(s));

                allAssets.AddRange(newAssets);

                allAssets.RemoveAll(ma => !ContentClient.Shared.AvContent [UserRoles.General].Any(a => a.Id == ma.Id));
            }

            allAssets?.Sort((x, y) => y.Music.Timestamp.CompareTo(x.Music.Timestamp));

            BeginInvokeOnMainThread(() =>
            {
                TableView.ReloadData();

                if (RefreshControl?.Refreshing ?? false)
                {
                    RefreshControl.EndRefreshing();
                }
            });
        }
Example #40
0
 public static bool CheckForUpdate()
 {
     try
     {
         List <GitHubCommit> gits    = GitAccess.GetHeaderCommit();
         List <string>       gitshas = new List <string>();
         foreach (GitHubCommit git in gits)
         {
             gitshas.Add(git.Sha);
         }
         gitshas.Sort();
         List <string> shas = LocalData.LoadFileToList("SHAs");
         if (shas == null)
         {
             LocalData.SaveFile(gitshas, "SHAs");
             shas = LocalData.LoadFileToList("SHas");
         }
         shas?.Sort();
         if (!shas.SequenceEqual(gitshas))
         {
             LocalData.SaveFile(gitshas, "SHAs");
             return(true);
         }
         else
         {
             return(false);
         }
     }
     catch (Exception e)
     {
         MessageBox.Show("Can't check for new updates!\n" + e.ToString());
     }
     return(false);
 }
Example #41
0
        internal static List <FoodTruckLocation> CalculateDistancesToFoodTrucks(
            Location currentLocationCoordinates, List <FoodTruckLocation> foodTruckLocations)
        {
            foreach (var foodTruckLocation in foodTruckLocations)
            {
                try
                {
                    var sCoord = new GeoCoordinate(currentLocationCoordinates.Coordinates[0], currentLocationCoordinates.Coordinates[1]);
                    var eCoord = new GeoCoordinate(double.Parse(foodTruckLocation.Latitude), double.Parse(foodTruckLocation.Longitude));

                    foodTruckLocation.DistanceFromCurrentLocation = sCoord.GetDistanceTo(eCoord);
                }
                catch (Exception exc)
                {
                    Console.WriteLine($"Exception was encountered in calculating distance for food truck: {foodTruckLocation.Applicant} "
                                      + exc.Message);
                    continue;
                }
            }

            foodTruckLocations?.Sort(delegate(FoodTruckLocation one, FoodTruckLocation two)
            {
                return(one.DistanceFromCurrentLocation.CompareTo(two.DistanceFromCurrentLocation));
            });

            return(foodTruckLocations);
        }
Example #42
0
        /// <summary> Сортировка списка чатов </summary>
        private List <ModelChat> SortCurrentListModelChat(List <ModelChat> listModelChat)
        {
            // решение по сортировке не айс по производительности, но нет времени переписывать пока (p.s. пох...)

            listModelChat?.Sort((modelChat1, modelChat2) => modelChat2.LastModifiedDate.CompareTo(modelChat1.LastModifiedDate));

            return(listModelChat);
        }
Example #43
0
    internal override void OnValidate()
    {
        base.OnValidate();

        sprite = AssetHandler.LoadNearbyAssetWithSameName <Sprite>(this);
        // TODO: optimize, to avoid sorting all objects each validation
        // sort ascending by drop chance, for easier loot spawning
        lootTable?.Sort((x, y) => y.dropChance.CompareTo(x.dropChance));
        lootTable?.Reverse();
    }
Example #44
0
        /// <inheritdoc/>
        public List <Employee> SortBySalaryDefault(List <Employee> employees)
        {
            _logger.LogInformation("Sort by defaut started");

            employees?.Sort();

            _logger.LogInformation("Sort by defaut finished");

            return(employees ?? new List <Employee>());
        }
Example #45
0
        /// <inheritdoc/>
        public List <Employee> SortBySalaryAsc(List <Employee> employees)
        {
            _logger.LogInformation("Sort by salary ascending started");

            employees?.Sort(new Employee.SortBySalaryAsc());

            _logger.LogInformation("Sort by salary ascending finished");

            return(employees ?? new List <Employee>());
        }
Example #46
0
        public IUnitView GetIntersectInputPositionUnit(Vector3 input_world_position)
        {
            List <IUnitView> intersects = _all_units_on_location.Where(unit => input_world_position.x >= unit.Bounds.center.x - unit.Bounds.extents.x &&
                                                                       input_world_position.x <= unit.Bounds.center.x + unit.Bounds.extents.x &&
                                                                       input_world_position.y >= unit.Bounds.center.y - unit.Bounds.extents.y &&
                                                                       input_world_position.y <= unit.Bounds.center.y + unit.Bounds.extents.y).ToList();

            intersects?.Sort();

            return(intersects.Count > 0 ? intersects[0] : null);
        }
Example #47
0
 private Rule(ERuleType ruleType, List <Rule> children, List <int> strIndex, int index, int len, int offset, byte[] buffer = null)
 {
     RuleType = ruleType;
     Children = children;
     strIndex?.Sort();
     StrIndex  = strIndex;
     Index     = index;
     Len       = len;
     Offset    = offset;
     AddBuffer = buffer;
 }
Example #48
0
        public static void UpdateContests()
        {
            var cf   = new Codeforces(DateTime.Now);
            var dmoj = new DMOJ(DateTime.Now);

            Contests?.Clear();

            Contests = cf.GetContestsList().Result;
            Contests.AddRange(dmoj.GetContestsList().Result);

            Contests?.Sort();
        }
Example #49
0
        public RunResult Run(char[] data, int index, int length, List <Capture> captureOutput = null)
        {
            Data          = data;
            EndPos        = index + length;
            CaptureOutput = captureOutput;

            var result = InternalRun(Methods[0], LabelPositions[0], index);

            CaptureOutput?.Sort();
            var successful = result.Label == 0;

            return(new RunResult(successful, result.Label, result.Position, 0));
        }
Example #50
0
        static void ListaContatosPassar(List <Pessoa> ListaContatos)
        {
            ListaContatos?.Sort((contato1, contato2) => contato1.Nome.CompareTo(contato2.Nome));
            ListaContatos.ForEach(contato =>
            {
                Console.WriteLine(contato);

                Console.WriteLine("\n0 - Sair\n1 - Proximo");
                int op = int.Parse(Console.ReadLine());
                if (op == 0)
                {
                    return;
                }
            });
        }
Example #51
0
        public async Task <IEnumerable <Reservation> > GetReservationsByIdAsync(int id)
        {
            List <Reservation> res = null;

            using (RoomsContext dbContext = new RoomsContext())
            {
                var room = await dbContext.MeetingRooms.FirstOrDefaultAsync(c => c.Id == id);

                if (room != null)
                {
                    res = room.Reservations.ToList();
                }
                res?.Sort();
            }
            return(res);
        }
    public int GetBestScoreByIndex(int index)
    {
        List <int> list = bestScoreArr?.ToList();

        //从大到小进行排序
        list?.Sort((x, y) => (-x.CompareTo(y)));
        bestScoreArr = list?.ToArray();
        if (bestScoreArr?.Length >= index)
        {
            return(bestScoreArr[index]);
        }
        else
        {
            return(0);
        }
    }
Example #53
0
        void Test(List <int> scores)
        {
            Completed?.Invoke(this, 100);

            var x = scores?[0];
            int?size;

            size = scores == null ? null : (int?)scores.Count;

            size = scores?.Count;
            int siz = scores?.Count ?? 0;

            scores?.Sort();

            Item parent = new Item();
            var  p      = parent?.Child?.Child?.Child;
        }
        /// <summary>
        /// 장비 목록 결과를 정렬
        /// </summary>
        /// <param name="myList"></param>
        /// <returns></returns>
        private List <RemodelItemListItem> SortList(List <RemodelItemListItem> myList)
        {
            myList?.Sort((x, y) =>
            {
                SlotItemIconType?a = x.IconType, b = y.IconType;

                if (Enum.GetName(typeof(SlotItemIconType), a) == null)
                {
                    a = SlotItemIconType.Unknown;
                }
                if (Enum.GetName(typeof(SlotItemIconType), b) == null)
                {
                    b = SlotItemIconType.Unknown;
                }

                return(((int)a.Value).CompareTo((int)b.Value));
            });
            return(myList);
        }
        //获取相同张数数量
        public static Dictionary <int, int> GetSameCount <T>(T cardSizes, ref List <int> sameCount) where T : IList <int>
        {
            Dictionary <int, int> sameCountDic = new Dictionary <int, int>();

            foreach (var size in cardSizes)
            {
                if (sameCountDic.ContainsKey(size))
                {
                    sameCountDic[size]++;
                }
                else
                {
                    sameCountDic[size] = 1;
                }
            }
            foreach (var same in sameCountDic)
            {
                sameCount?.Add(same.Value);
            }
            sameCount?.Sort();//默认就是从小到大排序
            return(sameCountDic);
        }
Example #56
0
        /// <summary>
        /// Sorteds the keys from key array.
        /// </summary>
        /// <typeparam name="TKey">
        /// The type of the key.
        /// </typeparam>
        /// <typeparam name="TValue">
        /// The type of the value.
        /// </typeparam>
        /// <param name="target">
        /// The target.
        /// </param>
        /// <param name="keyArray">
        /// The key array.
        /// </param>
        /// <returns>
        /// The <see cref="List"/>.
        /// </returns>
        public static List <TKey> SortedKeysFromKeyArray <TKey, TValue>(
            this Dictionary <TKey, TValue> target,
            List <TKey> keyArray) where TValue : IComparable
        {
            keyArray?.Sort(
                (obj1, obj2) =>
            {
                var v1 = target.ValueOrDefault(obj1);
                var v2 = target.ValueOrDefault(obj2);
                if (v2 == null)
                {
                    if (v1 == null)
                    {
                        return(0);
                    }

                    return(-1);
                }

                return(v1 == null ? 1 : v1.CompareTo(v2));
            });

            return(keyArray);
        }
Example #57
0
 /// <summary>
 /// Sorts a list of decks by deck level
 /// </summary>
 /// <param name="decks"></param>
 public static void SortByLevel(List <Deck> decks)
 {
     decks?.Sort((x, y) => (x.Level).CompareTo(y.Level));
 }
Example #58
0
            public override TextParserResult GetSpans(string s, IComparer <LinePositionSpanInfo> comparer = null)
            {
                StringBuilder sb = StringBuilderCache.GetInstance(s.Length - TokensLength);

                var startPending = false;
                LinePositionInfo            start = default;
                Stack <LinePositionInfo>    stack = null;
                List <LinePositionSpanInfo> spans = null;

                int lastPos = 0;

                int line   = 0;
                int column = 0;

                int length = s.Length;

                int i = 0;

                while (i < length)
                {
                    switch (s[i])
                    {
                    case '\r':
                    {
                        if (PeekNextChar() == '\n')
                        {
                            i++;
                        }

                        line++;
                        column = 0;
                        i++;
                        continue;
                    }

                    case '\n':
                    {
                        line++;
                        column = 0;
                        i++;
                        continue;
                    }

                    case '[':
                    {
                        char nextChar = PeekNextChar();
                        if (nextChar == '|')
                        {
                            sb.Append(s, lastPos, i - lastPos);

                            var start2 = new LinePositionInfo(sb.Length, line, column);

                            if (stack != null)
                            {
                                stack.Push(start2);
                            }
                            else if (!startPending)
                            {
                                start        = start2;
                                startPending = true;
                            }
                            else
                            {
                                stack = new Stack <LinePositionInfo>();
                                stack.Push(start);
                                stack.Push(start2);
                                startPending = false;
                            }

                            i      += 2;
                            lastPos = i;
                            continue;
                        }
                        else if (nextChar == '[' &&
                                 PeekChar(2) == '|' &&
                                 PeekChar(3) == ']')
                        {
                            i++;
                            column++;
                            CloseSpan();
                            i      += 3;
                            lastPos = i;
                            continue;
                        }

                        break;
                    }

                    case '|':
                    {
                        if (PeekNextChar() == ']')
                        {
                            CloseSpan();
                            i      += 2;
                            lastPos = i;
                            continue;
                        }

                        break;
                    }
                    }

                    column++;
                    i++;
                }

                if (startPending ||
                    stack?.Count > 0)
                {
                    throw new InvalidOperationException();
                }

                sb.Append(s, lastPos, s.Length - lastPos);

                spans?.Sort(comparer ?? LinePositionSpanInfoComparer.Index);

                return(new TextParserResult(
                           StringBuilderCache.GetStringAndFree(sb),
                           spans?.ToImmutableArray() ?? ImmutableArray <LinePositionSpanInfo> .Empty));

                char PeekNextChar()
                {
                    return(PeekChar(1));
                }

                char PeekChar(int offset)
                {
                    return((i + offset >= s.Length) ? '\0' : s[i + offset]);
                }

                void CloseSpan()
                {
                    if (stack != null)
                    {
                        start = stack.Pop();
                    }
                    else if (startPending)
                    {
                        startPending = false;
                    }
                    else
                    {
                        throw new InvalidOperationException();
                    }

                    var end = new LinePositionInfo(sb.Length + i - lastPos, line, column);

                    var span = new LinePositionSpanInfo(start, end);

                    (spans ??= new List <LinePositionSpanInfo>()).Add(span);

                    sb.Append(s, lastPos, i - lastPos);
                }
            }
Example #59
0
 public static List <T> SortEx <T>(this List <T> list)
 {
     list?.Sort();
     return(list);
 }
Example #60
0
        static void Main(string[] args)
        {
            List <Pessoa> listaPessoa = new List <Pessoa>();

            int opc;

            do
            {
                Console.WriteLine("Agenda telefonica");
                Console.WriteLine("1-Cadastrar Numero\n2-Excluir Numero\n3-Procurar por Contato\n4-Lista telefonica\n5-Impressão indiviual\n6-Quantidade de Contatos\n0-Sair");
                opc = int.Parse(Console.ReadLine());

                switch (opc)
                {
                case 1:
                    Console.Clear();
                    Console.WriteLine("Cadastro do contato");
                    Console.Write("Digite o nome:");
                    string nome = Console.ReadLine();
                    Console.Write("Digite o DDD:");
                    int ddd = int.Parse(Console.ReadLine());
                    Console.Write("Digite Numero:");
                    int num = int.Parse(Console.ReadLine());
                    Console.Write("Digite o tipo do telefone:");
                    string tipo = Console.ReadLine();

                    Pessoa nova = new Pessoa
                    {
                        Nome     = nome,
                        telefone = new List <Telefone> {
                            new Telefone {
                                DDD    = ddd,
                                Numero = num,
                                Tipo   = tipo
                            }
                        }
                    };
                    listaPessoa.Add(nova);
                    listaPessoa = listaPessoa.OrderBy(ordem => ordem.Nome).ToList();
                    listaPessoa.ForEach(i => Console.WriteLine(i.ToString() + "\n"));
                    break;

                case 2:
                    Console.Clear();
                    Console.WriteLine("Digite o nome de quem quer excluir:");
                    Console.WriteLine("Digite o nome da pessoa que deseja excluir:");
                    string excluir = (Console.ReadLine());
                    if (listaPessoa.Remove(listaPessoa.Find(contato => contato.Nome.Equals(excluir))))
                    {
                        Console.WriteLine("Contato removido com sucesso");
                    }
                    else
                    {
                        Console.WriteLine("Contato não localizado");
                    }

                    break;

                case 3:
                    Console.Clear();

                    Console.WriteLine("Procurar Por contato:");
                    string pesq = Console.ReadLine();
                    Console.WriteLine(listaPessoa?.Find(contato => contato.Nome.Equals(pesq)));

                    break;

                case 4:
                    Console.Clear();
                    Console.WriteLine("Impressão");
                    listaPessoa.ForEach(i => Console.WriteLine(i.ToString() + "\n"));

                    break;

                case 5:
                    Console.Clear();
                    Console.WriteLine("impressão Individual");

                    listaPessoa?.Sort((contato1, contato2) => contato1.Nome.CompareTo(contato2.Nome));

                    listaPessoa.ForEach(contato =>
                    {
                        Console.WriteLine(contato);

                        Console.WriteLine("deseja ir para o proximo: \nS - sim \nN - não ");
                        string op = Console.ReadLine();
                    });
                    break;

                case 6:
                    Console.Clear();
                    Console.WriteLine($"\nVocê tem {listaPessoa.Count()} contatos\n");
                    break;

                default:
                    Console.WriteLine("Opção Invalida!");
                    break;
                }
            } while (opc != 0);
        }