private void PollMessages(object state)
        {
            var copyOfCachedMessages = new HashSet<Message>(_messageCache);
            var sinceId = copyOfCachedMessages.OrderByDescending(x => x.Created).First().IdValue;
            var messageService = CreateBaseMessageService.Invoke();
            var messages = messageService.GetMessagesSinceAsync(sinceId).Result.ToList();

            if (messages.Count == 0)
                return;

            foreach (var message in messages)
            {
                copyOfCachedMessages.Add(message);
            }

            if (copyOfCachedMessages.Count > MaxCacheCount)
            {
                var reducedCachedMessages = 
                    copyOfCachedMessages
                        .OrderByDescending(x => x.Created)
                        .Take(MaxCacheCount);

                copyOfCachedMessages.Clear();

                foreach (var message in reducedCachedMessages)
                {
                    copyOfCachedMessages.Add(message);
                }
            }

            lock (_padlock)
            {
                _messageCache = copyOfCachedMessages;
            }
        }
示例#2
0
        static void Main(string[] args)
        {
            var dllFiles = Directory.GetFiles(DIR, "Plugin*.DLL", SearchOption.AllDirectories);
            var plugins  = new HashSet <Assembly>();

            var references = typeof(Program).Assembly.GetReferencedAssemblies();

            foreach (var dllPath in dllFiles.Where(x => new Regex(@"\d+").Match(x).Success))
            {
                string name = Path.GetFileNameWithoutExtension(dllPath);
                if (!references.Any(x => x.Name == name) && !plugins.Any(x => x.GetName().Name == name))
                {
                    plugins.Add(Assembly.LoadFrom(dllPath));
                }
            }


            foreach (var plugin in plugins.OrderBy(x => x.GetName().Name))
            {
                WriteData(plugin);
            }
            Console.WriteLine("");

            foreach (var plugin in plugins.OrderByDescending(x => x.GetName().Name))
            {
                WriteData(plugin);
            }
            Console.ReadKey();
        }
示例#3
0
        /// <summary>
        ///
        /// 耗时更多。。。
        ///
        /// Runtime: 112 ms, faster than 71.75% of C# online submissions for Sort Characters By Frequency.
        /// Memory Usage: 24.5 MB, less than 80.00% of C# online submissions for Sort Characters By Frequency.
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public string Try(string s)
        {
            int[] arr = new int[58];// 97 + 26 - 65

            HashSet <char> set = new HashSet <char>();

            for (int i = 0; i < s.Length; i++)
            {
                arr[s[i] - 65]++;
                if (!set.Contains(s[i]))
                {
                    set.Add(s[i]);
                }
            }

            StringBuilder builder = new StringBuilder();

            foreach (var item in set.OrderByDescending(u => arr[u - 65]))
            {
                for (int i = 0; i < arr[item - 65]; i++)
                {
                    builder.Append(item);
                }
            }

            return(builder.ToString());
        }
示例#4
0
        /// <summary>
        /// 得到动画的播出年份
        ///
        /// 例如,有一串动画,播出年份分别是
        /// 2018年,2008年,2018年,2017年,
        /// 那么返回就是2018年2008年2017年
        ///
        /// 相当于去除重复?
        ///
        /// </summary>
        /// <param name="animes">动画链表</param>
        /// <returns></returns>
        public List <int> GetAnimeYears(List <Anime> animes)
        {
            HashSet <int> year = new HashSet <int>();

            if (animes == null)
            {
                return(new List <int>());
            }

            Span <Anime> anime = new Span <Anime>(animes.ToArray());

            //长度
            int l = anime.Length;
            int Y;

            for (int i = 0; i < l; i++)
            {
                Y = anime[i].AnimePlayTime.Year;
                if (year.Contains(Y))
                {
                    continue;
                }
                else
                {
                    year.Add(Y);
                }
            }
            return(year.OrderByDescending(r => r).ToList());
        }
示例#5
0
        /// <summary>
        /// Gets the list of years and months.
        /// </summary>
        /// <param name="transactions">The list of transactions.</param>
        /// <param name="greaterOrEqualThanDate">Optional filter to select only years and months greater or equal to the specified date.</param>
        /// <returns>The list of year and months keys.</returns>
        public IEnumerable <YearMonthKey> GetMonthsInTransaction(IEnumerable <BankTransaction> transactions, DateTime?greaterOrEqualThanDate)
        {
            ISet <YearMonthKey> distinctMonths = new HashSet <YearMonthKey>();

            if (transactions == null)
            {
                return(new List <YearMonthKey>());
            }

            // Get the list of all distint months.
            foreach (var transaction in transactions)
            {
                if (greaterOrEqualThanDate != null && greaterOrEqualThanDate.HasValue)
                {
                    if (transaction.TransactionTime < greaterOrEqualThanDate.Value)
                    {
                        // Skip this transaction.
                        continue;
                    }
                }

                YearMonthKey monthKey = new YearMonthKey(
                    transaction.TransactionTime.Year, transaction.TransactionTime.Month);

                distinctMonths.Add(monthKey);
            }

            return(distinctMonths
                   .OrderByDescending(m => m.Year)
                   .ThenByDescending(m => m.Month));
        }
示例#6
0
        private static void VerificarGanhador(List <Log> lista, DateTime inicioProva)
        {
            var rank = new HashSet <Rank>();

            foreach (var item in lista)
            {
                var corredor = (Rank)item;
                corredor.TempoTotal = corredor.Hora.Subtract(inicioProva).TotalMilliseconds;
                rank.Add(corredor);
            }

            var podium = rank.OrderByDescending(x => x.QuantidadeVoltas).ThenBy(x => x.Hora).ToArray();

            for (int i = 0; i < podium.Count(); i++)
            {
                if (i == 0)
                {
                    var tempoTotal = podium[i].TempoTotal;

                    Console.WriteLine("Tempo total de prova: {0} ms\n", tempoTotal);
                }

                Console.WriteLine("{0} {1}", i + 1, podium[i]);
            }
        }
        private static Tile GetStartLoc(Civilization civilization, GameInitializationConfig config, Map map)
        {
            var maxFertility = 0m;
            var tiles        = new HashSet <Tile>();

            for (int y = 0; y < map.Tile.GetLength(1); y++)
            {
                for (int x = 0; x < map.Tile.GetLength(0); x++)
                {
                    var tile = map.Tile[x, y];
                    if (tile.Fertility < maxFertility)
                    {
                        continue;
                    }
                    if (tile.Fertility > maxFertility)
                    {
                        tiles.Clear();
                        maxFertility = tile.Fertility;
                    }

                    tiles.Add(tile);
                }
            }

            var selectedTile = tiles.OrderByDescending(t => DistanceToNearestStart(config, t)).First();

            config.StartTiles.Add(selectedTile);
            map.SetAsStartingLocation(selectedTile, civilization.Id);
            return(selectedTile);
        }
示例#8
0
        private int OptimizationAttempt1(int numDigits)
        {
            if (numDigits == 1)
            {
                return(9);
            }

            var upperLimit = (int)Math.Pow(10, numDigits) - 1;
            var lowerLimit = upperLimit - (int)Math.Pow(10, numDigits - 1);

            var           range   = new EulerRange(lowerLimit, upperLimit);
            HashSet <int> numbers = new HashSet <int>();

            //Get every multiple
            foreach (var item in range)
            {
                range.Select(x => numbers.Add(item * x)).ToList();
            }

            foreach (var item in numbers.OrderByDescending(x => x))
            {
                if (NumberStringHelper.IsNumberPalindrome(item))
                {
                    return(item);
                }
            }
            return(-1);
        }
示例#9
0
        private static Tuple <int, int> Solve(int A, int B, int C, int D, int E, int F)
        {
            var set   = new HashSet <Tuple <int, int> >();
            var queue = new Queue <Tuple <int, int> >();
            var zero  = new Tuple <int, int>(0, 0);

            set.Add(zero);
            queue.Enqueue(zero);
            while (queue.Count > 0)
            {
                var t1 = queue.Dequeue();
                int w1 = t1.Item1;
                int s1 = t1.Item2;
                foreach (var t2 in new[] { new Tuple <int, int>(w1 + 100 * A, s1),
                                           new Tuple <int, int>(w1 + 100 * B, s1),
                                           new Tuple <int, int>(w1, s1 + C),
                                           new Tuple <int, int>(w1, s1 + D) })
                {
                    int w2 = t2.Item1;
                    int s2 = t2.Item2;
                    if (!set.Contains(t2) && w2 * E >= s2 * 100 && w2 + s2 <= F)
                    {
                        set.Add(t2);
                        queue.Enqueue(t2);
                    }
                }
            }
            return(set.OrderByDescending(t => (double)t.Item2 / (t.Item1 + t.Item2)).ElementAt(0));
        }
 private static void PrintTrainers(HashSet <Trainer> trainers)
 {
     foreach (var trainer in trainers.OrderByDescending(p => p.NumberOfBadges))
     {
         Console.WriteLine(trainer);
     }
 }
        private void UpdateGameVersionComboBox(bool TriggeredByRefresh = false)
        {
            HashSet <string> versionNames = GetGameVersionsFromSpreadsheet(TriggeredByRefresh);

            // Sort versions descending
            IEnumerable <string> sortedVersions = versionNames.OrderByDescending(v => int.Parse(v));

            if (sortedVersions.Count() > 0)
            {
                LatestVersion = int.Parse(sortedVersions.First());
            }

            // Update game version ComboBox values
            cmbGameVersion.Items.Clear();

            cmbGameVersion.Items.Add("Latest");

            foreach (var ver in sortedVersions)
            {
                cmbGameVersion.Items.Add(ver);
            }

            cmbGameVersion.SelectedItem = "Latest";

            GameVersionComboBoxValuesDirty = false;
        }
        private void ReductElement()
        {
            HashSet <int> elems = new HashSet <int>();

            for (int i = 0; i < elements.Count; i++)
            {
                if (elems.Contains(i))
                {
                    continue;
                }
                for (int j = i + 1; j < elements.Count; j++)
                {
                    if (elems.Contains(j))
                    {
                        continue;
                    }
                    if (elements[i].IsNegative(elements[j]))
                    {
                        elems.Add(i);
                        elems.Add(j);
                        break;
                    }
                }
            }
            foreach (var idx in elems.OrderByDescending(e => e))
            {
                elements.RemoveAt(idx);
            }
        }
示例#13
0
    public int FindLUSlength(string[] strs)
    {
        ISet <string> one = new HashSet <string>(), multiple = new HashSet <string>();

        foreach (string s in strs)
        {
            if (one.Contains(s))
            {
                one.Remove(s);
                multiple.Add(s);
            }
            else
            {
                if (!multiple.Contains(s))
                {
                    one.Add(s);
                }
            }
        }

        foreach (string p in one.OrderByDescending(p => p.Length))
        {
            if (!multiple.Any(s => isSubsequence(p, s)))
            {
                return(p.Length);
            }
        }
        return(-1);
    }
示例#14
0
        public static void Main(string[] args)
        {
            var names = new HashSet <string>();

            names.Add("Sonoo");
            names.Add("Ankit");
            names.Add("Peter");
            names.Add("Irfan");
            names.Add("Ankit");//will not be added

            // Iterate HashSet elements using foreach loop
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }

            names = names.OrderBy(i => i).ToHashSet();     // Ascending order sort
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }

            Console.WriteLine();

            names = new HashSet <String>(names.OrderByDescending(i => i));        // Discending order sort
            foreach (var name in names)
            {
                Console.WriteLine(name);
            }
        }
示例#15
0
        void RecalculatePriority()
        {
            if (debug)
            {
                Debug.Log("Recalculating music zone priorities...");
            }

            orderedZones.Clear();
            orderedZones = activeZones.OrderByDescending(track => track.priority).ToList();

            // If there are no music zones left, just pause whatever is playing.
            if (orderedZones.Count < 1)
            {
                if (currentTrackSource)
                {
                    currentTrackSource.Pause();
                }

                return;
            }

            // Play the highest priority music zone from the list (index 0)
            var topMusicZone = orderedZones[0];

            Play(topMusicZone);
        }
示例#16
0
 private void InvalidateNodes(HashSet <RdcTreeNode> set)
 {
     foreach (RdcTreeNode item in set.OrderByDescending((RdcTreeNode n) => n, new InvalidateComparer()))
     {
         item.InvalidateNode();
     }
 }
示例#17
0
        private (Yaku, int) Flags()
        {
            var bestHan = 0;
            var bestFu  = 0;
            var results = new HashSet <Yaku>();

            foreach (var arrangement in _arrangements)
            {
                var(yaku, fu) = YakuForArrangement(arrangement);
                var han = Han.Calculate(yaku);

                if (han > bestHan || han == bestHan && fu > bestFu)
                {
                    results.Clear();
                    bestHan = han;
                    bestFu  = fu;
                }

                if (han == bestHan && fu == bestFu)
                {
                    results.Add(yaku);
                }
            }

            return(results.OrderByDescending(x => x).First(), bestFu);
        }
示例#18
0
        /// <summary>
        /// Highlight the any regex matches in the html
        /// </summary>
        public static string ApplyHighlights(string html, string colour, IEnumerable <Regex> regexes)
        {
            ISet <string> allMatches = new HashSet <string>();

            string openTag  = string.Format("<span style=\"background:{0};\">", colour);
            string closeTag = "</span>";

            foreach (Regex regex in regexes)
            {
                MatchCollection matches = regex.Matches(html);

                foreach (Match match in matches)
                {
                    // make sure doesn't contain html
                    if (match.Value.Contains("<"))
                    {
                        continue;
                    }

                    allMatches.Add(match.Value);
                }
            }

            IList <string> orderedMatches = allMatches.OrderByDescending(a => a.Length).ToList();

            foreach (string match in orderedMatches)
            {
                html = html.Replace(match, openTag + match + closeTag);
            }

            return(html);
        }
示例#19
0
        public void WriteListings()
        {
            HashSet<ArchiveListing> set = new HashSet<ArchiveListing>();
            foreach (ArchiveListing listing in _set)
            {
                ArchiveListing item = listing;
                while (item != null && set.Add(item))
                    item = item.Parent;
            }

            Action<ArchiveListing> writer;
            switch (InteractionService.GamePart)
            {
                case FFXIIIGamePart.Part1:
                    writer = ArchiveListingWriterV1.Write;
                    break;
                case FFXIIIGamePart.Part2:
                    writer = ArchiveListingWriterV2.Write;
                    break;
                default:
                    throw new NotSupportedException(InteractionService.GamePart.ToString());
            }

            foreach (ArchiveListing listing in set.OrderByDescending(l => l.Accessor.Level))
                writer(listing);
        }
示例#20
0
        /// <summary>
        ///   Analyzes the <paramref name="model" /> via reflection to discover all root <see cref="IComponent" /> instances.
        /// </summary>
        /// <param name="model">The model the roots should be discovered for.</param>
        internal static void DiscoverRoots(ModelBase model)
        {
            Requires.NotNull(model, nameof(model));

            const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
            var components = new HashSet <IComponent>(ReferenceEqualityComparer <IComponent> .Default);
            var kinds      = new Dictionary <IComponent, RootKind>(ReferenceEqualityComparer <IComponent> .Default);

            CollectRoots(components, kinds, model.GetType().GetFields(bindingFlags), info => info.FieldType,
                         info => info.GetValue(model));
            CollectRoots(components, kinds, model.GetType().GetProperties(bindingFlags), info => info.PropertyType,
                         info => info.CanRead ? info.GetValue(model) : null);
            CollectRoots(components, kinds, model.GetType().GetMethods(bindingFlags), info => info.ReturnType, info =>
            {
                if (info.GetParameters().Length == 0)
                {
                    return(info.Invoke(model, new object[0]));
                }

                return(null);
            });

            if (components.Count == 0)
            {
                throw new InvalidOperationException(
                          $"At least one property, field, or method of the model must be marked with '{typeof(RootAttribute).FullName}'.");
            }

            model.Roots = components.OrderByDescending(component => kinds[component]).ToArray();
        }
示例#21
0
        public void WriteListings()
        {
            HashSet <ArchiveListing> set = new HashSet <ArchiveListing>();

            foreach (ArchiveListing listing in _set)
            {
                ArchiveListing item = listing;
                while (item != null && set.Add(item))
                {
                    item = item.Parent;
                }
            }

            Action <ArchiveListing> writer;

            switch (InteractionService.GamePart)
            {
            case FFXIIIGamePart.Part1:
                writer = ArchiveListingWriterV1.Write;
                break;

            case FFXIIIGamePart.Part2:
                writer = ArchiveListingWriterV2.Write;
                break;

            default:
                throw new NotSupportedException(InteractionService.GamePart.ToString());
            }

            foreach (ArchiveListing listing in set.OrderByDescending(l => l.Accessor.Level))
            {
                writer(listing);
            }
        }
示例#22
0
        public static int FindPrimitive(int n)
        {
            HashSet <int> s = new HashSet <int>();

            int phi = n - 1;

            FindPrimefactors(s, phi);

            var d = s.OrderByDescending(prim => prim);

            for (int r = phi - 1; r >= 2; r--)
            {
                bool flag = false;

                foreach (int a in d)
                {
                    if (Power(r, phi / (a), n) == 1)
                    {
                        flag = true;
                        break;
                    }
                }

                if (!flag)
                {
                    return(r);
                }
            }
            return(-1);
        }
示例#23
0
        public static List <int[]> ChooseSets(IList <int[]> sets, IList <int> universe)
        {
            var result = new List <int[]>();

            var universeSet = new HashSet <int>(universe);
            var setsSet     = new HashSet <int[]>(sets);

            while (universeSet.Count > 0)
            {
                //take the set with maximum CONTAINED elements, not just maximum elements in a set!
                //my bad
                var currentSet = setsSet
                                 .OrderByDescending
                                     (s => s.Count(e => universeSet.Contains(e)))
                                 .First();

                result.Add(currentSet);


                foreach (var number in currentSet)
                {
                    universeSet.Remove(number);
                }
            }

            return(result);
        }
示例#24
0
        public (int startLine, int startColumn, int endLine, int endColumn) GetExtents()
        {
            var start = methods.OrderBy(m => m.StartLocation.Line).ThenBy(m => m.StartLocation.Column).First();
            var end   = methods.OrderByDescending(m => m.EndLocation.Line).ThenByDescending(m => m.EndLocation.Column).First();

            return(start.StartLocation.Line, start.StartLocation.Column, end.EndLocation.Line, end.EndLocation.Column);
        }
        public static List <int[]> ChooseSets(IList <int[]> sets, IList <int> universe)
        {
            HashSet <int[]> setsHash     = new HashSet <int[]>(sets);
            HashSet <int>   universeHash = new HashSet <int>(universe);

            List <int[]> resultSets = new List <int[]>();

            while (universeHash.Any())
            {
                int[] currentSet = setsHash
                                   .OrderByDescending(s => s.Count(el => universeHash.Contains(el)))
                                   .First();

                resultSets.Add(currentSet);

                foreach (var element in currentSet)
                {
                    if (universeHash.Contains(element))
                    {
                        universeHash.Remove(element);
                    }
                }
            }

            return(resultSets);
        }
示例#26
0
        private void LoadAllDirectionals()
        {
            var items = new HashSet <string>();

            foreach (var dir in _directionTranslationMap.Split(new char[] { ':', ',', ';' }))
            {
                items.Add(dir);
            }

            _allDirectionals = new HashSet <string>(items.OrderByDescending(x => x.Length), StringComparer.OrdinalIgnoreCase);

            items = new HashSet <string>();
            foreach (var dir in _onePartDirectionalsMap.Split(new char[] { ':', ',', ';' }))
            {
                items.Add(dir);
            }

            _onePartDirectionals = new HashSet <string>(items.OrderByDescending(x => x.Length), StringComparer.OrdinalIgnoreCase);

            items = new HashSet <string>();
            foreach (var dir in _twoPartDirectionalsMap.Split(new char[] { ':', ',', ';' }))
            {
                items.Add(dir);
            }

            _twoPartDirectionals = new HashSet <string>(items.OrderByDescending(x => x.Length), StringComparer.OrdinalIgnoreCase);
        }
示例#27
0
        internal static IEnumerable <PhotoGroupTDO> GetProcessedPhotoGroupsByDate(Event ev, FotoShoutDbContext db)
        {
            IEnumerable <IGrouping <string, Photo> > photoGroups = ev.Photos.Where(p => (p.Status == (byte)PhotoStatus.Submitted || p.Status == (byte)PhotoStatus.PendingPublish || p.Status == (byte)PhotoStatus.Published)).GroupBy(p => p.Created.ToShortDateString());

            HashSet <PhotoGroupTDO> tdos = new HashSet <PhotoGroupTDO>();

            if (!photoGroups.Any())
            {
                return(tdos);
            }

            foreach (IGrouping <string, Photo> photoGroup in photoGroups)
            {
                if (photoGroup.Any())
                {
                    PhotoGroupTDO tdo = new PhotoGroupTDO {
                        Created   = DateTime.Parse(photoGroup.Key),
                        NumPhotos = photoGroup.Count(),
                        Thumbnail = AppConfigs.VirtualRoot + photoGroup.FirstOrDefault().Thumbnail
                    };
                    tdos.Add(tdo);
                }
            }

            return(tdos.OrderByDescending(tdo => tdo.Created));
        }
        /// <summary>
        /// 分词
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public List <string> CutKeywords(string keyword)
        {
            if (_memoryCache.TryGetValue(keyword, out List <string> list))
            {
                return(list);
            }

            var set = new HashSet <string>
            {
                keyword
            };
            var mc = Regex.Matches(keyword, @"(([A-Z]*[a-z]*)[\d]*)([\u4E00-\u9FA5]+)*((?!\p{P}).)*");

            foreach (Match m in mc)
            {
                set.Add(m.Value);
                foreach (Group g in m.Groups)
                {
                    set.Add(g.Value);
                }
            }

            var segmenter = new JiebaSegmenter();

            foreach (string word in segmenter.CutForSearch(keyword))
            {
                set.Add(word);
            }
            set.RemoveWhere(s => s.Length < 2 || Regex.IsMatch(s, @"^\p{P}.*"));
            list = set.OrderByDescending(s => s.Length).ToList();
            _memoryCache.Set(keyword, list, TimeSpan.FromHours(1));
            return(list);
        }
        static void Main(string[] args)
        {
            HashSet <Trainer> trainers = new HashSet <Trainer>();

            while (true)
            {
                string input = Console.ReadLine();

                if (input == "Tournament")
                {
                    break;
                }

                string[] inputInfo      = input.Split(" ", StringSplitOptions.RemoveEmptyEntries);
                string   trainerName    = inputInfo[0];
                string   pokemonName    = inputInfo[1];
                string   pokemonElement = inputInfo[2];
                int      pokemonHealth  = int.Parse(inputInfo[3]);

                Pokemon pokemon = new Pokemon(pokemonName, pokemonElement, pokemonHealth);

                if (!trainers.Any(n => n.Name == trainerName))
                {
                    Trainer trainer = new Trainer(trainerName, 0, new List <Pokemon>());
                    trainer.Pokemons.Add(pokemon);
                    trainers.Add(trainer);
                }
                else
                {
                    foreach (var trainer in trainers)
                    {
                        if (trainer.Name == trainerName)
                        {
                            trainer.Pokemons.Add(pokemon);
                        }
                    }
                }
            }

            while (true)
            {
                string command = Console.ReadLine();

                if (command == "End")
                {
                    break;
                }
                if (command == "Fire" || command == "Water" || command == "Electricity")
                {
                    TrainerAndPokemon(trainers, command);
                }
            }

            trainers = trainers.OrderByDescending(n => n.NumberOfBadges).ToHashSet();

            foreach (var trainer in trainers)
            {
                Console.WriteLine(trainer);
            }
        }
示例#30
0
        public IEnumerable <Order> GetListForShipper(string userID, List <string> FindByUser, string OrderID)
        {
            HashSet <Order> result = new HashSet <Order>();

            if (FindByUser.Count > 0)
            {
                foreach (var FindUser in FindByUser)
                {
                    var listTemp = _unitOfWork.OrderRepository
                                   .Where(user => user.Shipper == userID && user.State != 1 && user.UserId.ToLower().Contains(FindUser.ToLower()));
                    foreach (var temp in listTemp)
                    {
                        result.Add(temp);
                    }
                }
            }
            else
            {
                var listTemp = _unitOfWork.OrderRepository
                               .Where(order => order.State != 1 && order.Id.ToString().Contains(OrderID.ToLower()));
                foreach (var temp in listTemp)
                {
                    result.Add(temp);
                }
            }

            return(result.OrderByDescending(sort => sort.CreateDate).AsEnumerable());
        }
示例#31
0
        public static void UpdateCharset(TftConfig.CharSet charSet, string assetDirectory, bool sortByFrequency = false)
        {
            if (string.IsNullOrEmpty(charSet.ExtractFromDictionaries))
            {
                return;
            }
            var characters = new HashSet <char>();
            var frequency  = new Dictionary <char, int>();
            var dict       = new LocalizationDictionary();

            foreach (var localization in charSet.ExtractFromDictionaries.Split(','))
            {
                // cause EN is default dictionary
                var loc      = localization == "EN" ? string.Empty : localization;
                var dictPath = AssetPath.Combine(assetDirectory, Localization.DictionariesPath,
                                                 $"Dictionary.{loc}.txt".Replace("..", "."));
                if (!File.Exists(dictPath))
                {
                    Console.WriteLine($"Dictionary of {localization} localization is missing!: {dictPath}");
                    continue;
                }
                using (var stream = File.Open(dictPath, FileMode.Open)) {
                    dict.ReadFromStream(stream);
                }
                ExtractCharacters(dict, characters, frequency);
            }
            charSet.Chars = string.Join("", sortByFrequency ?
                                        characters.OrderByDescending(c => frequency[c]) : characters.OrderBy(c => c));
        }
示例#32
0
        /// <summary>
        /// Returns only the latest id/version combination for each package. Older edits are ignored.
        /// </summary>
        /// <param name="start">End time of the previous window. Commits exactly matching the start time will NOT be included. This is designed to take the cursor time.</param>
        /// <param name="end">Maximum time to include. Exact matches will be included.</param>
        /// <param name="token">Cancellation token.</param>
        /// <returns>Entries within the start and end time. Start time is NOT included.</returns>
        public async Task <IReadOnlyList <CatalogEntry> > GetFlattenedEntriesAsync(DateTimeOffset start, DateTimeOffset end, CancellationToken token)
        {
            var set     = new HashSet <CatalogEntry>();
            var deleted = new HashSet <CatalogEntry>();

            var entries = await GetEntriesCommitTimeDescAsync(start, end, token);

            foreach (var entry in entries)
            {
                if (entry.IsDelete)
                {
                    // Mark as deleted, this has no
                    // impact if the package was re-added. It will
                    // already be in the set in that case.
                    deleted.Add(entry);
                }
                else if (entry.IsAddOrUpdate && !deleted.Contains(entry))
                {
                    // ignore items we have already seen
                    set.Add(entry);
                }
            }

            return(set.OrderByDescending(e => e.CommitTimeStamp).ToList());
        }
示例#33
0
        public void WriteListings()
        {
            HashSet<ArchiveListing> set = new HashSet<ArchiveListing>();
            foreach (ArchiveListing listing in _set)
            {
                ArchiveListing item = listing;
                while (item != null && set.Add(item))
                    item = item.Parent;
            }

            foreach (ArchiveListing listing in set.OrderByDescending(l => l.Accessor.Level))
                ArchiveListingWriter.Write(listing);
        }
        internal IEnumerable<RepositoryCommitModel> GetTags(string name, int page, int p, out string referenceName, out int totalCount)
        {
            var commit = GetCommitByName(name, out referenceName);
            if (commit == null)
            {
                totalCount = 0;
                return Enumerable.Empty<RepositoryCommitModel>();
            }
            var tags = _repository.Tags;
            var commits = new HashSet<RepositoryCommitModel>(AnonymousComparer.Create<RepositoryCommitModel>((x, y) => x.ID == y.ID, obj => obj.ID.GetHashCode()));
            foreach (var tag in tags)
            {
                var c = _repository.Lookup(tag.Target.Id) as Commit;
                commits.Add(ToModel(c));

            }
            totalCount = commits.Count();

            return commits.OrderByDescending(x => x, (x, y) => x.Date.CompareTo(y.Date));
        }
示例#35
0
 static void Main(string[] args)
 {
     Console.WriteLine(11111);
     //SortedSet<TestSort> s = new SortedSet<TestSort>(new TestSort[] {new TestSort {Name="bar", Age=1}});
     HashSet<TestSort> s = new HashSet<TestSort>();
     s.Add(  new TestSort {Name="foo6", Age=6} );
     s.Add(  new TestSort {Name="bar1", Age=1} );
     s.Add(  new TestSort {Name="hoge5", Age=5} );
     //SortedSet<TestSort> s = new SortedSet<TestSort>(new TestSort[] {
     //  new TestSort {Name="foo", Age=6},
     //  new TestSort {Name="bar", Age=1},
     //  new TestSort {Name="hoge", Age=5},
     //});
     Console.WriteLine(22222);
     Console.WriteLine(s);
     IEnumerable<TestSort>new_s = s.OrderByDescending(pet => pet.Age);
     foreach (TestSort ts in new_s)
     {
       Console.WriteLine(ts.Name);
     }
 }
示例#36
0
        public List<LSHashTweet> GetNearestNeighbors(LSHashTweet tweet, int n)
        {
            if (_content.Count == 0)
                return new List<LSHashTweet>();

            HashSet<LSHashTweet> candidates = new HashSet<LSHashTweet>();
            List<long> wordIDs = tweet.Vector.GetItemIDs();
            foreach (long wordID in wordIDs)
            {
                if (_wordIndex.ContainsKey(wordID))
                {
                    foreach (LSHashTweet candidate in _wordIndex[wordID])
                        candidates.Add(candidate);
                }
            }

            if (candidates.Count == 0)
                return new List<LSHashTweet>();

            return candidates.OrderByDescending(t => t.Vector * tweet.Vector).Take(n).ToList();
        }
		public static ulong[] GetScores()
		{
			var scores = new HashSet<ulong>();

			// row scores.
			for (var col = 0; col < 4; col++)
			{
				for (var row = 0; row < 6; row++)
				{
					ulong line = 0x0F;
					line <<= col + (row << 3);
					scores.Add(line);
				}
			}

			// column scores.
			for (var col = 0; col < 7; col++)
			{
				for (var row = 0; row < 3; row++)
				{
					ulong line = 0x01010101;
					line <<= col + (row << 3);
					scores.Add(line);
				}
			}
			// diagonal scores.
			for (var col = 0; col < 4; col++)
			{
				for (var row = 0; row < 3; row++)
				{
					ulong dig0 = 0x08040201;
					ulong dig1 = 0x01020408;
					dig0 <<= col + (row << 3);
					dig1 <<= col + (row << 3);
					scores.Add(dig0);
					scores.Add(dig1);
				}
			}
			return scores.OrderByDescending(s => s).ToArray();
		}
        /// <summary>
        /// Writes a player to the scoreboard database.
        /// </summary>
        /// <param name="player">PLayer to be written.</param>
        public void WriteToScoreBoard(IPlayer player)
        {
            ICollection<IPlayer> currentScoreBoard = new HashSet<IPlayer>();
            currentScoreBoard = this.ReadScoreboard();

            bool reorder = true;
            foreach (var currPlayer in currentScoreBoard.Where(cp => cp.Name == player.Name))
            {
                if (currPlayer.Score <= player.Score)
                {
                    currPlayer.Score = player.Score;
                    reorder = false;
                }
            }

            var sortedScoreBoard = currentScoreBoard;
            if (reorder)
            {
                currentScoreBoard.Add(player);
                sortedScoreBoard = currentScoreBoard.OrderByDescending(pl => Convert.ToInt32(pl.Score)).ThenBy(pl => pl.Name).ToList();
            }

            DataSerialization.WriteToFile(sortedScoreBoard, FileNames.scoreboard);
        }
示例#39
0
 /// <summary>
 /// Finds the most common word
 /// </summary>
 /// <param name="rank">How far down the list you want to go. for example if you wanted the 4th equal words you's pass 3</param>
 /// <returns>a list of either one or more strings that represtent the word or words equally tied at that rank</returns>
 public List<string> FindMostCommonWord(int rank)
 {
     var groupedWords = Words.GroupBy(e => e.WordText) // this linq statement groups and counts words based on their length
         .Select(group => new { Value = group.Key, Count = group.Count() })
         .OrderByDescending(x => x.Count)
         .ToList();
     ISet<int> commoness = new HashSet<int>();
     foreach (var item in groupedWords)
     {
         commoness.Add(item.Count); // add the count of each word to the set
     }
     int i = commoness.OrderByDescending(e => e).ToList()[rank]; // this gets the number of times the most common word occured
     List<string> commonWords = new List<string>();
     foreach (var word in groupedWords.Where(e => e.Count == i)) // this filters for words that occured that many times
     {
         commonWords.Add(word.Value);
     }
     return commonWords;
 }
示例#40
0
 /// <summary>
 /// This gets the longest words excluding punctuation 
 /// </summary>
 /// <param name="rank">How far down the list you want to go. for example if you wanted the 4th equal words you's pass 3</param>
 /// <returns>a list of either one or more strings that represtent the word or words equally tied at that rank</returns>
 public List<string> FindLongestWord(int rank)
 {
     ISet<int> wordLengths = new HashSet<int>(); // a set is needed for this because we need to avoid duplication i.e. two words of length 13 should only be counted once
     foreach (Word word in Words)
     {
         wordLengths.Add(word.WordLength); // add the lengths of all words to the set
     }
     List<int> sortedWordLengths = wordLengths.OrderByDescending(e => e).ToList(); // sort them from highest to lowest so we can fetch highest, 3rd highest, etc
     List<string> longestWords = new List<string>();
     int wordLength = 0;
     try
     {
         wordLength = sortedWordLengths[rank]; // try to use what has been passed in with the rank parameter but it might be out of range
     }
     catch (IndexOutOfRangeException)
     {
         wordLength = sortedWordLengths.Last(); // if out of range just call the last one (this doesn't help if there's nothing in the list though)
     }
     foreach (Word word in Words.Where(e => e.WordLength == wordLength)) // filter words by their length, the length to use is calc using rank
     {
         longestWords.Add(word.WordText);
     }
     return longestWords;
 }
示例#41
0
 public void RemoveActivities(System.Collections.IList items)
 {
     var indexes = new HashSet<int>();
     foreach (Activity activity in items) {
         indexes.Add(this.Activities.IndexOf(activity));
     }
     foreach (int index in indexes.OrderByDescending(i=>i))
     {
         this.Activities.RemoveAt(index);
     }
 }
示例#42
0
        private void UpdateBehaviorTreeView()
        {
            behaviorTreeView.BeginUpdate();
            behaviorTreeView.Nodes.Clear();

            var rootKeys = new HashSet<string>(BT.Roots().Select(r => r.Key));
            foreach (var key in PublicRoots)
                rootKeys.Add(key);

            foreach (var key in rootKeys.OrderByDescending(k => PublicRoots.Contains(k)).ThenBy(k => k))
            {
                Behavior root;
                if (BT.Tree.TryGetValue(key, out root))
                {
                    var btPath = new BTPath { Path = new List<Behavior>() };
                    var newNode = AddNode(btPath, root, behaviorTreeView.Nodes);
                    btPath.Path.Add(root);
                    Expand(newNode, btPath);

                    if (expandedPaths.Contains(newNode.Tag.ToString()))
                        newNode.Expand();
                }
            }
            behaviorTreeView.EndUpdate();

            if (configParser.Errors.Count > 0 || analyzer.Errors.Count > 0)
            {
                errorListBox.BeginUpdate();
                errorListBox.Items.Clear();

                foreach (var error in configParser.Errors)
                    errorListBox.Items.Add(error);
                foreach (var error in analyzer.Errors)
                    errorListBox.Items.Add(error);

                errorListBox.EndUpdate();

                errorListBox.Show();
                errorLabel.Show();
            }
            else
            {
                errorListBox.Hide();
                errorLabel.Hide();
            }

            overviewTooltipStatuslabel.Text = string.Format("{0} files, {1} nodes", layers.Count(l => l.Enabled),
                BT.Tree.Count);

            expandedPaths.Clear();
        }
        public Task<IEnumerable<Message>> GetMessagesAsync()
        {
            var copyOfCachedMessages = new HashSet<Message>(_messageCache);

            return Task.FromResult(
                copyOfCachedMessages
                    .OrderByDescending(x => x.Created)
                    .Take(Count));
        }
示例#44
0
 private void GetAllVariablesByDescending()
 {
     var variables = new HashSet<Variable>();
     foreach (var equation in _equationsList)
     {
         equation.MoveAllVarsToLeft();
         foreach (var expression in equation.LeftPart)
         {
             var variable = expression.Variable;
             if (!variable.Equals(Variable.NULL))
                 variables.Add(variable);
         }
     }
     _variablesList = variables.OrderByDescending(x => x.Name).ToList();
 }
示例#45
0
 /// <summary>
 /// Finds a list of sentances with the highest or highest equal word count
 /// </summary>
 /// <returns>Returns a list containing either a single or mulitple sentences</returns>
 public List<Sentence> FindSentenceWithMostWords(int rank)
 {
     ISet<int> sentenceWordCount = new HashSet<int>(); // a set is needed for this because we need to avoid duplication i.e. two sentances of count 13 should only be counted once
     foreach (Sentence sentence in Sentences) // this loop adds the word count of each sentence to the set
     {
         sentenceWordCount.Add(sentence.WordCount);// if a count already exists, say there has already been a count of 13, it trys to add a different sentence that has a count of 13, this statement will skip over that silently
     }
     List<int> sortedSentenceWordCount = sentenceWordCount.OrderByDescending(e => e).ToList(); // the set in order say { 16, 7, 13 } need to be sorted to { 16, 13, 7 }
     return Sentences.Where(e => e.WordCount == sortedSentenceWordCount[rank]).ToList(); // this gets all the sentances with the requird word count
 }
        private static void ShowAchievementUnlocked(Achievement a)
        {
            var content = new GUIContent("ACHIEVEMENT UNLOCKED\n" + a.Title, GetIcon ());

            // Find the best window to display this on
            var allWindows = new HashSet<EditorWindow>((EditorWindow[])Resources.FindObjectsOfTypeAll(typeof(EditorWindow)));
            allWindows.RemoveWhere (IsEditorWindowHiddenTab);

            var targetWindow = allWindows.OrderByDescending(w => Mathf.Pow(w.position.width, WidthBias) * w.position.height).FirstOrDefault();
            if(targetWindow)
            {
            targetWindow.ShowNotification(content);
            }

            Debug.Log (string.Format("ACHIEVEMENT UNLOCKED: {0}\n{1}\n\n\n\n\n", a.Title, a.Description));
        }
示例#47
0
        private static IEnumerable<Obj_AI_Hero> TargetWeights(List<Obj_AI_Hero> targets)
        {
            try
            {
                foreach (var item in WeightedItems.Where(w => w.Weight > 0))
                {
                    item.UpdateMinMax(targets);
                }

                var targetsList = new HashSet<Target>();
                var multiplicator =
                    _menu.Item(_menu.Name + ".weights.heroes.weight-multiplicator").GetValue<Slider>().Value;
                foreach (var target in targets)
                {
                    var tmpWeight = WeightedItems.Where(w => w.Weight > 0).Sum(w => w.CalculatedWeight(target));
                    if (_menu != null)
                    {
                        tmpWeight +=
                            (_menu.Item(_menu.Name + ".weights.heroes." + target.ChampionName).GetValue<Slider>().Value *
                             _averageWeight + 0.1f) * multiplicator;
                    }

                    targetsList.Add(new Target(target, tmpWeight));
                }
                return targetsList.Count > 0 ? targetsList.OrderByDescending(t => t.Weight).Select(t => t.Hero) : null;
            }
            catch (Exception ex)
            {
                Global.Logger.AddItem(new LogItem(ex));
            }
            return null;
        }