System.Collections.Generic.IEnumerable.Except(System.Collections.Generic.IEnumerable)

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

903 Examples 7

19 Source : PermutationTableTests.cs
with MIT License
from damageboy

[Test]
        [Repeat(1000)]
        public unsafe void GeneratedPermutationsAreCorrect()
        {
            var perms = GenerateStableIntPermTableValues().ToArray();

            for (var i = 0U; i < 256U; i++) {
                var pivot = 666;

                var r = new Random((int) DateTime.UtcNow.Ticks);

                var data = new int[8] {-1, -1, -1, -1, -1, -1, -1, -1};
                for (var j = 0; j < 8; j++) {
                    data[j] = (((i >> j) & 0x1) == 0) ? r.Next(0, 666) : r.Next(777, 1000);
                }

                // Check if I messed up and there's a -1 somewhere
                replacedert.That(data, Is.All.Not.Negative);

                var permutedData = new int[8];

                fixed (int* perm = &perms[i][0])
                fixed (int* pSrc = &data[0])
                fixed (int* pDest = &permutedData[0]) {
                    var dataVector = LoadDquVector256(pSrc);
                    dataVector = PermuteVar8x32(dataVector, LoadDquVector256(perm));
                    Store(pDest, dataVector);
                }

                var numLeft = 8 - (int) Popcnt.PopCount(i);
                replacedert.That(permutedData[0..numLeft], Is.All.LessThan(pivot));
                replacedert.That(permutedData[numLeft..], Is.All.GreaterThan(pivot));
                replacedert.That(data.Except(permutedData), Is.Empty);
            }
        }

19 Source : Program.cs
with MIT License
from damienbod

public static int Main(string[] args)
        {
            var seed = args.Any(x => x == "/seed");
            if (seed) args = args.Except(new[] { "/seed" }).ToArray();

            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                .Enrich.FromLogContext()
                .WriteTo.Console()
                .CreateLogger();

            try
            {
                Log.Information("Starting web host");

                if (seed)
                {
                    var host = CreateHostBuilder(args).Build();

                    SeedData.EnsureSeedData(host.Services);
                    return 0;
                }

                CreateHostBuilder(args).Build().Run();
                return 0;
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
                return 1;
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

19 Source : AndroidManifest.cs
with MIT License
from dansiegel

public void SetAndroidPermissions(IEnumerable<string> permissions)
        {
            var newPerms = new HashSet<string>(permissions.Select(FullyQualifyPermission));
            var current = new HashSet<string>(AndroidPermissionsQualified);
            AddAndroidPermissions(newPerms.Except(current));
            RemoveAndroidPermissions(current.Except(newPerms));
        }

19 Source : EMFloorFunction.cs
with MIT License
from DanzaG

private void MoveFloor(TR2Level level)
        {
            // Find the vertices of the current floor for the tile at the given location, create 4 additional 
            // vertices on top and make new TRFace4 entries for the sides so the platform isn't floating.
            // TODO: how to handle raising/lowering slants, all of this replacedumes a flat floor to begin with.

            int clickChange = Clicks * ClickSize;

            FDControl fdc = new FDControl();
            fdc.ParseFromLevel(level);

            short roomNumber = (short)ConverreplacedemNumber(Location.Room, level.NumRooms);
            TR2Room room = level.Rooms[roomNumber];
            TRRoomSector sector = FDUtilities.GetRoomSector(Location.X, Location.Y, Location.Z, roomNumber, level, fdc);
            int sectorIndex = room.SectorList.ToList().IndexOf(sector);

            // Find the current vertices for this tile
            short x = (short)(sectorIndex / room.NumZSectors * SectorSize);
            short z = (short)(sectorIndex % room.NumZSectors * SectorSize);
            short y = (short)(sector.Floor * ClickSize);

            List<TR2RoomVertex> vertices = room.RoomData.Vertices.ToList();
            List<ushort> oldVertIndices = new List<ushort>();

            List<TRVertex> defVerts = GetTileVertices(x, y, z, false);
            // Check the Y vals are unanimous because we currently only support raising/lowering flat surfaces
            if (!defVerts.All(v => v.Y == defVerts[0].Y))
            {
                throw new NotImplementedException("Floor manipulation is limited to flat surfaces only.");
            }

            for (int i = 0; i < defVerts.Count; i++)
            {
                TRVertex vert = defVerts[i];
                int vi = vertices.FindIndex(v => v.Vertex.X == vert.X && v.Vertex.Z == vert.Z && v.Vertex.Y == vert.Y);
                if (vi != -1)
                {
                    oldVertIndices.Add((ushort)vi);
                }
            }

            // Create new vertices - we can't just change the original vertex Y vals as adjoining tiles also use 
            // those and we need the originals for the new sides to this platform.
            List<ushort> newVertIndices = new List<ushort>();
            foreach (ushort vert in oldVertIndices)
            {
                TR2RoomVertex oldRoomVertex = vertices[vert];
                TRVertex oldVert = vertices[vert].Vertex;
                TRVertex newVertex = new TRVertex
                {
                    X = oldVert.X,
                    Y = (short)(oldVert.Y + clickChange),
                    Z = oldVert.Z
                };
                newVertIndices.Add((ushort)CreateRoomVertex(room, newVertex, oldRoomVertex.Lighting, oldRoomVertex.Lighting2));
            }

            // Refresh
            vertices = room.RoomData.Vertices.ToList();

            // Get the tile face that matches the vertex list
            List<TRFace4> rectangles = room.RoomData.Rectangles.ToList();
            TRFace4 floorFace = rectangles.Find(r => r.Vertices.ToList().All(oldVertIndices.Contains));

            // If the floor has been lowered (remember +Clicks = move down, -Clicks = move up)
            // then the sides will also need lowering.
            if (Clicks > 0)
            {
                // Find faces that share 2 of the old vertices
                int floorY = room.RoomData.Vertices[floorFace.Vertices[0]].Vertex.Y;
                foreach (TRFace4 face in rectangles)
                {
                    if (face == floorFace)
                    {
                        continue;
                    }

                    List<ushort> faceVerts = face.Vertices.ToList();
                    List<ushort> sharedVerts = faceVerts.Where(oldVertIndices.Contains).ToList();
                    List<ushort> uniqueVerts = faceVerts.Except(sharedVerts).ToList();
                    if (sharedVerts.Count == 2 && uniqueVerts.Count == 2)
                    {
                        foreach (ushort sharedVert in sharedVerts)
                        {
                            int i = faceVerts.IndexOf(sharedVert);
                            TRVertex oldVert = vertices[sharedVert].Vertex;
                            foreach (ushort newVert in newVertIndices)
                            {
                                TRVertex newVertex = vertices[newVert].Vertex;
                                if (newVertex.X == oldVert.X && newVertex.Z == oldVert.Z)
                                {
                                    faceVerts[i] = newVert;
                                }
                            }
                        }
                        face.Vertices = faceVerts.ToArray();
                    }
                }
            }

            // Now change the floor face's vertices, and its texture provided we want to.
            if (floorFace != null && !RetainOriginalFloor)
            {
                floorFace.Vertices = newVertIndices.ToArray();
                if (FloorTexture != ushort.MaxValue)
                {
                    floorFace.Texture = FloorTexture;
                }
            }

            // Make faces for the new platform's sides if we have clicked up, again provided we want to.
            if (Clicks < 0 && SideTexture != ushort.MaxValue)
            {
                for (int i = 0; i < 4; i++)
                {
                    // Only texture this side if it's set in the flags
                    if (((1 << i) & Flags) > 0)
                    {
                        int j = i == 3 ? 0 : (i + 1);
                        rectangles.Add(new TRFace4
                        {
                            Texture = SideTexture,
                            Vertices = new ushort[]
                            {
                                newVertIndices[j],
                                newVertIndices[i],
                                oldVertIndices[i],
                                oldVertIndices[j]
                            }
                        });
                    }
                }
            }

            // Save the new faces
            room.RoomData.Rectangles = rectangles.ToArray();
            room.RoomData.NumRectangles = (short)rectangles.Count;

            // Account for the added faces
            room.NumDataWords = (uint)(room.RoomData.Serialize().Length / 2);

            // Now shift the actual sector info and adjust the box if necessary
            sector.Floor += Clicks;
            AlterSectorBox(level, room, sectorIndex);

            // Move any enreplacedies that share the same floor sector up or down the relevant number of clicks
            foreach (TR2Enreplacedy enreplacedy in level.Enreplacedies)
            {
                if (enreplacedy.Room == roomNumber)
                {
                    TRRoomSector enreplacedySector = FDUtilities.GetRoomSector(enreplacedy.X, enreplacedy.Y, enreplacedy.Z, enreplacedy.Room, level, fdc);
                    if (enreplacedySector == sector)
                    {
                        enreplacedy.Y += clickChange;
                    }
                }
            }
        }

19 Source : ChannelMovieNotifier.cs
with MIT License
from darkalfx

private void HandleRemovedUsers(HashSet<ulong> discordUserIds, HashSet<ulong> userNotified, CancellationToken token)
        {
            var currentMembers = new HashSet<ulong>(_discordClient.Guilds.SelectMany(x => x.Value.Members).Select(x => x.Value.Id));

            foreach (var missingUserIds in discordUserIds.Except(currentMembers))
            {
                if (token.IsCancellationRequested)
                    return;

                userNotified.Add(missingUserIds);
                _logger.LogWarning($"Removing movie notification for user with ID {missingUserIds} as it could not be found in any of the guilds.");
            }
        }

19 Source : ChannelTvShowNotifier.cs
with MIT License
from darkalfx

private void HandleRemovedUsers(HashSet<ulong> discordUserIds, HashSet<ulong> userNotified, CancellationToken token)
        {
            var currentMembers = new HashSet<ulong>(_discordClient.Guilds.SelectMany(x => x.Value.Members).Select(x => x.Value.Id));

            foreach (var missingUserIds in discordUserIds.Except(currentMembers))
            {
                if (token.IsCancellationRequested)
                    return;

                userNotified.Add(missingUserIds);
                _logger.LogWarning($"Removing tv show notification for user with ID {missingUserIds} as it could not be found in any of the guilds.");
            }
        }

19 Source : Program.cs
with MIT License
from DarinHan

public static void Main(string[] args)
        {
            var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClreplacedLogger();
            try
            {
                logger.Debug("init main");
                var seed = args.Contains("--seed");
                if (seed)
                {
                    args = args.Except(new[] { "--seed" }).ToArray();
                }
                var host = CreateWebHostBuilder(args).Build();

                if (seed)
                {
                    SeedData.EnsureSeedData(host.Services);
                }

                host.Run();
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Stopped program because of exception");
                throw;
            }
            finally
            {
                NLog.LogManager.Shutdown();
            }
        }

19 Source : Patcher.cs
with MIT License
from darktohka

public static void PatchAll() {
            if (MessageBox.Show("Are you sure you want to patch your system-wide Flash plugins to allow Flash games to be played in your browser?", "FlashPatch!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) {
                return;
            }

            if (MessageBox.Show("Have you closed ALL your browser windows yet?\n\nIf not, please close them right now!", "FlashPatch!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) {
                return;
            }

            if (MessageBox.Show("WARNING!\n\nThe developers of this program do not replacedume any responsibility for the usage of this tool.\n\nEven though the developers have tried their best to ensure the quality of this tool, it may introduce instability, or even crash your computer.\n\nAll changes made by the program may be reverted using the \"Restore\" button, but even this option is provided on a best-effort basis.\n\nAll responsibility falls upon your shoulders.\n\nEven so, are you sure you want to continue?", "FlashPatch!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes) {
                return;
            }

            IntPtr redirection = DisableRedirection();

            string flashDir32 = GetFlashDir32();

            if (!Directory.Exists(flashDir32)) {
                ShowError(string.Format("Could not find 32-bit Flash directory!\n\n{0} does not exist.", flashDir32));
                return;
            }

            bool x64 = Environment.Is64BitOperatingSystem;
            string flashDir64 = null;

            if (x64) {
                flashDir64 = GetFlashDir64();

                if (!Directory.Exists(flashDir64)) {
                    ShowError(string.Format("Could not find 64-bit Flash directory!\n\n{0} does not exist.", flashDir64));
                    return;
                }
            }

            foreach (string service in telemetryServices) {
                try {
                    ChangeServiceStartMode(service, "Disabled");
                } catch (Exception) {
                    // It's fine if this doesn't work
                }

                try {
                    StopService(service);
                } catch (Exception) {
                    // It's fine if this doesn't work
                }
            }

            try {
                foreach (string telemetryApp in telemetryApps) {
                    PreventExecution(telemetryApp);
                }
            } catch (Exception e) {
                ShowError(string.Format("Could not disable Flash Player telemetry! Are you running this application as administrator?\n\n{0}", e.Message));
            }

            List<string> patched = new List<string>();
            List<string> alreadyPatched = new List<string>();
            List<string> notFound = new List<string>();
            List<string> incompatibleVersion = new List<string>();
            List<string> ownershipFailed = new List<string>();
            List<string> locked = new List<string>();
            List<string> errors = new List<string>();

            string backupFolder = Path.Combine(Environment.CurrentDirectory, "Backup");
            bool madeBackupFolder = false;

            foreach (PatchableBinary binary in Patches.GetBinaries()) {
                if (!binary.HasFilenames()) {
                    // This is a special binary, as we do not specifically look for it.
                    // This binary can only be patched using the "Patch File..." option
                    continue;
                }

                bool binaryX64 = binary.IsX64();

                if (binaryX64 && !x64) {
                    // This is a 64-bit binary, but we are not on a 64-bit system.
                    continue;
                }

                string name = binary.GetName();
                bool found = false;

                foreach (string filename in binary.GetFilenames()) {
                    List<string> paths = new List<string>();

                    paths.Add(Path.Combine(binaryX64 ? flashDir64 : flashDir32, filename));
                    paths.AddRange(binary.GetAlternatePaths());

                    foreach (string path in paths) {
                        if (!File.Exists(path)) {
                            continue;
                        }

                        string version = GetVersion(path);

                        if (!binary.GetVersion().Equals(version)) {
                            // We've encountered an incompatible version.
                            found = true;
                            incompatibleVersion.Add(string.Format("{0} ({1})", name, version));
                            continue;
                        }

                        long size = new FileInfo(path).Length;

                        if (binary.HasFileSize() && binary.GetFileSize() != size) {
                            // This file's size does not match the expected file size.
                            continue;
                        }

                        found = true;

                        try {
                            TakeOwnership(path);
                        } catch {
                            // We failed to get ownership of the file...
                            // No continue here, we still want to try to patch the file
                            ownershipFailed.Add(name);
                        }

                        try {
                            using (FileStream fileStream = File.Open(path, FileMode.Open, FileAccess.Read)) {
                                if (!binary.IsPatchable(fileStream)) {
                                    // This binary has already been patched.
                                    alreadyPatched.Add(name);
                                    continue;
                                }
                            }

                            if (!madeBackupFolder && !Directory.Exists(backupFolder)) {
                                Directory.CreateDirectory(backupFolder);
                                madeBackupFolder = true;
                            }

                            // Back up the current plugin to our backup folder
                            File.Copy(path, Path.Combine(backupFolder, binary.GetBackupFileName(filename)), true);

                            using (FileStream fileStream = File.Open(path, FileMode.Open, FileAccess.ReadWrite)) {
                                // Apply all pending binary patches!
                                binary.PatchFile(fileStream);
                            }

                            if (!patched.Contains(name)) {
                                patched.Add(name);
                            }
                        } catch (Exception e) {
                            if (IsSharingViolation(e)) {
                                // This is a sharing violation; i.e. the file is currently being used.
                                locked.Add(name);
                            } else {
                                errors.Add(e.Message);
                            }
                        }
                    }
                }

                if (!found && !notFound.Contains(name)) {
                    // Add this binary to the not found list.
                    notFound.Add(name);
                }
            }

            EnableRedirection(redirection);

            StringBuilder report = new StringBuilder();
            MessageBoxIcon icon = MessageBoxIcon.Information;

            alreadyPatched = alreadyPatched.Except(patched).ToList();
            notFound = notFound.Except(patched).Except(alreadyPatched).ToList();
            incompatibleVersion = incompatibleVersion.Except(patched).Except(alreadyPatched).ToList();

            AppendItems(report, "Successfully patched these plugins:", patched);
            AppendItems(report, "These plugins have already been patched:", alreadyPatched);
            AppendItems(report, "These plugins have not been found on your system:", notFound);
            AppendItems(report, "These plugins are incompatible with the patch because their version is outdated:", incompatibleVersion);
            AppendItems(report, "These plugins could not be patched because their respective browser is currently open:", locked);
            AppendItems(report, "Caught exceptions:", errors);

            if (incompatibleVersion.Count > 0 || locked.Count > 0 || errors.Count > 0) {
                icon = MessageBoxIcon.Warning;
                report.AppendLine("Errors have been encountered during the patching process.\nPlease try again after reading the message above carefully.\nIf the browser you're using has been patched successfully, then no more action is required.");
            } else if (patched.Count > 0) {
                report.AppendLine("CONGRATULATIONS! The patching process has completed as expected. Enjoy your Flash games!");
            } else if (alreadyPatched.Count > 0) {
                report.AppendLine("Flash Player has already been patched on this system.\n\nNo more action is required! Enjoy your games!");
            } else {
                report.AppendLine("No action has been taken.");
            }

            MessageBox.Show(report.ToString(), "FlashPatch!", MessageBoxButtons.OK, icon);
        }

19 Source : EdsmPlugin.cs
with MIT License
from DarkWanderer

public override void ReloadSettings()
        {
            FlushQueue();
            var actualApiKeys = GetActualApiKeys();

            // Update keys for which new values were provided
            foreach (var kvp in actualApiKeys)
                ApiKeys.AddOrUpdate(kvp.Key, kvp.Value, (key, oldValue) => kvp.Value);

            // Remove keys which were removed from config
            foreach (string key in ApiKeys.Keys.Except(actualApiKeys.Keys))
                ApiKeys.TryRemove(key, out string _);
        }

19 Source : HasConditionInWithValuesExtensions.cs
with MIT License
from daryllabar

private static bool ValuesInConditionIn(this ConditionExpression c1, string attributeName, IEnumerable<object> values)
        {
            var list = values.ToList();
            return (c1 != null && attributeName != null && list.Any() &&
                c1.AttributeName == attributeName &&
                c1.Operator == ConditionOperator.In &&
                !list.Except(c1.Values).Any()); // http://stackoverflow.com/questions/332973/linq-check-whether-an-array-is-a-subset-of-another
        }

19 Source : DataBuilderGenerator.cs
with MIT License
from dasMulli

private static bool TryAddBuildMethod(GeneratorExecutionContext context, BuilderToGenerate builder, ref ClreplacedDeclarationSyntax builderClreplaced)
        {
            var objectType = ParseTypeName(builder.Name);
            var buildMethodStatements = new List<StatementSyntax>();

            var creationExpression = ObjectCreationExpression(objectType);
            var propertiesSetViaConstructor = new List<PropertyToGenerate>();

            if (builder.ConstructorToUse is { } constructorToUse)
            {
                var arguments = new ArgumentSyntax[constructorToUse.Parameters.Length];
                var blocked = false;
                for (var i = 0; i < constructorToUse.Parameters.Length; i++)
                {
                    var parameterName = constructorToUse.Parameters[i].Name;
                    var matchingProperty = builder.Properties.FirstOrDefault(p =>
                        p.PropertyName.Equals(parameterName, StringComparison.OrdinalIgnoreCase));
                    if (matchingProperty == null)
                    {
                        context.ReportDiagnostic(Diagnostic.Create(CannotInferBuilderPropertyFromArgumentDiagnostic,
                            constructorToUse.Parameters[i].Locations[0]));
                        blocked = true;
                    }
                    else
                    {
                        arguments[i] = Argument(PropertyAccessAndDefaultingExpression(matchingProperty));
                        propertiesSetViaConstructor.Add(matchingProperty);
                    }

                    foreach (var property in propertiesSetViaConstructor)
                    {
                        if (property.IsReferenceType && !property.IsNullable)
                        {
                            var throwStatement = ThrowStatement(ObjectCreationExpression(ParseTypeName("System.InvalidOperationException"))
                                .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression,
                                    Literal($"No value present for required property '{property.PropertyName}'.")))));
                            buildMethodStatements.Add(IfStatement(NullCheck(IdentifierName(property.FieldName)), throwStatement));
                        }
                    }
                }

                if (blocked)
                {
                    return false;
                }

                creationExpression = creationExpression.AddArgumentListArguments(arguments);
            }
            else
            {
                creationExpression = creationExpression.WithArgumentList(ArgumentList());
            }

            var buildingInstanceIdentifier = Identifier("instance");
            buildMethodStatements.Add(LocalDeclarationStatement(VariableDeclaration(IdentifierName("var"))
                .AddVariables(VariableDeclarator(buildingInstanceIdentifier)
                    .WithInitializer(EqualsValueClause(creationExpression)))));

            buildMethodStatements.AddRange(builder.Properties.Except(propertiesSetViaConstructor).Select(property =>
                (StatementSyntax)IfStatement(
                     PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, ParenthesizedExpression(NullCheck(IdentifierName(property.FieldName)))),
                     ExpressionStatement(
                        replacedignmentExpression(SyntaxKind.SimplereplacedignmentExpression,
                            MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
                                IdentifierName(buildingInstanceIdentifier),
                                IdentifierName(property.PropertyName)),
                            PropertyAccessUnwrappingNullables(property))))));

            buildMethodStatements.Add(ReturnStatement(IdentifierName(buildingInstanceIdentifier)));

            builderClreplaced = builderClreplaced.AddMembers(
                MethodDeclaration(objectType, "Build")
                    .AddModifiers(Token(SyntaxKind.PublicKeyword))
                    .WithBody(Block(buildMethodStatements)));

            return true;
        }

19 Source : ServiceDefinition.cs
with Apache License 2.0
from Dasync

public bool RemoveInterface(Type interfaceType)
        {
            if (!_interfaces.Contains(interfaceType))
                return false;
            _interfaces = _interfaces.Except(new[] { interfaceType }).ToArray();
            Model.OnServiceInterfaceRemoved(this, interfaceType);
            return true;
        }

19 Source : IndexBuilder.ClusteredIndexes.cs
with MIT License
from DataObjects-NET

private static IndexInfo ChooseClusteredIndexConcreteTable(TypeInfo type, List<IndexInfo> indexes, Dictionary<TypeInfo, IndexInfo> clusteredIndexesMap)
    {
      var declaredIndexes = indexes.Where(i => i.DeclaringType==i.ReflectedType).ToList();
      var inheritedIndexes = indexes.Except(declaredIndexes).ToList();

      if (declaredIndexes.Count > 1)
        throw TooManyClusteredIndexes(type, indexes);

      if (declaredIndexes.Count==1) {
        // Use secondary clustered index declared in this type.
        DeclareNonClustered(GetPrimaryIndexForCorrespondingTable(type));
        DeclareNonClustered(inheritedIndexes);
        return declaredIndexes[0];
      }

      // Use secondary clustered index inherited from parent (if any).

      if (inheritedIndexes.Count==0)
        return null;

      if (inheritedIndexes.Count==1) {
        // Use the only inherited clustered index.
        DeclareNonClustered(GetPrimaryIndexForCorrespondingTable(type));
        return inheritedIndexes[0];
      }

      // We need to choose index that is clustered in parent type.

      var parentClusteredIndex = clusteredIndexesMap[type.GetAncestor()];
      if (parentClusteredIndex == null)
        throw Exceptions.InternalError("inheritedIndexes is not empty, but parentClusteredIndex is not specified", BuildLog.Instance);

      var winner = inheritedIndexes.FirstOrDefault(i => i.DeclaringIndex==parentClusteredIndex.DeclaringIndex);
      if (winner == null)
        throw Exceptions.InternalError("matching inherited index is not found", BuildLog.Instance);
      DeclareNonClustered(GetPrimaryIndexForCorrespondingTable(type));
      DeclareNonClustered(inheritedIndexes.Where(i => i != winner));
      return winner;
    }

19 Source : Issue0808_StructSerialization.cs
with MIT License
from DataObjects-NET

[Test]
    public void MainTest()
    {
      var t = typeof(UnifiedCustomerID);
      Expression<Func<int, UnifiedCustomerID>> ex = a => new UnifiedCustomerID { Id = 2 };
      var serializableExpression = ex.ToSerializableExpression();
      var memoryStream = new MemoryStream();

      var serializer = new DataContractSerializer(typeof (SerializableLambdaExpression),
        SerializableExpressionTypes.Except(Enumerable.Repeat(typeof (SerializableLambdaExpression), 1)));

      serializer.WriteObject(memoryStream, serializableExpression);

      memoryStream.Position = 0;

      var deserializedExpression = (SerializableLambdaExpression) serializer.ReadObject(memoryStream);

      var ex2 = deserializedExpression.ToExpression();
    }

19 Source : GroupByTest.cs
with MIT License
from DataObjects-NET

[Test]
    public void EnreplacedyGroupTest()
    {
      Require.ProviderIsNot(StorageProvider.SqlServerCe);
      var groupByResult = Session.Query.All<Track>().GroupBy(t => t.MediaType);
      IEnumerable<MediaType> result = groupByResult
        .ToList()
        .Select(g => g.Key);
      IEnumerable<MediaType> expectedKeys = Session.Query.All<Track>()
        .Select(p => p.MediaType)
        .Distinct()
        .ToList();

      replacedert.That(result, Is.Not.Empty);
      replacedert.AreEqual(0, expectedKeys.Except(result).Count());

      foreach (var grouping in groupByResult) {
        var items = Session.Query.All<Track>()
          .Where(t => t.MediaType==grouping.Key)
          .ToList();
        replacedert.AreEqual(0, items.Except(grouping).Count());
      }
      DumpGrouping(groupByResult);
    }

19 Source : TopologicalSorterTest.cs
with MIT License
from DataObjects-NET

[Test]
        public void RemoveWholeNodeTest()
        {
            var node1 = new Node<int, string>(1);
            var node2 = new Node<int, string>(2);
            var connection12_1 = new NodeConnection<int, string>(node1, node2, "ConnectionItem 1->2 1");
            connection12_1.BindToNodes();
            var connection12_2 = new NodeConnection<int, string>(node1, node2, "ConnectionItem 1->2 2");
            connection12_2.BindToNodes();
            var connection21_1 = new NodeConnection<int, string>(node2, node1, "ConnectionItem 2->1 1");
            connection21_1.BindToNodes();

            // Remove edge by edge.

            List<NodeConnection<int, string>> removedEdges;
            List<int> result = TopologicalSorter.Sort(new[] {node2, node1}, out removedEdges);
            replacedert.AreEqual(2, result.Count);
            replacedert.AreEqual(node1.Item, result[0]);
            replacedert.AreEqual(node2.Item, result[1]);

            replacedert.AreEqual(1, removedEdges.Count);
            replacedert.AreEqual(connection21_1, removedEdges[0]);

            // Remove whole node
            connection12_1.BindToNodes();
            connection12_2.BindToNodes();
            connection21_1.BindToNodes();

            result = TopologicalSorter.Sort(new[] {node2, node1}, out removedEdges, true);
            replacedert.AreEqual(2, result.Count);
            replacedert.AreEqual(node1.Item, result[1]);
            replacedert.AreEqual(node2.Item, result[0]);

            replacedert.AreEqual(2, removedEdges.Count);
            replacedert.AreEqual(0, removedEdges.Except(new[] {connection12_1, connection12_2}).Count());
        }

19 Source : ProfilerResult.cs
with MIT License
from daveaglick

public override bool Equals(object obj)
        {
            if (!(obj is ProfilerResult))
            {
                return false;
            }

            ProfilerResult result = (ProfilerResult)obj;

            return (ProfiledLocations == result.ProfiledLocations)
                   || (ProfiledLocations.Count == result.ProfiledLocations.Count
                    && !ProfiledLocations.Except(result.ProfiledLocations).Any());
        }

19 Source : Feature.cs
with MIT License
from davetimmins

public bool AttributesAreTheSame(Feature<T> other)
        {
            if (other == null || other.Attributes == null || Attributes == null || !Attributes.Any())
            {
                return false;
            }

            return (Attributes.Count == other.Attributes.Count) && !(Attributes.Except(other.Attributes)).Any();
        }

19 Source : CityGMLReader.cs
with GNU General Public License v3.0
from dd-bim

private CityGml_Surface ReadSurfaceData(XElement poly, CityGml_Surface rawFace)
        {
            var surface = new CityGml_Surface
            {
                SurfaceId = rawFace.SurfaceId,
                SurfaceAttributes = rawFace.SurfaceAttributes,
                Facetype = rawFace.Facetype
            };

            #region ExteriorPolygon

            //only one could (should) exist

            var exteriorF = poly.Descendants(allns["gml"] + "exterior").FirstOrDefault();

            var posListExt = exteriorF.Descendants(allns["gml"] + "posList");

            var ptList = new List<C2BPoint>();

            if (posListExt.Any())
            {
                ptList.AddRange(CollectPoints(posListExt.FirstOrDefault(), lowerCornerPt));
            }
            else
            {
                var posExt = exteriorF.Descendants(allns["gml"] + "pos");

                foreach (var pos in posExt)
                {
                    ptList.Add(CollectPoint(pos, lowerCornerPt));
                }
            }

            //-------------------Check section-----------------------

            //Start = End

            if (!CheckSameStartEnd(ptList))
                ptList.Add(ptList[0]);

            List<C2BPoint> pointsRed = ptList;
            //-------------

            var deletionXY = CheckForDeadEndAtAxisPlane(pointsRed, 'z');

            if (deletionXY.Count > 0)
            {
                bool addNewStart = false;

                if (deletionXY.Where(p => p.X == pointsRed[0].X && p.Y == pointsRed[0].Y && p.Z == pointsRed[0].Z).Any())
                    addNewStart = true;

                pointsRed = pointsRed.Except(deletionXY).ToList();

                if (addNewStart)
                    pointsRed.Add(pointsRed[0]);
            }

            var deletionXZ = CheckForDeadEndAtAxisPlane(pointsRed, 'y');

            if (deletionXZ.Count > 0)
            {
                bool addNewStart = false;

                if (deletionXZ.Where(p => p.X == pointsRed[0].X && p.Y == pointsRed[0].Y && p.Z == pointsRed[0].Z).Any())
                    addNewStart = true;

                pointsRed = pointsRed.Except(deletionXZ).ToList();

                if (addNewStart)
                    pointsRed.Add(pointsRed[0]);
            }

            var deletionYZ = CheckForDeadEndAtAxisPlane(pointsRed, 'x');

            if (deletionYZ.Count > 0)
            {
                bool addNewStart = false;

                if (deletionYZ.Where(p => p.X == pointsRed[0].X && p.Y == pointsRed[0].Y && p.Z == pointsRed[0].Z).Any())
                    addNewStart = true;

                pointsRed = pointsRed.Except(deletionYZ).ToList();

                if (addNewStart)
                    pointsRed.Add(pointsRed[0]);
            }

            //--------------

            //Duplicates:
            pointsRed = CheckDuplicates(pointsRed);

            //Too few points (possibly reduced point list will be investigated because dead end could be removed)
            if (!CheckNumberOfPoints(pointsRed))
                ptList.Clear();

            //-----------------------------------------------------------

            surface.ExteriorPts = pointsRed;

            #endregion ExteriorPolygon

            #region InteriorPolygon

            //if existent, it also could have more than one hole

            var interiorF = poly.Descendants(allns["gml"] + "interior");

            var posListInt = interiorF.Descendants(allns["gml"] + "posList").ToList();

            if (posListInt.Any())
            {
                List<List<C2BPoint>> interiorPolys = new List<List<C2BPoint>>();

                for (var j = 0; j < posListInt.Count(); j++)
                {
                    interiorPolys.Add(CollectPoints(posListInt[j], LowerCornerPt));
                }
                surface.InteriorPts = interiorPolys;
            }
            else
            {
                var rings = interiorF.Descendants(allns["gml"] + "LinearRing").ToList();

                List<List<C2BPoint>> interiorPolys = new List<List<C2BPoint>>();

                for (var k = 0; k < rings.Count() - 1; k++)
                {
                    var posInt = rings[k].Descendants(allns["gml"] + "pos");

                    if (posInt.Any())
                    {
                        var ptListI = new List<C2BPoint>();

                        foreach (var pos in posInt)
                        {
                            ptListI.Add(CollectPoint(pos, lowerCornerPt));
                        }
                        interiorPolys.Add(ptListI);
                    }
                }
                surface.InteriorPts = interiorPolys;
            }

            #endregion InteriorPolygon

            return surface;
        }

19 Source : CityGMLReader.cs
with GNU General Public License v3.0
from dd-bim

private List<CityGml_Surface> ReadSurfaces(XElement bldgEl, HashSet<Xml_AttrRep> attributes, out CityGml_Bldg.LodRep lod)
        {
            var bldgParts = bldgEl.Elements(allns["bldg"] + "consistsOfBuildingPart");
            var bldg = bldgEl.Elements().Except(bldgParts);

            var surfaces = new List<CityGml_Surface>();

            bool poly = bldg.Descendants().Where(l => l.Name.LocalName.Contains("Polygon")).Any();

            if (!poly)                  //no polygons --> directly return (e.g. Buildings with Parts but no geometry at building level)
            {
                lod = CityGml_Bldg.LodRep.unknown;
                return surfaces;
            }
            bool lod2 = bldg.DescendantsAndSelf().Where(l => l.Name.LocalName.Contains("lod2")).Count() > 0;
            bool lod1 = bldg.DescendantsAndSelf().Where(l => l.Name.LocalName.Contains("lod1")).Count() > 0;

            if (lod2)
            {
                lod = CityGml_Bldg.LodRep.LOD2;

                #region WallSurfaces

                var lod2Walls = bldg.DescendantsAndSelf(allns["bldg"] + "WallSurface");

                foreach (var wall in lod2Walls)
                {
                    List<CityGml_Surface> wallSurface = ReadSurfaceType(wall, CityGml_Surface.FaceType.wall);
                    if (wallSurface == null)
                        return null;

                    surfaces.AddRange(wallSurface);
                }

                #endregion WallSurfaces

                #region RoofSurfaces

                var lod2Roofs = bldg.DescendantsAndSelf(allns["bldg"] + "RoofSurface");

                foreach (var roof in lod2Roofs)
                {
                    List<CityGml_Surface> roofSurface = ReadSurfaceType(roof, CityGml_Surface.FaceType.roof);
                    surfaces.AddRange(roofSurface);
                }

                #endregion RoofSurfaces

                #region GroundSurfaces

                var lod2Grounds = bldg.DescendantsAndSelf(allns["bldg"] + "GroundSurface");

                foreach (var ground in lod2Grounds)
                {
                    List<CityGml_Surface> groundSurface = ReadSurfaceType(ground, CityGml_Surface.FaceType.ground);
                    surfaces.AddRange(groundSurface);
                }

                #endregion GroundSurfaces

                #region ClosureSurfaces

                var lod2Closures = bldg.DescendantsAndSelf(allns["bldg"] + "ClosureSurface");

                foreach (var closure in lod2Closures)
                {
                    List<CityGml_Surface> closureSurface = ReadSurfaceType(closure, CityGml_Surface.FaceType.closure);
                    surfaces.AddRange(closureSurface);
                }

                #endregion ClosureSurfaces

                #region OuterCeilingSurfaces

                var lod2OuterCeiling = bldg.DescendantsAndSelf(allns["bldg"] + "OuterCeilingSurface");

                foreach (var ceiling in lod2OuterCeiling)
                {
                    List<CityGml_Surface> outerCeilingSurface = ReadSurfaceType(ceiling, CityGml_Surface.FaceType.outerCeiling);
                    surfaces.AddRange(outerCeilingSurface);
                }

                #endregion OuterCeilingSurfaces

                #region OuterFloorSurfaces

                var lod2OuterFloor = bldg.DescendantsAndSelf(allns["bldg"] + "OuterFloorSurface");

                foreach (var floor in lod2OuterFloor)
                {
                    List<CityGml_Surface> outerFloorSurface = ReadSurfaceType(floor, CityGml_Surface.FaceType.outerFloor);
                    surfaces.AddRange(outerFloorSurface);
                }

                #endregion OuterFloorSurfaces
            }
            else if (lod1)
            {
                #region lod1Surfaces

                lod = CityGml_Bldg.LodRep.LOD1;

                //one occurence per building
                var lod1Rep = bldg.DescendantsAndSelf(allns["bldg"] + "lod1Solid").FirstOrDefault();

                if (lod1Rep == null)
                    lod1Rep = bldg.DescendantsAndSelf(allns["bldg"] + "lod1MultiSurface").FirstOrDefault();

                if (lod1Rep != null)
                {
                    var polys = lod1Rep.Descendants(allns["gml"] + "Polygon").ToList();
                    var elemsWithID = lod1Rep.DescendantsAndSelf().Where(a => a.Attribute(allns["gml"] + "id") != null);

                    for (var i = 0; i < polys.Count(); i++)          //normally 1 polygon but sometimes surfaces are grouped under the surface type
                    {
                        var surface = new CityGml_Surface();

                        /*
                        var faceID = polys[i].Attribute(allns["gml"] + "id").Value;

                        if (faceID == null)
                        {
                            var gmlSolid = lod1Rep.Descendants(allns["gml"] + "Solid").FirstOrDefault();

                            faceID = gmlSolid.Attribute(allns["gml"] + "id").Value;

                            if (faceID == null)
                            {
                                faceID = bldgEl.Attribute(allns["gml"] + "id").Value + "_" + i;
                            }
                        }
                        */

                        surface.Facetype = CityGml_Surface.FaceType.unknown;
                        surface.SurfaceAttributes = new ReadSemValues().ReadAttributeValuesSurface(polys[i], attributes, CityGml_Surface.FaceType.unknown);

                        var surfacePl = ReadSurfaceData(polys[i], surface);

                        surfaces.Add(surfacePl);
                    }
                }

                #endregion lod1Surfaces
            }
            else
                lod = CityGml_Bldg.LodRep.unknown;

            return surfaces;
        }

19 Source : ReadSemValues.cs
with GNU General Public License v3.0
from dd-bim

public Dictionary<Xml_AttrRep, string> ReadAttributeValuesBldg(XElement bldgEl, HashSet<Xml_AttrRep> attributes, Dictionary<string, XNamespace> nsp)
        {
            var bldgAttributes = attributes.Where(a => a.Reference == Xml_AttrRep.AttrHierarchy.bldgCity);

            var bldgParts = bldgEl.Elements(nsp["bldg"] + "consistsOfBuildingPart");
            var bldg = bldgEl.Elements().Except(bldgParts);

            var kvp = new Dictionary<Xml_AttrRep, string>();

            foreach(var attr in bldgAttributes)
            {
                //values im tag eingeschlossen:

                var matchAttr = bldg.DescendantsAndSelf().Where(n => n.Name.LocalName == attr.Name).ToList();
                //ar match = bldg.Descendants().Where(n => n.Name.LocalName == attr.Name).FirstOrDefault();

                //generische Attribute:

                if(attr.XmlNamespace == Xml_AttrRep.AttrNsp.gen)
                {
                    matchAttr = bldg.DescendantsAndSelf().Where(n => n.Name.LocalName == "value" && n.Parent.Attribute("name").Value == attr.Name).ToList();
                }

                if(attr.XmlNamespace == Xml_AttrRep.AttrNsp.gml)
                {
                    matchAttr = bldg.DescendantsAndSelf().Where(n => n.Name.LocalName == attr.Name && n.Name.Namespace == nsp["gml"]).ToList();
                }

                if(matchAttr != null && matchAttr.Count() == 1)
                {
                    kvp.Add(attr, matchAttr[0].Value.Trim());
                }
                else if(matchAttr.Count > 1)
                {
                    var valList = new List<string>();

                    foreach(var m in matchAttr)
                    {
                        valList.Add(m.Value.Trim());
                    }

                    var distList = valList.Distinct().ToList();

                    if(distList.Count() == 1)
                    {
                        kvp.Add(attr, distList[0]);
                    }
                    else
                    {
                        kvp.Add(attr, distList.Where(c => !c.Equals("")).First());
                    }
                }
                else
                {
                    switch(attr.Name)
                    {
                        case ("LocalityType"):
                            var matchElem = bldg.DescendantsAndSelf().Where(n => n.Name.LocalName == "Locality").FirstOrDefault();
                            if(matchElem != null)
                            {
                                kvp.Add(attr, AddTypeValues(matchElem));
                            }
                            break;

                        case ("DependentLocalityType"):
                            var matchElem2 = bldg.DescendantsAndSelf().Where(n => n.Name.LocalName == "DependentLocality").FirstOrDefault();
                            if(matchElem2 != null)
                            {
                                kvp.Add(attr, AddTypeValues(matchElem2));
                            }
                            break;

                        case ("ThoroughfareType"):
                            var matchElem3 = bldg.DescendantsAndSelf().Where(n => n.Name.LocalName == "Thoroughfare").FirstOrDefault();
                            if(matchElem3 != null)
                            {
                                kvp.Add(attr, AddTypeValues(matchElem3));
                            }
                            break;

                        case ("Building_ID"):
                            var id = bldgEl.Attribute(nsp["gml"] + "id").Value;
                            if(id != null)
                                kvp.Add(attr, id);
                            break;

                        default:
                            break;
                    }
                }
            }
            return kvp;
        }

19 Source : DllMap.cs
with GNU General Public License v3.0
from deccer

private static DllMapOS GetCurrentPlatform()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                return DllMapOS.Linux;
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                return DllMapOS.Windows;
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                return DllMapOS.OSX;
            }

            var operatingDesc = RuntimeInformation.OSDescription.ToUpperInvariant();
            foreach (var system in Enum.GetValues(typeof(DllMapOS))
                .Cast<DllMapOS>()
                .Except(new[] { DllMapOS.Linux, DllMapOS.Windows, DllMapOS.OSX }))
            {
                if (operatingDesc.Contains(system.ToString().ToUpperInvariant()))
                {
                    return system;
                }
            }

            throw new PlatformNotSupportedException($"Couldn't detect platform: {RuntimeInformation.OSDescription}");
        }

19 Source : AvatarModifierArea.cs
with Apache License 2.0
from decentraland

private void Update()
    {
        if (cachedModel?.area == null)
        {
            return;
        }

        // Find avatars currently on the area
        HashSet<GameObject> newAvatarsInArea = DetectAllAvatarsInArea();
        if (AreSetEquals(avatarsInArea, newAvatarsInArea))
            return;

        if (avatarsInArea == null)
            avatarsInArea = new HashSet<GameObject>();

        if (newAvatarsInArea == null)
            newAvatarsInArea = new HashSet<GameObject>();

        // Call event for avatars that just entered the area
        foreach (GameObject avatarThatEntered in newAvatarsInArea.Except(avatarsInArea))
        {
            OnAvatarEnter?.Invoke(avatarThatEntered);
        }

        // Call events for avatars that just exited the area
        foreach (GameObject avatarThatExited in avatarsInArea.Except(newAvatarsInArea))
        {
            OnAvatarExit?.Invoke(avatarThatExited);
        }

        avatarsInArea = newAvatarsInArea;
    }

19 Source : CleanUtilPageViewModel.cs
with GNU General Public License v3.0
from deepak-rathi

public void DoClreplacedification()
        {
            if (string.IsNullOrWhiteSpace(SelectedFolderPath))
                return;

            ModuleCollection.Clear();
            OldVersionModule.Clear();

            DirectoryInfo dirInfo = new DirectoryInfo(SelectedFolderPath);
            if (dirInfo != null && !dirInfo.Exists)
            {
                SelectedFolderPath = "";
                return;
            }

            //clreplacedification
            DirectoryInfo archiveDirectoryInfo = null;
            var directories = dirInfo.GetDirectories();
            foreach (var directory in directories)
            {
                var vsModule = new VSModule();
                if (directory.Name.Contains(","))
                {
                    var stringSplit = directory.Name.Split(',').ToList();
                    vsModule.Name = stringSplit.FirstOrDefault();
                    vsModule.Version = stringSplit[1];
                    stringSplit.Remove(vsModule.Name);
                    stringSplit.Remove(vsModule.Version);
                    if (stringSplit.Count() > 0)
                    {
                        foreach (var item in stringSplit)
                            vsModule.Name = vsModule.Name + "," + item;
                    }
                }
                else if (directory.Name.Equals("Archive"))
                {
                    archiveDirectoryInfo = directory;
                }
                else
                {
                    continue;
                }
                vsModule.FullPath = directory.FullName;
                ModuleCollection.Add(vsModule);
            }

            //Select all the Modules with same name from ModuleCollection
            var duplicateModules =
            ModuleCollection.Where(module =>
            ModuleCollection
            .Except(new ObservableCollection<VSModule> { module })
            .Any(x => x.Name == module.Name)
            ).ToObservableCollection();

            //Get all the old version modules/folder from duplicateModules
            OldVersionModule =
            duplicateModules.Where(module =>
            duplicateModules
            .Except(new ObservableCollection<VSModule> { module })
            .Any(x => x.Name == module.Name && x.VersionObject.CompareTo(module.VersionObject) > 0)
            ).ToObservableCollection();

            //Add archive folder to old version module
            if (archiveDirectoryInfo != null)
                OldVersionModule.Add(new VSModule()
                {
                    FullPath = archiveDirectoryInfo.FullName,
                    Name = archiveDirectoryInfo.Name
                });
        }

19 Source : SwitchDetection.cs
with MIT License
from deepakkumar1984

private bool SwitchUsesGoto(List<ControlFlowNode> flowNodes, List<ControlFlowNode> caseNodes, out Block breakBlock)
		{
			// cases with predecessors that aren't part of the switch logic 
			// must either require "goto case" statements, or consist of a single "break;"
			var externalCases = caseNodes.Where(c => c.Predecessors.Any(n => !flowNodes.Contains(n))).ToList();

			breakBlock = null;
			if (externalCases.Count > 1)
				return true; // cannot have more than one break case without gotos
			
			// check that case nodes flow through a single point
			var breakTargets = caseNodes.Except(externalCases).SelectMany(n => loopContext.GetBreakTargets(n)).ToHashSet();

			// if there are multiple break targets, then gotos are required
			// if there are none, then the external case (if any) can be the break target
			if (breakTargets.Count != 1)
				return breakTargets.Count > 1;
			
			breakBlock = (Block) breakTargets.Single().UserData;

			// external case must consist of a single "break;"
			return externalCases.Count == 1 && breakBlock != externalCases.Single().UserData;
		}

19 Source : NumericalTimeSeries.cs
with GNU General Public License v3.0
from DeepHydro

public TimeSeriesConsistencyInfo[]  GetTimeSeriesConsistencyInfo()
        {
            var dtv = DateTimes;
            var derivedValues = dtv.GroupBy(t => new { t.Year }).Select(group =>
                    new { Year=group.Key.Year, Count = group.Count()});
            TimeSeriesConsistencyInfo[] infos = null;
            if (derivedValues.Count() > 0)
            {
                infos = new TimeSeriesConsistencyInfo[derivedValues.Count()];
                int i = 0;
                foreach (var dv in derivedValues)
                {
                    infos[i] = new TimeSeriesConsistencyInfo(TimeUnits.CommanYear);
                    infos[i].DateTimeStamp = new DateTime(dv.Year, 1, 1);
                    infos[i].AcutalCounts = dv.Count;
                    infos[i].DesiredCounts = DateTime.IsLeapYear(dv.Year) ? 366 : 365;
                    if (infos[i].AcutalCounts != infos[i].DesiredCounts)
                    {
                        infos[i].IsNormal = false;
                        DateTime [] desiredTimes=new DateTime[infos[i].DesiredCounts];
                        DateTime start=new DateTime(dv.Year, 1, 1);
                        for (int j= 0; j < infos[i].DesiredCounts; j++)
                        {
                            desiredTimes[j] = start.AddDays(j);
                        }
                        var times = (from t in dtv where t >= start && t <= new DateTime(dv.Year, 12, 31) select t).ToArray();
                        infos[i].MissingDateTimes.AddRange(desiredTimes.Except(times).ToArray());
                    }
                    i++;
                }         
            }
            return infos;
        }

19 Source : Trainer.cs
with MIT License
from Dentrax

private void PrintFinalValues(Dictionary<string[], int> group) {

            Console.WriteLine("---------------------------------------------------------------------------------------------");
            Console.WriteLine("RESULTS");
            Console.WriteLine("--------------------");
            int index = 1;
            foreach (KeyValuePair<string[], int> product in group) {
                string[] keys = product.Key;

                for (int i = -1; i < keys.Length; i++) {
                    Console.Write($"RESULT {index} : ");

                    string[] ins;
                    string[] outs;

                    if (i == -1) {
                        ins = new string[] { keys[0], keys[1] };
                        outs = keys.Except(ins).ToArray();
                        PrintThresholdRule(keys, ins, outs);
                        index++;
                        Console.WriteLine();
                        continue;
                    }

                    ins = new string[] { keys[i] };
                    outs = keys.Except(ins).ToArray();

                    PrintThresholdRule(keys, ins, outs);

                    index++;
                    Console.WriteLine();
                }
                Console.WriteLine();
            }
            Console.WriteLine("---------------------------------------------------------------------------------------------");
        }

19 Source : DatabaseEntrySorter.cs
with GNU General Public License v3.0
from Depressurizer

public static int CompareLists(SortedSet<string> sortedX, SortedSet<string> sortedY)
        {
            if (sortedX == null)
            {
                if (sortedY == null)
                {
                    return 0;
                }

                return 1;
            }

            if (sortedY == null)
            {
                return -1;
            }

            if (sortedX.Count == sortedY.Count && !sortedX.Except(sortedY).Any())
            {
                return 0;
            }

            List<string> listX = sortedX.ToList();
            List<string> listY = sortedY.ToList();

            for (int i = 0; i < sortedX.Count && i < sortedY.Count; i++)
            {
                int res = string.Compare(listX[i], listY[i], StringComparison.Ordinal);
                if (res == 0)
                {
                    continue;
                }

                return res;
            }

            return 0;
        }

19 Source : Steam.cs
with GNU General Public License v3.0
from Depressurizer

public static async void GrabBanners(IEnumerable<int> appIds)
        {
            appIds = appIds.Distinct().Except(IgnoreList);
            await Task.Run(() => { Parallel.ForEach(appIds, FetchBanner); });

#if DEBUG
            // Report failing banners using Sentry.IO
            if (BannerFailed.Count <= 0)
            {
                return;
            }

            IgnoreList.AddRange(BannerFailed);
            IgnoreList.Sort();

            InvalidDataException exception = new InvalidDataException("Found new failing banners!");
            exception.Data.Add("IgnoreList", JsonConvert.SerializeObject(IgnoreList.Distinct()));

            SentrySdk.CaptureException(exception);
#endif
        }

19 Source : LoadingForm.cs
with GNU General Public License v3.0
from DesktopGooseUnofficial

public void LoadData(out dynamic loadedData, out List<string> enabledMods, out List<string> disabledMods)
        {
            metroLabel1.Text = "Getting data from website.\nPlease wait...";
            WebRequest request = WebRequest.Create("https://raw.githubusercontent.com/DesktopGooseUnofficial/launcher-backend/master/data.json");
            WebResponse response = request.GetResponse();
            Stream data = response.GetResponseStream();
            string html = String.Empty;
            using (StreamReader sr = new StreamReader(data))
            {
                html = sr.ReadToEnd();
            }

            dynamic array = JsonConvert.DeserializeObject(html);
            loadedData = array;
            metroLabel1.Text = "Getting enabled mods.\nPlease wait...";
            if (!Directory.Exists("Disabled Mods"))
                Directory.CreateDirectory("Disabled Mods");

            if (!Directory.Exists("Mods"))
                Directory.CreateDirectory("Mods");

            string[] enabled = Directory.GetDirectories("Mods");
            enabled = enabled.Except(new string[] { "ResourceHubUpdater" }).ToArray();
            List<string> enabledNames = new List<string>();
            foreach (string element in enabled)
            {
                enabledNames.Add(Path.GetFileName(element));
            }
            enabledMods = enabledNames;
            metroLabel1.Text = "Getting disabled mods.\nPlease wait...";
            string[] disabled = Directory.GetDirectories("Disabled Mods");
            List<string> disabledNames = new List<string>();
            foreach (string element in disabled)
            {
                disabledNames.Add(Path.GetFileName(element));
            }
            disabledMods = disabledNames;
            this.Close();
        }

19 Source : ConfigurationManager.cs
with MIT License
from DevExpress

public static void RemoveOfflineServers(IEnumerable<string> serverAddresses, int port) {
            IEnumerable<string> serversOnFarm = GetServersFromFarmConfiguration();
            var offlineServers = serversOnFarm.Except(serverAddresses);
            RemoveServers(offlineServers);
        }

19 Source : ConfigurationManager.cs
with MIT License
from DevExpress

static void AddNewServers(IEnumerable<string> serverAddresses, int port) {
            IEnumerable<string> serversOnFarm = GetServersFromFarmConfiguration();
            var newServers = serverAddresses.Except(serversOnFarm);
            AddServers(newServers, port);
        }

19 Source : VRTK_SDKManagerEditor.cs
with MIT License
from dhcdht

public override void OnInspectorGUI()
        {
            serializedObject.Update();

            VRTK_SDKManager sdkManager = (VRTK_SDKManager)target;
            const string manageNowButtonText = "Manage Now";

            using (new EditorGUILayout.VerticalScope("Box"))
            {
                VRTK_EditorUtilities.AddHeader("Scripting Define Symbols", false);

                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUI.BeginChangeCheck();
                    bool autoManage = EditorGUILayout.Toggle(
                        VRTK_EditorUtilities.BuildGUIContent<VRTK_SDKManager>("autoManageScriptDefines", "Auto Manage"),
                        sdkManager.autoManageScriptDefines,
                        GUILayout.ExpandWidth(false)
                    );
                    if (EditorGUI.EndChangeCheck())
                    {
                        serializedObject.FindProperty("autoManageScriptDefines").boolValue = autoManage;
                        serializedObject.ApplyModifiedProperties();
                        sdkManager.ManageScriptingDefineSymbols(false, true);
                    }

                    using (new EditorGUI.DisabledGroupScope(sdkManager.autoManageScriptDefines))
                    {
                        GUIContent manageNowGUIContent = new GUIContent(
                            manageNowButtonText,
                            "Manage the scripting define symbols defined by the installed SDKs."
                            + (sdkManager.autoManageScriptDefines
                                   ? "\n\nThis button is disabled because the SDK Manager is set up to manage the scripting define symbols automatically."
                                     + " Disable the checkbox on the left to allow managing them manually instead."
                                   : "")
                        );
                        if (GUILayout.Button(manageNowGUIContent, GUILayout.MaxHeight(GUI.skin.label.CalcSize(manageNowGUIContent).y)))
                        {
                            sdkManager.ManageScriptingDefineSymbols(true, true);
                        }
                    }
                }

                using (new EditorGUILayout.VerticalScope("Box"))
                {
                    VRTK_EditorUtilities.AddHeader("Active Symbols Without SDK Clreplacedes", false);

                    VRTK_SDKInfo[] availableSDKInfos = VRTK_SDKManager
                        .AvailableSystemSDKInfos
                        .Concat(VRTK_SDKManager.AvailableBoundariesSDKInfos)
                        .Concat(VRTK_SDKManager.AvailableHeadsetSDKInfos)
                        .Concat(VRTK_SDKManager.AvailableControllerSDKInfos)
                        .ToArray();
                    HashSet<string> sdkSymbols = new HashSet<string>(availableSDKInfos.Select(info => info.description.symbol));
                    IGrouping<BuildTargetGroup, VRTK_SDKManager.ScriptingDefineSymbolPredicateInfo>[] availableGroupedPredicateInfos = VRTK_SDKManager
                        .AvailableScriptingDefineSymbolPredicateInfos
                        .GroupBy(info => info.attribute.buildTargetGroup)
                        .ToArray();
                    foreach (IGrouping<BuildTargetGroup, VRTK_SDKManager.ScriptingDefineSymbolPredicateInfo> grouping in availableGroupedPredicateInfos)
                    {
                        VRTK_SDKManager.ScriptingDefineSymbolPredicateInfo[] possibleActiveInfos = grouping
                            .Where(info => !sdkSymbols.Contains(info.attribute.symbol)
                                           && grouping.Except(new[] { info })
                                                      .All(predicateInfo => !(predicateInfo.methodInfo == info.methodInfo
                                                                              && sdkSymbols.Contains(predicateInfo.attribute.symbol))))
                            .OrderBy(info => info.attribute.symbol)
                            .ToArray();
                        if (possibleActiveInfos.Length == 0)
                        {
                            continue;
                        }

                        EditorGUI.indentLevel++;

                        BuildTargetGroup targetGroup = grouping.Key;
                        isBuildTargetActiveSymbolsFoldOut[targetGroup] = EditorGUI.Foldout(
                            EditorGUILayout.GetControlRect(),
                            isBuildTargetActiveSymbolsFoldOut[targetGroup],
                            targetGroup.ToString(),
                            true
                        );

                        if (isBuildTargetActiveSymbolsFoldOut[targetGroup])
                        {
                            foreach (VRTK_SDKManager.ScriptingDefineSymbolPredicateInfo predicateInfo in possibleActiveInfos)
                            {
                                int symbolIndex = sdkManager
                                    .activeScriptingDefineSymbolsWithoutSDKClreplacedes
                                    .FindIndex(attribute => attribute.symbol == predicateInfo.attribute.symbol);
                                string symbolLabel = predicateInfo.attribute.symbol.Remove(
                                    0,
                                    SDK_ScriptingDefineSymbolPredicateAttribute.RemovableSymbolPrefix.Length
                                );

                                if (!(bool)predicateInfo.methodInfo.Invoke(null, null))
                                {
                                    symbolLabel += " (not installed)";
                                }

                                EditorGUI.BeginChangeCheck();
                                bool isSymbolActive = EditorGUILayout.ToggleLeft(symbolLabel, symbolIndex != -1);
                                if (EditorGUI.EndChangeCheck())
                                {
                                    Undo.RecordObject(sdkManager, "Active Symbol Change");
                                    if (isSymbolActive)
                                    {
                                        sdkManager.activeScriptingDefineSymbolsWithoutSDKClreplacedes.Add(predicateInfo.attribute);
                                    }
                                    else
                                    {
                                        sdkManager.activeScriptingDefineSymbolsWithoutSDKClreplacedes.RemoveAt(symbolIndex);
                                    }
                                    sdkManager.ManageScriptingDefineSymbols(false, true);
                                }
                            }
                        }

                        EditorGUI.indentLevel--;
                    }
                }

                VRTK_EditorUtilities.DrawUsingDestructiveStyle(GUI.skin.button, style =>
                {
                    GUIContent clearSymbolsGUIContent = new GUIContent(
                        "Remove All Symbols",
                        "Remove all scripting define symbols of VRTK. This is handy if you removed the SDK files from your project but still have"
                        + " the symbols defined which results in compile errors."
                        + "\nIf you have the above checkbox enabled the symbols will be managed automatically after clearing them. Otherwise hit the"
                        + " '" + manageNowButtonText + "' button to add the symbols for the currently installed SDKs again."
                    );

                    if (GUILayout.Button(clearSymbolsGUIContent, style))
                    {
                        BuildTargetGroup[] targetGroups = VRTK_SharedMethods.GetValidBuildTargetGroups();

                        foreach (BuildTargetGroup targetGroup in targetGroups)
                        {
                            string[] currentSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup)
                                                                    .Split(';')
                                                                    .Distinct()
                                                                    .OrderBy(symbol => symbol, StringComparer.Ordinal)
                                                                    .ToArray();
                            string[] newSymbols = currentSymbols
                                .Where(symbol => !symbol.StartsWith(SDK_ScriptingDefineSymbolPredicateAttribute.RemovableSymbolPrefix, StringComparison.Ordinal))
                                .ToArray();

                            if (currentSymbols.SequenceEqual(newSymbols))
                            {
                                continue;
                            }

                            PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, string.Join(";", newSymbols));

                            string[] removedSymbols = currentSymbols.Except(newSymbols).ToArray();
                            if (removedSymbols.Length > 0)
                            {
                                VRTK_Logger.Info(VRTK_Logger.GetCommonMessage(VRTK_Logger.CommonMessageKeys.SCRIPTING_DEFINE_SYMBOLS_REMOVED, targetGroup, string.Join(", ", removedSymbols)));
                            }
                        }
                    }
                });
            }

            using (new EditorGUILayout.VerticalScope("Box"))
            {
                VRTK_EditorUtilities.AddHeader("Script Aliases", false);
                EditorGUILayout.PropertyField(
                    serializedObject.FindProperty("scriptAliasLeftController"),
                    VRTK_EditorUtilities.BuildGUIContent<VRTK_SDKManager>("scriptAliasLeftController", "Left Controller")
                );
                EditorGUILayout.PropertyField(
                    serializedObject.FindProperty("scriptAliasRightController"),
                    VRTK_EditorUtilities.BuildGUIContent<VRTK_SDKManager>("scriptAliasRightController", "Right Controller")
                );
            }

            using (new EditorGUILayout.VerticalScope("Box"))
            {
                VRTK_EditorUtilities.AddHeader("Setups", false);

                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUI.BeginChangeCheck();
                    bool autoManage = EditorGUILayout.Toggle(
                        VRTK_EditorUtilities.BuildGUIContent<VRTK_SDKManager>("autoManageVRSettings"),
                        sdkManager.autoManageVRSettings,
                        GUILayout.ExpandWidth(false)
                    );
                    if (EditorGUI.EndChangeCheck())
                    {
                        serializedObject.FindProperty("autoManageVRSettings").boolValue = autoManage;
                        serializedObject.ApplyModifiedProperties();
                        sdkManager.ManageVRSettings(false);
                    }

                    using (new EditorGUI.DisabledGroupScope(sdkManager.autoManageVRSettings))
                    {
                        GUIContent manageNowGUIContent = new GUIContent(
                            manageNowButtonText,
                            "Manage the VR settings of the Player Settings to allow for all the installed SDKs."
                            + (sdkManager.autoManageVRSettings
                                   ? "\n\nThis button is disabled because the SDK Manager is set up to manage the VR Settings automatically."
                                     + " Disable the checkbox on the left to allow managing them manually instead."
                                   : "")
                        );
                        if (GUILayout.Button(manageNowGUIContent, GUILayout.MaxHeight(GUI.skin.label.CalcSize(manageNowGUIContent).y)))
                        {
                            sdkManager.ManageVRSettings(true);
                        }
                    }
                }

                EditorGUILayout.PropertyField(
                    serializedObject.FindProperty("autoLoadSetup"),
                    VRTK_EditorUtilities.BuildGUIContent<VRTK_SDKManager>("autoLoadSetup", "Auto Load")
                );

                setupsList.DoLayoutList();

                GUIContent autoPopulateGUIContent = new GUIContent("Auto Populate", "Automatically populates the list of SDK Setups with Setups in the scene.");
                if (GUILayout.Button(autoPopulateGUIContent))
                {
                    SerializedProperty serializedProperty = setupsList.serializedProperty;
                    serializedProperty.ClearArray();
                    VRTK_SDKSetup[] setups = sdkManager.GetComponentsInChildren<VRTK_SDKSetup>(true)
                                                       .Concat(VRTK_SharedMethods.FindEvenInactiveComponents<VRTK_SDKSetup>(true))
                                                       .Distinct()
                                                       .ToArray();

                    for (int index = 0; index < setups.Length; index++)
                    {
                        VRTK_SDKSetup setup = setups[index];
                        serializedProperty.InsertArrayElementAtIndex(index);
                        serializedProperty.GetArrayElementAtIndex(index).objectReferenceValue = setup;
                    }
                }

                if (sdkManager.setups.Length > 1)
                {
                    EditorGUILayout.HelpBox("Duplicated setups are removed automatically.", MessageType.Info);
                }

                if (Enumerable.Range(0, sdkManager.setups.Length).Any(IsSDKSetupNeverUsed))
                {
                    EditorGUILayout.HelpBox("Gray setups will never be loaded because either the SDK Setup isn't valid or there"
                                        + " is a valid Setup before it that uses any non-VR SDK.",
                                        MessageType.Warning);
                }
            }

            using (new EditorGUILayout.VerticalScope("Box"))
            {
                VRTK_EditorUtilities.AddHeader("Target Platform Group Exclusions", false);
                SerializedProperty excludeTargetGroups = serializedObject.FindProperty("excludeTargetGroups");
                excludeTargetGroups.arraySize = EditorGUILayout.IntField("Size", excludeTargetGroups.arraySize);
                for (int i = 0; i < excludeTargetGroups.arraySize; i++)
                {
                    EditorGUILayout.PropertyField(excludeTargetGroups.GetArrayElementAtIndex(i));
                }
            }

            EditorGUILayout.PropertyField(serializedObject.FindProperty("persistOnLoad"));

            serializedObject.ApplyModifiedProperties();
        }

19 Source : VRTK_SDKSetup.cs
with MIT License
from dhcdht

public string[] GetSimplifiedErrorDescriptions()
        {
            List<string> sdkErrorDescriptions = new List<string>();

            ReadOnlyCollection<VRTK_SDKInfo>[] installedSDKInfosList = {
                VRTK_SDKManager.InstalledSystemSDKInfos,
                VRTK_SDKManager.InstalledBoundariesSDKInfos,
                VRTK_SDKManager.InstalledHeadsetSDKInfos,
                VRTK_SDKManager.InstalledControllerSDKInfos
            };
            VRTK_SDKInfo[] currentSDKInfos = { systemSDKInfo, boundariesSDKInfo, headsetSDKInfo, controllerSDKInfo };

            for (int index = 0; index < installedSDKInfosList.Length; index++)
            {
                ReadOnlyCollection<VRTK_SDKInfo> installedSDKInfos = installedSDKInfosList[index];
                VRTK_SDKInfo currentSDKInfo = currentSDKInfos[index];

                Type baseType = VRTK_SharedMethods.GetBaseType(currentSDKInfo.type);
                if (baseType == null)
                {
                    continue;
                }

                if (currentSDKInfo.originalTypeNameWhenFallbackIsUsed != null)
                {
                    sdkErrorDescriptions.Add(string.Format("The SDK '{0}' doesn't exist anymore.", currentSDKInfo.originalTypeNameWhenFallbackIsUsed));
                }
                else if (currentSDKInfo.description.describesFallbackSDK)
                {
                    sdkErrorDescriptions.Add("A fallback SDK is used. Make sure to set a real SDK.");
                }
                else if (!installedSDKInfos.Contains(currentSDKInfo))
                {
                    sdkErrorDescriptions.Add(string.Format("The vendor SDK for '{0}' is not installed.", currentSDKInfo.description.prettyName));
                }
            }

            if (usedVRDeviceNames.Except(new[] { "None" }).Count() > 1)
            {
                sdkErrorDescriptions.Add("The current SDK selection uses multiple VR Devices. It's not possible to use more than one VR Device at the same time.");
            }

            return sdkErrorDescriptions.Distinct().ToArray();
        }

19 Source : AuthorizationService.cs
with MIT License
from discord-csharp

public async Task<IReadOnlyCollection<AuthorizationClaim>> GetGuildUserMissingClaimsAsync(ulong user, ulong guild, IReadOnlyList<ulong> roles, params AuthorizationClaim[] claims)
            => claims.Except(await GetGuildUserClaimsAsync(user, guild, roles, claims))
                .ToArray();

19 Source : AuthorizationService.cs
with MIT License
from discord-csharp

public void RequireClaims(params AuthorizationClaim[] claims)
        {
            RequireAuthenticatedUser();

            if (claims == null)
                throw new ArgumentNullException(nameof(claims));

            var missingClaims = claims
                .Except(CurrentClaims)
                .ToArray();

            if (missingClaims.Length != 0)
                // TODO: Booooo for exception-based flow control
                throw new InvalidOperationException($"The current operation could not be authorized. The following claims were missing: {string.Join(", ", missingClaims)}");
        }

19 Source : TestFileCleanupVerifier.cs
with MIT License
from divjackdiv

public void VerifyNoNewFilesAdded()
        {
            var currentFiles = GetAllFilesInreplacedetsDirectory().ToList();

            //Expect that if its the same amount of files, there havent been any changes
            //This is to optimize if there are many files
            if (currentFiles.Count != m_ExistingFiles.Count)
            {
                LogWarningForFilesIfAny(currentFiles.Except(m_ExistingFiles));
            }
        }

19 Source : Template.cs
with MIT License
from dj-nitehawk

public string RenderToString()
        {
            if (!cacheHit && !hasAppendedStages)
            {
                cache[cacheKey] = builder.ToString();
                cacheHit = true; //in case this method is called multiple times
            }

            foreach (var t in valueTags.ToArray())
            {
                builder.Replace(t.Key, t.Value);
                replacedTags.Add(t.Key);
            }

            if (missingTags.Count > 0)
                throw new InvalidOperationException($"The following tags were missing from the template: [{string.Join(",", missingTags)}]");

            var unReplacedTags = goalTags.Except(replacedTags);

            if (unReplacedTags.Any())
                throw new InvalidOperationException($"Replacements for the following tags are required: [{string.Join(",", unReplacedTags)}]");

            return builder.ToString();
        }

19 Source : Plugin.cs
with GNU Affero General Public License v3.0
from djkaty

public void PreProcessBinary(Il2CppBinary binary, PluginPreProcessBinaryEventInfo data) {

            // Enable surrogate properties
            Binary = binary;

            // We can only perform this re-ordering if we can refer to a loaded global-Metadata.dat
            if (Metadata == null)
                return;

            // Do nothing if binary metadata appears to be valid
            if (MetadataRegistration.typesCount >= MetadataRegistration.typeDefinitionsSizesCount
                && MetadataRegistration.genericMethodTableCount >= MetadataRegistration.genericInstsCount
                && CodeRegistration.reversePInvokeWrapperCount <= 0x4000
                && CodeRegistration.unresolvedVirtualCallCount <= 0x4000 // >= 22
                && CodeRegistration.interopDataCount <= 0x1000           // >= 23
                && (Image.Version > 24.1 || CodeRegistration.invokerPointersCount <= CodeRegistration.methodPointersCount))
                return;

            // Don't cause corruption in unsupported versions
            if (Image.Version < 19 || Image.Version > 24.1)
                return;

            // If the section table is not available, give up and do nothing
            if (!Image.TryGetSections(out var sections))
                return;

            // Get relevant image sections
            var codeSections = sections.Where(s => s.IsExec).ToList();
            var dataSections = sections.Where(s => s.IsData && !s.IsBSS).ToList();
            var bssSections  = sections.Where(s => s.IsBSS).ToList();

            // For PE files, data sections in memory can be larger than in the image
            // The unmapped portion is BSS data so create fake sections for this and shrink the existing ones
            foreach (var section in dataSections) {
                var virtualSize = section.VirtualEnd - section.VirtualStart;
                var imageSize   = section.ImageEnd   - section.ImageStart;

                if (imageSize < virtualSize) {
                    var bssEnd = section.VirtualEnd;
                    section.VirtualEnd = section.VirtualStart + imageSize;

                    bssSections.Add(new Section {
                        VirtualStart = section.VirtualStart + imageSize + 1,
                        VirtualEnd = bssEnd,

                        ImageStart = 0,
                        ImageEnd = 0,

                        IsExec = false,
                        IsData = false,
                        IsBSS = true,

                        Name = ".bss"
                    });
                }
            }

            // Fetch and sanitize our pointer and count lists
            var (codePtrsOrdered, codeCountLimits, codeCounts)
                = preparePointerList(typeof(Il2CppCodeRegistration), binary.CodeRegistrationPointer, dataSections, true);

            var (metaPtrsOrdered, metaCountLimits, metaCounts)
                = preparePointerList(typeof(Il2CppMetadataRegistration), binary.MetadataRegistrationPointer, dataSections);

            // Progress updater
            var maxProgress = codeCounts.Sum() + metaCounts.Sum();
            var currentProgress = 0;

            var lastUpdate = string.Empty;
            void UpdateProgress(int workDone) {
                currentProgress += workDone;
                var thisUpdate = $"Reconstructing obfuscated registration metadata ({currentProgress * 100 / maxProgress:F0}%)";

                if (thisUpdate != lastUpdate) {
                    lastUpdate = thisUpdate;
                    PluginServices.For(this).StatusUpdate(thisUpdate);
                }
            }

            UpdateProgress(0);

            // Counts from minimal compiles

            // v21 test project:
            // genericMethodPointers - 0x07B5, customAttributeGenerators - 0x0747, invokerPointers - 0x04DB, methodPointers - 0x226A
            // v24.1 empty Unity project:
            // genericMethodPointers - 0x0C15, customAttributeGenerators - 0x0A21, invokerPointers - 0x0646, methodPointers - 0x268B
            // v24.2 without Unity:
            // genericMethodPointers - 0x2EC2, customAttributeGenerators - 0x15EC, invokerPointers - 0x0B65

            // v21 test project:
            // genericInsts - 0x0150, genericMethodTable - 0x0805, types - 0x1509, methodSpecs - 0x08D8, fieldOffsets - 0x0569, metadataUsages - 0x1370
            // v24.1 empty Unity project:
            // genericInsts - 0x025E, genericMethodTable - 0x0E3F, types - 0x2632, methodSpecs - 0x0FD4, fieldOffsets - 0x0839, metadataUsages - 0x1850
            // v24.2 without Unity:
            // genericInsts - 0x06D4, genericMethodTable - 0x31E8, types - 0x318A, methodSpecs - 0x3AD8, fieldOffsets - 0x0B3D, metadataUsages - 0x3BA8

            // Some heuristic constants

            // The maximum address gap in a sequential list of pointers before the sequence is considered to be 'broken'
            const int MAX_SEQUENCE_GAP = 0x10000;

            // The minimum number of Il2CppTypes we expect
            const int MIN_TYPES = 0x1400;

            // The maximum number of generic type parameters we expect for any clreplaced or method
            const int MAX_GENERIC_TYPE_PARAMETERS = 32;

            // The minimum number of Il2CppGenericInsts we expect
            const int MIN_GENERIC_INSTANCES = 0x140;

            // The maximum number of generic methods in generic clreplacedes we expect to find in a single sequence of Il2CppMethodSpec
            // The highest we have seen in a production app is 3414; the next highest 2013, the next highest 1380
            // 300-600 is typical
            const int MAX_SEQUENTIAL_GENERIC_CLreplaced_METHODS = 5000;

            // The minimum number of Il2CppMethodSpecs we expect
            const int MIN_METHOD_SPECS = 0x0800;

            // The minimum number of Il2CppGenericMethodFunctionsDefinitions we expect
            const int MIN_GENERIC_METHOD_TABLE = 0x600;

            // The minimum spread of values in an instance of Il2CppGenericMethodFunctionsDefinitions under which the threshold counter is incremented
            const int MIN_GENERIC_METHOD_TABLE_SPREAD = 100;

            // The maximum number of instances in a row with a spread under the minimum we expect to find in a single sequence
            const int MAX_SEQUENTIAL_GENERIC_METHOD_TABLE_LOW_SPREAD_INSTANCES = 100;

            // The minimum number of field offsets we expect
            const int MIN_FIELD_OFFSETS = 0x400;

            // The maximum value for a field offset
            const int MAX_FIELD_OFFSET = 0x100000;

            // The minimum and maximum proportions of inversions we expect in a non-pointer field offset list
            // Example values: 0.385, 0.415, 0.468
            const double MIN_FIELD_OFFSET_INVERSION = 0.3;
            const double MAX_FIELD_OFFSET_INVERSION = 0.6;

            // The minimum and maximum proportions of zeroes we expect in a non-pointer field offset list
            // Example values: 0.116, 0.179, 0.303, 0.321, 0.385
            // The main thing is to force enough zeroes to prevent it being confused with a list with no zeroes (eg. genericClreplacedes)
            const double MIN_FIELD_OFFSET_ZEROES = 0.10;
            const double MAX_FIELD_OFFSET_ZEROES = 0.5;

            // The maximum allowed gap between two field offsets
            const int MAX_FIELD_OFFSET_GAP = 0x10000;

            // Things we need from Il2CppCodeRegistration

            // methodPointers (<=24.1)         -> list of function pointers (1st count) (non-sequential)
            // genericMethodPointers           -> list of function pointers (first IS zero) (2nd count) (not sequential)
            // customAttributeGenerators (<27) -> list of function pointers (first MAY be zero) (2nd count) (sequential)
            // invokerPointers                 -> list of function pointers (3rd count) (sequential)
            // codeGenModules (>=24.2)         -> list of Il2CppCodeGenModule* // TODO: We only support <=24.1 currently
            // (interopData will probably have 6 sequential pointers since Il2CppInteropData starts with 5 function pointers and a GUID)

            // Let's see how many valid pointers and sequential valid pointers we actually find at each address
            // Scan each pointer address for valid list of function pointers and sort into size order
            // Consider the sequence to be broken if there is a gap over a certain threshold
            var fnPtrs = new SortedDictionary<ulong, int>();
            var seqFnPtrs = new SortedDictionary<ulong, int>();
            for (var i = 0; i < codePtrsOrdered.Count; i++) {

                // Non-sequential valid pointers
                var ptrs = Image.ReadMappedArray<ulong>(codePtrsOrdered[i], codeCountLimits[i]);
                var foundCount = ptrs.TakeWhile(p => codeSections.Any(s => p >= s.VirtualStart && p <= s.VirtualEnd || p == 0)).Count();

                // Prune count of trailing zero pointers
                while (foundCount > 0 && ptrs[foundCount - 1] == 0ul)
                    foundCount--;

                fnPtrs.Add(codePtrsOrdered[i], foundCount);

                // Binaries compiled with MSVC (generally PE files) use /OPT:ICF by default (enable ICF) so this won't work.
                // For these binaries, we'll use a different selection strategy below
                if (Image is PEReader)
                    continue;

                // Sequential valid pointers (a subset of non-sequential valid pointers)
                if (foundCount > 0) {
                    foundCount = ptrs.Take(foundCount)
                        .Zip(ptrs.Take(foundCount).Skip(1), (a, b) => (a, b))
                        .TakeWhile(t => ((long) t.b - (long) t.a >= 0 || t.b == 0)
                                        && ((long) t.b - (long) t.a < MAX_SEQUENCE_GAP || t.a == 0)
                                        // Disallow two zero pointers in a row
                                        && (t.a != 0 || t.b != 0))
                        .Count() + 1;

                    // Prune count of trailing zero pointers
                    while (foundCount > 0 && ptrs[foundCount - 1] == 0ul)
                        foundCount--;
                }

                seqFnPtrs.Add(codePtrsOrdered[i], foundCount);

                UpdateProgress(foundCount);
            }

            KeyValuePair<ulong, int> methodPointers, genericMethodPointers, customAttributeGenerators, invokerPointers;

            // Solution without ICF
            if (!(Image is PEReader)) {
                // The two largest sequential groups are customAttributeGenerators and invokerPointers
                var seqLongest = seqFnPtrs.OrderByDescending(kv => kv.Value).Take(2).ToList();
                (customAttributeGenerators, invokerPointers) = (seqLongest[0], seqLongest[1]);

                // For >=27, customAttributeGenerators is zero and so the largest group is invokerPointers
                if (Image.Version >= 27) {
                    invokerPointers = customAttributeGenerators;
                    customAttributeGenerators = new KeyValuePair<ulong, int>(0ul, 0);
                }

                // After removing these from the non-sequential list, the largest groups are methodPointers and genericMethodPointers
                var longest = fnPtrs.Except(seqLongest).OrderByDescending(kv => kv.Value).Take(2).ToList();
                (methodPointers, genericMethodPointers) = (longest[0], longest[1]);

                // For >=24.2, methodPointers is zero and so the largest group is genericMethodPointers
                if (Image.Version >= 24.2) {
                    genericMethodPointers = methodPointers;
                    methodPointers = new KeyValuePair<ulong, int>(0ul, 0);
                }

                // Prune genericMethodPointers at 2nd zero (first pointer is always zero)
                var gmPtr = Image.ReadMappedArray<ulong>(genericMethodPointers.Key, genericMethodPointers.Value);
                var gmZero = Array.IndexOf(gmPtr, 0ul, 1);
                if (gmZero != -1)
                    genericMethodPointers = new KeyValuePair<ulong, int>(genericMethodPointers.Key, gmZero);
            }

            // Solution with ICF
            else {
                // Take and remove the first item and replacedume it's methodPointers for <=24.1, otherwise set to zero
                var orderedPtrs = fnPtrs.OrderByDescending(kv => kv.Value).ToList();
                if (Image.Version <= 24.1) {
                    methodPointers = orderedPtrs[0];
                    orderedPtrs.RemoveAt(0);
                } else
                    methodPointers = new KeyValuePair<ulong, int>(0ul, 0);

                // replacedume this order is right most of the time
                // TODO: generic and custom attribute might be the wrong way round (eg. #102)
                (genericMethodPointers, customAttributeGenerators, invokerPointers) = (orderedPtrs[0], orderedPtrs[1], orderedPtrs[2]);

                // customAttributeGenerators is removed in metadata >=27
                if (Image.Version >= 27) {
                    invokerPointers = customAttributeGenerators;
                    customAttributeGenerators = new KeyValuePair<ulong, int>(0ul, 0);
                }
            }

#region Debugging validation checks
#if false
        // Used on non-obfuscated binaries during development to confirm the output is correct
        if (methodPointers.Key != CodeRegistration.pmethodPointers)
            throw new Exception("Method Pointers incorrect");
        if (invokerPointers.Key != CodeRegistration.invokerPointers)
            throw new Exception("Invoker Pointers incorrect");
        if (customAttributeGenerators.Key != CodeRegistration.customAttributeGenerators)
            throw new Exception("Custom attribute generators incorrect");
        if (genericMethodPointers.Key != CodeRegistration.genericMethodPointers)
            throw new Exception("Generic method pointers incorrect");

        if (methodPointers.Value != (int) CodeRegistration.methodPointersCount)
            throw new Exception("Count of Method Pointers incorrect");
        if (invokerPointers.Value != (int) CodeRegistration.invokerPointersCount)
            throw new Exception("Count of Invoker Pointers incorrect");
        if (customAttributeGenerators.Value != (int) CodeRegistration.customAttributeCount)
            throw new Exception("Count of Custom attribute generators incorrect");
        if (genericMethodPointers.Value != (int) CodeRegistration.genericMethodPointersCount)
            throw new Exception("Count of Generic method pointers incorrect");
#endif
#endregion

            // Things we need from Il2CppMetadataRegistration

            // genericInsts               -> list of Il2CppGenericInst* (argc is count of Il2CppType* at data pointer argv; datapoint = GenericParameterIndex)
            // genericMethodTable         -> list of Il2CppGenericMethodFunctionsDefinitions (genericMethodIndex, methodIndex, invokerIndex)
            // types                      -> list of Il2CppType*
            // methodSpecs                -> list of Il2CppMethodSpec
            // methodReferences (<=16)    -> list of uint (ignored, we don't support <=16 here)
            // fieldOffsets (fieldOffsetsArePointers) -> either a list of data pointers (some zero, some VAs not mappable) to list of uints, or a list of uints
            // metadataUsages (>=19, <27) -> list of unmappable data pointers

            // Read in all the required data once since we'll be using nested loops
            var metaPtrData = new List<(ulong, int, ulong[], int)>();

            for (var i = 0; i < metaPtrsOrdered.Count; i++) {
                // Pointers in this list
                var ptrs = Image.ReadMappedArray<ulong>(metaPtrsOrdered[i], metaCountLimits[i] / (Image.Bits / 8));

                // First set of pointers that point to a data section virtual address
                var foundDataPtrsCount = ptrs.TakeWhile(p => dataSections.Any(s => p >= s.VirtualStart && p <= s.VirtualEnd)).Count();

                // First set of pointers that can be mapped anywhere into the image
                var foundImageMappablePtrsCount = ptrs.TakeWhile(p => Image.TryMapVATR(p, out _)).Count();
#if DEBUG
                // First set of pointers that can be mapped into a data section in the image
                var mappableDataPtrs = ptrs.Take(foundImageMappablePtrsCount)
                    .TakeWhile(p => dataSections.Any(s => Image.MapVATR(p) >= s.ImageStart && Image.MapVATR(p) <= s.ImageEnd))
                    .ToArray();

                var foundNonBSSDataPtrsCount = mappableDataPtrs.Length;

                if (foundDataPtrsCount != foundNonBSSDataPtrsCount)
                    throw new Exception($"Pointer count mismatch: {foundDataPtrsCount:x8} / {foundNonBSSDataPtrsCount:x8}");
#endif
                metaPtrData.Add((metaPtrsOrdered[i], metaCountLimits[i], ptrs, foundDataPtrsCount));
            }

            // Items we need to search for
            var types              = (ptr: 0ul, count: -1);
            var genericInsts       = (ptr: 0ul, count: -1);
            var methodSpecs        = (ptr: 0ul, count: -1);
            var genericMethodTable = (ptr: 0ul, count: -1);
            var metadataUsages     = (ptr: 0ul, count: -1);
            var fieldOffsets       = (ptr: 0ul, count: -1);

            var NOT_FOUND          = (ptr: 0xfffffffful, count: -1);

            // Intermediary items
            var typesPtrs = new List<ulong>();
            Il2CppMethodSpec[] methodSpec = null;

            // IL2CPP doesn't calculate metadataUsagesCount correctly so we do it here
            // Adapted from Il2CppInspector.buildMetadataUsages()
            var usages = new HashSet<uint>();

            // Only on supported metadata versions (>=19, <27)
            if (Metadata.MetadataUsageLists != null)
                foreach (var metadataUsageList in Metadata.MetadataUsageLists)
                    for (var i = 0; i < metadataUsageList.count; i++)
                        usages.Add(Metadata.MetadataUsagePairs[metadataUsageList.start + i].destinationindex);

            // Determine what each pointer is
            // We need to do this in a certain order because validating some items relies on earlier items
            while (metaPtrData.Any()) {

                ref var foundItem = ref NOT_FOUND;
                (ulong ptr, int count) foundData = (0ul, -1);

                // We loop repeatedly through every set of data looking for our next target item,
                // remove the matching set from the list and then repeat the outer while loop
                // until there is nothing left to find
                foreach (var (ptr, limit, ptrs, dataPtrsCount) in metaPtrData) {

                    foundData = (ptr, 0);

                    // Test for Il2CppType**
                    // ---------------------
                    if (types.count == -1) {

                        // We don't ever expect there to be less than MIN_TYPES types
                        if (dataPtrsCount >= MIN_TYPES) {

                            var tesreplacedems = Image.ReadMappedObjectPointerArray<Il2CppType>(ptr, dataPtrsCount);

                            foreach (var item in tesreplacedems) {
                                // TODO: v27 will fail this because of the bit shifting in Il2CppType.bits
                                if (item.num_mods != 0)
                                    break;
                                if (!Enum.IsDefined(typeof(Il2CppTypeEnum), item.type))
                                    break;
                                if (item.type == Il2CppTypeEnum.IL2CPP_TYPE_END)
                                    break;

                                // Test datapoint
                                if (item.type switch {
                                    var t when (t is Il2CppTypeEnum.IL2CPP_TYPE_VALUETYPE || t is Il2CppTypeEnum.IL2CPP_TYPE_CLreplaced)
                                                && item.datapoint >= (ulong) Metadata.Types.Length => false,

                                    var t when (t is Il2CppTypeEnum.IL2CPP_TYPE_VAR || t is Il2CppTypeEnum.IL2CPP_TYPE_MVAR)
                                                && item.datapoint >= (ulong) Metadata.GenericParameters.Length => false,

                                    var t when (t is Il2CppTypeEnum.IL2CPP_TYPE_PTR || t is Il2CppTypeEnum.IL2CPP_TYPE_SZARRAY)
                                                && !ptrs.Take(dataPtrsCount).Contains(item.datapoint) => false,

                                    // Untested cases, we could add more here (IL2CPP_TYPE_ARRAY, IL2CPP_TYPE_GENERICINST)
                                    _ => true
                                })
                                    foundData.count++;
                                else
                                    break;
                            }

                            if (foundData.count >= MIN_TYPES) {
                                foundItem = ref types;
                                typesPtrs = ptrs.ToList();
                                break;
                            }
                        }
                    }

                    // Test for Il2CppGenericInst**
                    // ----------------------------
                    else if (genericInsts.count == -1) {

                        if (dataPtrsCount >= MIN_GENERIC_INSTANCES) {

                            var tesreplacedems = Image.ReadMappedObjectPointerArray<Il2CppGenericInst>(ptr, dataPtrsCount);

                            foreach (var item in tesreplacedems) {
                                // Let's pray no generic type has more than this many type parameters
                                if (item.type_argc > MAX_GENERIC_TYPE_PARAMETERS)
                                    break;

                                // All the generic type paramters must be in the total list of types,
                                // ie. typePtrs must be a subset of typesData.Keys
                                try {
                                    var typePtrs = Image.ReadMappedArray<ulong>(item.type_argv, (int) item.type_argc);
                                    if (typePtrs.Any(p => !typePtrs.Contains(p)))
                                        break;
                                    // Pointers were invalid
                                }
                                catch (InvalidOperationException) {
                                    break;
                                }

                                foundData.count++;
                            }

                            if (foundData.count >= MIN_GENERIC_INSTANCES) {
                                foundItem = ref genericInsts;
                                break;
                            }
                        }
                    }

                    // Test for Il2CppMethodSpec*
                    // --------------------------
                    else if (methodSpecs.count == -1) {
                        var max = limit / Metadata.Sizeof(typeof(Il2CppMethodSpec));

                        if (max >= MIN_METHOD_SPECS) {

                            var tesreplacedems = Image.ReadMappedArray<Il2CppMethodSpec>(ptr, max);
                            var nonNegativePairs = 0;

                            foreach (var item in tesreplacedems) {
                                if (item.methodDefinitionIndex < 0 || item.methodDefinitionIndex >= Metadata.Methods.Length)
                                    break;
                                if (item.clreplacedIndexIndex < -1 || item.clreplacedIndexIndex >= genericInsts.count)
                                    break;
                                if (item.methodIndexIndex < -1 || item.methodIndexIndex >= genericInsts.count)
                                    break;

                                // Non-negative pairs shouldn't appear in large groups
                                nonNegativePairs = item.clreplacedIndexIndex != -1 && item.methodIndexIndex != -1 ? nonNegativePairs + 1 : 0;
                                if (nonNegativePairs > MAX_SEQUENTIAL_GENERIC_CLreplaced_METHODS)
                                    break;

                                foundData.count++;
                            }

                            // replacedumes last methods are not generic methods in generic clreplacedes
                            foundData.count -= nonNegativePairs;

                            if (foundData.count >= MIN_METHOD_SPECS) {
                                foundItem = ref methodSpecs;
                                methodSpec = tesreplacedems;
                                break;
                            }
                        }
                    }

                    // Test for Il2CppGenericMethodFunctionsDefinitions*
                    // -------------------------------------------------
                    else if (genericMethodTable.count == -1) {
                        var max = limit / Metadata.Sizeof(typeof(Il2CppGenericMethodFunctionsDefinitions));

                        if (max >= MIN_GENERIC_METHOD_TABLE) {

                            var tesreplacedems = Image.ReadMappedArray<Il2CppGenericMethodFunctionsDefinitions>(ptr, max);
                            var lowSpreadCount = 0;

                            foreach (var item in tesreplacedems) {
                                if (item.genericMethodIndex < 0 || item.genericMethodIndex >= methodSpecs.count)
                                    break;
                                if (item.indices.methodIndex < 0 || item.indices.methodIndex >= genericMethodPointers.Value)
                                    break;
                                if (item.indices.invokerIndex < 0 || item.indices.invokerIndex >= invokerPointers.Value)
                                    break;
                                // methodIndex is an index into the method pointer table
                                // For generic type definitions, there is no concrete function so this must be 0xffffffff
                                // TODO: For >=24.2, we need to use the method token to look up the value in an Il2CppCodeGenModule, not currently implemented
                                if (Image.Version <= 24.1)
                                    if (Metadata.Methods[methodSpec[item.genericMethodIndex].methodDefinitionIndex].methodIndex != -1)
                                        break;
                                foundData.count++;

                                // Instances where all the values are clustered should be rare
                                var spread = Math.Max(Math.Max(item.indices.methodIndex, item.indices.invokerIndex), item.genericMethodIndex)
                                        - Math.Min(Math.Min(item.indices.methodIndex, item.indices.invokerIndex), item.genericMethodIndex);

                                lowSpreadCount = spread < MIN_GENERIC_METHOD_TABLE_SPREAD ? lowSpreadCount + 1 : 0;
                                if (lowSpreadCount > MAX_SEQUENTIAL_GENERIC_METHOD_TABLE_LOW_SPREAD_INSTANCES)
                                    break;
                            }

                            // replacedumes the last instances don't have clustered values
                            foundData.count -= lowSpreadCount;

                            if (foundData.count >= MIN_GENERIC_METHOD_TABLE) {
                                foundItem = ref genericMethodTable;
                                break;
                            }
                        }
                    }

                    // Test for metadata usages
                    // ------------------------
                    else if (metadataUsages.count == -1) {

                        // No metadata usages for these versions
                        if (Image.Version < 19 || Image.Version >= 27) {
                            foundData.ptr = 0ul;
                            foundItem = ref metadataUsages;
                            break;
                        }

                        // Metadata usages always map to BSS sections (dataPtrsCount == 0)
                        // For images dumped from memory, metadata usages must always map to data sections
                        if ((dataPtrsCount == 0 && limit / (Image.Bits / 8) >= usages.Count)
                            || dataPtrsCount >= usages.Count) {

                            // No null pointers allowed (this test only applies to non-dumped images)
                            if (ptrs.Take(usages.Count).All(p => p != 0ul)) {

                                // For normal images, all the pointers must map to a BSS section
                                // For PE files this relies on our section modding above
                                // For dumped images, BSS sections are also data sections so we can use the same test
                                var bssMappableCount = ptrs.Take(usages.Count).Count(p => bssSections.Any(s => p >= s.VirtualStart && p <= s.VirtualEnd));

                                foundData.count = bssMappableCount;
                                foundItem = ref metadataUsages;
                                break;
                            }
                        }
                    }

                    // Test for field offsets
                    // ----------------------
                    else if (fieldOffsets.count == -1) {
                        // This could be a list of pointers to locally incrementing sequences of uints,
                        // or it could be a sequence of uints

                        // Some uints may be zero, but must otherwise never be less than the minimum heap offset of the first parameter
                        // for the binary's function calling convention, and never greater than the maximum heap offset of the last parameter

                        // Try as sequence of uints
                        if (Metadata.Version <= 21) {
                            var max = limit / sizeof(uint);

                            if (max >= MIN_FIELD_OFFSETS) {

                                var tesreplacedems = Image.ReadMappedArray<uint>(ptr, max);
                                var previousItem = 0u;
                                var inversions = 0;
                                var zeroes = 0;

                                foreach (var item in tesreplacedems) {
                                    if (item > MAX_FIELD_OFFSET && item != 0xffffffff)
                                        break;
                                    if (item > previousItem + MAX_FIELD_OFFSET_GAP && item != 0xffffffff)
                                        break;
                                    // Count zeroes and inversions (equality counts as inversion here since two arguments can't share a heap offset)
                                    if (item <= previousItem)
                                        inversions++;
                                    if (item == 0)
                                        zeroes++;
                                    previousItem = item;

                                    foundData.count++;
                                }

                                if (foundData.count >= MIN_FIELD_OFFSETS) {
                                    var inversionsPc = (double) inversions / foundData.count;
                                    var zeroesPc = (double) zeroes / foundData.count;

                                    if (inversionsPc >= MIN_FIELD_OFFSET_INVERSION && inversionsPc <= MAX_FIELD_OFFSET_INVERSION
                                        && zeroesPc >= MIN_FIELD_OFFSET_ZEROES && zeroesPc <= MAX_FIELD_OFFSET_ZEROES) {
                                        foundItem = ref fieldOffsets;
                                        break;
                                    }
                                }
                            }
                        }

                        // Try as a sequence of pointers to sets of uints
                        if (Metadata.Version >= 21) {
                            foundData.count = 0;
                            var max = limit / (Image.Bits / 8);

                            if (max >= MIN_FIELD_OFFSETS) {

                                var tesreplacedems = Image.ReadMappedArray<ulong>(ptr, max);
                                var zeroes = 0;

                                foreach (var item in tesreplacedems) {
                                    // Every pointer must either be zero or mappable into a data or BSS section
                                    if (item != 0ul && !dataSections.Any(s => item >= s.VirtualStart && item < s.VirtualEnd)
                                                    && !bssSections.Any(s => item >= s.VirtualStart && item < s.VirtualEnd))
                                        break;

                                    // Count zeroes
                                    if (item == 0ul)
                                        zeroes++;

                                    // Every valid pointer must point to a series of incrementing offsets until an inversion or a large gap
                                    else if (dataSections.Any(s => item >= s.VirtualStart && item < s.VirtualEnd)) {
                                        Image.Position = Image.MapVATR(item);
                                        var previous = 0u;
                                        var offset = 0u;
                                        var valid = true;
                                        while (offset != 0xffffffff && offset > previous && valid) {
                                            previous = offset;
                                            offset = Image.ReadUInt32();
                                            // Consider a large gap as the end of the sequence
                                            if (offset > previous + MAX_FIELD_OFFSET_GAP && offset != 0xffffffff)
                                                break;
                                            // A few offsets seem to have the top bit set for some reason
                                            if (offset >= previous && (offset & 0x7fffffff) > MAX_FIELD_OFFSET && offset != 0xffffffff)
                                                valid = false;
                                        }
                                        if (!valid)
                                            break;
                                    }

                                    foundData.count++;
                                }

                                if (foundData.count >= MIN_FIELD_OFFSETS) {
                                    var zeroesPc = (double) zeroes / foundData.count;

                                    if (zeroesPc >= MIN_FIELD_OFFSET_ZEROES && zeroesPc <= MAX_FIELD_OFFSET_ZEROES) {
                                        foundItem = ref fieldOffsets;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    foundData = (0ul, -1);
                }

                // We didn't find anything - break to avoid an infinite loop
                if (foundItem == NOT_FOUND)
                    break;

                // Remove pointer from list of remaining pointers to test
                metaPtrData = metaPtrData.Where(m => foundData.ptr != m.Item1).ToList();

                // Select the highest count in the original data that is lower or equal to our found count
                // Skip items not implemented by the specific metadata version we are replacedyzing (ptr == 0, count == 0)
                // Skip metadataUsages because it is calculated incorrectly by IL2CPP and the count is wrong
                if (foundData.count > 0 && foundData.count != usages.Count) {
                    // Aggregate uses the first value for 'next' as the seed for 'nearest' unless we specify a starting seed
                    foundData.count = metaCounts.Aggregate(0, (nearest, next) => next - foundData.count > nearest - foundData.count && next - foundData.count <= 0 ? next : nearest);
                    metaCounts = metaCounts.Where(c => c != foundData.count).ToList();
                }

                // Set item via ref
                foundItem = foundData;

                // If we just found the Il2CppTypes data, prune the pointer list to the correct length
                if (foundItem == types && typesPtrs.Count != foundData.count)
                    typesPtrs = typesPtrs.Take(foundData.count).ToList();

                UpdateProgress(foundData.count);
            }

19 Source : Helper.cs
with MIT License
from DogusTeknoloji

private static List<string> GetInterfaces(Type type, TypeScriptContext context) {
            var interfaces = type.GetInterfaces().ToList();
            return interfaces
                .Except(type.BaseType?.GetInterfaces() ?? Enumerable.Empty<Type>())
                .Except(interfaces.SelectMany(i => i.GetInterfaces())) // get only implemented by this type
                .Where(i => PopulateTypeDefinition(i, context) != null)
                .Select(i => GetTypeRef(i, context))
                .ToList();
        }

19 Source : SharpTreeView.cs
with MIT License
from dolkensp

void flattener_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			// Deselect nodes that are being hidden, if any remain in the tree
			if (e.Action == NotifyCollectionChangedAction.Remove && Items.Count > 0) {
				List<SharpTreeNode> selectedOldItems = null;
				foreach (SharpTreeNode node in e.OldItems) {
					if (node.IsSelected) {
						if (selectedOldItems == null)
							selectedOldItems = new List<SharpTreeNode>();
						selectedOldItems.Add(node);
					}
				}
				if (!updatesLocked && selectedOldItems != null) {
					var list = SelectedItems.Cast<SharpTreeNode>().Except(selectedOldItems).ToList();
					UpdateFocusedNode(list, Math.Max(0, e.OldStartingIndex - 1));
				}
			}
		}

19 Source : Program.cs
with MIT License
from Doomer3D

private void Stats()
        {
            var list = new List<string>();

            for (int i = 0; i < 99999; i++)
            {
                list.Add(RussianNumber.ToString(i).ToLowerInvariant());
            }

            // список символов
            var chars = list.SelectMany(e => e).Distinct().Where(e => char.IsLetter(e)).OrderBy(e => e).ToArray();

            // список токенов
            var tokens = list.SelectMany(e => e.Split()).Distinct().OrderBy(e => (e.Length, e)).ToArray();

            // используемые символы
            var validChars = new string(chars);

            // неиспользуемые символы
            var invalidChars = new string("абвгдеёжзийклмнопрстуфхцчшщъыьэюя".Except(chars).ToArray());

            // список токенов текстом
            var tokensList = string.Join(Environment.NewLine, tokens);
        }

19 Source : ProvisioningProfileProvider.cs
with MIT License
from dotnet

private void AddProfileToArchive(string archivePath, string profilePath)
        {
            // App comes with a profile already
            using ZipArchive zipArchive = _zipArchiveManager.OpenArchive(archivePath, ZipArchiveMode.Update);

            HashSet<string> rootLevelAppBundles = new();
            HashSet<string> appBundlesWithProfile = new();

            foreach (ZipArchiveEntry entry in zipArchive.Entries)
            {
                if (!s_topLevelAppPattern.IsMatch(entry.FullName))
                {
                    continue;
                }

                string appBundleName = entry.FullName.Split(new[] { '/' }, 2).First();
                
                if (entry.FullName == appBundleName + "/" + ProfileFileName)
                {
                    appBundlesWithProfile.Add(appBundleName);
                    _log.LogMessage($"{appBundleName} already contains provisioning profile");
                }
                else
                {
                    rootLevelAppBundles.Add(appBundleName);
                }
            }

            rootLevelAppBundles = rootLevelAppBundles.Except(appBundlesWithProfile).ToHashSet();

            // If no .app bundles, add it to the root
            if (!rootLevelAppBundles.Any())
            {
                _log.LogMessage($"No app bundles found in the archive. Adding provisioning profile to root");

                // Check if archive comes with a profile already
                if (!zipArchive.Entries.Any(e => e.FullName == ProfileFileName))
                {
                    zipArchive.CreateEntryFromFile(profilePath, ProfileFileName);
                }

                return;
            }

            // Else inject profile to every app bundle in the root of the archive
            foreach (string appBundle in rootLevelAppBundles)
            {
                var profileDestPath = appBundle + "/" + ProfileFileName;
                _log.LogMessage($"Adding provisioning profile to {appBundle}");
                zipArchive.CreateEntryFromFile(profilePath, profileDestPath);
            }
        }

19 Source : CreateFrameworkListFile.cs
with MIT License
from dotnet

public override bool Execute()
        {
            XAttribute[] rootAttributes = RootAttributes
                ?.Select(item => new XAttribute(item.ItemSpec, item.GetMetadata("Value")))
                .ToArray();

            var frameworkManifest = new XElement("FileList", rootAttributes);

            Dictionary<string, ITaskItem> fileClreplacedLookup = FileClreplacedifications
                ?.ToDictionary(
                    item => item.ItemSpec,
                    item => item,
                    StringComparer.OrdinalIgnoreCase);

            var singleFileHostIncludeFilenames = SingleFileHostIncludeFilenames?.ToHashSet();

            var usedFileClreplacedes = new HashSet<string>();

            foreach (var f in Files
                .Where(IsTargetPathIncluded)
                .Select(item => new
                {
                    Item = item,
                    Filename = Path.GetFileName(item.ItemSpec),
                    TargetPath = item.GetMetadata("TargetPath"),
                    replacedemblyName = FileUtilities.GetreplacedemblyName(item.ItemSpec),
                    FileVersion = FileUtilities.GetFileVersion(item.ItemSpec),
                    IsNative = item.GetMetadata("IsNative") == "true",
                    IsSymbolFile = item.GetMetadata("IsSymbolFile") == "true",
                    IsPgoData = item.GetMetadata("IsPgoData") == "true",
                    IsResourceFile = item.ItemSpec
                        .EndsWith(".resources.dll", StringComparison.OrdinalIgnoreCase)
                })
                .Where(f =>
                    !f.IsSymbolFile &&
                    (f.Filename.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || f.IsNative || f.IsPgoData))
                // Remove duplicate files this task is given.
                .GroupBy(f => f.Item.ItemSpec)
                .Select(g => g.First())
                // Make order stable between builds.
                .OrderBy(f => f.TargetPath, StringComparer.Ordinal)
                .ThenBy(f => f.Filename, StringComparer.Ordinal))
            {
                string type = "Managed";

                if (f.IsNative)
                {
                    type = "Native";
                }
                else if (f.IsResourceFile)
                {
                    type = "Resources";
                }
                else if (f.IsPgoData)
                {
                    type = "PgoData";
                }

                string path = Path.Combine(f.TargetPath, f.Filename).Replace('\\', '/');

                if (path.StartsWith("runtimes/"))
                {
                    var pathParts = path.Split('/');
                    if (pathParts.Length > 1 && pathParts[1].Contains("_"))
                    {
                        // This file is a runtime file with a "rid" containing "_". This is replacedumed
                        // to mean it's a cross-targeting tool and shouldn't be deployed in a
                        // self-contained app. Leave it off the list.
                        continue;
                    }
                }

                string replacedyzerLanguage = null;

                if (path.StartsWith("replacedyzers/"))
                {
                    type = "replacedyzer";

                    if (path.EndsWith(".resources.dll"))
                    {
                        // omit replacedyzer resources
                        continue;
                    }

                    var pathParts = path.Split('/');

                    if (pathParts.Length < 3 || !pathParts[1].Equals("dotnet", StringComparison.Ordinal) || pathParts.Length > 4)
                    {
                        Log.LogError($"Unexpected replacedyzer path format {path}.  Expected  'replacedyzers/dotnet(/language)/replacedyzer.dll");
                    }

                    if (pathParts.Length > 3)
                    {
                        replacedyzerLanguage = pathParts[2];
                    }
                }

                var element = new XElement(
                    "File",
                    new XAttribute("Type", type),
                    new XAttribute("Path", path));

                if (replacedyzerLanguage != null)
                {
                    element.Add(new XAttribute("Language", replacedyzerLanguage));
                }

                if (f.IsResourceFile)
                {
                    element.Add(
                        new XAttribute("Culture", Path.GetFileName(Path.GetDirectoryName(path))));
                }

                if (f.IsPgoData)
                {
                    // Pgo data is never carried with single file images
                    element.Add(new XAttribute("DropFromSingleFile", "true"));
                }
                else if (f.replacedemblyName != null)
                {
                    byte[] publicKeyToken = f.replacedemblyName.GetPublicKeyToken();
                    string publicKeyTokenHex;

                    if (publicKeyToken != null)
                    {
                        int len = publicKeyToken.Length;
                        StringBuilder publicKeyTokenBuilder = new StringBuilder(len * 2);
                        for (int i = 0; i < len; i++)
                        {
                            publicKeyTokenBuilder.Append(publicKeyToken[i].ToString("x2", CultureInfo.InvariantCulture));
                        }
                        publicKeyTokenHex = publicKeyTokenBuilder.ToString();
                    }
                    else
                    {
                        Log.LogError($"No public key token found for replacedembly {f.Item.ItemSpec}");
                        publicKeyTokenHex = "";
                    }

                    element.Add(
                        new XAttribute("replacedemblyName", f.replacedemblyName.Name),
                        new XAttribute("PublicKeyToken", publicKeyTokenHex),
                        new XAttribute("replacedemblyVersion", f.replacedemblyName.Version));
                }
                else if (!f.IsNative)
                {
                    // This file isn't managed and isn't native. Leave it off the list.
                    continue;
                }

                element.Add(new XAttribute("FileVersion", f.FileVersion));

                if (fileClreplacedLookup != null)
                {
                    if (fileClreplacedLookup.TryGetValue(f.Filename, out ITaskItem clreplacedItem))
                    {
                        string profile = clreplacedItem.GetMetadata("Profile");

                        if (!string.IsNullOrEmpty(profile))
                        {
                            element.Add(new XAttribute("Profile", profile));
                        }

                        string referencedByDefault = clreplacedItem.GetMetadata("ReferencedByDefault");

                        if (!string.IsNullOrEmpty(referencedByDefault))
                        {
                            element.Add(new XAttribute("ReferencedByDefault", referencedByDefault));
                        }

                        usedFileClreplacedes.Add(f.Filename);
                    }
                    else
                    {
                        Log.LogError($"File matches no clreplacedification: {f.Filename}");
                    }
                }

                if (f.IsNative)
                {
                    // presence of inclusion list indicates that 
                    // all other native files should be marked as "DropFromSingleFile"
                    if (singleFileHostIncludeFilenames != null &&
                        !singleFileHostIncludeFilenames.Contains(f.Filename))
                    {
                        element.Add(new XAttribute("DropFromSingleFile", "true"));
                    }
                }

                frameworkManifest.Add(element);
            }

            foreach (var unused in fileClreplacedLookup
                ?.Keys.Except(usedFileClreplacedes).OrderBy(p => p)
                ?? Enumerable.Empty<string>())
            {
                Log.LogError($"Clreplacedification matches no files: {unused}");
            }

            Directory.CreateDirectory(Path.GetDirectoryName(TargetFile));
            File.WriteAllText(TargetFile, frameworkManifest.ToString());

            return !Log.HasLoggedErrors;
        }

19 Source : ChooseColumnsByIndexTransform.cs
with MIT License
from dotnet

private static void ComputeSources(bool drop, int[] selectedColumnIndexes, DataViewSchema sourceSchema, out int[] sources)
            {
                // Compute the mapping, <see cref="_sources"/>, from output column index to input column index.
                if (drop)
                    // Drop columns indexed by args.Indices
                    sources = Enumerable.Range(0, sourceSchema.Count).Except(selectedColumnIndexes).ToArray();
                else
                    // Keep columns indexed by args.Indices
                    sources = selectedColumnIndexes;

                // Make sure the output of this transform is meaningful.
                Contracts.Check(sources.Length > 0, "Choose columns by index has no output column.");
            }

19 Source : SlotDropper.cs
with MIT License
from dotnet

public IEnumerable<long> GetPreservedSlots()
        {
            var slots = Enumerable.Range(0, _srcLength);
            var droppedSlots = Enumerable.Range(SlotsMin[0], SlotsMax[0] - SlotsMin[0] + 1);
            for (int i = 1; i < SlotsMin.Length; i++)
            {
                droppedSlots = droppedSlots.Concat(Enumerable.Range(SlotsMin[i], SlotsMax[i] - SlotsMin[i] + 1));
            }
            return slots.Except(droppedSlots).Select(i => (long)i);
        }

19 Source : RootCauseAnalyzer.cs
with MIT License
from dotnet

public override bool Equals(Dictionary<string, object> x, Dictionary<string, object> y)
        {
            if (x == null && y == null)
            {
                return true;
            }
            if ((x == null && y != null) || (x != null && y == null))
            {
                return false;
            }
            if (x.Count != y.Count)
            {
                return false;
            }
            if (x.Keys.Except(y.Keys).Any())
            {
                return false;
            }
            if (y.Keys.Except(x.Keys).Any())
            {
                return false;
            }
            foreach (var pair in x)
            {
                if (!object.Equals(pair.Value, y[pair.Key]))
                {
                    return false;
                }
            }
            return true;
        }

19 Source : AllergenData.cs
with MIT License
from dotnet

public static AllergenData WithAllergensRemoved(AllergenData srcData, List<string> allergensToRemove)
        {
            AllergenData result = new AllergenData();
            result.Allergens = AllergensInFile.Except(allergensToRemove).ToList();
            int[] indexMapper = AllergensInFile.Select(str => result.Allergens.IndexOf(str)).ToArray();

            result.SkinTestData = Util.ArrayInit(AllergenData.NumYears, y => Util.ArrayInit(srcData.NumChildren, n => Util.ArrayInit(result.NumAllergens, a => (int?)null)));
            result.IgeTestData = Util.ArrayInit(AllergenData.NumYears, y => Util.ArrayInit(srcData.NumChildren, n => Util.ArrayInit(result.NumAllergens, a => (int?)null)));

            for (int n = 0; n < srcData.NumChildren; n++)
            {
                for (int a = 0; a < srcData.NumAllergens; a++)
                {
                    int mappedAllergenIndex = indexMapper[a];
                    if (mappedAllergenIndex < 0)
                    {
                        continue;
                    }

                    for (int y = 0; y < AllergenData.NumYears; y++)
                    {

                        result.SkinTestData[y][n][mappedAllergenIndex] = srcData.SkinTestData[y][n][a];
                        result.IgeTestData[y][n][mappedAllergenIndex] = srcData.IgeTestData[y][n][a];
                    }
                }
            }

            result.setStatisticsFromData();
            return result;
        }

19 Source : CrowdData.cs
with MIT License
from dotnet

public Dictionary<Mode, CrowdData> SplitData(
            double fractionGoldLabelsForTraining,
            int randomSeed)
        {
            Rand.Restart(randomSeed);
            var allTweets = this.CrowdLabels.GroupBy(cd => cd.TweetId)
                .ToDictionary(grp => grp.Key, grp => grp.ToList());
            var allTweetIds = new HashSet<string>(allTweets.Keys);

            // The tweet ids in some order
            var goldTweetIds = this.GoldLabels.Keys.ToArray();
            var goldPerm = Rand.Perm(goldTweetIds.Length);
            var numGoldForTraining = (int)(fractionGoldLabelsForTraining * goldTweetIds.Length);
            var goldPermForTraining = goldPerm.Take(numGoldForTraining).ToList();
            var goldPermForValidation = goldPerm.Skip(numGoldForTraining).ToList();

            var goldTweetIdsForValidation =
                goldPermForValidation.Select(idx => goldTweetIds[idx]).ToList();

            var allTweetIdsForTraining = allTweetIds.Except(goldTweetIdsForValidation).ToArray();

            var trainingData = allTweetIdsForTraining.SelectMany(id => allTweets[id]).ToList();
            var validationData = goldTweetIdsForValidation.SelectMany(id => allTweets[id]).ToList();

            var trainingGoldLabels = goldPermForTraining.ToDictionary(
                idx => goldTweetIds[idx],
                idx => this.GoldLabels[goldTweetIds[idx]]);
            var validationGoldLabels = goldPermForValidation.ToDictionary(
                idx => goldTweetIds[idx],
                idx => this.GoldLabels[goldTweetIds[idx]]);
            var result = new Dictionary<Mode, CrowdData>
                             {
                                 [Mode.Training] =
                                     new CrowdData
                                         {
                                             CrowdLabels = trainingData.ToList(),
                                             GoldLabels = trainingGoldLabels
                                         },
                                 [Mode.Validation] =
                                     new CrowdData
                                         {
                                             CrowdLabels =
                                                 validationData.ToList(),
                                             GoldLabels = validationGoldLabels
                                         }
                             };

            return result;
        }

19 Source : CrowdData.cs
with MIT License
from dotnet

public virtual CrowdData LimitData(
            int maxJudgements = int.MaxValue,
            int maxNumTweets = int.MaxValue,
            int maxNumWorkers = int.MaxValue,
            int maxJudgmentsPerWorker = int.MaxValue,
            int maxJudgmentsPerTweet = int.MaxValue,
            bool balanceTweetsByLabel = false,
            int randomSeed = 12347)
        {
            var crowdLabels = this.CrowdLabels;
            var goldLabels = this.GoldLabels;

            // Restrict the tweets if requested.
            Rand.Restart(randomSeed);
            var selectedTweets = new HashSet<string>(crowdLabels.Select(cd => cd.TweetId).Distinct());
            if (selectedTweets.Count > maxNumTweets || balanceTweetsByLabel)
            {
                var goldTweets = goldLabels.Keys.ToArray();
                var nonGoldTweets = selectedTweets.Except(goldTweets).ToArray();

                var goldPerm = Rand.Perm(goldTweets.Length);
                var nonGoldPerm = Rand.Perm(nonGoldTweets.Length);

                var permutedGoldTweets = goldPerm.Select(i => goldTweets[i]);
                var permutedNonGoldTweets = nonGoldPerm.Select(i => nonGoldTweets[i]);
                var selectedTweetList = permutedGoldTweets.Concat(permutedNonGoldTweets).Take(maxNumTweets).ToList();
                selectedTweets = new HashSet<string>(selectedTweetList);
                crowdLabels = crowdLabels.Where(cd => selectedTweets.Contains(cd.TweetId)).ToList();

                if (balanceTweetsByLabel)
                {
                    var majorityVoteLabels = CrowdData.MajorityVoteLabels(crowdLabels);
                    var tweetCountsPerLabel = majorityVoteLabels.Values.GroupBy(lab => lab).Select(grp => grp.Count()).ToArray();
                    var smallestCount = tweetCountsPerLabel.Min();
                    selectedTweets.Clear();

                    var counts = Util.ArrayInit(tweetCountsPerLabel.Length, i => 0);

                    Util.ArrayInit(tweetCountsPerLabel.Length, labVal => new List<int>());
                    foreach (var tweet in selectedTweetList)
                    {
                        var lab = majorityVoteLabels[tweet];
                        if (++counts[lab] <= smallestCount)
                        {
                            selectedTweets.Add(tweet);
                        }
                    }

                    crowdLabels = crowdLabels.Where(cd => selectedTweets.Contains(cd.TweetId)).ToList();
                }

                goldLabels = goldLabels.Where(kvp => selectedTweets.Contains(kvp.Key))
                    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            }

            // Limit workers
            var numWorkers = crowdLabels.Select(cd => cd.WorkerId).Distinct().Count();
            if (numWorkers > maxNumWorkers)
            {
                crowdLabels = crowdLabels.GroupBy(cd => cd.WorkerId)
                    .OrderByDescending(wcds => wcds.Count(wcd => selectedTweets.Contains(wcd.TweetId)))
                    .Take(maxNumWorkers).SelectMany(cds => cds).ToList();
            }

            // Limit judgments per worker
            if (maxJudgmentsPerWorker < int.MaxValue)
            {
                crowdLabels = crowdLabels.GroupBy(cd => cd.WorkerId).Select(
                    gp =>
                        {
                            var judgments = gp.ToArray();
                            var perm = Rand.Perm(gp.Count());
                            var limitCount = Math.Min(perm.Length, maxJudgmentsPerWorker);
                            var limitedJudgments = Util.ArrayInit(limitCount, i => judgments[perm[i]]);
                            return limitedJudgments;
                        }).SelectMany(cds => cds).ToList();
            }

            // Limit judgments per tweet
            if (maxJudgmentsPerTweet < int.MaxValue)
            {
                crowdLabels = crowdLabels.GroupBy(cd => cd.TweetId).Select(
                    gp =>
                        {
                            var judgments = gp.ToArray();
                            var perm = Rand.Perm(gp.Count());
                            var limitCount = Math.Min(perm.Length, maxJudgmentsPerTweet);
                            var limitedJudgments = Util.ArrayInit(limitCount, i => judgments[perm[i]]);
                            return limitedJudgments;
                        }).SelectMany(cds => cds).ToList();
            }

            // Limit the total judgments
            if (maxJudgements < int.MaxValue)
            {
                var numJudgments = crowdLabels.Count;
                var perm = Rand.Perm(numJudgments);
                var limitedNumJudgments = Math.Min(numJudgments, maxJudgements);
                crowdLabels = Util.ArrayInit(limitedNumJudgments, i => crowdLabels[perm[i]]).ToList();
            }

            return new CrowdData { CrowdLabels = crowdLabels, GoldLabels = goldLabels };
        }

See More Examples