System.Collections.Generic.IEnumerable.OrderByDescending(System.Func)

Here are the examples of the csharp api System.Collections.Generic.IEnumerable.OrderByDescending(System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

2229 Examples 7

19 Source : DbManager.cs
with MIT License
from 0x1000000

private static IReadOnlyList<TableRef> SortTablesByForeignKeys(Dictionary<TableRef, Dictionary<ColumnRef, ColumnModel>> acc)
        {
            var tableGraph = new Dictionary<TableRef, int>();
            var maxValue = 0;

            foreach (var pair in acc)
            {
                CountTable(pair.Key, pair.Value, 1);
            }

            return acc
                .Keys
                .OrderByDescending(k => tableGraph.TryGetValue(k, out var value) ? value : maxValue)
                .ThenBy(k => k)
                .ToList();

            void CountTable(TableRef table, Dictionary<ColumnRef, ColumnModel> columns, int value)
            {
                var parentTables = columns.Values
                    .Where(c => c.Fk != null)
                    .SelectMany(c => c.Fk!)
                    .Select(f => f.Table)
                    .Distinct()
                    .Where(pt => !pt.Equals(table))//Self ref
                    .ToList();

                bool hasParents = false;
                foreach (var parentTable in parentTables)
                {
                    if (tableGraph.TryGetValue(parentTable, out int oldValue))
                    {
                        if (value >= 1000)
                        {
                            throw new SqExpressCodeGenException("Cycle in tables");
                        }

                        if (oldValue < value)
                        {
                            tableGraph[parentTable] = value;
                        }
                    }
                    else
                    {
                        tableGraph.Add(parentTable, value);
                    }

                    if (maxValue < value)
                    {
                        maxValue = value;
                    }

                    CountTable(parentTable, acc[parentTable], value + 1);
                    hasParents = true;
                }

                if (hasParents && !tableGraph.ContainsKey(columns.Keys.First().Table))
                {
                    tableGraph.Add(table, 0);
                }
            }
        }

19 Source : IsoHeaderParser.cs
with MIT License
from 13xforever

public static (List<FileRecord> files, List<string> dirs) GetFilesystemStructure(this CDReader reader)
        {
            var fsObjects = reader.GetFileSystemEntries(reader.Root.FullName).ToList();
            var nextLevel = new List<string>();
            var filePaths = new List<string>();
            var dirPaths = new List<string>();
            while (fsObjects.Any())
            {
                foreach (var path in fsObjects)
                {
                    if (reader.FileExists(path))
                        filePaths.Add(path);
                    else if (reader.DirectoryExists(path))
                    {
                        dirPaths.Add(path);
                        nextLevel.AddRange(reader.GetFileSystemEntries(path));
                    }
                    else
                        Log.Warn($"Unknown filesystem object: {path}");
                }
                (fsObjects, nextLevel) = (nextLevel, fsObjects);
                nextLevel.Clear();
            }
            
            var filenames = filePaths.Distinct().Select(n => n.TrimStart('\\')).ToList();
            var dirnames = dirPaths.Distinct().Select(n => n.TrimStart('\\')).OrderByDescending(n => n.Length).ToList();
            var deepestDirnames = new List<string>();
            foreach (var dirname in dirnames)
            {
                var tmp = dirname + "\\";
                if (deepestDirnames.Any(n => n.StartsWith(tmp)))
                    continue;
                
                deepestDirnames.Add(dirname);
            }
            dirnames = deepestDirnames.OrderBy(n => n).ToList();
            var dirnamesWithFiles = filenames.Select(Path.GetDirectoryName).Distinct().ToList();
            var emptydirs = dirnames.Except(dirnamesWithFiles).ToList();

            var fileList = new List<FileRecord>();
            foreach (var filename in filenames)
            {
                var clusterRange = reader.PathToClusters(filename);
                if (clusterRange.Length != 1)
                    Log.Warn($"{filename} is split in {clusterRange.Length} ranges");
                if (filename.EndsWith("."))
                    Log.Warn($"Fixing potential mastering error in {filename}");
                fileList.Add(new FileRecord(filename.TrimEnd('.'), clusterRange.Min(r => r.Offset), reader.GetFileLength(filename)));
            }
            fileList = fileList.OrderBy(r => r.StartSector).ToList();
            return (files: fileList, dirs: emptydirs);
        }

19 Source : IrdTests.cs
with MIT License
from 13xforever

[Test, Explicit("Requires custom data")]
        public async Task TocSizeTest()
        {
            var path = @"E:\FakeCDs\PS3 Games\ird";
            var result = new List<(string filename, long size)>();
            foreach (var f in Directory.EnumerateFiles(path, "*.ird", SearchOption.TopDirectoryOnly))
            {
                var bytes = await File.ReadAllBytesAsync(f).ConfigureAwait(false);
                var ird = IrdParser.Parse(bytes);
                using (var header = GetDecompressHeader(ird))
                    result.Add((Path.GetFileName(f), header.Length));
            }
            replacedert.That(result.Count, Is.GreaterThan(0));

            var groupedStats = (from t in result
                    group t by t.size into g
                    select new {size = g.Key, count = g.Count()}
                ).OrderByDescending(i => i.count)
                .ThenByDescending(i => i.size)
                .ToList();

            var largest = groupedStats.Max(i => i.size);
            var largesreplacedem = result.First(i => i.size == largest);
            Console.WriteLine($"Largest TOC: {largesreplacedem.filename} ({largest.replacedtorageUnit()})");

            foreach (var s in groupedStats)
                Console.WriteLine($"{s.count} items of size {s.size}");

            replacedert.That(groupedStats.Count, Is.EqualTo(1));
        }

19 Source : ReflectionExtensions.cs
with Apache License 2.0
from 42skillz

public static IEnumerable<ConstructorInfo> GetConstructorsOrderedByNumberOfParametersDesc(this Type type)
        {
            var constructors = ((System.Reflection.TypeInfo)type).DeclaredConstructors;

            return constructors.OrderByDescending(c => c.GetParameters().Length);
        }

19 Source : PhysicsLayerInfos.cs
with MIT License
from a3geek

public void Update(Dictionary<int, string> layers, bool adjustID = true)
        {
            var ids = this.LayerIDs.ToList();

            foreach(var layer in layers)
            {
                ids.Remove(layer.Key);

                var lay = this[layer.Key] ?? this.AddPhysicsLayer(layer.Key, layer.Value);
                lay.LayerName = layer.Value;
            }
            
            foreach(var id in ids.OrderByDescending(id => id))
            {
                this.DeleteLayer(id, adjustID);
            }
        }

19 Source : GameUtils.cs
with Apache License 2.0
from AantCoder

public static int FindThings(ThingDef def, int destroy, bool getMaxByMap)
        {
            int countAll = 0;
            int countMax = 0;
            List<Pair<List<Thing>, int>> maps = new List<Pair<List<Thing>, int>>();
            for (int i = 0; i < Current.Game.Maps.Count; i++)
            {
                var m = Current.Game.Maps[i];
                if (m.IsPlayerHome)
                {
                    List<Thing> things = GameUtils.GetAllThings(m)
                        .Where(t => t.def == def).ToList();
                    var c = things.Sum(t => t.stackCount);
                    maps.Add(new Pair<List<Thing>, int>(things, c));
                    countAll += c;
                    if (countMax < c) countMax = c;
                }
            }
            int count = getMaxByMap ? countMax : countAll;
            if (destroy > 0 && destroy < count)
            {
                var destroyProcess = destroy;
                while (maps.Count > 0 && destroyProcess > 0)
                {
                    var m = maps.OrderByDescending(p => p.Second).First();
                    foreach (Thing thing in m.First)
                    {
                        if (thing.stackCount < destroyProcess)
                        {
                            destroyProcess -= thing.stackCount;
                            thing.Destroy();
                        }
                        else
                        {
                            thing.SplitOff(destroyProcess);
                            destroyProcess = 0;
                            break;
                        }
                    }
                }
            }
            return count;
        }

19 Source : UwpAppxBuildTools.cs
with Apache License 2.0
from abist-co-ltd

private static async Task<string> FindMsBuildPathAsync()
        {
            // Finding msbuild.exe involves different work depending on whether or not users
            // have VS2017 or VS2019 installed.
            foreach (VSWhereFindOption findOption in VSWhereFindOptions)
            {
                string arguments = findOption.arguments;
                if (string.IsNullOrWhiteSpace(EditorUserBuildSettings.wsaUWPVisualStudioVersion))
                {
                    arguments += " -latest";
                }
                else
                {
                    // Add version number with brackets to find only the specified version
                    arguments += $" -version [{EditorUserBuildSettings.wsaUWPVisualStudioVersion}]";
                }

                var result = await new Process().StartProcessAsync(
                new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    Arguments = arguments,
                    WorkingDirectory = @"C:\Program Files (x86)\Microsoft Visual Studio\Installer"
                });

                foreach (var path in result.Output)
                {
                    if (!string.IsNullOrEmpty(path))
                    {
                        string[] paths = path.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

                        if (paths.Length > 0)
                        {
                            // if there are multiple visual studio installs,
                            // prefer enterprise, then pro, then community
                            string bestPath = paths.OrderByDescending(p => p.ToLower().Contains("enterprise"))
                                .ThenByDescending(p => p.ToLower().Contains("professional"))
                                .ThenByDescending(p => p.ToLower().Contains("community")).First();

                            string finalPath = $@"{bestPath}{findOption.pathSuffix}";
                            if (File.Exists(finalPath))
                            {
                                return finalPath;
                            }
                        }
                    }
                }
            }

            return string.Empty;
        }

19 Source : OVRDirectorySyncer.cs
with MIT License
from absurd-joy

[SuppressMessage("ReSharper", "ParameterTypeCanBeEnumerable.Local")]
	private void DeleteOutdatedEmptyDirectoriesFromTarget(HashSet<string> sourceDirs, HashSet<string> targetDirs,
		CancellationToken cancellationToken)
	{
		var deleted = targetDirs.Except(sourceDirs).OrderByDescending(s => s);

		// By sorting in descending order above, we delete leaf-first,
		// this is simpler than collapsing the list above (which would also allow us to run these ops in parallel).
		// replacedumption is that there are few empty folders to delete
		foreach (var dir in deleted)
		{
			Directory.Delete(Path.Combine(Target, dir));
			cancellationToken.ThrowIfCancellationRequested();
		}
	}

19 Source : WorkFlowManager.cs
with Apache License 2.0
from AbpApp

public async Task<WorkflowDefinitionVersion> GetWorkflowDefinitionAsync(
            string id,
            VersionOptions version,
            CancellationToken cancellationToken)
        {
            var workflowDefinitions = await ReadCacheAsync(cancellationToken);

            return workflowDefinitions
                .Where(x => x.DefinitionId == id)
                .OrderByDescending(x => x.Version)
                .WithVersion(version).FirstOrDefault();
        }

19 Source : RealtimeOrthogonalHeatmap3DChart.xaml.cs
with MIT License
from ABTSoftware

private void OnNewData(object sender, EventArgs e)
        {
            _tick++;
            if (_tick == 2)
            {
                _tick = 0;
                _step = _random.Next(0, 11);
            }

            var mreplacedVal = new double[100];

            for (int i = 0; i < 100; i++)
            {
                double y = _step * Math.Sin(((2 * Math.PI) * 0.4) * t) + _random.NextDouble() * 2;
                _yValues[i] = y;
                _tValues[i] = t;
                mreplacedVal[i] = y + 10;                

                t += dt;
            }

            var sortData = mreplacedVal.OrderByDescending(x => x);

            using (_series0.SuspendUpdates())
            using (_series1.SuspendUpdates())
            using (_series2.SuspendUpdates())
            {
                _series0.Append(_tValues, _yValues);
                _series1.PushRow(sortData.ToArray());
                _series2.PushRow(sortData.ToArray());
            }
        }

19 Source : ExampleSearchProvider.cs
with MIT License
from ABTSoftware

private IEnumerable<Guid> RankDoreplacedents(string[] terms, IEnumerable<Guid> examplePageIds, IDictionary<string, Posting> invertedIndex)
        {
            var queryVector = new double[terms.Length];
            var docVectors = new Dictionary<Guid, double[]>();
            var docScores = new Dictionary<Guid, double>();

            for (int i = 0; i < terms.Length; i++)
            {
                string term = terms[i];
                if (!invertedIndex.ContainsKey(term))
                {
                    continue;
                }

                var posting = invertedIndex[term];
                queryVector[i] = (posting.InvertedDoreplacedentFrequency);

                foreach (var termInfo in posting.TermInfos)
                {
                    var examplePageId = termInfo.ExamplePageId;
                    if (examplePageIds.Contains(examplePageId))
                    {
                        if (!docVectors.ContainsKey(examplePageId))
                        {
                            docVectors[examplePageId] = new double[terms.Length];
                        }
                        docVectors[examplePageId][i] = termInfo.TermFrequency;
                    }
                }
            }

            foreach (var docVector in docVectors)
            {
                var dotProduct = DotProduct(docVector.Value, queryVector);
                docScores.Add(docVector.Key, dotProduct);
            }

            return docScores.OrderByDescending(pair => pair.Value).Select(pair => pair.Key);
        }

19 Source : LifestonedLoader.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static bool TryLoadWeenies(string folder, out List<global::Lifestoned.DataModel.Gdle.Weenie> results)
        {
            try
            {
                results = new List<global::Lifestoned.DataModel.Gdle.Weenie>();

                var files = Directory.GetFiles(folder, "*.json", SearchOption.AllDirectories).OrderByDescending(f => new FileInfo(f).CreationTime).ToList();

                foreach (var file in files)
                {
                    if (TryLoadWeenie(file, out var result))
                        results.Add(result);
                }

                return true;
            }
            catch
            {
                results = null;
                return false;
            }
        }

19 Source : LifestonedLoader.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static bool TryLoadWeeniesConverted(string folder, out List<Weenie> results, bool correctForEnumShift = false)
        {
            try
            {
                results = new List<Weenie>();

                var files = Directory.GetFiles(folder, "*.json", SearchOption.AllDirectories).OrderByDescending(f => new FileInfo(f).CreationTime).ToList();

                foreach (var file in files)
                {
                    if (TryLoadWeenieConverted(file, out var result, correctForEnumShift))
                        results.Add(result);
                }

                return true;
            }
            catch
            {
                results = null;
                return false;
            }
        }

19 Source : PropertiesEnchantmentRegistryExtensions.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static List<PropertiesEnchantmentRegistry> GetEnchantmentsTopLayer(this ICollection<PropertiesEnchantmentRegistry> value, ReaderWriterLockSlim rwLock, HashSet<int> setSpells)
        {
            if (value == null)
                return null;

            rwLock.EnterReadLock();
            try
            {
                var results = from e in value
                    group e by e.SpellCategory
                    into categories
                    //select categories.OrderByDescending(c => c.LayerId).First();
                    select categories.OrderByDescending(c => c.PowerLevel)
                        .ThenByDescending(c => Level8AuraSelfSpells.Contains(c.SpellId))
                        .ThenByDescending(c => setSpells.Contains(c.SpellId) ? c.SpellId : c.StartTime).First();

                return results.ToList();
            }
            finally
            {
                rwLock.ExitReadLock();
            }
        }

19 Source : PropertiesEnchantmentRegistryExtensions.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static List<PropertiesEnchantmentRegistry> GetEnchantmentsTopLayerByStatModType(this ICollection<PropertiesEnchantmentRegistry> value, EnchantmentTypeFlags statModType, ReaderWriterLockSlim rwLock, HashSet<int> setSpells)
        {
            if (value == null)
                return null;

            rwLock.EnterReadLock();
            try
            {
                var valuesByStatModType = value.Where(e => (e.StatModType & statModType) == statModType);

                var results = from e in valuesByStatModType
                    group e by e.SpellCategory
                    into categories
                    //select categories.OrderByDescending(c => c.LayerId).First();
                    select categories.OrderByDescending(c => c.PowerLevel)
                        .ThenByDescending(c => Level8AuraSelfSpells.Contains(c.SpellId))
                        .ThenByDescending(c => setSpells.Contains(c.SpellId) ? c.SpellId : c.StartTime).First();

                return results.ToList();
            }
            finally
            {
                rwLock.ExitReadLock();
            }
        }

19 Source : AddEnchantmentResult.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void BuildStack(List<PropertiesEnchantmentRegistry> entries, Spell spell, WorldObject caster, bool equip = false)
        {
            Surpreplaced = new List<PropertiesEnchantmentRegistry>();
            Refresh = new List<PropertiesEnchantmentRegistry>();
            Surpreplaceded = new List<PropertiesEnchantmentRegistry>();

            var powerLevel = spell.Power;

            foreach (var entry in entries.OrderByDescending(i => i.PowerLevel))
            {
                if (powerLevel > entry.PowerLevel)
                {
                    // surpreplaceding existing spell
                    Surpreplaced.Add(entry);
                }
                else if (powerLevel == entry.PowerLevel)
                {
                    // refreshing existing spell
                    if (spell.Id == entry.SpellId)
                    {
                        Refresh.Add(entry);

                        // this could be valid
                        // consider the case: i equip an item that casts strength 6 on me
                        // then i cast strength 6 on myself
                        // the self-cast would find the existing spell from the item, but it wouldn't refresh that one
                        // it should cast to its own layer?

                        //if (Refresh.Count > 1)
                            //Console.WriteLine($"AddEnchantmentResult.BuildStack(): multiple refresh entries");
                    }
                    else
                    {
                        // handle special case to prevent message: Pumpkin Shield casts Web of Defense on you, refreshing Aura of Defense
                        var spellDuration = equip ? double.PositiveInfinity : spell.Duration;

                        if (!equip && caster is Player player && player.AugmentationIncreasedSpellDuration > 0)
                            spellDuration *= 1.0f + player.AugmentationIncreasedSpellDuration * 0.2f;

                        var entryDuration = entry.Duration == -1 ? double.PositiveInfinity : entry.Duration;

                        if (spellDuration > entryDuration || spellDuration == entryDuration && !SpellSet.SetSpells.Contains(entry.SpellId))
                            Surpreplaced.Add(entry);
                        else if (spellDuration < entryDuration)
                            Surpreplaceded.Add(entry);
                        else
                        {
                            // fallback on spell id, for overlapping set spells in multiple sets, where the different 'level' names each have the same spellLevel and powerLevel?
                            // ie. for Gauntlet Damage Boost I and II
                            // this bug still exists in acclient visual enchantment display, unknown whether this bug existed on retail server
                            if (spell.Id > entry.SpellId)
                                Surpreplaced.Add(entry);
                            else
                                Surpreplaceded.Add(entry);
                        }
                    }
                }
                else if (powerLevel < entry.PowerLevel)
                {
                    // surpreplaceded by existing spell
                    Surpreplaceded.Add(entry);
                }

                if (entry.LayerId > TopLayerId)
                    TopLayerId = entry.LayerId;
            }

            SetStackType();
            SetSpell();

            if (Refresh.Count > 0)
                SetRefreshCaster(caster);
        }

19 Source : AllegianceNode.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void CalculateRank()
        {
            // http://asheron.wikia.com/wiki/Rank

            // A player's allegiance rank is a function of the number of Vreplacedals and how they are
            // organized. First, take the two highest ranked vreplacedals. Now the Patron's rank will either be
            // one higher than the lower of the two, or equal to the highest rank vreplacedal, whichever is greater.

            // sort vreplacedals by rank
            var sortedVreplacedals = Vreplacedals.Values.OrderByDescending(v => v.Rank).ToList();

            // get 2 highest rank vreplacedals
            var r1 = sortedVreplacedals.Count > 0 ? sortedVreplacedals[0].Rank : 0;
            var r2 = sortedVreplacedals.Count > 1 ? sortedVreplacedals[1].Rank : 0;

            var lower = Math.Min(r1, r2);
            var higher = Math.Max(r1, r2);

            Rank = Math.Max(lower + 1, higher);
        }

19 Source : HouseManager.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static void QueryMultiHouse()
        {
            var slumlordBiotas = DatabaseManager.Shard.BaseDatabase.GetBiotasByType(WeenieType.SlumLord);

            var playerHouses = new Dictionary<IPlayer, List<Biota>>();
            var accountHouses = new Dictionary<string, List<Biota>>();

            foreach (var slumlord in slumlordBiotas)
            {
                var biotaOwner = slumlord.BiotaPropertiesIID.FirstOrDefault(i => i.Type == (ushort)PropertyInstanceId.HouseOwner);
                if (biotaOwner == null)
                {
                    // this is fine. this is just a house that was purchased, and then later abandoned
                    //Console.WriteLine($"HouseManager.QueryMultiHouse(): couldn't find owner for house {slumlord.Id:X8}");
                    continue;
                }
                var owner = PlayerManager.FindByGuid(biotaOwner.Value);
                if (owner == null)
                {
                    Console.WriteLine($"HouseManager.QueryMultiHouse(): couldn't find owner {biotaOwner.Value:X8}");
                    continue;
                }

                if (!playerHouses.TryGetValue(owner, out var houses))
                {
                    houses = new List<Biota>();
                    playerHouses.Add(owner, houses);
                }
                houses.Add(slumlord);

                var accountName = owner.Account != null ? owner.Account.AccountName : "NULL";

                if (!accountHouses.TryGetValue(accountName, out var aHouses))
                {
                    aHouses = new List<Biota>();
                    accountHouses.Add(accountName, aHouses);
                }
                aHouses.Add(slumlord);
            }


            if (PropertyManager.GetBool("house_per_char").Item)
            {
                var results = playerHouses.Where(i => i.Value.Count() > 1).OrderByDescending(i => i.Value.Count());

                if (results.Count() > 0)
                    Console.WriteLine("Multi-house owners:");

                foreach (var playerHouse in results)
                {
                    Console.WriteLine($"{playerHouse.Key.Name}: {playerHouse.Value.Count}");

                    for (var i = 0; i < playerHouse.Value.Count; i++)
                        Console.WriteLine($"{i + 1}. {GetCoords(playerHouse.Value[i])}");
                }
            }
            else
            {
                var results = accountHouses.Where(i => i.Value.Count() > 1).OrderByDescending(i => i.Value.Count());

                if (results.Count() > 0)
                    Console.WriteLine("Multi-house owners:");

                foreach (var accountHouse in results)
                {
                    Console.WriteLine($"{accountHouse.Key}: {accountHouse.Value.Count}");

                    for (var i = 0; i < accountHouse.Value.Count; i++)
                        Console.WriteLine($"{i + 1}. {GetCoords(accountHouse.Value[i])}");
                }
            }
        }

19 Source : AuthenticationHandler.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static void SendConnectResponse(Session session, List<Character> characters)
        {
            characters = characters.OrderByDescending(o => o.LastLoginTimestamp).ToList(); // The client highlights the first character in the list. We sort so the first character sent is the one we last logged in
            session.UpdateCharacters(characters);

            GameMessageCharacterList characterListMessage = new GameMessageCharacterList(session.Characters, session);
            GameMessageServerName serverNameMessage = new GameMessageServerName(ConfigManager.Config.Server.WorldName, PlayerManager.GetOnlineCount(), (int)ConfigManager.Config.Server.Network.MaximumAllowedSessions);
            GameMessageDDDInterrogation dddInterrogation = new GameMessageDDDInterrogation();

            session.Network.EnqueueSend(characterListMessage, serverNameMessage);
            session.Network.EnqueueSend(dddInterrogation);
        }

19 Source : BoundingBox.cs
with GNU General Public License v3.0
from ACEmulator

public Facing GetTargetFace()
        {
            var eval = new List<Face>() { Faces[(int)Facing.Front], Faces[(int)Facing.Left], Faces[(int)Facing.Top] };
            var gfxObjMode = ModelViewer.Instance.GfxObjMode;
            if (gfxObjMode)
                eval = new List<Face>() { Faces[(int)Facing.Back], Faces[(int)Facing.Right], Faces[(int)Facing.Top] };

            var sorted = eval.OrderByDescending(i => i.Area).ToList();

            //foreach (var face in sorted)
            //Console.WriteLine($"Face: {face.Facing} - Area: {face.Area}");

            var mostArea = sorted[0];

            if (mostArea.Facing == Facing.Top)
            {
                var secondMostArea = sorted[1];
                var ratio = secondMostArea.Area / mostArea.Area;
                if (ratio > 0.5f)     // should we still be using top? it was originally designed for screenshot mode, and can be confusing w/ camera
                    return sorted[1].Facing;
            }

            return sorted[0].Facing;
        }

19 Source : CmdLineActions.cs
with MIT License
from action-bi-toolkit

[ArgActionMethod, ArgShortcut("cache"), ArgDescription("Manages the internal replacedembly cache.")]
        [ArgExample("pbi-tools.exe cache list", "Lists all cache folders present in the current user profile.")]
        public void Cache(
            [ArgRequired, ArgDescription("The cache action to perform.")] CacheAction action
        )
        {
            var folders = Directory.GetDirectories(ApplicationFolders.AppDataFolder);
            
            switch (action)
            {
                case CacheAction.List:
                    Array.ForEach(folders, f =>
                        Console.WriteLine($"- {Path.GetFileName(f)}")
                    );
                    break;
                case CacheAction.ClearAll:
                    Array.ForEach(folders, f => 
                    {
                        Directory.Delete(f, recursive: true);
                        Console.WriteLine($"Deleted: {Path.GetFileName(f)}");
                    });
                    break;
                case CacheAction.ClearOutdated:
                    Array.ForEach(folders.OrderByDescending(x => x).Skip(1).ToArray(), f => 
                    {
                        Directory.Delete(f, recursive: true);
                        Console.WriteLine($"Deleted: {Path.GetFileName(f)}");
                    });
                    break;
            }
        }

19 Source : IOUtil.cs
with MIT License
from actions

public static void DeleteDirectory(string path, bool contentsOnly, bool continueOnContentDeleteError, CancellationToken cancellationToken)
        {
            ArgUtil.NotNullOrEmpty(path, nameof(path));
            DirectoryInfo directory = new DirectoryInfo(path);
            if (!directory.Exists)
            {
                return;
            }

            if (!contentsOnly)
            {
                // Remove the readonly flag.
                RemoveReadOnly(directory);

                // Check if the directory is a reparse point.
                if (directory.Attributes.HasFlag(FileAttributes.ReparsePoint))
                {
                    // Delete the reparse point directory and short-circuit.
                    directory.Delete();
                    return;
                }
            }

            // Initialize a concurrent stack to store the directories. The directories
            // cannot be deleted until the files are deleted.
            var directories = new ConcurrentStack<DirectoryInfo>();

            if (!contentsOnly)
            {
                directories.Push(directory);
            }

            // Create a new token source for the parallel query. The parallel query should be
            // canceled after the first error is encountered. Otherwise the number of exceptions
            // could get out of control for a large directory with access denied on every file.
            using (var tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
            {
                try
                {
                    // Recursively delete all files and store all subdirectories.
                    Enumerate(directory, tokenSource)
                        .AsParallel()
                        .WithCancellation(tokenSource.Token)
                        .ForAll((FileSystemInfo item) =>
                        {
                            bool success = false;
                            try
                            {
                                // Remove the readonly attribute.
                                RemoveReadOnly(item);

                                // Check if the item is a file.
                                if (item is FileInfo)
                                {
                                    // Delete the file.
                                    item.Delete();
                                }
                                else
                                {
                                    // Check if the item is a directory reparse point.
                                    var subdirectory = item as DirectoryInfo;
                                    ArgUtil.NotNull(subdirectory, nameof(subdirectory));
                                    if (subdirectory.Attributes.HasFlag(FileAttributes.ReparsePoint))
                                    {
                                        try
                                        {
                                            // Delete the reparse point.
                                            subdirectory.Delete();
                                        }
                                        catch (DirectoryNotFoundException)
                                        {
                                            // The target of the reparse point directory has been deleted.
                                            // Therefore the item is no longer a directory and is now a file.
                                            //
                                            // Deletion of reparse point directories happens in parallel. This case can occur
                                            // when reparse point directory FOO points to some other reparse point directory BAR,
                                            // and BAR is deleted after the DirectoryInfo for FOO has already been initialized.
                                            File.Delete(subdirectory.FullName);
                                        }
                                    }
                                    else
                                    {
                                        // Store the directory.
                                        directories.Push(subdirectory);
                                    }
                                }

                                success = true;
                            }
                            catch (Exception) when (continueOnContentDeleteError)
                            {
                                // ignore any exception when continueOnContentDeleteError is true.
                                success = true;
                            }
                            finally
                            {
                                if (!success)
                                {
                                    tokenSource.Cancel(); // Cancel is thread-safe.
                                }
                            }
                        });
                }
                catch (Exception)
                {
                    tokenSource.Cancel();
                    throw;
                }
            }

            // Delete the directories.
            foreach (DirectoryInfo dir in directories.OrderByDescending(x => x.FullName.Length))
            {
                cancellationToken.ThrowIfCancellationRequested();
                dir.Delete();
            }
        }

19 Source : EventHost.cs
with MIT License
from ad313

private async Task sample_publish_queue()
        {
            var key = "sample_publish_queue";

            _eventBusProvider.SubscribeQueue<int>(key, async func =>
            {
                var data = await func(1000);
                foreach (var v in data)
                {
                    queue.Enqueue(v);
                    Console.WriteLine($"--------------------------------------{v}-----------------1");
                }

                Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  11");

                await Task.CompletedTask;
            });

            _eventBusProvider.SubscribeQueue<int>(key, async func =>
            {
                var data = await func(1000);
                foreach (var v in data)
                {
                    queue.Enqueue(v);
                    Console.WriteLine($"--------------------------------------{v}-----------------2");
                }

                Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  12");

                await Task.CompletedTask;
            });

            Enumerable.Range(0, 1000).AsParallel().ForAll(i =>
            {
                //Console.WriteLine($"{i}");
                _eventBusProvider.PublishQueueAsync(key, new List<int>() { i }).GetAwaiter().GetResult();
            });

            //await _eventBusProvider.PublishQueueAsync(key, new List<int>());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(0, 200).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(200, 200).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(400, 200).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(600, 200).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(800, 200).ToList());
        }

19 Source : EventHost.cs
with MIT License
from ad313

private async Task sample_publish_queue_all2()
        {
            var key = "sample_publish_queue_all3";

            //var queue = new ConcurrentQueue<int>();

            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------11");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  11");
                    //index1 = 0;
                    await Task.CompletedTask;
                });

            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------12");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  12");
                    //index1 = 0;
                    await Task.CompletedTask;
                });

            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------13");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  13");
                    //index1 = 0;
                    await Task.CompletedTask;
                });


            //await Task.Delay(2000);

            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(0, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(100, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(200, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(300, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());

            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(400, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(500, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(600, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(700, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());

        }

19 Source : EventHost.cs
with MIT License
from ad313

private async Task sample_publish_queue_all3_big()
        {
            var key = "sample_publish_queue_all3";
            var key2 = "sample_publish_queue_all4";

            var index1 = 0;
            var index2 = 0;
            var index3 = 0;


            var queue = new ConcurrentQueue<int>();

            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------11");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  11");
                    //index1 = 0;
                    await Task.CompletedTask;
                });

            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------12");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  12");
                    //index1 = 0;
                    await Task.CompletedTask;
                });

            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------13");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  13");
                    //index1 = 0;
                    await Task.CompletedTask;
                });






            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key2, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------21");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  21");
                    //index1 = 0;
                    await Task.CompletedTask;
                });

            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key2, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------22");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  22");
                    //index1 = 0;
                    await Task.CompletedTask;
                });

            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key2, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------23");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  23");
                    //index1 = 0;
                    await Task.CompletedTask;
                });


            await Task.Delay(2000);



            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(0, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(100, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(200, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(300, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());

            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(400, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(500, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(600, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(700, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());


            await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1000, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1100, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1200, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1300, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());

            await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1400, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1500, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1600, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            await _eventBusProvider.PublishQueueAsync(key2, Enumerable.Range(1700, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());

            await Task.Delay(20000);
        }

19 Source : EventHost2.cs
with MIT License
from ad313

private async Task sample_publish_queue_all2()
        {
            var key = "aaaaaaa";
            
            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------11");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  11");
                    //index1 = 0;
                    await Task.CompletedTask;
                });
            
            //await Task.Delay(2000);
            await _eventBusProvider.PublishQueueAsync(key, new List<TestClreplacedModel>());

            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(0, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(100, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(200, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(300, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());

            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(400, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(500, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(600, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(700, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());

        }

19 Source : EventHost.cs
with MIT License
from ad313

private async Task sample_publish_queue_all3()
        {
            var key = "sample_publish_queue_all4";

            //var queue = new ConcurrentQueue<int>();

            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------11");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  11");
                    //index1 = 0;
                    await Task.CompletedTask;
                });

            //_eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
            //    async data =>
            //    {
            //        foreach (var v in data)
            //        {
            //            queue.Enqueue(v.Index);
            //            Console.WriteLine($"--------------------------------------{v.Index}-----------------12");
            //        }

            //        await Task.CompletedTask;
            //    }, completed: async () =>
            //    {
            //        Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  12");
            //        //index1 = 0;
            //        await Task.CompletedTask;
            //    });

            //_eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
            //    async data =>
            //    {
            //        foreach (var v in data)
            //        {
            //            queue.Enqueue(v.Index);
            //            Console.WriteLine($"--------------------------------------{v.Index}-----------------13");
            //        }

            //        await Task.CompletedTask;
            //    }, completed: async () =>
            //    {
            //        Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  13");
            //        //index1 = 0;
            //        await Task.CompletedTask;
            //    });


            //await Task.Delay(2000);

            await _eventBusProvider.PublishQueueAsync(key, new List<TestClreplacedModel>());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(1000, 1).Select(d => new TestClreplacedModel() { Index = d }).ToList());

            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(1000, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(1100, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(1200, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(1300, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());

            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(1400, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(1500, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(1600, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(1700, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());

        }

19 Source : EventHost3.cs
with MIT License
from ad313

private async Task sample_publish_queue_all2()
        {
            var key = "bbbbbbb";
            
            _eventBusProvider.SubscribeQueue<TestClreplacedModel>(key, 10, 1, ExceptionHandlerEnum.PushToSelfQueueAndContinue,
                async data =>
                {
                    foreach (var v in data)
                    {
                        queue.Enqueue(v.Index);
                        Console.WriteLine($"--------------------------------------{v.Index}-----------------11");
                    }

                    await Task.CompletedTask;
                }, completed: async () =>
                {
                    Console.WriteLine($"{queue.Count} {queue.ToArray().GroupBy(d => d).ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value).FirstOrDefault().Value.ToString()}  11");
                    //index1 = 0;
                    await Task.CompletedTask;
                });
            
            //await Task.Delay(2000);
            await _eventBusProvider.PublishQueueAsync(key, new List<TestClreplacedModel>());

            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(0, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(100, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(200, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(300, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());

            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(400, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(500, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(600, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());
            //await _eventBusProvider.PublishQueueAsync(key, Enumerable.Range(700, 100).Select(d => new TestClreplacedModel() { Index = d }).ToList());

        }

19 Source : PolyRelationsSieveProgress.cs
with GNU General Public License v3.0
from AdamWhiteHat

public string FormatRelations(IEnumerable<Relation> relations)
		{
			StringBuilder result = new StringBuilder();

			result.AppendLine($"Smooth relations:");
			result.AppendLine("\t_______________________________________________");
			result.AppendLine($"\t|   A   |  B | ALGEBRAIC_NORM | RATIONAL_NORM | \t\tRelations count: {Relations.SmoothRelations.Count} Target quanreplacedy: {SmoothRelations_TargetQuanreplacedy}");
			result.AppendLine("\t```````````````````````````````````````````````");
			foreach (Relation rel in relations.OrderByDescending(rel => rel.A * rel.B))
			{
				result.AppendLine(rel.ToString());
				result.AppendLine("Algebraic " + rel.AlgebraicFactorization.FormatStringAsFactorization());
				result.AppendLine("Rational  " + rel.RationalFactorization.FormatStringAsFactorization());
				result.AppendLine();
			}
			result.AppendLine();

			return result.ToString();
		}

19 Source : ObjectCacheExtensions.cs
with MIT License
from Adoxio

public static Dictionary<string, object> GetCacheFootprintJson(this ObjectCache cache, bool expanded, Uri requestUrl)
		{
			var alternateLink = new Uri(requestUrl.GetLeftPart(UriPartial.Path));

			var enreplacedies = new List<Dictionary<string, object>>();
			
			var footprint = GetCacheFootprint(cache, alternateLink);
			foreach (var enreplacedyType in footprint)
			{
				var enreplacedy = new Dictionary<string, object>
				{
					{ "Name", enreplacedyType.Name },
					{ "Count", enreplacedyType.GetCount() },
					{ "Size", enreplacedyType.GetSize() }
				};

				if (expanded)
				{
					var records = new Collection<Dictionary<string, object>>();
					foreach (var item in enreplacedyType.Items)
					{
						var record = new Dictionary<string, object>
						{
							{ "LogicalName", item.Enreplacedy.LogicalName },
							{ "Name", item.Enreplacedy.GetAttributeValueOrDefault("adx_name", string.Empty) },
							{ "Id", item.Enreplacedy.Id }
						};

						var recordCache = new Dictionary<string, object>
						{
							{ "Id", item.CacheItemKey },
							{ "Type", item.CacheItemType },
							{ "Link", item.Link.ToString() },
							{ "Size", GetEnreplacedySizeInMemory(item.Enreplacedy) }
						};

						record.Add("Cache", recordCache);
						records.Add(record);
					}
					enreplacedy.Add("Items", records);
				}

				enreplacedies.Add(enreplacedy);
			}

			var enreplacediesWrapper = new Dictionary<string, object>();
			if (!expanded)
			{
				// Add link to the Expanded view with enreplacedy record details
				var query = System.Web.HttpUtility.ParseQueryString(requestUrl.Query);
				query[Web.Handlers.CacheFeedHandler.QueryKeys.Expanded] = bool.TrueString;
				var uriBuilder = new UriBuilder(requestUrl.ToString()) { Query = query.ToString() };
				enreplacediesWrapper.Add("ExpandedView", uriBuilder.ToString());
			}
			enreplacediesWrapper.Add("Enreplacedies", enreplacedies.OrderByDescending(e => e["Size"]));
			var retval = new Dictionary<string, object> { { "CacheFootprint", enreplacediesWrapper } };
			return retval;
		}

19 Source : ObjectCacheExtensions.cs
with MIT License
from Adoxio

public static XmlDoreplacedent GetCacheFootprintXml(this ObjectCache cache, bool expanded, Uri requestUrl)
		{
			var alternateLink = new Uri(requestUrl.GetLeftPart(UriPartial.Path));

			var doc = new XmlDoreplacedent();
			var rootElement = doc.CreateElement("CacheFootprint");
			var enreplacedyElements = new List<XmlElement>();
			var footprint = GetCacheFootprint(cache, alternateLink);
			foreach (var enreplacedyType in footprint)
			{
				var enreplacedyElement = doc.CreateElement("Enreplacedy");
				enreplacedyElement.SetAttribute("Name", enreplacedyType.Name);
				enreplacedyElement.SetAttribute("Count", enreplacedyType.GetCount().ToString());
				enreplacedyElement.SetAttribute("Size", enreplacedyType.GetSize().ToString());

				if (expanded)
				{
					foreach (var item in enreplacedyType.Items)
					{
						var itemElement = doc.CreateElement("Item");
						itemElement.SetAttribute("LogicalName", item.Enreplacedy.LogicalName);
						itemElement.SetAttribute("Name", item.Enreplacedy.GetAttributeValueOrDefault("adx_name", string.Empty));
						itemElement.SetAttribute("Id", item.Enreplacedy.Id.ToString());

						var cacheElement = doc.CreateElement("Cache");
						cacheElement.SetAttribute("Id", item.CacheItemKey);
						cacheElement.SetAttribute("Type", item.CacheItemType.ToString());
						cacheElement.SetAttribute("Link", item.Link.ToString());
						cacheElement.SetAttribute("Size", GetEnreplacedySizeInMemory(item.Enreplacedy).ToString());

						itemElement.AppendChild(cacheElement);
						enreplacedyElement.AppendChild(itemElement);
					}
				}

				enreplacedyElements.Add(enreplacedyElement);
			}

			// Sort the enreplacedies by descending size
			enreplacedyElements = enreplacedyElements.OrderByDescending(el => int.Parse(el.GetAttribute("Size"))).ToList();

			var enreplacediesElement = doc.CreateElement("Enreplacedies");
			foreach (var enreplacedyElement in enreplacedyElements)
			{
				enreplacediesElement.AppendChild(enreplacedyElement);
			}
			
			if (!expanded)
			{
				// Add link to the Expanded view with enreplacedy record details
				var query = System.Web.HttpUtility.ParseQueryString(requestUrl.Query);
				query[Web.Handlers.CacheFeedHandler.QueryKeys.Expanded] = bool.TrueString;
				var uriBuilder = new UriBuilder(requestUrl.ToString()) { Query = query.ToString() };
				var expandedView = doc.CreateElement("expandedView");
				expandedView.InnerText = uriBuilder.ToString();
				rootElement.AppendChild(expandedView);
			}
			rootElement.AppendChild(enreplacediesElement);
			doc.AppendChild(rootElement);
			return doc;
		}

19 Source : EntityListPackageRepositoryDataAdapter.cs
with MIT License
from Adoxio

private IEnumerable<Package> GetPackages(IEnumerable<IGrouping<Guid, Enreplacedy>> enreplacedyGroupings, Func<Guid, string> getPackageUrl)
		{
			var website = Dependencies.GetWebsite();

			foreach (var enreplacedyGrouping in enreplacedyGroupings)
			{
				var enreplacedy = enreplacedyGrouping.FirstOrDefault();

				if (enreplacedy == null)
				{
					continue;
				}

				var versions = GetPackageVersions(enreplacedyGrouping, website.Id)
					.OrderByDescending(e => e.ReleaseDate)
					.ToArray();

				var currentVersion = versions.FirstOrDefault();

				if (currentVersion == null)
				{
					continue;
				}

				PackageImage icon;

				var images = GetPackageImages(enreplacedyGrouping, website.Id, enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_iconid"), out icon)
					.OrderBy(e => e.Name)
					.ToArray();

				yield return new Package
				{
					Categories = GetPackageCategories(enreplacedyGrouping).ToArray(),
					Components = GetPackageComponents(enreplacedyGrouping, website.Id).OrderBy(e => e.Order).ThenBy(e => e.CreatedOn).ToArray(),
					ContentUrl = currentVersion.Url,
					Dependencies = GetPackageDependencies(enreplacedyGrouping, website.Id).OrderBy(e => e.Order).ThenBy(e => e.CreatedOn).ToArray(),
					Description = enreplacedy.GetAttributeValue<string>("adx_description"),
					DisplayName = enreplacedy.GetAttributeValue<string>("adx_name"),
					HideFromPackageListing = enreplacedy.GetAttributeValue<bool?>("adx_hidefromlisting").GetValueOrDefault(false),
					Icon = icon,
					Images = images,
					OverwriteWarning = enreplacedy.GetAttributeValue<bool?>("adx_overwritewarning").GetValueOrDefault(false),
					PublisherName = enreplacedy.GetAttributeAliasedValue<string>("adx_name", "publisher"),
					ReleaseDate = currentVersion.ReleaseDate,
					RequiredInstallerVersion = currentVersion.RequiredInstallerVersion,
					Summary = enreplacedy.GetAttributeValue<string>("adx_summary"),
					Type = GetPackageType(enreplacedy.GetAttributeValue<OptionSetValue>("adx_type")),
					UniqueName = enreplacedy.GetAttributeValue<string>("adx_uniquename"),
					Uri = GetPackageUri(enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_packagerepositoryid"), website.Id, enreplacedy.GetAttributeValue<string>("adx_uniquename")),
					Url = getPackageUrl(enreplacedy.Id),
					Version = currentVersion.Version,
					Versions = versions,
					Configuration = currentVersion.Configuration
				};
			}
		}

19 Source : PackageDataAdapter.cs
with MIT License
from Adoxio

public Package SelectPackage()
		{
			var serviceContext = Dependencies.GetServiceContext();
			var website = Dependencies.GetWebsite();

			var fetch = new Fetch
			{
				Version = "1.0",
				MappingType = MappingType.Logical,
				Enreplacedy = new FetchEnreplacedy
				{
					Name = Package.LogicalName,
					Attributes = FetchAttribute.All,
					Filters = new[]
					{
						new Filter
						{
							Type = LogicalOperator.And,
							Conditions = new[]
							{
								new Condition("adx_packageid", ConditionOperator.Equal, Package.Id),
								new Condition("statecode", ConditionOperator.Equal, 0),
							}
						}
					},
					Links = new Collection<Link>()
				}
			};

			AddPackageCategoryJoin(fetch.Enreplacedy);
			AddPackageComponentJoin(fetch.Enreplacedy);
			AddPackageDependencyJoin(fetch.Enreplacedy);
			AddPackageImageJoin(fetch.Enreplacedy);
			AddPackagePublisherJoin(fetch.Enreplacedy);
			AddPackageVersionJoin(fetch.Enreplacedy);

			var enreplacedyGrouping = FetchEnreplacedies(serviceContext, fetch)
				.GroupBy(e => e.Id)
				.FirstOrDefault();

			if (enreplacedyGrouping == null)
			{
				return null;
			}

			var enreplacedy = enreplacedyGrouping.FirstOrDefault();

			if (enreplacedy == null)
			{
				return null;
			}

			var versions = GetPackageVersions(enreplacedyGrouping, website.Id)
				.OrderByDescending(e => e.ReleaseDate)
				.ToArray();

			var currentVersion = versions.FirstOrDefault();

			if (currentVersion == null)
			{
				return null;
			}

			PackageImage icon;

			var images = GetPackageImages(enreplacedyGrouping, website.Id, enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_iconid"), out icon)
				.OrderBy(e => e.Name)
				.ToArray();

			var packageRepository = enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_packagerepository");

			return new Package
			{
				Categories = GetPackageCategories(enreplacedyGrouping).ToArray(),
				Components = GetPackageComponents(enreplacedyGrouping, website, packageRepository).OrderBy(e => e.Order).ThenBy(e => e.CreatedOn).ToArray(),
				ContentUrl = currentVersion.Url,
				Dependencies = GetPackageDependencies(enreplacedyGrouping, website, packageRepository).OrderBy(e => e.Order).ThenBy(e => e.CreatedOn).ToArray(),
				Description = enreplacedy.GetAttributeValue<string>("adx_description"),
				DisplayName = enreplacedy.GetAttributeValue<string>("adx_name"),
				HideFromPackageListing = enreplacedy.GetAttributeValue<bool?>("adx_hidefromlisting").GetValueOrDefault(false),
				Icon = icon,
				Images = images,
				OverwriteWarning = enreplacedy.GetAttributeValue<bool?>("adx_overwritewarning").GetValueOrDefault(false),
				PublisherName = enreplacedy.GetAttributeAliasedValue<string>("adx_name", "publisher"),
				ReleaseDate = currentVersion.ReleaseDate,
				RequiredInstallerVersion = currentVersion.RequiredInstallerVersion,
				Summary = enreplacedy.GetAttributeValue<string>("adx_summary"),
				Type = GetPackageType(enreplacedy.GetAttributeValue<OptionSetValue>("adx_type")),
				UniqueName = enreplacedy.GetAttributeValue<string>("adx_uniquename"),
				Uri = GetPackageUri(packageRepository, website.Id, enreplacedy.GetAttributeValue<string>("adx_uniquename")),
				Url = null,
				Version = currentVersion.Version,
				Versions = versions
			};
		}

19 Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio

private static void UpdateThreadOnPostDelete(this OrganizationServiceContext context, Enreplacedy post)
		{
			post.replacedertEnreplacedyName("adx_communityforumpost");

			var parentThread = post.GetRelatedEnreplacedy(context, "adx_communityforumthread_communityforumpost");

			if (parentThread == null) throw new NullReferenceException("Error retrieving parent Forum Thread");

			var currentLastPostId = parentThread.GetAttributeValue<EnreplacedyReference>("adx_lastpostid") == null ? Guid.Empty : parentThread.GetAttributeValue<EnreplacedyReference>("adx_lastpostid").Id;

			var currentFirstPostId = parentThread.GetAttributeValue<EnreplacedyReference>("adx_firstpostid") == null ? Guid.Empty : parentThread.GetAttributeValue<EnreplacedyReference>("adx_firstpostid").Id;

			var currentPostId = post.GetAttributeValue<Guid>("adx_communityforumpostid");

			if (currentPostId == currentLastPostId)
			{
				var lastPost = GetForumPosts(context).Where(p => p.GetAttributeValue<EnreplacedyReference>("adx_forumthreadid") != null && p.GetAttributeValue<EnreplacedyReference>("adx_forumthreadid").Equals(parentThread.ToEnreplacedyReference()) && p.GetAttributeValue<Guid>("adx_communityforumpostid") != currentPostId).OrderByDescending(p => p.GetAttributeValue<DateTime>("adx_date")).First();

				if (lastPost != null)
				{
					parentThread["adx_lastpostid"] = lastPost.ToEnreplacedyReference();
				}
			}

			if (currentPostId == currentFirstPostId)
			{
				var firstPost = GetForumPosts(context).Where(p => p.GetAttributeValue<EnreplacedyReference>("adx_forumthreadid") != null && p.GetAttributeValue<EnreplacedyReference>("adx_forumthreadid").Equals(parentThread.ToEnreplacedyReference()) && p.GetAttributeValue<Guid>("adx_communityforumpostid") != currentPostId).OrderBy(p => p.GetAttributeValue<DateTime>("adx_date")).First();

				if (firstPost != null)
				{
					parentThread["adx_firstpostid"] = firstPost.ToEnreplacedyReference();
				}
			}

			parentThread["adx_postcount"] = parentThread.GetAttributeValue<int>("adx_postcount") > 0 ? parentThread.GetAttributeValue<int>("adx_postcount") - 1 : 0;

			context.UpdateObject(parentThread);

			context.SaveChanges();
		}

19 Source : PortalFacetedIndexSearcher.cs
with MIT License
from Adoxio

private IEnumerable<ConstraintHit> GroupRecordTypeFacet(KeyValuePair<string, IFacetAccessible> currentFacet, IEnumerable<FacetConstraints> clientFacetConstraints)
		{
			var enreplacedyToRecordMap = new Dictionary<string, string>();
			var groupedFacets = new Dictionary<string, int>();
			var settingsString = this.RecordTypeFacetsEnreplacedies;
			var result = new List<ConstraintHit>();

			settingsString = this.RemoveDuplicates(settingsString);

			if (string.IsNullOrEmpty(settingsString))
			{
				return this.BrowseFacetsToConstraintHits(currentFacet, clientFacetConstraints);
			}

			foreach (var groupName in Web.Mvc.Html.SettingExtensions.SplitSearchFilterOptions(settingsString))
			{
				var trimmedGroupName = groupName.Value.Trim();

				if (string.IsNullOrEmpty(trimmedGroupName))
				{
					continue;
				}

				foreach (var logicalName in trimmedGroupName.Split(','))
				{
					var trimmedLogicalName = logicalName.Trim();

					if (string.IsNullOrEmpty(trimmedLogicalName))
					{
						continue;
					}

					enreplacedyToRecordMap.Add(trimmedLogicalName, trimmedGroupName);
				}

				groupedFacets.Add(trimmedGroupName, 0);
			}

			var browseFacets = currentFacet.Value.GetFacets();
			foreach (var facet in browseFacets)
			{
				var logicalName = facet.Value;

				// adds browseFacet if it's not present in site setting grouping
				if (!enreplacedyToRecordMap.ContainsKey(logicalName))
				{
					groupedFacets.Add(logicalName, facet.FacetValueHitCount);
					continue;
				}

				groupedFacets[enreplacedyToRecordMap[logicalName]] += facet.FacetValueHitCount;
			}

			foreach (var facet in groupedFacets)
			{
				if (facet.Value > 0 || clientFacetConstraints.Where(constraints => constraints.FacetName == currentFacet.Key).SelectMany(constraints => constraints.Constraints).Any(constraintName => facet.Key.Contains(constraintName)))
				{
					result.Add(new ConstraintHit(facet.Key, facet.Value, Web.Extensions.LocalizeRecordTypeName(facet.Key.Split(',')[0])));
				}
			}

			return result.OrderByDescending(x => x.HitCount);
		}

19 Source : SimpleHtmlHighlightedFragmentProvider.cs
with MIT License
from Adoxio

public string GetFragment(Doreplacedent doreplacedent)
		{
			if (doreplacedent == null)
			{
				throw new ArgumentNullException("doreplacedent");
			}

			var contentField = doreplacedent.GetField(_index.ContentFieldName);

			if (contentField == null || !contentField.IsStored)
			{
				return string.Empty;
			}

			var content = contentField.StringValue;

			var tokenStream = _index.replacedyzer.TokenStream(contentField.Name, new StringReader(content));

			var rawFragment = _highlighter.GetBestFragments(tokenStream, content, 1, "...");

			var bestFragment = Regex.Split(rawFragment, @"^\s*$", RegexOptions.Multiline)
				.OrderByDescending(f => Regex.Matches(f, Regex.Escape(_highlighterStartTag)).Count)
				.First();

			var fragment = bestFragment.Trim();

			if (string.IsNullOrEmpty(fragment))
			{
				return string.Empty;
			}

			return "… {0} …".FormatWith(fragment);
		}

19 Source : EnumerableFilters.cs
with MIT License
from Adoxio

public static object OrderBy(object input, string key, string direction = "asc")
		{
			var blogPostsDrop = input as BlogPostsDrop;

			if (blogPostsDrop != null)
			{
				return BlogFunctions.OrderBy(blogPostsDrop, key, direction);
			}

			var forumThreadsDrop = input as ForumThreadsDrop;

			if (forumThreadsDrop != null)
			{
				return ForumFunctions.OrderBy(forumThreadsDrop, key, direction);
			}

			var enumerable = input as IEnumerable;

			if (enumerable != null)
			{
				return string.Equals(direction, "desc", StringComparison.InvariantCultureIgnoreCase)
					|| string.Equals(direction, "descending", StringComparison.InvariantCultureIgnoreCase)
					? enumerable.Cast<object>().OrderByDescending(e => Get(e, key))
					: enumerable.Cast<object>().OrderBy(e => Get(e, key));
			}

			return input;
		}

19 Source : TagCloudDataSourceView.cs
with MIT License
from Adoxio

protected override IEnumerable ExecuteSelect(DataSourceSelectArguments arguments)
		{
			var context = PortalContext.Current.ServiceContext;

			var pageTags = context.GetPageTags().ToList().Select(tag => new PageTagInfo(tag)).Where(tagInfo => tagInfo.TaggedItemCount > 0);
			var eventTags = context.GetEventTags().ToList().Select(tag => new EventTagInfo(tag)).Where(tagInfo => tagInfo.TaggedItemCount > 0);
			var threadTags = context.GetForumThreadTags().ToList().Select(tag => new ForumThreadTagInfo(tag)).Where(tagInfo => tagInfo.TaggedItemCount > 0);

			IEnumerable<TagCloudDataItem> items = new TagCloudData(
				Owner.NumberOfWeights,
				StringComparer.InvariantCultureIgnoreCase,
				pageTags.Cast<ITagInfo>(),
				eventTags.Cast<ITagInfo>(),
				threadTags.Cast<ITagInfo>()).ToList();

			if (string.Equals(Owner.SortExpression, "TaggedItemCount", StringComparison.InvariantCultureIgnoreCase))
			{
				items = Owner.SortDirection == SortDirection.Descending
					? items.OrderByDescending(item => item.TaggedItemCount)
					: items.OrderBy(item => item.TaggedItemCount);
			}
			else
			{
				items = Owner.SortDirection == SortDirection.Descending
					? items.OrderByDescending(item => item.Name)
					: items.OrderBy(item => item.Name);
			}

			foreach (var item in items)
			{
				item.CssClreplaced = Owner.WeightCssClreplacedPrefix + item.Weight;
			}

			return items.ToList();
		}

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void applyupdate()
        {
            statuslabel.Content = "Merging NCA's...";

            string curdir = AppDomain.CurrentDomain.BaseDirectory;
            string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";
            string upddir = AppDomain.CurrentDomain.BaseDirectory + "\\upd";
            string nspudir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
            string basenca = tmpdir + "\\NCAID_PLAIN.nca";

            var di = new DirectoryInfo(upddir);
            var result = di.GetFiles().OrderByDescending(x => x.Length).Take(1).ToList();
            var larupdnca = di.GetFiles().OrderByDescending(x => x.Length).Take(1).Select(x => x.FullName).ToList();

            string updnca = String.Join(" ", larupdnca);

            string replacedlkeyp = updreplacedlkyinput.Text;
            string upgtk = new string(replacedlkeyp.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray());

            string arg1 = @"-k keys.txt " + "--replacedlekey=" + upgtk + " --basenca=" + basenca + " --section1=" + curdir + "\\romfs.bin" + " --exefsdir=";
            string arg2 = tmpdir + "\\exefs " + updnca;
            string arg = arg1 + arg2; 

            Process aplupd = new Process();
            aplupd.StartInfo.FileName = nspudir;
            aplupd.StartInfo.Arguments = arg;
            aplupd.StartInfo.CreateNoWindow = true;
            aplupd.StartInfo.UseShellExecute = false;
            aplupd.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            aplupd.EnableRaisingEvents = true;

            aplupd.Start();

            await Task.Run(() => aplupd.WaitForExit());

            aplupd.Close();

            stopbar();

            statuslabel.Content = "";

            Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\\tmp", true);
            Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\\upd", true);

            onbtn();

            System.Windows.MessageBox.Show("Update applyment finished.\nYou can now use your updated romFS via fs-mitm.");
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void decryptbsgnca()
        {
            offbtn();

            startbar();

            statuslabel.Content = "Decrypting Base Game NCA...";

            string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";

            var di = new DirectoryInfo(tmpdir);
            var result = di.GetFiles().OrderByDescending(x => x.Length).Take(1).ToList();
            var larbnca = di.GetFiles().OrderByDescending(x => x.Length).Take(1).Select(x => x.FullName).ToList();

            string basenca = String.Join(" ", larbnca);

            string nspddir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
            string replacedlkeyp = bsgreplacedlkyinput.Text;
            string bsgtk = new string(replacedlkeyp.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray());
            string arg1 = @"-k keys.txt " + "--replacedlekey=" + bsgtk + " " + basenca;
            string arg2 = " --plaintext=" + tmpdir + "\\NCAID_PLAIN.nca";
            string arg = arg1 + arg2;
          
            Process decrnca = new Process();
            decrnca.StartInfo.FileName = nspddir;
            decrnca.StartInfo.Arguments = arg;
            decrnca.StartInfo.CreateNoWindow = true;
            decrnca.StartInfo.UseShellExecute = false;
            decrnca.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            decrnca.EnableRaisingEvents = true;

            decrnca.Start();

            await Task.Run(() => decrnca.WaitForExit());

            decrnca.Close();

            extractncau();
        }

19 Source : TreeViewExtensions.cs
with MIT License
from Adsito

public static IOrderedEnumerable<T> Order<T, TKey>(this IEnumerable<T> source, Func<T, TKey> selector, bool ascending)
	{
		if (ascending)
			return source.OrderBy(selector);
		else
			return source.OrderByDescending(selector);
	}

19 Source : IInValueCache.cs
with MIT License
from AElfProject

public Hash GetInValue(long roundId)
        {
            // Remove old in values. (Keep 10 in values.)
            const int keepInValuesCount = 10;
            if (_inValues.Keys.Count > keepInValuesCount)
            {
                foreach (var id in _inValues.Keys.OrderByDescending(id => id).Skip(keepInValuesCount))
                {
                    _inValues.Remove(id);
                }
            }

            _inValues.TryGetValue(roundId, out var inValue);
            return inValue ?? Hash.Empty;
        }

19 Source : LogManager.cs
with MIT License
from aguang-xyz

public Task<IEnumerable<string>> GetLogFileNamesAsync()
        {
            try
            {
                var directoryInfo = new DirectoryInfo(PathUtils.LogFolder);
                var fileNames = directoryInfo
                    .GetFiles("*.log")
                    .Select(file => file.Name)
                    .OrderByDescending(fileName => fileName)
                    .AsEnumerable();
                
                return Task.FromResult(fileNames);
            }
            catch (Exception)
            {
                return Task.FromResult(Array.Empty<string>().AsEnumerable());
            }
        }

19 Source : YtbMediaProvider.cs
with MIT License
from aguang-xyz

private static string GetThumbnailUrl(IEnumerable<Thumbnail> thumbnails)
        {
            return thumbnails
                .OrderByDescending(thumbnail => thumbnail.Resolution.Width)
                .FirstOrDefault()?.Url;
        }

19 Source : LinqSample.cs
with The Unlicense
from ahotko

private void SumAgeByLastnameGroupingOrderedDescending()
        {
            var ageLastnameGroups =
                (from sample in _sampleList
                 group sample by sample.LastName into sampleGroup
                 select
                 new
                 {
                     Group = sampleGroup.Key,
                     SumAge = sampleGroup.Sum(x => x.Age),
                     CountMembers = sampleGroup.Count()
                 }).OrderByDescending(x => x.CountMembers);
            //use result
            foreach (var sample in ageLastnameGroups)
            {
                Console.WriteLine($"Lastname = {sample.Group}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}");
            }
        }

19 Source : LinqSample.cs
with The Unlicense
from ahotko

private void SumAgeByLastnameAndPlaceGroupingOrderedTop5()
        {
            var ageLastnameGroups =
                (from sample in _sampleList
                 group sample by new { sample.LastName, sample.Place } into sampleGroup
                 select
                 new
                 {
                     GroupingKey = sampleGroup.Key,
                     SumAge = sampleGroup.Sum(x => x.Age),
                     CountMembers = sampleGroup.Count()
                 }).OrderByDescending(x => x.CountMembers).Take(5);
            //use result
            foreach (var sample in ageLastnameGroups)
            {
                Console.WriteLine($"Lastname = {sample.GroupingKey.LastName}, Place = {sample.GroupingKey.Place}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}");
            }
        }

19 Source : LinqSample.cs
with The Unlicense
from ahotko

private void SumAgeByLastnameAndPlaceGroupingOrderedSecond5()
        {
            var ageLastnameGroups =
                (from sample in _sampleList
                 group sample by new { sample.LastName, sample.Place } into sampleGroup
                 select
                 new
                 {
                     GroupingKey = sampleGroup.Key,
                     SumAge = sampleGroup.Sum(x => x.Age),
                     CountMembers = sampleGroup.Count()
                 }).OrderByDescending(x => x.CountMembers).Skip(5).Take(5);
            //use result
            foreach (var sample in ageLastnameGroups)
            {
                Console.WriteLine($"Lastname = {sample.GroupingKey.LastName}, Place = {sample.GroupingKey.Place}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}");
            }
        }

19 Source : LinqSample.cs
with The Unlicense
from ahotko

private void SumAgeByLastnameAndPlaceGroupingOrderedLast5()
        {
            var ageLastnameGroups =
                (from sample in _sampleList
                 group sample by new { sample.LastName, sample.Place } into sampleGroup
                 select
                 new
                 {
                     GroupingKey = sampleGroup.Key,
                     SumAge = sampleGroup.Sum(x => x.Age),
                     CountMembers = sampleGroup.Count()
                 }).OrderByDescending(x => x.CountMembers);
            var last5AgeLastnameGroups = ageLastnameGroups.Skip(Math.Max(0, ageLastnameGroups.Count() - 5));
            //use result
            foreach (var sample in last5AgeLastnameGroups)
            {
                Console.WriteLine($"Lastname = {sample.GroupingKey.LastName}, Place = {sample.GroupingKey.Place}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}");
            }
        }

19 Source : Command.cs
with MIT License
from Aiko-IT-Systems

public virtual async Task<CommandResult> ExecuteAsync(CommandContext ctx)
        {
            CommandResult res = default;
            try
            {
                var executed = false;
                foreach (var ovl in this.Overloads.OrderByDescending(x => x.Priority))
                {
                    ctx.Overload = ovl;
                    var args = await CommandsNextUtilities.BindArguments(ctx, ctx.Config.IgnoreExtraArguments).ConfigureAwait(false);

                    if (!args.IsSuccessful)
                        continue;

                    ctx.RawArguments = args.Raw;

                    var mdl = ovl.InvocationTarget ?? this.Module?.GetInstance(ctx.Services);
                    if (mdl is BaseCommandModule bcmBefore)
                        await bcmBefore.BeforeExecutionAsync(ctx).ConfigureAwait(false);

                    args.Converted[0] = mdl;
                    var ret = (Task)ovl.Callable.DynamicInvoke(args.Converted);
                    await ret.ConfigureAwait(false);
                    executed = true;
                    res = new CommandResult
                    {
                        IsSuccessful = true,
                        Context = ctx
                    };

                    if (mdl is BaseCommandModule bcmAfter)
                        await bcmAfter.AfterExecutionAsync(ctx).ConfigureAwait(false);
                    break;
                }

                if (!executed)
                    throw new ArgumentException("Could not find a suitable overload for the command.");
            }
            catch (Exception ex)
            {
                res = new CommandResult
                {
                    IsSuccessful = false,
                    Exception = ex,
                    Context = ctx
                };
            }

            return res;
        }

19 Source : GroupConversation.cs
with MIT License
from AiursoftWeb

public override Conversation Build(string userId, OnlineJudger onlineJudger)
        {
            DisplayName = GetDisplayName(userId);
            DisplayImagePath = GetDisplayImagePath(userId);
            Users = Users.OrderByDescending(t => t.UserId == OwnerId).ThenBy(t => t.JoinTime);
            foreach (var user in Users)
            {
                user.User.Build(onlineJudger);
            }
            return this;
        }

See More Examples