System.Collections.Generic.List.FindIndex(System.Predicate)

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

1196 Examples 7

19 Source : Contributors.xaml.cs
with MIT License
from automuteus

public async void AddContributors()
        {
            List<long> BlockedIDs = new List<long> {25180681, 49699333};
            GitHubClient client = new GitHubClient(new ProductHeaderValue("AmongUsCapture"));
            var autoMuteUsOrgRepos = new List<int>{294825566, 295776544};
            var ListOfContribs = new List<BetterRepoContributor>();
            foreach (var repo in autoMuteUsOrgRepos)
            {
                var RepoContributors = await client.Repository.GetAllContributors(repo);
                foreach (var contributor in RepoContributors)
                {
                    if (ListOfContribs.All(x => x.HtmlUrl != contributor.HtmlUrl))
                    {
                        ListOfContribs.Add(new BetterRepoContributor(contributor.Id,contributor.Contributions, contributor.AvatarUrl, contributor.HtmlUrl, contributor.Login));
                    }
                    else
                    {
                        var indexOfReal = ListOfContribs.FindIndex(x => x.HtmlUrl == contributor.HtmlUrl);
                        ListOfContribs[indexOfReal].Contributions += contributor.Contributions;
                    }
                }
            }

            var tempList = ListOfContribs.Where(x => !BlockedIDs.Contains(x.Id)).OrderByDescending(x=>x.Contributions).ToList();
            RepoContributorsToBeAdded = new Queue<BetterRepoContributor>(tempList);
            CurrentContributors.Add(RepoContributorsToBeAdded.Dequeue());
            
            System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            dispatcherTimer.Tick += dispatcherTimer_Tick;
            dispatcherTimer.Interval = TimeSpan.FromMilliseconds(1);
            dispatcherTimer.Start();
        }

19 Source : FileSet.cs
with MIT License
from autostep

public bool TryRemoveFile(string relativePath)
        {
            var indexOf = files.FindIndex(f => f.Relative == relativePath);

            if (indexOf > -1)
            {
                files.RemoveAt(indexOf);
            }

            return false;
        }

19 Source : SequenceUtils.cs
with GNU General Public License v3.0
from az64

public static void RebuildAudioSeq(List<SequenceInfo> SequenceList, OutputSettings _settings)
        {
            // spoiler log output DEBUG
            StringBuilder log = new StringBuilder();
            void WriteOutput(string str)
            {
                Debug.WriteLine(str); // we still want debug output though
                log.AppendLine(str);
            }

            List<MMSequence> OldSeq = new List<MMSequence>();
            int f = RomUtils.GetFileIndexForWriting(Addresses.SeqTable);
            int basea = RomData.MMFileList[f].Addr;

            for (int i = 0; i < 128; i++)
            {
                MMSequence entry = new MMSequence();
                if (i == 0x1E) // intro music when link gets ambushed
                {
                    entry.Addr = 2;
                    entry.Size = 0;
                    OldSeq.Add(entry);
                    continue;
                }

                int entryaddr = Addresses.SeqTable + (i * 16);
                entry.Addr = (int)ReadWriteUtils.Arr_ReadU32(RomData.MMFileList[f].Data, entryaddr - basea);
                entry.Size = (int)ReadWriteUtils.Arr_ReadU32(RomData.MMFileList[f].Data, (entryaddr - basea) + 4);
                if (entry.Size > 0)
                {
                    entry.Data = new byte[entry.Size];
                    Array.Copy(RomData.MMFileList[4].Data, entry.Addr, entry.Data, 0, entry.Size);
                }
                else
                {
                    int j = SequenceList.FindIndex(u => u.Replaces == i);
                    if (j != -1)
                    {
                        if ((entry.Addr > 0) && (entry.Addr < 128))
                        {
                            if (SequenceList[j].Replaces != 0x28) // 28 (fairy fountain)
                            {
                                SequenceList[j].Replaces = entry.Addr;
                            }
                            else
                            {
                                entry.Data = OldSeq[0x18].Data;
                                entry.Size = OldSeq[0x18].Size;
                            }
                        }
                    }
                }
                OldSeq.Add(entry);
            }

            List<MMSequence> NewSeq = new List<MMSequence>();
            int addr = 0;
            byte[] NewAudioSeq = new byte[0];
            for (int i = 0; i < 128; i++)
            {
                MMSequence newentry = new MMSequence();
                if (OldSeq[i].Size == 0)
                {
                    newentry.Addr = OldSeq[i].Addr;
                }
                else
                {
                    newentry.Addr = addr;
                }

                if (SequenceList.FindAll(u => u.Replaces == i).Count > 1)
                {
                    WriteOutput("Error: Slot " + i.ToString("X") + " has multiple songs pointing at it!");
                }

                int p = RomData.PointerizedSequences.FindIndex(u => u.PreviousSlot == i);
                int j = SequenceList.FindIndex(u => u.Replaces == i);
                if (p != -1){ // found song we want to pointerize
                    newentry.Addr = RomData.PointerizedSequences[p].Replaces;
                    newentry.Size = 0;
                }
                else if (j != -1){ // new song to replace old slot found
                    if (SequenceList[j].MM_seq != -1)
                    {
                        newentry.Size = OldSeq[SequenceList[j].MM_seq].Size;
                        newentry.Data = OldSeq[SequenceList[j].MM_seq].Data;
                        WriteOutput("Slot " + i.ToString("X") + " -> " + Path.GetFileName(SequenceList[j].Name));

                    }
                    else if (SequenceList[j].SequenceBinaryList != null && SequenceList[j].SequenceBinaryList[0] != null)
                    {
                        if (SequenceList[j].SequenceBinaryList.Count == 0)
                            throw new Exception("Reached music write without a song to write");
                        if (SequenceList[j].SequenceBinaryList.Count > 1)
                            WriteOutput("Warning: writing song with multiple sequence/bank combos, selecting first available");
                        newentry.Size = SequenceList[j].SequenceBinaryList[0].SequenceBinary.Length;
                        newentry.Data = SequenceList[j].SequenceBinaryList[0].SequenceBinary;
                        WriteOutput("Slot " + i.ToString("X") + " := " + Path.GetFileName(SequenceList[j].Name) + " *");

                    }
                    else // non mm, load file and add
                    {
                        BinaryReader sequence = new BinaryReader(File.Open(SequenceList[j].Name, FileMode.Open));
                        byte[] data = new byte[(int)sequence.BaseStream.Length];
                        sequence.Read(data, 0, data.Length);
                        sequence.Close();

                        // if the sequence is not padded to 16 bytes, the DMA fails
                        //  music can stop from playing and on hardware it will just straight crash
                        if (data.Length % 0x10 != 0)
                            data = data.Concat(new byte[0x10 - (data.Length % 0x10)]).ToArray();

                        // I think this checks if the sequence type is correct for MM
                        //  because DB ripped sequences from SF64/SM64/MK64 without modifying them
                        if (data[1] != 0x20)
                        {
                            data[1] = 0x20;
                        }

                        newentry.Size = data.Length;
                        newentry.Data = data;
                        WriteOutput("Slot " + i.ToString("X") + " := " + Path.GetFileName(SequenceList[j].Name));

                    }
                }
                else // not found, song wasn't touched by rando, just transfer over
                {
                    newentry.Size = OldSeq[i].Size;
                    newentry.Data = OldSeq[i].Data;
                }

                NewSeq.Add(newentry);
                // TODO is there not a better way to write this?
                if (newentry.Data != null)
                {

                    NewAudioSeq = NewAudioSeq.Concat(newentry.Data).ToArray();
                }

                addr += newentry.Size;
            }

            // discovered when MM-only music was fixed, if the audioseq is left in it's old spot
            // audio quality is garbage, sounds like static
            //if (addr > (RomData.MMFileList[4].End - RomData.MMFileList[4].Addr))
            //else
                //RomData.MMFileList[4].Data = NewAudioSeq;

            int index = RomUtils.AppendFile(NewAudioSeq);
            ResourceUtils.ApplyHack(Values.ModsDirectory, "reloc-audio");
            RelocateSeq(index);
            RomData.MMFileList[4].Data = new byte[0];
            RomData.MMFileList[4].Cmp_Addr = -1;
            RomData.MMFileList[4].Cmp_End = -1;

            //update sequence index pointer table
            f = RomUtils.GetFileIndexForWriting(Addresses.SeqTable);
            for (int i = 0; i < 128; i++)
            {
                ReadWriteUtils.Arr_WriteU32(RomData.MMFileList[f].Data, (Addresses.SeqTable + (i * 16)) - basea, (uint)NewSeq[i].Addr);
                ReadWriteUtils.Arr_WriteU32(RomData.MMFileList[f].Data, 4 + (Addresses.SeqTable + (i * 16)) - basea, (uint)NewSeq[i].Size);
            }

            //update inst sets used by each new seq
            // this is NOT the audiobank, its the complementary instrument set value for each sequence
            //   IE, sequence 7 uses instrument set "10", we replaced it with sequnece ae which needs bank "23"
            f = RomUtils.GetFileIndexForWriting(Addresses.InstSetMap);
            basea = RomData.MMFileList[f].Addr;
            for (int i = 0; i < 128; i++)
            {
                // huh? paddr? pointer? padding?
                int paddr = (Addresses.InstSetMap - basea) + (i * 2) + 2;

                int j = -1;
                if (NewSeq[i].Size == 0) // pointer, we need to copy the instrumnet set from the destination
                {
                    j = SequenceList.FindIndex(u => u.Replaces == NewSeq[i].Addr);
                }
                else
                {
                    j = SequenceList.FindIndex(u => u.Replaces == i);
                }

                if (j != -1)
                {
                    RomData.MMFileList[f].Data[paddr] = (byte)SequenceList[j].Instrument;
                }

            }

            // DEBUG spoiler log output
            String dir = Path.GetDirectoryName(_settings.OutputROMFilename);
            String path = $"{Path.GetFileNameWithoutExtension(_settings.OutputROMFilename)}";
            // spoiler log should already be written by the time we reach this far
            if (File.Exists(Path.Combine(dir, path + "_SpoilerLog.txt")))
                path += "_SpoilerLog.txt";
            else // TODO add HTML log compatibility
                path += "_SongLog.txt";

            using (StreamWriter sw = new StreamWriter(Path.Combine(dir, path), append: true))
            {
                sw.WriteLine(""); // spacer
                sw.Write(log);
            }


        }

19 Source : Enemies.cs
with GNU General Public License v3.0
from az64

public static void SetSceneEnemyActors(Scene scene, List<ValueSwap[]> A)
        {
            for (int i = 0; i < scene.Maps.Count; i++)
            {
                for (int j = 0; j < scene.Maps[i].Actors.Count; j++)
                {
                    int k = A.FindIndex(u => u[0].OldV == scene.Maps[i].Actors[j].n);
                    if (k != -1)
                    {
                        scene.Maps[i].Actors[j].n = A[k][0].NewV;
                        scene.Maps[i].Actors[j].v = A[k][1].NewV;
                        A.RemoveAt(k);
                    }
                }
            }
        }

19 Source : Enemies.cs
with GNU General Public License v3.0
from az64

public static List<int> GetSceneEnemyActors(Scene scene)
        {
            List<int> ActorList = new List<int>();
            for (int i = 0; i < scene.Maps.Count; i++)
            {
                for (int j = 0; j < scene.Maps[i].Actors.Count; j++)
                {
                    int k = EnemyList.FindIndex(u => u.Actor == scene.Maps[i].Actors[j].n);
                    if (k != -1)
                    {
                        if (!EnemyList[k].SceneExclude.Contains(scene.Number))
                        {
                            ActorList.Add(EnemyList[k].Actor);
                        }
                    }
                }
            }
            return ActorList;
        }

19 Source : Enemies.cs
with GNU General Public License v3.0
from az64

public static List<int> GetSceneEnemyObjects(Scene scene)
        {
            List<int> ObjList = new List<int>();
            for (int i = 0; i < scene.Maps.Count; i++)
            {
                for (int j = 0; j < scene.Maps[i].Objects.Count; j++)
                {
                    int k = EnemyList.FindIndex(u => u.Object == scene.Maps[i].Objects[j]);
                    if (k != -1)
                    {
                        if (!ObjList.Contains(EnemyList[k].Object))
                        {
                            if (!EnemyList[k].SceneExclude.Contains(scene.Number))
                            {
                                ObjList.Add(EnemyList[k].Object);
                            }
                        }
                    }
                }
            }
            return ObjList;
        }

19 Source : Enemies.cs
with GNU General Public License v3.0
from az64

public static void SwapSceneEnemies(Scene scene, Random rng)
        {
            List<int> Actors = GetSceneEnemyActors(scene);
            if (Actors.Count == 0)
            {
                return;
            }
            List<int> Objects = GetSceneEnemyObjects(scene);
            if (Objects.Count == 0)
            {
                return;
            }
            // if actor doesn't exist but object does, probably spawned by something else
            List<int> ObjRemove = new List<int>();
            foreach (int o in Objects)
            {
                List<Enemy> ObjectMatch = EnemyList.FindAll(u => u.Object == o);
                bool exists = false;
                for (int i = 0; i < ObjectMatch.Count; i++)
                {
                    exists |= Actors.Contains(ObjectMatch[i].Actor);
                }
                if (!exists)
                {
                    ObjRemove.Add(o); ;
                }
            }
            foreach (int o in ObjRemove)
            {
                Objects.Remove(o);
            }
            List<ValueSwap[]> ActorsUpdate = new List<ValueSwap[]>();
            List<ValueSwap> ObjsUpdate;
            List<List<Enemy>> Updates;
            List<List<Enemy>> Matches;
            while (true)
            {
                ObjsUpdate = new List<ValueSwap>();
                Updates = new List<List<Enemy>>();
                Matches = new List<List<Enemy>>();
                int oldsize = 0;
                int newsize = 0;
                for (int i = 0; i < Objects.Count; i++)
                {
                    Updates.Add(EnemyList.FindAll(u => ((u.Object == Objects[i]) && (Actors.Contains(u.Actor)))));
                    Matches.Add(GetMatchPool(Updates[i], rng));
                    int k = rng.Next(Matches[i].Count);
                    int newobj = Matches[i][k].Object;
                    newsize += Matches[i][k].ObjectSize;
                    oldsize += Updates[i][0].ObjectSize;
                    ValueSwap NewObject = new ValueSwap();
                    NewObject.OldV = Objects[i];
                    NewObject.NewV = newobj;
                    ObjsUpdate.Add(NewObject);
                }
                if (newsize <= oldsize)
                {
                    //this should take into account map/scene size and size of all loaded actors...
                    //not really accurate but *should* work for now to prevent crashing
                    break;
                }
            }
            for (int i = 0; i < ObjsUpdate.Count; i++)
            {
                int j = 0;
                while (j != Actors.Count)
                {
                    Enemy Old = Updates[i].Find(u => u.Actor == Actors[j]);
                    if (Old != null)
                    {
                        List<Enemy> SubMatches = Matches[i].FindAll(u => u.Object == ObjsUpdate[i].NewV);
                        int l;
                        while (true)
                        {
                            l = rng.Next(SubMatches.Count);
                            if ((Old.Type == SubMatches[l].Type) && (Old.Stationary == SubMatches[l].Stationary))
                            {
                                break;
                            }
                            else
                            {
                                if ((Old.Type == SubMatches[l].Type) && (rng.Next(5) == 0))
                                {
                                    break;
                                }
                            }
                            if (SubMatches.FindIndex(u => u.Type == Old.Type) == -1)
                            {
                                break;
                            }
                        }
                        ValueSwap NewActor = new ValueSwap();
                        NewActor.OldV = Actors[j];
                        NewActor.NewV = SubMatches[l].Actor;
                        ValueSwap NewVar = new ValueSwap();
                        NewVar.NewV = SubMatches[l].Variables[rng.Next(SubMatches[l].Variables.Count)];
                        ActorsUpdate.Add(new ValueSwap[] { NewActor, NewVar });
                        Actors.RemoveAt(j);
                    }
                    else
                    {
                        j++;
                    }
                }
            }
            SetSceneEnemyActors(scene, ActorsUpdate);
            SetSceneEnemyObjects(scene, ObjsUpdate);
            SceneUtils.UpdateScene(scene);
        }

19 Source : Enemies.cs
with GNU General Public License v3.0
from az64

public static void SetSceneEnemyObjects(Scene scene, List<ValueSwap> O)
        {
            for (int i = 0; i < scene.Maps.Count; i++)
            {
                for (int j = 0; j < scene.Maps[i].Objects.Count; j++)
                {
                    int k = O.FindIndex(u => u.OldV == scene.Maps[i].Objects[j]);
                    if (k != -1)
                    {
                        scene.Maps[i].Objects[j] = O[k].NewV;
                    }
                }
            }
        }

19 Source : ApiDocGenerator.cs
with MIT License
from azist

public string AddTypeToDescribe(Type type, object instance = null)
    {
      if (type == typeof(object)) return "object";
      if (type == typeof(string)) return "string";
      if (type == typeof(decimal)) return "decimal";
      if (type == typeof(DateTime)) return "datetime";
      if (type == typeof(TimeSpan)) return "timespan";
      if (type == typeof(GDID)) return "gdid";
      if (type == typeof(Atom)) return "atom";
      if (type == typeof(Guid)) return "gdid";
      if (type.IsPrimitive) return "{0}".Args(type.Name.ToLowerInvariant());
      if (type.IsArray) return "array({0})".Args(AddTypeToDescribe(type.GetElementType()));
      if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) return "nullable({0})".Args(AddTypeToDescribe(type.GetGenericArguments()[0]));
      if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) return "array({0})".Args(AddTypeToDescribe(type.GetGenericArguments()[0]));

      if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>))
        return "map({0},{1})".Args(AddTypeToDescribe(type.GetGenericArguments()[0]), AddTypeToDescribe(type.GetGenericArguments()[1]));

      if (IgnoreTypePatterns.Any(ignore => type.FullName.MatchPattern(ignore))) return DetailLevel > MetadataDetailLevel.Public ? type.Name : "sys";

      instanceList list;
      if (!m_TypesToDescribe.TryGetValue(type, out list))
      {
        list = new instanceList("@{0:x2}-{1}".Args(m_TypesToDescribe.Count, MetadataUtils.GetMetadataTokenId(type)));
        list.Add((null, false));//always at index #0
        m_TypesToDescribe.Add(type, list);
      }

      var idx = list.FindIndex( litem => object.ReferenceEquals(litem.item, instance));
      if (idx < 0)
      {
        list.Add((instance, false));
        idx = list.Count-1;
      }

      return "{0}:{1}".Args(list.ID, idx);
    }

19 Source : TraceMiddleware.cs
with Apache License 2.0
from Azure-App-Service

private static void LogEndRequest(HttpContext httpContext)
        {
            if (whiteListedPaths.FindIndex(x => x.Contains(httpContext.Request.Path.ToString(),
                    StringComparison.OrdinalIgnoreCase)) != -1)
            {
                return;
            }

            OperationManager.SafeExecute(() =>
            {
                var request = httpContext.Request;
                var response = httpContext.Response;
                var requestId = (string) httpContext.Items[Constants.RequestIdHeader];
                var requestTime = (DateTime) httpContext.Items[Constants.RequestDateTimeUtc];
                var latencyInMilliseconds = (long) (DateTime.UtcNow - requestTime).TotalMilliseconds;
                KuduEventGenerator.Log().ApiEvent(
                    ServerConfiguration.GetApplicationName(),
                    "OnEndRequest",
                    GetRawUrl(request),
                    request.Method,
                    requestId,
                    response.StatusCode,
                    latencyInMilliseconds,
                    request.GetUserAgent());
            });
        }

19 Source : TraceMiddleware.cs
with Apache License 2.0
from Azure-App-Service

private static void LogBeginRequest(HttpContext httpContext)
        {
            if (whiteListedPaths.FindIndex(x => x.Contains(httpContext.Request.Path.ToString(),
                    StringComparison.OrdinalIgnoreCase)) != -1)
            {
                return;
            }

            OperationManager.SafeExecute(() =>
            {
                var request = httpContext.Request;
                var requestId = request.GetRequestId() ?? Guid.NewGuid().ToString();
                httpContext.Items[Constants.RequestIdHeader] = requestId;
                httpContext.Items[Constants.RequestDateTimeUtc] = DateTime.UtcNow;
                KuduEventGenerator.Log().ApiEvent(
                    ServerConfiguration.GetApplicationName(),
                    "OnBeginRequest",
                    GetRawUrl(request),
                    request.Method,
                    requestId,
                    0,
                    0,
                    request.GetUserAgent());
            });
        }

19 Source : ListExt.cs
with MIT License
from baba-s

public static void Remove<T>( this List<T> self, Predicate<T> match )
		{
			var index = self.FindIndex( match );
			if ( index == -1 ) return;
			self.RemoveAt( index );
		}

19 Source : CommandList.cs
with MIT License
from baba-s

public int FindIndex( Predicate<string> match )
		{
			return m_list.FindIndex( match );
		}

19 Source : SmartDataParameterEditorViewModel.cs
with The Unlicense
from BAndysc

private void replacedignCurrentParamKey()
        {
            var index = ParameterKeys.FindIndex(x => x.Key == Source.Type);
            if (index != -1)
            {
                selectedKey = ParameterKeys[index];
                AreValuesVisible = ParameterKeys[index].UseValues;
            }
        }

19 Source : EditorSession.cs
with The Unlicense
from BAndysc

public void Insert(ISolutionItem item, string query)
        {
            var indexOf = queries.FindIndex(pair => pair.Item1.Equals(item));
            if (indexOf == -1)
            {
                if (!string.IsNullOrEmpty(query))
                {
                    queries.Add((item, query));
                    CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, queries.Count - 1));
                }
            }
            else
            {
                if (string.IsNullOrEmpty(query))
                {
                    queries.RemoveAt(indexOf);
                    CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, indexOf));
                }
                else
                {
                    queries[indexOf] = (item, query);
                }
            }
        }

19 Source : EditorMainMenuItemsProvider.cs
with The Unlicense
from BAndysc

public void AddSubItems(IEnumerable<IMenuItem> items)
        {
            foreach (var item in items)
            {
                var itemIndex = subItems.FindIndex(x => x.ItemName == item.ItemName);
                if (itemIndex == -1)
                    subItems.Add(item);
                else
                {
                    var existingItem = subItems[itemIndex];
                    if (existingItem is IMenuSeparator && item is IMenuSeparator)
                    {
                        subItems.Add(item);
                        continue;
                    }
                    
                    if (existingItem is not IMenuCategoryItem && item is not IMenuCategoryItem)
                        throw new DuplicatedMenuItemException(
                    $"Found duplicated menu item of non category type in MainMenuItem ({ItemName})! Duplicated name: {item.ItemName}");

                    if (existingItem is MenuItemsAggregator aggregator)
                    {
                        if (item is IMenuCategoryItem categoryItem)
                            aggregator.AddSubItems(categoryItem.CategoryItems);
                        else
                            aggregator.AddSubItems(new List<IMenuItem> { item });
                    }
                    else
                    {
                        subItems.RemoveAt(itemIndex);
                        var mia = new MenuItemsAggregator(existingItem.ItemName, new List<IMenuItem>());
                        if (existingItem is IMenuCategoryItem categoryItem)
                            mia.AddSubItems(categoryItem.CategoryItems);
                        else
                            mia.AddSubItems(new List<IMenuItem> { existingItem });
                        
                        if (item is IMenuCategoryItem newCategoryItem)
                            mia.AddSubItems(newCategoryItem.CategoryItems);
                        else
                            mia.AddSubItems(new List<IMenuItem> { item });
                        subItems.Insert(itemIndex, mia);
                    }
                }
            }
        }

19 Source : EditorMainMenuItemsProvider.cs
with The Unlicense
from BAndysc

internal void AddSubItems(List<IMenuItem> items)
        {
            foreach (var item in items)
            {
                var itemIndex = subItems.FindIndex(x => x.ItemName == item.ItemName);
                if (itemIndex == -1)
                    subItems.Add(item);
                else
                {
                    var existingItem = subItems[itemIndex];
                    if (existingItem is IMenuSeparator && item is IMenuSeparator)
                    {
                        subItems.Add(item);
                        continue;
                    }
                    
                    if (existingItem is not IMenuCategoryItem && item is not IMenuCategoryItem)
                        throw new DuplicatedMenuItemException(
                            $"Found duplicated menu item of non category type in MainMenuItem ({ItemName})! Duplicated name: {item.ItemName}");

                    if (existingItem is MenuItemsAggregator aggregator)
                    {
                        if (item is IMenuCategoryItem categoryItem)
                            aggregator.AddSubItems(categoryItem.CategoryItems);
                        else
                            aggregator.AddSubItems(new List<IMenuItem> { item });
                    }
                    else
                    {
                        subItems.RemoveAt(itemIndex);
                        var mia = new MenuItemsAggregator(existingItem.ItemName, new List<IMenuItem>());
                        if (existingItem is IMenuCategoryItem categoryItem)
                            mia.AddSubItems(categoryItem.CategoryItems);
                        else
                            mia.AddSubItems(new List<IMenuItem> { existingItem });
                        
                        if (item is IMenuCategoryItem newCategoryItem)
                            mia.AddSubItems(newCategoryItem.CategoryItems);
                        else
                            mia.AddSubItems(new List<IMenuItem> { item });
                        subItems.Insert(itemIndex, mia);
                    }
                }
            }
        }

19 Source : MainWindow.xaml.cs
with MIT License
from bayoen

private void LauncherWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            if (IsGoogleOn)
            {
                this.CheckLocalVersion();

                this.UpdatorTextBlock.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                {
                    this.UpdatorTextBlock.Text += string.Format(" {0}", this.currentVersion.ToString());
                }));
                Thread.Sleep(1);

                #region CheckReleases::
                ok::GitHubClient client;
                ok::Release latest;
                bool nextBigVersionFlag = false;

                try
                {
                    client = new ok::GitHubClient(new ok::ProductHeaderValue("bayoen"));
                    //latest = client.Repository.Release.GetLatest("bayoen", "bayoen-star-exe").Result;

                    List<ok.Release> releases = client.Repository.Release.GetAll("bayoen", "bayoen-star-exe").Result.ToList();

                    int nextBigVersion = releases.FindIndex(x => Version.Parse(x.TagName.GetVersionNumbers()) >= new Version(0, 2));

                    if (nextBigVersion == 0)
                    {
                        latest = null;
                    }
                    else if (nextBigVersion > 0)
                    {
                        nextBigVersionFlag = true;
                        latest = releases[nextBigVersion - 1];
                    }
                    else
                    {
                        latest = releases.First();
                    }                    
                }
                catch
                {
                    latest = null;
                }

                if (latest == null)
                {                    
                    MessageBox.Show("We can't find any latest version", "Warning");
                    Environment.Exit(0);
                }
                else
                {
                    Version latestVersion = Version.Parse(latest.TagName.GetVersionNumbers());
                    
                    if (currentVersion <= latestVersion)
                    {
                        this.UpdatorTextBlock.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                        {
                            this.UpdatorTextBlock.Text += string.Format(" to {0}...", latestVersion.ToString());
                            if (nextBigVersionFlag)
                            {
                                this.UpdatorTextBlock.Text += $"\nWe can not update modules to upper versions!\nPlease visit 'https://bayoen.github.io/star/'";
                            }
                        }));
                        Thread.Sleep(1);

                        List<string> fileNameList = new List<string>();
                        foreach (ok::Releasereplacedet replacedetToken in latest.replacedets)
                        {
                            using (System.Net.WebClient web = new System.Net.WebClient())
                            {
                                string url = replacedetToken.BrowserDownloadUrl;
                                string fileName = url.Split('/').Last();
                                web.DownloadFile(url, fileName);
                                fileNameList.Add(fileName);
                            }
                        }

                        List<string> UpdaterList = File.ReadAllText(coreListName, Encoding.UTF8).Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();

                        string rootPath = System.IO.Path.GetDirectoryName(System.Reflection.replacedembly.GetEntryreplacedembly().Location);
                        string updatingFolderPath = System.IO.Path.Combine(rootPath, updatingFolderName);
                        if (Directory.Exists(updatingFolderPath)) Directory.Delete(updatingFolderPath, true);
                        foreach (string fileNameToken in fileNameList)
                        {
                            if (fileNameToken.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
                            {
                                using (ZipArchive readingToken = ZipFile.Open(fileNameToken, ZipArchiveMode.Update))
                                {                                    
                                    readingToken.ExtractToDirectory(updatingFolderPath);
                                }
                                if (File.Exists(fileNameToken)) File.Delete(fileNameToken);
                            }
                        }

                        if (Directory.Exists(updatingFolderPath))
                        {
                            List<string> fileList = Directory.GetFiles(updatingFolderPath, "*.*", SearchOption.AllDirectories).ToList();
                            bool updaterFlag = fileList.Remove(System.IO.Path.Combine(updatingFolderPath, UpdatarName));

                            foreach (string filePath in fileList)
                            {
                                string token = filePath.Replace(updatingFolderPath + '\\', "");
                                if (UpdaterList.IndexOf(token) > -1) continue;

                                if (File.Exists(filePath))
                                {
                                    string targetPath = System.IO.Path.Combine(rootPath, System.IO.Path.GetFileName(filePath));
                                    if (File.Exists(targetPath))
                                    {
                                        File.SetAttributes(targetPath, FileAttributes.Normal);
                                        File.Delete(targetPath);
                                    }
                                    File.Move(filePath, targetPath);
                                }
                            }

                            if (!updaterFlag) Directory.Delete(updatingFolderPath);
                        }

                        File.WriteAllText(versionDataName, latestVersion.ToString());
                    }
                    else //if (currentVersion > latestVersion)
                    {
                        MessageBox.Show("Hm... we are doing well, right?", "Warning");
                    }
                }

                #endregion

                if (File.Exists(bayoenStarName)) Process.Start(bayoenStarName);
                Environment.Exit(0);
            }
            else
            {
                System.Media.SystemSounds.Hand.Play();
            }

        }

19 Source : AssemblyManager.cs
with MIT License
from bcssov

internal static replacedembly Getreplacedembly(replacedemblyName replacedemblyName)
        {
            replacedemblyCache.TryGetValue(replacedemblyName.FullName, out var replacedembly);
            if (replacedembly == null)
            {
                // Default replacedemblies take priority
                var replacedemblies = replacedemblyLoadContext.Default.replacedemblies.Where(s => s.GetName().Name.Equals(replacedemblyName.Name));
                if (replacedemblies.Count() == 0)
                {
                    // Search anywhere now
                    replacedemblies = replacedemblyLoadContext.All.SelectMany(p => p.replacedemblies.Where(s => s.GetName().Name.Equals(replacedemblyName.Name)));
                }
                if (replacedemblies.Count() > 0)
                {
                    var sorted = new List<replacedemblySort>() { new replacedemblySort { Version = replacedemblyName.Version, IsComparerObject = true } };
                    foreach (var item in replacedemblies)
                    {
                        sorted.Add(new replacedemblySort()
                        {
                            Version = item.GetName().Version,
                            replacedembly = item
                        });
                    }
                    if (sorted.Any(p => !p.IsComparerObject && p.Version == replacedemblyName.Version))
                    {
                        replacedembly = sorted.FirstOrDefault(p => !p.IsComparerObject && p.Version == replacedemblyName.Version).replacedembly;
                    }
                    else
                    {
                        sorted = sorted.OrderBy(p => p.Version).ToList();
                        var sortedIdx = sorted.FindIndex(p => p.IsComparerObject);
                        var prev = sortedIdx - 1;
                        var next = sortedIdx + 1;
                        if (next < sorted.Count)
                        {
                            replacedembly = sorted[next].replacedembly;
                        }
                        else if (prev > -1)
                        {
                            replacedembly = sorted[prev].replacedembly;
                        }
                    }

                    if (replacedembly != null)
                    {
                        replacedemblyCache.TryAdd(replacedemblyName.FullName, replacedembly);
                    }
                }
            }
            if (replacedembly != null)
            {
                return replacedembly;
            }
            return null;
        }

19 Source : InstructionRange.cs
with GNU Lesser General Public License v3.0
from bcmpinc

public InstructionRange Follow(int i) {
            var op = insts[start+i].operand;
            if (op == null || !(op is Label)) {
                throw new InvalidBranchException("Expected a branch instruction, got: "+insts[start+i]);
            }
            Label lbl = (Label)op;
            int pos = insts.FindIndex(inst => inst.labels.Contains(lbl));
            if (pos < 0) throw new InvalidBranchException($"Label not found: LBL_{lbl.GetHashCode()}");
            var res = new InstructionRange(insts, pos, 0);
            // Hack.Log($"Jump points to {pos}:");
            return res;
        }

19 Source : PhotonAnimatorView.cs
with MIT License
from bddckr

public SynchronizeType GetLayerSynchronizeType(int layerIndex)
    {
        int index = this.m_SynchronizeLayers.FindIndex(item => item.LayerIndex == layerIndex);

        if (index == -1)
        {
            return SynchronizeType.Disabled;
        }

        return this.m_SynchronizeLayers[index].SynchronizeType;
    }

19 Source : PhotonAnimatorView.cs
with MIT License
from bddckr

public SynchronizeType GetParameterSynchronizeType(string name)
    {
        int index = this.m_SynchronizeParameters.FindIndex(item => item.Name == name);

        if (index == -1)
        {
            return SynchronizeType.Disabled;
        }

        return this.m_SynchronizeParameters[index].SynchronizeType;
    }

19 Source : PhotonAnimatorView.cs
with MIT License
from bddckr

public void SetParameterSynchronized(string name, ParameterType type, SynchronizeType synchronizeType)
    {
        if (Application.isPlaying == true)
        {
            this.m_WreplacedynchronizeTypeChanged = true;
        }

        int index = this.m_SynchronizeParameters.FindIndex(item => item.Name == name);

        if (index == -1)
        {
            this.m_SynchronizeParameters.Add(new SynchronizedParameter { Name = name, Type = type, SynchronizeType = synchronizeType });
        }
        else
        {
            this.m_SynchronizeParameters[index].SynchronizeType = synchronizeType;
        }
    }

19 Source : PhotonAnimatorView.cs
with MIT License
from bddckr

public bool DoesLayerSynchronizeTypeExist(int layerIndex)
    {
        return this.m_SynchronizeLayers.FindIndex(item => item.LayerIndex == layerIndex) != -1;
    }

19 Source : PhotonAnimatorView.cs
with MIT License
from bddckr

public void SetLayerSynchronized(int layerIndex, SynchronizeType synchronizeType)
    {
        if (Application.isPlaying == true)
        {
            this.m_WreplacedynchronizeTypeChanged = true;
        }

        int index = this.m_SynchronizeLayers.FindIndex(item => item.LayerIndex == layerIndex);

        if (index == -1)
        {
            this.m_SynchronizeLayers.Add(new SynchronizedLayer { LayerIndex = layerIndex, SynchronizeType = synchronizeType });
        }
        else
        {
            this.m_SynchronizeLayers[index].SynchronizeType = synchronizeType;
        }
    }

19 Source : PhotonAnimatorView.cs
with MIT License
from bddckr

public bool DoesParameterSynchronizeTypeExist(string name)
    {
        return this.m_SynchronizeParameters.FindIndex(item => item.Name == name) != -1;
    }

19 Source : RegionManager.cs
with MIT License
from bdfzchen2015

public bool RemoveRegionWithName(string name)
		{
			lock (_regions)
			{
				int index = _regions.ServerRegions.FindIndex(region => region.Name == name);
				if (index != -1)
				{
					_regions.ServerRegions.RemoveAt(index);
					foreach (var player in ServerSideCharacter.XmlData.Data)
					{
						int id = player.Value.ownedregion.FindIndex(region => region.Name == name);
						if (id != -1)
						{
							player.Value.ownedregion.RemoveAt((id));
						}
					}
					return true;
				}
				else
				{
					return false;
				}
			}
		}

19 Source : RegionManager.cs
with MIT License
from bdfzchen2015

public void ShareRegion(ServerPlayer p, ServerPlayer target, string name)
		{
			int index = _regions.ServerRegions.FindIndex(region => region.Name == name);
			if (index == -1)
			{
				p.SendErrorInfo("Cannot find this region!");
				return;
			}
			var reg = _regions.ServerRegions[index];
			reg.SharedOwner.Add(target.UUID);
			p.SendSuccessInfo("Successfully shared " + reg.Name + " to " + target.Name);
			target.SendSuccessInfo(p.Name + " shared region " + reg.Name + " with you!");
		}

19 Source : CommonServices.cs
with Apache License 2.0
from beckzhu

private static string[] GetEqualWidthFonts()
        {
            List<string> list = new List<string>();

            Gdi32.FontEnumProc FontEnumProc = (ref Gdi32.ENUMLOGFONT lpelf, IntPtr lpntm, uint FontType, IntPtr lParam) =>
            {
                if ((lpelf.elfLogFont.lfPitchAndFamily & 0x3) == 1)
                {
                    string fontName = lpelf.elfLogFont.lfFaceName;
                    if (list.FindIndex(m => m == fontName) < 0)
                    {
                        list.Add(fontName);
                    }
                }
                return 1;
            };

            IntPtr hdc = Gdi32.GetDC(IntPtr.Zero);
            Gdi32.EnumFontFamiliesEx(hdc, IntPtr.Zero, FontEnumProc, IntPtr.Zero, 0);
            Gdi32.ReleaseDC(IntPtr.Zero, hdc);

            return list.ToArray();
        }

19 Source : DbRemoteTree.cs
with Apache License 2.0
from beckzhu

public int Insert(DbRemoteTree remoteTree)
        {
            var items = remoteTree.Type == RemoteType.dir ? Dirs : Items;
            items.Add(remoteTree);
            items.Sort((x, y) => string.Compare(x.Name, y.Name));
            int index = items.FindIndex(m => m.uuid == remoteTree.uuid);
            if (remoteTree.Type == RemoteType.dir) return index;
            return index + Dirs.Count;
        }

19 Source : DbRemoteTree.cs
with Apache License 2.0
from beckzhu

public int GetSortIndex(DbRemoteTree remoteTree)
        {
            var items = remoteTree.Type == RemoteType.dir ? Dirs : Items;
            items.Sort((x, y) => string.Compare(x.Name, y.Name));
            int index = items.FindIndex(m => m.uuid == remoteTree.uuid);
            if (remoteTree.Type == RemoteType.dir) return index;
            return index + Dirs.Count;
        }

19 Source : InMemoryAccountRepository.cs
with GNU Affero General Public License v3.0
from benukhanov

public void Update(Account enreplacedy)
        {
            lock (locker)
            {
                var index = collection.FindIndex(x => x.Id == enreplacedy.Id);
                if (index != -1)
                {
                    collection[index] = enreplacedy;
                }
            }
        }

19 Source : NetworkInfoAsync.cs
with GNU General Public License v3.0
from berichan

public static string getMacByIp(string ip)
    {
        var macIpPairs = GetAllMacAddressesAndIppairs();
        int index = macIpPairs.FindIndex(x => x.IpAddress == ip);
        if (index >= 0)
        {
            return macIpPairs[index].MacAddress.ToUpper();
        }
        else
        {
            return null;
        }
    }

19 Source : NetworkInfoUnity.cs
with GNU General Public License v3.0
from berichan

public static string getMacByIp(string ip)
    {
        var macIpPairs = GetAllMacAddressesAndIppairs(ip);
        int index = macIpPairs.FindIndex(x => x.IpAddress == ip);
        if (index >= 0)
        {
            return macIpPairs[index].MacAddress.ToUpper();
        }
        else
        {
            return null;
        }
    }

19 Source : ColorHelper.cs
with GNU General Public License v3.0
from berichan

public static int ClosestColor1(IReadOnlyCollection<Color> colors, Color target)
    {
        var hue1 = target.GetHue();
        var diffs = colors.Select(n => GetHueDistance(n.GetHue(), hue1));
        var diffMin = diffs.Min(n => n);
        return diffs.ToList().FindIndex(n => n == diffMin);
    }

19 Source : ColorHelper.cs
with GNU General Public License v3.0
from berichan

public static int ClosestColor2(IReadOnlyCollection<Color> colors, Color target)
    {
        var colorDiffs = colors.Select(n => ColorDiff(n, target)).Min(n => n);
        return colors.ToList().FindIndex(n => ColorDiff(n, target) == colorDiffs);
    }

19 Source : ColorHelper.cs
with GNU General Public License v3.0
from berichan

public static int ClosestColor3(IReadOnlyCollection<Color> colors, Color target)
    {
        float hue1 = target.GetHue();
        var num1 = ColorNum(target);
        var diffs = colors.Select(n => Math.Abs(ColorNum(n) - num1) +
                                       GetHueDistance(n.GetHue(), hue1));
        var diffMin = diffs.Min(x => x);
        return diffs.ToList().FindIndex(n => n == diffMin);
    }

19 Source : EventManager.cs
with MIT License
from Bian-Sh

private void DelEvent(Action<BaseEventArgs> action)
        {
            if (null != action)
            {
                List<Action<BaseEventArgs>> actionsArr = new List<Action<BaseEventArgs>>(listeners.Values);
                List<Enum> eventTypeArr = new List<Enum>(listeners.Keys);
                Predicate<Action<BaseEventArgs>> predicate = v =>
                {
                    Delegate[] d = v?.GetInvocationList();
                    return (null != d && Array.Exists(d, vv => vv == (Delegate)action));
                };
                int index = actionsArr.FindIndex(predicate);
                if (index != -1)
                {
                    DelEvent(eventTypeArr[index], action);
                }
                else
                {
                    UnityEngine.Debug.LogWarning("移除的事件未曾注册过 !");
                }
            }
            else
            {
                UnityEngine.Debug.LogWarning("指定移除的事件为 null !");
            }
        }

19 Source : TouchPad.cs
with MIT License
from Bian-Sh

private void Update() //不要使用 FixedUpdate 感觉 Touch 不能正确同步状态
    {
        if (Input.touchCount > 0)
        {
            foreach (var item in Input.touches)
            {
                int index = fingerIds.FindIndex(touch => touch.fingerId == item.fingerId);
                //1. 如果 Touch 未被收录,考虑收录之
                if (index == -1)
                {
                    //2. 收集有效 Touch ,其特点为:刚按下 + 没打到UI上 + 在屏幕右侧
                    if (item.phase == TouchPhase.Began && item.position.x > Screen.width * 0.5f && !item.IsRaycastUI(filterPrefix))
                    {
                        fingerIds.Add(item);
                    }
                }
                else
                {
                    if (item.phase == TouchPhase.Ended || item.phase == TouchPhase.Canceled)
                    {
                        fingerIds.RemoveAt(index); //3. 如果此Touch 已失效(unity 会回传 phase = end 的 touch),则剔除之
                    }
                    else
                    {
                        fingerIds[index] = item; //4. 由于Touch是  非引用类型的临时变量,所以要主动更新之
                    }
                }
            }
            //5. 有效Touch 处于 move 则可以驱动事件了:
            foreach (var item in fingerIds)
            {
                if (item.phase == TouchPhase.Moved)
                {
                    OnTouchPadValueChanged.Invoke(item.deltaPosition);
                }
            }
        }

#if UNITY_EDITOR
        // 仅供编辑器测试, 如此段代码编译到移动端由于 Unity 默认开启 Touch 模拟鼠标功能而导致 TouchPad 表现异常
        if (Input.GetMouseButtonDown(1) && !IsMouseRaycastUI("#"))
        {
            canmove = true;
        }
        if (Input.GetMouseButtonUp(1))
        {
            canmove = false;
        }
        if (Input.GetMouseButton(1) && canmove)
        {
            var h = Input.GetAxis("Mouse X");
            var v = Input.GetAxis("Mouse Y");
            OnTouchPadValueChanged.Invoke(new Vector2(h, v));
        }
#endif
    }

19 Source : ObjectTranslator.cs
with MIT License
from bjfumac

bool RemoveFromGCList(int id)
        {
            int index = gcList.FindIndex((p) => { return p.id == id; });

            if (index >= 0)
            {
                gcList.RemoveAt(index);
                return true;                       
            }

            return false;
        }

19 Source : ToLuaMenu.cs
with MIT License
from bjfumac

static void AutoAddBaseType(BindType bt, bool beDropBaseType)
    {
        Type t = bt.baseType;

        if (t == null)
        {
            return;
        }

        if (CustomSettings.sealedList.Contains(t))
        {
            CustomSettings.sealedList.Remove(t);
            Debugger.LogError("{0} not a sealed clreplaced, it is parent of {1}", LuaMisc.GetTypeName(t), bt.name);
        }

        if (t.IsInterface)
        {
            Debugger.LogWarning("{0} has a base type {1} is Interface, use SetBaseType to jump it", bt.name, t.FullName);
            bt.baseType = t.BaseType;
        }
        else if (dropType.IndexOf(t) >= 0)
        {
            Debugger.LogWarning("{0} has a base type {1} is a drop type", bt.name, t.FullName);
            bt.baseType = t.BaseType;
        }
        else if (!beDropBaseType || baseType.IndexOf(t) < 0)
        {
            int index = allTypes.FindIndex((iter) => { return iter.type == t; });

            if (index < 0)
            {
#if JUMP_NODEFINED_ABSTRACT
                if (t.IsAbstract && !t.IsSealed)
                {
                    Debugger.LogWarning("not defined bindtype for {0}, it is abstract clreplaced, jump it, child clreplaced is {1}", LuaMisc.GetTypeName(t), bt.name);
                    bt.baseType = t.BaseType;
                }
                else
                {
                    Debugger.LogWarning("not defined bindtype for {0}, autogen it, child clreplaced is {1}", LuaMisc.GetTypeName(t), bt.name);
                    bt = new BindType(t);
                    allTypes.Add(bt);
                }
#else
                Debugger.LogWarning("not defined bindtype for {0}, autogen it, child clreplaced is {1}", LuaMisc.GetTypeName(t), bt.name);
                bt = new BindType(t);
                allTypes.Add(bt);
#endif
            }
            else
            {
                return;
            }
        }
        else
        {
            return;
        }

        AutoAddBaseType(bt, beDropBaseType);
    }

19 Source : FolderEntry.cs
with GNU General Public License v2.0
from BlackTasty

private void LoadSingleFolderOnDemand(FolderEntry entry)
        {
            if (!entry.FoldersLoaded)
            {
                int entryIndex = SubDirectories.FindIndex(x => x.Path.Equals(entry.Path));
                SubDirectories[entryIndex] = new FolderEntry(entry.mUnloadedEntry.DirectoryInfo, false, TreeDepth + 1);
            }
        }

19 Source : Utils.cs
with MIT License
from BleuBleu

public static void Permutations(int[] array, List<int[]> permutations, int idx = 0)
        {
            if (idx == array.Length)
            {
                // Avoid duplicates.
                if (permutations.FindIndex(a => CompareArrays(a, array) == 0) < 0)
                    permutations.Add(array.Clone() as int[]);
            }

            for (int i = idx; i < array.Length; i++)
            {
                Swap(ref array[idx], ref array[i]);
                Permutations(array, permutations, idx + 1);
                Swap(ref array[idx], ref array[i]);
            }
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v3.0
from BLinssen

private void ScanScreenTem(bool save)
        {
            //Init
            Bitmap memoryImageLeft;
            memoryImageLeft = new Bitmap(ResolutionSettings.SnipW, ResolutionSettings.SnipH);
            System.Drawing.Size sL = new System.Drawing.Size(ResolutionSettings.SnipW, ResolutionSettings.SnipH);

            Graphics memoryGraphicsLeft = Graphics.FromImage(memoryImageLeft);

            //Scan TemTem Left
            memoryGraphicsLeft.CopyFromScreen(ResolutionSettings.TemLeftX, ResolutionSettings.TemLeftY, 0, 0, sL);            

            //Tesseract OCR
            memoryImageLeft = OCR.Whitify(memoryImageLeft);
            string temOCR = OCR.Tesseract(memoryImageLeft);
            //log.Info($"FoundOCR-L:{temOCR}");
            temOCR = temOCR.Split(' ')[0];
            temOCR = new String(temOCR.Where(Char.IsLetter).ToArray());
            int temOCRindex = TemTems.FindIndex(x => x.Name.Contains(temOCR));

            //Set left Tem label text
            if (!OCR.ScanForMenu() || (EnemyTemLeft.Content.ToString() != temOCR && temOCR != "" && temOCRindex > 0))
            {
                if (TemValid(temOCR))
                {
                    EnemyTemLeft.Content = temOCR;
                }
            }

            //If we found a tem update the table
            if (EnemyTemLeft.Content.ToString() != "")
            {
                //Get Tem Details
                TemLeft = GetMatchup(EnemyTemLeft.Content.ToString());

                if (!TemLeft.Type2.Equals("None"))
                {
                    EnemyTemLeftType.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("Resources/" + TemLeft.Type2 + ".png", UriKind.Relative));
                    EnemyTemLeftType2.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("Resources/" + TemLeft.Type1 + ".png", UriKind.Relative));
                }
                else
                {
                    EnemyTemLeftType.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("Resources/" + TemLeft.Type1 + ".png", UriKind.Relative));
                    EnemyTemLeftType2.Source = null;
                }

                //Get Type Defense
                LMNeutral.Content = TypeString(TemLeft.TypeNeutral);
                LMFire.Content = TypeString(TemLeft.TypeFire);
                LMWater.Content = TypeString(TemLeft.TypeWater);
                LMNature.Content = TypeString(TemLeft.TypeNature);
                LMElectric.Content = TypeString(TemLeft.TypeElectric);
                LMEarth.Content = TypeString(TemLeft.TypeEarth);
                LMMental.Content = TypeString(TemLeft.TypeMental);
                LMWind.Content = TypeString(TemLeft.TypeWind);
                LMDigital.Content = TypeString(TemLeft.TypeDigital);
                LMMelee.Content = TypeString(TemLeft.TypeMelee);
                LMCrystal.Content = TypeString(TemLeft.TypeCrystal);
                LMToxic.Content = TypeString(TemLeft.TypeToxic);

                //Add Colored background
                AddColor(LeftMatchup.Children);
                LeftMatchup.Visibility = Visibility.Visible;
                LeftType.Visibility = Visibility.Visible;

                // Trait Visibility
                if (Properties.Settings.Default.TraitDisplay == "Always")
                {
                    SetTrait(TemLeft);
                    TemTraitsGridUp.Visibility = Visibility.Visible;
                }
            }
            else
            {
                LeftMatchup.Visibility = Visibility.Collapsed;
                LeftType.Visibility = Visibility.Collapsed;

                // Trait Visibility
                if (Properties.Settings.Default.TraitDisplay == "Always")
                {
                    TemTraitsGridUp.Visibility = Visibility.Collapsed;
                }
            }

            //Init
            Bitmap memoryImageRight;
            memoryImageRight = new Bitmap(ResolutionSettings.SnipW, ResolutionSettings.SnipH);
            System.Drawing.Size sR = new System.Drawing.Size(ResolutionSettings.SnipW, ResolutionSettings.SnipH);

            Graphics memoryGraphicsRight = Graphics.FromImage(memoryImageRight);

            //Scan TemTem Right
            memoryGraphicsRight.CopyFromScreen(ResolutionSettings.TemRightX, ResolutionSettings.TemRightY, 0, 0, sR);

            //Tesseract OCR
            memoryImageRight = OCR.Whitify(memoryImageRight);
            //string fileName = string.Format(Environment.GetFolderPath(Environment.SpecialFolder.MyDoreplacedents) +
            //    @"\TemTem\" +
            //    DateTime.Now.ToString("(dd_MMMM_hh_mm_ss_tt)") + "R.png");
            //memoryImageRight.Save(fileName);
            temOCR = OCR.Tesseract(memoryImageRight);
            //log.Info($"FoundOCR-R:{temOCR}");
            temOCR = temOCR.Split(' ')[0];
            temOCR = new String(temOCR.Where(Char.IsLetter).ToArray());
            temOCRindex = TemTems.FindIndex(x => x.Name.Contains(temOCR));

            //Set left Tem label text
            if (!OCR.ScanForMenu() || (EnemyTemRight.Content.ToString() != temOCR && temOCR != "" && temOCRindex > 0))
            {
                if (TemValid(temOCR))
                {
                    EnemyTemRight.Content = temOCR;
                }                
            };

            //If we found a Tem update the table
            if (EnemyTemRight.Content.ToString() != "")
            {
                //Get Tem Details
                TemRight = GetMatchup(EnemyTemRight.Content.ToString());

                if (!TemRight.Type2.Equals("None"))
                {
                    EnemyTemRightType.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("Resources/" + TemRight.Type2 + ".png", UriKind.Relative));
                    EnemyTemRightType2.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("Resources/" + TemRight.Type1 + ".png", UriKind.Relative));
                }
                else
                {
                    EnemyTemRightType.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("Resources/" + TemRight.Type1 + ".png", UriKind.Relative));
                    EnemyTemRightType2.Source = null;
                }

                //Get Type Defense
                RMNeutral.Content = TypeString(TemRight.TypeNeutral);
                RMFire.Content = TypeString(TemRight.TypeFire);
                RMWater.Content = TypeString(TemRight.TypeWater);
                RMNature.Content = TypeString(TemRight.TypeNature);
                RMElectric.Content = TypeString(TemRight.TypeElectric);
                RMEarth.Content = TypeString(TemRight.TypeEarth);
                RMMental.Content = TypeString(TemRight.TypeMental);
                RMWind.Content = TypeString(TemRight.TypeWind);
                RMDigital.Content = TypeString(TemRight.TypeDigital);
                RMMelee.Content = TypeString(TemRight.TypeMelee);
                RMCrystal.Content = TypeString(TemRight.TypeCrystal);
                RMToxic.Content = TypeString(TemRight.TypeToxic);

                //Add Colored Background
                AddColor(RightMatchup.Children);
                RightMatchup.Visibility = Visibility.Visible;
                RightType.Visibility = Visibility.Visible;

                // Trait Visibility
                if (Properties.Settings.Default.TraitDisplay == "Always")
                {
                    // Switch to Upper Grid if it's not in use
                    if (TemTraitsGridUp.Visibility == Visibility.Collapsed)
                    {
                        SetTrait(TemRight);
                        TemTraitsGridUp.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        SetTraitAlt(TemRight);
                        TemTraitsGridDown.Visibility = Visibility.Visible;
                    }                 
                }
            }
            else
            {
                RightMatchup.Visibility = Visibility.Collapsed;
                RightType.Visibility = Visibility.Collapsed;

                // Trait Visibility
                if (Properties.Settings.Default.TraitDisplay == "Always")
                {
                    TemTraitsGridDown.Visibility = Visibility.Collapsed;
                }
            }

            if (!TemTypeDef && (EnemyTemLeft.Content.ToString() != "" || EnemyTemRight.Content.ToString() != "") && !AlwaysShowDefense)
            {                
                TemTacOverlay.BeginStoryboard((Storyboard)this.Resources["TypeDefenseShow"]);
                TemTypeDef = true;               
            }
            else if (TemTypeDef && (EnemyTemLeft.Content.ToString() == "" && EnemyTemRight.Content.ToString() == "") && !AlwaysShowDefense)
            {
                TemTacOverlay.BeginStoryboard((Storyboard)this.Resources["TypeDefenseHide"]);
                TemTypeDef = false;
            }            
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v3.0
from BLinssen

private void SetTraitAlt(TemTem Tem)
        {
            string[] Traits = Tem.Trait.ToString().Split(':');
            if (Traits.Length > 0)
            {
                //Set Trait Name
                EnemyTemTraitName1Perma.Content = Traits[0];
                //Set Trait Description
                int index = TemTraits.FindIndex(x => x.Name.Contains(Traits[0]));
                TemTrait TemTrait = TemTraits[index];
                EnemyTemTraitDescription1Perma.Text = TemTrait.Description;
            }
            if (Traits.Length > 1)
            {
                //Set Trait Name
                EnemyTemTraitName2Perma.Content = Traits[1];
                //Set Trait Description
                int index = TemTraits.FindIndex(x => x.Name.Contains(Traits[1]));
                TemTrait TemTrait = TemTraits[index];
                EnemyTemTraitDescription2Perma.Text = TemTrait.Description;
            }
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v3.0
from BLinssen

private bool HandleResolution()
        {
            double dWidth = -1;
            double dHeight = -1;
            if (Properties.Settings.Default.Resolution == "None")
            {
                //Get Resolution
                dWidth = SystemParameters.PrimaryScreenWidth;
                dHeight = SystemParameters.PrimaryScreenHeight;
                log.Info($"Found resolution: {dWidth}x{dHeight}");
                //Check if Resolution is supported
                if (SupportedResolutions.FindIndex(x => x.Equals($"{dWidth}x{dHeight}")) != -1)
                {
                    Properties.Settings.Default.Resolution = $"{dWidth}x{dHeight}";
                    Properties.Settings.Default.Save();
                    ResolutionSettings = TemResolutions.Find(x => x.Resolution.Equals($"{dWidth}x{dHeight}"));
                    ComboBoxResolution.SelectedValue = $"{dWidth}x{dHeight}";
                    return true;
                }
                else
                {
                    System.Windows.MessageBox.Show($"{dWidth}x{dHeight} is currently not supported. \nVisit https://github.com/BLinssen/TemTacO/issues to request a resolution.'", "TemTacO");
                    return false;
                }
            }

            string[] resolution = Properties.Settings.Default.Resolution.Split('x'); 
            dWidth = Convert.ToInt32(resolution[0]);
            dHeight = Convert.ToInt32(resolution[1]);
            log.Info($"Settings resolution: {dWidth}x{dHeight}");
            ResolutionSettings = TemResolutions.Find(x => x.Resolution.Equals($"{dWidth}x{dHeight}"));
            ComboBoxResolution.SelectedValue = $"{dWidth}x{dHeight}";
            return true;        
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v3.0
from BLinssen

private void SetTrait(TemTem Tem)
        {
            string[] Traits = Tem.Trait.ToString().Split(':');
            if(Traits.Length > 0)
            {
                //Set Trait Name
                EnemyTemTraitName1.Content = Traits[0];
                //Set Trait Description
                int index = TemTraits.FindIndex(x => x.Name.Contains(Traits[0]));
                TemTrait TemTrait = TemTraits[index];
                EnemyTemTraitDescription1.Text = TemTrait.Description;
            }
            if(Traits.Length > 1)
            {
                //Set Trait Name
                EnemyTemTraitName2.Content = Traits[1];
                //Set Trait Description
                int index = TemTraits.FindIndex(x => x.Name.Contains(Traits[1]));
                TemTrait TemTrait = TemTraits[index];
                EnemyTemTraitDescription2.Text = TemTrait.Description;
            }
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v3.0
from BLinssen

private bool TemValid(string foundText)
        {
            int index = TemTems.FindIndex(x => x.Name.Contains(foundText));
            if (index != -1)
                return true;
            return false;
        }

19 Source : StreamingMeshRenderer.cs
with MIT License
from blkcatman

public void UpdateWithTime(double updateTime)
    {
      if(m_IsLastFrameReached)
        return;

      if(updateTime - m_CurrentFrameTime < (double)m_FrameInterval)
      {
        UpdateVertexInterpolate((float)(updateTime - m_CurrentFrameTime));
        return;
      }

      //Find index num based on updateTime
      int currentKeyedIndex = -1 + m_KeyedVertexDatas.FindIndex(m_CurrentKeyedIndex, it => {
        return it.Key > updateTime;
      });
      if(currentKeyedIndex < 0)
      {
        m_IsPlayable = false;
        return;
      }
      m_IsPlayable = true;

      double headTime = m_KeyedVertexDatas[currentKeyedIndex].Key;
      List<KeyValuePair<double, byte[]>> vertexDatas = m_KeyedVertexDatas[currentKeyedIndex].Value;
      int headIndex = vertexDatas.FindIndex( it => {
        return it.Key < updateTime && updateTime < it.Key + m_FrameInterval;
      });
      if(headIndex < 0) {
        return;
      }
      m_CurrentFrameTime = vertexDatas[headIndex].Key;

      KeyValuePair<double, byte[]> pairData;
      if(headIndex < vertexDatas.Count - 1)
        pairData = vertexDatas[headIndex + 1];
      else
      {
        if(currentKeyedIndex + 1 < m_KeyedVertexDatas.Count)
          pairData = m_KeyedVertexDatas[currentKeyedIndex + 1].Value[0];
        else {
          pairData = m_KeyedVertexDatas[currentKeyedIndex].Value.Last();
          //m_IsLastFrameReached = true;
        }
      }
      UpdateVertexBuffer(pairData.Value);
    }

19 Source : ProductionState.cs
with GNU Affero General Public License v3.0
from blockbasenetwork

private bool IsIpUpdateRequired(List<string> encryptedIpsInTable)
        {
            int numberOfIpsToSend = (int)Math.Ceiling(_producers.Count() / 4.0);
            var keysToUse = ListHelper.GetListSortedCountingFrontFromIndex(_producers, _producers.FindIndex(m => m.Key == _nodeConfigurations.AccountName)).Take(numberOfIpsToSend).Select(p => p.PublicKey).ToList();
            keysToUse.Add(_sidechainPool.ClientPublicKey);

            var listEncryptedIps = new List<string>();
            var endpoint = _networkConfigurations.GetResolvedIp() + ":" + _networkConfigurations.TcpPort;
            foreach (string receiverPublicKey in keysToUse)
            {
                listEncryptedIps.Add(replacedymetricEncryption.EncryptText(endpoint, _nodeConfigurations.ActivePrivateKey, receiverPublicKey));
            }

            return (listEncryptedIps.Except(encryptedIpsInTable).Any() || encryptedIpsInTable.Except(listEncryptedIps).Any());
        }

See More Examples