System.Collections.Generic.IEnumerable.Take(int)

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

4004 Examples 7

19 Source : RootTypeConverter.cs
with MIT License
from AdrianWilczynski

private IEnumerable<TypeNode> ConvertBaseTypes(IEnumerable<BaseTypeSyntax> baseTypes, TypeDeclarationSyntax containingType)
        {
            var types = baseTypes;
            if (!(containingType is InterfaceDeclarationSyntax))
            {
                types = types.Take(1);
            }

            var namedTypes = types
                .Select(t => _typeConverter.Handle(t.Type))
                .OfType<NamedTypeNode>();

            if (!(containingType is InterfaceDeclarationSyntax))
            {
                namedTypes = namedTypes.Where(t => !t.Name.HasInterfacePrefix());
            }

            return namedTypes;
        }

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

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

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

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

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

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

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

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

            aplupd.Start();

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

            aplupd.Close();

            stopbar();

            statuslabel.Content = "";

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

            onbtn();

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

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

public async void decryptbsgnca()
        {
            offbtn();

            startbar();

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

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

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

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

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

            decrnca.Start();

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

            decrnca.Close();

            extractncau();
        }

19 Source : PageListBlockController.cs
with Apache License 2.0
from advanced-cms

public override ActionResult Index(PageListBlock currentBlock)
        {
            var pages = FindPages(currentBlock);

            pages = Sort(pages, currentBlock.SortOrder);

            if(currentBlock.Count > 0)
            {
                pages = pages.Take(currentBlock.Count);
            }

            var model = new PageListModel(currentBlock)
                {
                    Pages = pages
                };

            ViewData.GetEditHints<PageListModel, PageListBlock>()
                .AddConnection(x => x.Heading, x => x.Heading);

            return PartialView(model);
        }

19 Source : UIPatches.cs
with GNU General Public License v3.0
from aedenthorn

public static void DialogueBox_Prefix(ref List<string> dialogues)
        {
            try
            {
                if (dialogues == null || dialogues.Count < 2)
                    return;

                if (dialogues[1] == Game1.content.LoadString("Strings\\StringsFromCSFiles:Event.cs.1826"))
                {
                    List<string> newDialogues = new List<string>()
                    {
                        dialogues[0]
                    };



                    List<NPC> spouses = Misc.GetSpouses(Game1.player,1).Values.OrderBy(o => Game1.player.friendshipData[o.Name].Points).Reverse().Take(4).ToList();

                    List<int> which = new List<int>{ 0, 1, 2, 3 };

                    Misc.ShuffleList(ref which);

                    List<int> myWhich = new List<int>(which).Take(spouses.Count).ToList();

                    for(int i = 0; i < spouses.Count; i++)
                    {
                        switch (which[i])
                        {
                            case 0:
                                newDialogues.Add(Game1.content.LoadString("Strings\\StringsFromCSFiles:Event.cs.1827", spouses[i].displayName));
                                break;
                            case 1:
                                newDialogues.Add(((spouses[i].Gender == 0) ? Game1.content.LoadString("Strings\\StringsFromCSFiles:Event.cs.1832") : Game1.content.LoadString("Strings\\StringsFromCSFiles:Event.cs.1834")) + " " + ((spouses[i].Gender == 0) ? Game1.content.LoadString("Strings\\StringsFromCSFiles:Event.cs.1837", spouses[i].displayName[0]) : Game1.content.LoadString("Strings\\StringsFromCSFiles:Event.cs.1838", spouses[i].displayName[0])));
                                break;
                            case 2:
                                newDialogues.Add(Game1.content.LoadString("Strings\\StringsFromCSFiles:Event.cs.1843", spouses[i].displayName));
                                break;
                            case 3:
                                newDialogues.Add(((spouses[i].Gender == 0) ? Game1.content.LoadString("Strings\\StringsFromCSFiles:Event.cs.1831") : Game1.content.LoadString("Strings\\StringsFromCSFiles:Event.cs.1833")) + " " + ((spouses[i].Gender == 0) ? Game1.content.LoadString("Strings\\StringsFromCSFiles:Event.cs.1837", spouses[i].displayName[0]) : Game1.content.LoadString("Strings\\StringsFromCSFiles:Event.cs.1838", spouses[i].displayName[i])));
                                break;
                        }
                    }
                    dialogues = new List<string>(newDialogues);
                }
            }
            catch (Exception ex)
            {
                Monitor.Log($"Failed in {nameof(DialogueBox_Prefix)}:\n{ex}", LogLevel.Error);
            }
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

private void Input_ButtonPressed(object sender, StardewModdingAPI.Events.ButtonPressedEventArgs e)
        {
            if (!Config.Enabled || !Context.IsWorldReady)
                return;

            Dictionary<string, string> npcDic;
            List<string> npcKeys;

            // check for click on dialogue

            if (Game1.activeClickableMenu != null && Game1.player?.currentLocation?.lastQuestionKey?.StartsWith("DialogueTrees_") == true)
            {
                IClickableMenu menu = Game1.activeClickableMenu;
                if (menu == null || menu.GetType() != typeof(DialogueBox))
                    return;

                DialogueBox db = menu as DialogueBox;
                int resp = db.selectedResponse;
                List<Response> resps = db.responses;

                if (resp < 0 || resps == null || resp >= resps.Count || resps[resp] == null)
                    return;

                string[] parts = resps[resp].responseKey.Split('#');
                string npcName = parts[1];
                string topicID = parts[2];
                string responseID = parts[3];
                npcDic = Helper.Content.Load<Dictionary<string, string>>($"Characters/Dialogue/{npcName}", ContentSource.GameContent);
                npcKeys = npcDic.Keys.ToList();

                if (Game1.player.currentLocation.lastQuestionKey == "DialogueTrees_Player_Question")
                {
                    Monitor.Log($"asking {npcName} about {loadedTopicNames[topicID]}");
                    var possibleResponses = npcKeys.FindAll(k => k.StartsWith("DialogueTrees_response_" + topicID + "_"));
                    NPC n = Game1.getCharacterFromName(npcName);
                    Game1.drawDialogue(n, npcDic[possibleResponses[myRand.Next(possibleResponses.Count)]]);

                    string nextTopicID = GetNextTopicID(topicID, "any");

                    if (nextTopicID != null && loadedDialogues.ContainsKey(nextTopicID) && npcKeys.Exists(k => k.StartsWith("DialogueTrees_response_" + nextTopicID + "_")))
                    {
                        if (responseData != null)
                        {
                            responseData.lastTopic = loadedDialogues[topicID];
                            responseData.nextTopic = loadedDialogues[nextTopicID];
                            responseData.npc = n;
                            responseData.topicResponses[topicID] = responseID;
                        }
                        else
                            responseData = new DialogueTreeResponse(loadedDialogues[topicID], loadedDialogues[nextTopicID], n, responseID);
                    }
                }
                else if(Game1.player.currentLocation.lastQuestionKey == "DialogueTrees_NPC_Question")
                {
                    Monitor.Log($"{npcName} is asking player about {loadedTopicNames[topicID]}, player response: {loadedResponseStrings[responseID]}");

                    var possibleReactions = npcKeys.FindAll(k => k.StartsWith("DialogueTrees_reaction_" + topicID + "_" + responseID + "_"));

                    if (!possibleReactions.Any())
                    {
                        Monitor.Log($"{npcName} has no reaction to {loadedTopicNames[topicID]} response {loadedResponseStrings[responseID]}! Check the [DT] content pack.", LogLevel.Warn);
                    }
                    else
                    {
                        NPC n = Game1.getCharacterFromName(npcName);
                        Game1.drawDialogue(n, npcDic[possibleReactions[myRand.Next(possibleReactions.Count)]]);
                        if (npcDic.ContainsKey("DialogueTrees_friendship_" + topicID + "_" + responseID) && int.TryParse(npcDic["DialogueTrees_friendship_" + topicID + "_" + responseID], out int amount))
                        {
                            Monitor.Log($"changing friendship with {n.Name} by {amount}");
                            Game1.player.changeFriendship(amount, n);
                        }

                        string nextTopicID = GetNextTopicID(topicID, responseID);

                        if (nextTopicID != null && loadedDialogues.ContainsKey(nextTopicID))
                        {
                            Monitor.Log($"Preparing followup dialogue {nextTopicID}");
                            if (responseData != null)
                            {
                                Monitor.Log($"Adding to existing responseData");

                                responseData.lastTopic = loadedDialogues[topicID];
                                responseData.nextTopic = loadedDialogues[nextTopicID];
                                responseData.npc = n;
                                responseData.topicResponses[topicID] = responseID;
                            }
                            else
                                responseData = new DialogueTreeResponse(loadedDialogues[topicID], loadedDialogues[nextTopicID], n, responseID);
                        }
                        else
                        {
                            if(responseData != null)
                                Monitor.Log("No next topic, erasing response data");
                            responseData = null;
                        }
                    }
                }
                
                Game1.player.currentLocation.lastQuestionKey = "";
                return;
            }

            // check for click on NPC

            if (Game1.activeClickableMenu != null || !Context.CanPlayerMove || (Config.ModButton != SButton.None && !Helper.Input.IsDown(Config.ModButton)) || (e.Button != Config.AskButton && e.Button != Config.AnswerButton))
                return;

            Monitor.Log($"Pressed modkey + {e.Button}");

            Rectangle tileRect = new Rectangle((int)Game1.currentCursorTile.X * 64, (int)Game1.currentCursorTile.Y * 64, 64, 64);

            NPC npc = null;

            foreach (NPC i in Game1.currentLocation.characters)
            {
                if (i != null && !i.IsMonster && (!Game1.player.isRidingHorse() || !(i is Horse)) && i.GetBoundingBox().Intersects(tileRect) && !i.IsInvisible && !i.checkAction(Game1.player, Game1.currentLocation))
                {
                    npc = i;
                    break;
                }
            }

            if (npc == null)
                return;
            try
            {
                npcDic = Helper.Content.Load<Dictionary<string, string>>($"Characters/Dialogue/{npc.Name}", ContentSource.GameContent);

            }
            catch
            {
                Monitor.Log($"No dialogue file for {npc.Name}", LogLevel.Warn);

                return;
            }
            npcKeys = npcDic.Keys.ToList();

            if (e.Button == Config.AskButton)
            {

                Monitor.Log($"Asking question of {npc.Name}");

                var shuffled = loadedDialogues.Values.ToList().FindAll(d => d.isStarter && d.playerCanAsk && npcKeys.Exists(k => k.StartsWith("DialogueTrees_response_" + d.topicID+"_")));

                if(!shuffled.Any())
                {
                    Monitor.Log($"No questions that {npc.Name} has a response to! Check the [DT] content pack.", LogLevel.Warn);
                    return;
                }
                Monitor.Log($"{shuffled.Count} questions that {npc.Name} has a response to.");

                ShuffleList(shuffled);
                var questions = shuffled.Take(Config.MaxPlayerQuestions);
                List<Response> responses = new List<Response>();
                foreach(var q in questions)
                {
                    Monitor.Log(q.topicID);
                    responses.Add(new Response($"DialogueTrees_Response#{npc.Name}#{q.topicID}", string.Format(loadedQuestionStrings[q.questionIDs[myRand.Next(q.questionIDs.Count)]], loadedTopicNames[q.topicID])));
                }

                Game1.player.currentLocation.createQuestionDialogue(string.Format(Helper.Translation.Get("ask-npc"), npc.Name), responses.ToArray(), "DialogueTrees_Player_Question");
            }
            else if (e.Button == Config.AnswerButton)
            {
                Monitor.Log($"Answering {npc.Name}'s question");

                var possibleQuestions = loadedDialogues.Values.ToList().FindAll(d => d.isStarter && npcKeys.Exists(k => k.StartsWith("DialogueTrees_reaction_" + d.topicID+"_")));

                if (!possibleQuestions.Any())
                {
                    Monitor.Log($"No questions that {npc.Name} can ask (no reactions)! Check the [DT] content pack.", LogLevel.Warn);
                    return;
                }

                DialogueTree p = possibleQuestions[myRand.Next(possibleQuestions.Count)];

                Monitor.Log($"Asking about {loadedTopicNames[p.topicID]}");

                List<Response> responses = new List<Response>();
                foreach(var r in p.responseIDs)
                {
                    Monitor.Log(r);

                    responses.Add(new Response($"DialogueTrees_Response#{npc.Name}#{p.topicID}#{r}", string.Format(loadedResponseStrings[r], loadedTopicNames[p.topicID])));
                }
                string qid = p.questionIDs[myRand.Next(p.questionIDs.Count)];

                List<string> possibleQuestionStrings = npcDic.Keys.ToList().FindAll(k => k.StartsWith("DialogueTrees_question_" + qid + "_"));
                string questionString = possibleQuestionStrings.Any() ? npcDic[possibleQuestionStrings[myRand.Next(possibleQuestionStrings.Count)]] : loadedQuestionStrings[qid];

                Game1.player.currentLocation.createQuestionDialogue(string.Format(questionString, loadedTopicNames[p.topicID]), responses.ToArray(), "DialogueTrees_NPC_Question");
                Game1.objectDialoguePortraitPerson = npc;
            }
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

private int RankStringForNPC(string npcString, string str, int checks)
        {
            int rank = 0;

            IEnumerable<string> stra = str.Split('/').Take(checks);
            IEnumerable<string> npca = npcString.Split('/').Take(checks);
            for (int i = 0; i < checks; i++)
            {
                if (stra.Count() == i)
                {
                    break;
                }
                string strai = stra.ElementAt(i);
                string npcai = npca.ElementAt(i);
                if (strai != "any")
                {
                    List<string> straia = strai.Split('|').ToList();
                    if (strai != "" && strai != npcai && !straia.Contains(npcai))
                    {
                        return -1;
                    }
                    rank++;
                }
            }
            return rank;
        }

19 Source : SwimMaps.cs
with GNU General Public License v3.0
from aedenthorn

public static void AddOceanForage(GameLocation l)
        {
            List<Vector2> spots = new List<Vector2>();
            for (int x = 0; x < l.map.Layers[0].LayerWidth; x++)
            {
                for (int y = 0; y < l.map.Layers[0].LayerHeight; y++)
                {
                    Tile tile = l.map.GetLayer("Back").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size);
                    if (tile != null && l.map.GetLayer("Buildings").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null && l.map.GetLayer("Front").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null && !l.overlayObjects.ContainsKey(new Vector2(x, y)))
                    {
                        spots.Add(new Vector2(x, y));
                    }
                }
            }
            int n = spots.Count;
            while (n > 1)
            {
                n--;
                int k = Game1.random.Next(n + 1);
                var value = spots[k];
                spots[k] = spots[n];
                spots[n] = value;
            }
            int forageNo = (int)(Game1.random.Next(Config.OceanForagePerThousandMin, Config.OceanForagePerThousandMax) / 1000f * spots.Count);
            List<Vector2> forageSpots = spots.Take(forageNo).ToList();

            foreach (Vector2 v in forageSpots)
            {
                double chance = Game1.random.NextDouble();
                if (chance < 0.25)
                {
                    l.overlayObjects[v] = new StardewValley.Object(v, 152, "Seaweed", true, true, false, true)
                    {
                        CanBeGrabbed = true
                    };
                }
                else if (chance < 0.4)
                {
                    l.overlayObjects[v] = new StardewValley.Object(v, 153, "Green Algae", true, true, false, true)
                    {
                        CanBeGrabbed = true
                    };
                }
                else if (chance < 0.6)
                {
                    l.overlayObjects[v] = new StardewValley.Object(v, 157, "White Algae", true, true, false, true)
                    {
                        CanBeGrabbed = true
                    };
                }
                else if (chance < 0.75)
                {
                    l.overlayObjects[v] = new StardewValley.Object(v, 372, "Clam", true, true, false, true)
                    {
                        CanBeGrabbed = true
                    };
                }
                else if (chance < 0.85)
                {
                    l.overlayObjects[v] = new StardewValley.Object(v, 393, "Coral", true, true, false, true)
                    {
                        CanBeGrabbed = true
                    };
                }
                else if (chance < 0.94)
                {
                    l.overlayObjects[v] = new StardewValley.Object(v, 397, "Sea Urchin", true, true, false, true)
                    {
                        CanBeGrabbed = true
                    };
                }
                else if (chance < 0.97)
                {
                    l.overlayObjects[v] = new StardewValley.Object(v, 394, "Rainbow Shell", true, true, false, true)
                    {
                        CanBeGrabbed = true
                    };
                }
                else
                {
                    l.overlayObjects[v] = new StardewValley.Object(v, 392, "Nautilus Shell", true, true, false, true)
                    {
                        CanBeGrabbed = true
                    };
                }
            }
        }

19 Source : SwimMaps.cs
with GNU General Public License v3.0
from aedenthorn

public static void AddMinerals(GameLocation l)
        {
            List<Vector2> spots = new List<Vector2>();
            for (int x = 0; x < l.map.Layers[0].LayerWidth; x++)
            {
                for (int y = 0; y < l.map.Layers[0].LayerHeight; y++)
                {
                    Tile tile = l.map.GetLayer("Back").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size);
                    if (tile != null && l.map.GetLayer("Buildings").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null && l.map.GetLayer("Front").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null)
                    {
                        spots.Add(new Vector2(x, y));
                    }
                }
            }
            int n = spots.Count;
            while (n > 1)
            {
                n--;
                int k = Game1.random.Next(n + 1);
                var value = spots[k];
                spots[k] = spots[n];
                spots[n] = value;
            }

            int mineralNo = (int)Math.Round(Game1.random.Next(Config.MineralPerThousandMin, Config.MineralPerThousandMax) / 1000f * spots.Count);
            List<Vector2> mineralSpots = spots.Take(mineralNo).ToList();

            foreach (Vector2 tile in mineralSpots)
            {
                double chance = Game1.random.NextDouble();

                if (chance < 0.2 && !l.map.GetLayer("Back").Tiles[(int)tile.X, (int)tile.Y].Properties.ContainsKey("Treasure") && !l.map.GetLayer("Back").Tiles[(int)tile.X, (int)tile.Y].Properties.ContainsKey("Diggable"))
                {
                    l.map.GetLayer("Back").Tiles[(int)tile.X, (int)tile.Y].TileIndex = 1299;
                    l.map.GetLayer("Back").Tiles[(int)tile.X, (int)tile.Y].Properties.Add("Treasure", new PropertyValue("Object " + SwimUtils.CheckForBuriedItem(Game1.player)));
                    l.map.GetLayer("Back").Tiles[(int)tile.X, (int)tile.Y].Properties.Add("Diggable", new PropertyValue("T"));
                }
                else if (chance < 0.4)
                {
                    l.overlayObjects[tile] = new StardewValley.Object(tile, 751, "Stone", true, false, false, false)
                    {
                        MinutesUntilReady = 2
                    };
                }
                else if (chance < 0.5)
                {
                    l.overlayObjects[tile] = new StardewValley.Object(tile, 290, "Stone", true, false, false, false)
                    {
                        MinutesUntilReady = 4 
                    };
                }
                else if (chance < 0.55)
                {
                    l.overlayObjects[tile] = new StardewValley.Object(tile, 764, "Stone", true, false, false, false)
                    {
                        MinutesUntilReady = 8
                    };
                }
                else if (chance < 0.56)
                {
                    l.overlayObjects[tile] = new StardewValley.Object(tile, 765, "Stone", true, false, false, false)
                    {
                        MinutesUntilReady = 16
                    };
                }
                else if (chance < 0.65)
                {
                    l.overlayObjects[tile] = new StardewValley.Object(tile, 80, "Stone", true, true, false, true);
                }
                else if (chance < 0.74)
                {
                    l.overlayObjects[tile] = new StardewValley.Object(tile, 82, "Stone", true, true, false, true);
                }
                else if (chance < 0.83)
                {
                    l.overlayObjects[tile] = new StardewValley.Object(tile, 84, "Stone", true, true, false, true);
                }
                else if (chance < 0.90)
                {
                    l.overlayObjects[tile] = new StardewValley.Object(tile, 86, "Stone", true, true, false, true);
                }
                else
                {
                    int[] gems = { 4,6,8,10,12,14,40 };
                    int whichGem = gems[Game1.random.Next(gems.Length)];
                    l.overlayObjects[tile] = new StardewValley.Object(tile, whichGem, "Stone", true, false, false, false)
                    {
                        MinutesUntilReady = 5

                    };
                }
            }
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

public T Load<T>(IreplacedetInfo replacedet)
        {
            Monitor.Log($"loading replacedet for {replacedet.replacedetName}");

            if (replacedet.replacedetName.StartsWith("Characters\\Baby") || replacedet.replacedetName.StartsWith("Characters\\Toddler") || replacedet.replacedetName.StartsWith("Characters/Baby") || replacedet.replacedetName.StartsWith("Characters/Toddler"))
            {
                if(replacedet.replacedetNameEquals("Characters\\Baby") || replacedet.replacedetNameEquals("Characters\\Baby_dark") || replacedet.replacedetNameEquals("Characters\\Toddler") || replacedet.replacedetNameEquals("Characters\\Toddler_dark") || replacedet.replacedetNameEquals("Characters\\Toddler_girl") || replacedet.replacedetNameEquals("Characters\\Toddler_girl_dark"))
                {
                    Monitor.Log($"loading default child replacedet for {replacedet.replacedetName}");
                    return (T)(object)Helper.Content.Load<Texture2D>($"replacedets/{replacedet.replacedetName.Replace("Characters\\", "").Replace("Characters/", "")}.png", ContentSource.ModFolder);
                }
                if(replacedet.replacedetNameEquals("Characters/Baby") || replacedet.replacedetNameEquals("Characters/Baby_dark") || replacedet.replacedetNameEquals("Characters/Toddler") || replacedet.replacedetNameEquals("Characters/Toddler_dark") || replacedet.replacedetNameEquals("Characters/Toddler_girl") || replacedet.replacedetNameEquals("Characters/Toddler_girl_dark"))
                {
                    Monitor.Log($"loading default child replacedet for {replacedet.replacedetName}");
                    return (T)(object)Helper.Content.Load<Texture2D>($"replacedets/{replacedet.replacedetName.Replace("Characters/", "")}.png", ContentSource.ModFolder);
                }

                Monitor.Log($"loading child replacedet for {replacedet.replacedetName}");

                string[] names = replacedet.replacedetName.Split('_');
                Texture2D babySheet = Helper.Content.Load<Texture2D>(string.Join("_", names.Take(names.Length - 1)), ContentSource.GameContent);
                Texture2D parentTexSheet = null;
                string parent = names[names.Length - 1];
                try
                {
                    parentTexSheet = Helper.Content.Load<Texture2D>($"Characters/{parent}", ContentSource.GameContent);
                }
                catch
                {
                    return (T)(object)babySheet;
                }
                if (parentTexSheet == null)
                {
                    Monitor.Log($"couldn't find parent sheet for {replacedet.replacedetName}");
                    return (T)(object)babySheet;
                }
                Rectangle newBounds = parentTexSheet.Bounds;
                newBounds.X = 0;
                newBounds.Y = 64;
                newBounds.Width = 16;
                newBounds.Height = 32;
                Texture2D parentTex = new Texture2D(Game1.graphics.GraphicsDevice, 16, 32);
                Color[] data = new Color[parentTex.Width * parentTex.Height];
                parentTexSheet.GetData(0, newBounds, data, 0, newBounds.Width * newBounds.Height);
                
                int start = -1;
                Dictionary<Color, int> colorCounts = new Dictionary<Color, int>();
                for (int i = 0; i < data.Length; i++)
                {
                    if(data[i] != Color.Transparent)
                    {
                        if(start == -1)
                        {
                            start = i / 16;
                        }
                        else
                        {
                            if (i / 16 - start > 8)
                                break;
                        }
                        if (colorCounts.ContainsKey(data[i]))
                        {
                            colorCounts[data[i]]++;
                        }
                        else
                        {
                            colorCounts.Add(data[i], 1);
                            Monitor.Log($"got hair color: {data[i]}");
                        }
                    }
                }

                if(colorCounts.Count == 0)
                {
                    Monitor.Log($"parent sheet empty for {replacedet.replacedetName}");
                    return (T)(object)babySheet;
                }

                var countsList = colorCounts.ToList();

                countsList.Sort((pair1, pair2) => pair2.Value.CompareTo(pair1.Value));

                List<Color> hairColors = new List<Color>();
                for (int k = 0; k < Math.Min(countsList.Count, 4); k++)
                {
                    Monitor.Log($"using hair color: {countsList[k].Key} {countsList[k].Value}");
                    hairColors.Add(countsList[k].Key);
                }
                hairColors.Sort((color1, color2) => (color1.R + color1.G + color1.B).CompareTo(color2.R + color2.G + color2.B));

                Texture2D hairSheet = Helper.Content.Load<Texture2D>($"replacedets/hair/{string.Join("_", names.Take(names.Length - 1)).Replace("Characters\\","").Replace("Characters/","").Replace("_dark","")}.png", ContentSource.ModFolder);
                Color[] babyData = new Color[babySheet.Width * babySheet.Height];
                Color[] hairData = new Color[babySheet.Width * babySheet.Height];
                babySheet.GetData(babyData);
                hairSheet.GetData(hairData);

                for(int i = 0; i < babyData.Length; i++)
                {
                    if(hairData[i] != Color.Transparent)
                    {
                        if(hairColors.Count == 1)
                        {
                            hairColors.Add(hairColors[0]);
                            hairColors.Add(hairColors[0]);
                            hairColors.Add(hairColors[0]);
                        }
                        else if(hairColors.Count == 2)
                        {
                            hairColors.Add(hairColors[1]);
                            hairColors.Add(hairColors[1]);
                            hairColors[1] = new Color((hairColors[0].R + hairColors[0].R + hairColors[1].R) / 3, (hairColors[0].G + hairColors[0].G + hairColors[1].G) / 3, (hairColors[0].B + hairColors[0].B + hairColors[1].B) / 3);
                            hairColors[2] = new Color((hairColors[0].R + hairColors[2].R + hairColors[2].R) / 3, (hairColors[0].G + hairColors[2].G + hairColors[2].G) / 3, (hairColors[0].B + hairColors[2].B + hairColors[2].B) / 3);
                        }
                        else if(hairColors.Count == 3)
                        {
                            hairColors.Add(hairColors[2]);
                            hairColors[2] = new Color((hairColors[1].R + hairColors[2].R + hairColors[2].R) / 3, (hairColors[1].G + hairColors[2].G + hairColors[2].G) / 3, (hairColors[1].B + hairColors[2].B + hairColors[2].B) / 3);
                            hairColors[1] = new Color((hairColors[0].R + hairColors[0].R + hairColors[1].R) / 3, (hairColors[0].G + hairColors[0].G + hairColors[1].G) / 3, (hairColors[0].B + hairColors[0].B + hairColors[1].B) / 3);
                        }
                        //Monitor.Log($"Hair grey: {hairData[i].R}");
                        switch (hairData[i].R)
                        {
                            case 42:
                                babyData[i] = hairColors[0];
                                break;
                            case 60:
                                babyData[i] = hairColors[1];
                                break;
                            case 66:
                                babyData[i] = hairColors[1];
                                break;
                            case 82:
                                babyData[i] = hairColors[2];
                                break;
                            case 93:
                                babyData[i] = hairColors[2];
                                break;
                            case 114:
                                babyData[i] = hairColors[3];
                                break;
                        }
                            //Monitor.Log($"Hair color: {babyData[i]}");
                    }
                }
                babySheet.SetData(babyData);
                return (T)(object)babySheet;
            }
            throw new InvalidOperationException($"Unexpected replacedet '{replacedet.replacedetName}'.");
        }

19 Source : SwimMaps.cs
with GNU General Public License v3.0
from aedenthorn

public static void AddOceanTreasure(GameLocation l)
        {
            List<Vector2> spots = new List<Vector2>();
            for (int x = 0; x < l.map.Layers[0].LayerWidth; x++)
            {
                for (int y = 0; y < l.map.Layers[0].LayerHeight; y++)
                {
                    Tile tile = l.map.GetLayer("Back").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size);
                    if (tile != null && l.map.GetLayer("Buildings").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null && l.map.GetLayer("Front").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null && !l.overlayObjects.ContainsKey(new Vector2(x, y)))
                    {
                        spots.Add(new Vector2(x, y));
                    }
                }
            }
            int n = spots.Count;
            while (n > 1)
            {
                n--;
                int k = Game1.random.Next(n + 1);
                var value = spots[k];
                spots[k] = spots[n];
                spots[n] = value;
            }

            int treasureNo = (int)(Game1.random.Next(Config.MinOceanChests, Config.MaxOceanChests));

            List<Vector2> treasureSpots = new List<Vector2>(spots).Take(treasureNo).ToList();

            foreach (Vector2 v in treasureSpots)
            {

                List<Item> treasures = new List<Item>();
                float chance = 1f;
                while (Game1.random.NextDouble() <= (double)chance)
                {
                    chance *= 0.4f;
                    if (Game1.random.NextDouble() < 0.5)
                    {
                        treasures.Add(new StardewValley.Object(774, 2 + ((Game1.random.NextDouble() < 0.25) ? 2 : 0), false, -1, 0));
                    }
                    switch (Game1.random.Next(4))
                    {
                        case 0:
                            if (Game1.random.NextDouble() < 0.03)
                            {
                                treasures.Add(new StardewValley.Object(386, Game1.random.Next(1, 3), false, -1, 0));
                            }
                            else
                            {
                                List<int> possibles = new List<int>();
                                possibles.Add(384);
                                if (possibles.Count == 0 || Game1.random.NextDouble() < 0.6)
                                {
                                    possibles.Add(380);
                                }
                                if (possibles.Count == 0 || Game1.random.NextDouble() < 0.6)
                                {
                                    possibles.Add(378);
                                }
                                if (possibles.Count == 0 || Game1.random.NextDouble() < 0.6)
                                {
                                    possibles.Add(388);
                                }
                                if (possibles.Count == 0 || Game1.random.NextDouble() < 0.6)
                                {
                                    possibles.Add(390);
                                }
                                possibles.Add(382);
                                treasures.Add(new StardewValley.Object(possibles.ElementAt(Game1.random.Next(possibles.Count)), Game1.random.Next(2, 7) * ((Game1.random.NextDouble() < 0.05 + (double)Game1.player.luckLevel.Value * 0.015) ? 2 : 1), false, -1, 0));
                                if (Game1.random.NextDouble() < 0.05 + (double)Game1.player.LuckLevel * 0.03)
                                {
                                    treasures.Last<Item>().Stack *= 2;
                                }
                            }
                            break;
                        case 1:
                            if (Game1.random.NextDouble() < 0.1)
                            {
                                treasures.Add(new StardewValley.Object(687, 1, false, -1, 0));
                            }
                            else if (Game1.random.NextDouble() < 0.25 && Game1.player.craftingRecipes.ContainsKey("Wild Bait"))
                            {
                                treasures.Add(new StardewValley.Object(774, 5 + ((Game1.random.NextDouble() < 0.25) ? 5 : 0), false, -1, 0));
                            }
                            else
                            {
                                treasures.Add(new StardewValley.Object(685, 10, false, -1, 0));
                            }
                            break;
                        case 2:
                            if (Game1.random.NextDouble() < 0.1 && Game1.netWorldState.Value.LostBooksFound.Value < 21 && Game1.player.hasOrWillReceiveMail("lostBookFound"))
                            {
                                treasures.Add(new StardewValley.Object(102, 1, false, -1, 0));
                            }
                            else if (Game1.player.archaeologyFound.Count() > 0)
                            {
                                if (Game1.random.NextDouble() < 0.25)
                                {
                                    treasures.Add(new StardewValley.Object(Game1.random.Next(585, 588), 1, false, -1, 0));
                                }
                                else if (Game1.random.NextDouble() < 0.5)
                                {
                                    treasures.Add(new StardewValley.Object(Game1.random.Next(103, 120), 1, false, -1, 0));
                                }
                                else
                                {
                                    treasures.Add(new StardewValley.Object(535, 1, false, -1, 0));
                                }
                            }
                            else
                            {
                                treasures.Add(new StardewValley.Object(382, Game1.random.Next(1, 3), false, -1, 0));
                            }
                            break;
                        case 3:
                            switch (Game1.random.Next(3))
                            {
                                case 0:
                                    switch (Game1.random.Next(3))
                                    {
                                        case 0:
                                            treasures.Add(new StardewValley.Object(537 + ((Game1.random.NextDouble() < 0.4) ? Game1.random.Next(-2, 0) : 0), Game1.random.Next(1, 4), false, -1, 0));
                                            break;
                                        case 1:
                                            treasures.Add(new StardewValley.Object(536 + ((Game1.random.NextDouble() < 0.4) ? -1 : 0), Game1.random.Next(1, 4), false, -1, 0));
                                            break;
                                        case 2:
                                            treasures.Add(new StardewValley.Object(535, Game1.random.Next(1, 4), false, -1, 0));
                                            break;
                                    }
                                    if (Game1.random.NextDouble() < 0.05 + (double)Game1.player.LuckLevel * 0.03)
                                    {
                                        treasures.Last<Item>().Stack *= 2;
                                    }
                                    break;
                                case 1:
                                    switch (Game1.random.Next(4))
                                    {
                                        case 0:
                                            treasures.Add(new StardewValley.Object(382, Game1.random.Next(1, 4), false, -1, 0));
                                            break;
                                        case 1:
                                            treasures.Add(new StardewValley.Object((Game1.random.NextDouble() < 0.3) ? 82 : ((Game1.random.NextDouble() < 0.5) ? 64 : 60), Game1.random.Next(1, 3), false, -1, 0));
                                            break;
                                        case 2:
                                            treasures.Add(new StardewValley.Object((Game1.random.NextDouble() < 0.3) ? 84 : ((Game1.random.NextDouble() < 0.5) ? 70 : 62), Game1.random.Next(1, 3), false, -1, 0));
                                            break;
                                        case 3:
                                            treasures.Add(new StardewValley.Object((Game1.random.NextDouble() < 0.3) ? 86 : ((Game1.random.NextDouble() < 0.5) ? 66 : 68), Game1.random.Next(1, 3), false, -1, 0));
                                            break;
                                    }
                                    if (Game1.random.NextDouble() < 0.05)
                                    {
                                        treasures.Add(new StardewValley.Object(72, 1, false, -1, 0));
                                    }
                                    if (Game1.random.NextDouble() < 0.05)
                                    {
                                        treasures.Last<Item>().Stack *= 2;
                                    }
                                    break;
                                case 2:
                                    if (Game1.player.FishingLevel < 2)
                                    {
                                        treasures.Add(new StardewValley.Object(770, Game1.random.Next(1, 4), false, -1, 0));
                                    }
                                    else
                                    {
                                        float luckModifier = (1f + (float)Game1.player.DailyLuck);
                                        if (Game1.random.NextDouble() < 0.05 * (double)luckModifier && !Game1.player.specialItems.Contains(14))
                                        {
                                            treasures.Add(new MeleeWeapon(14)
                                            {
                                                specialItem = true
                                            });
                                        }
                                        if (Game1.random.NextDouble() < 0.05 * (double)luckModifier && !Game1.player.specialItems.Contains(51))
                                        {
                                            treasures.Add(new MeleeWeapon(51)
                                            {
                                                specialItem = true
                                            });
                                        }
                                        if (Game1.random.NextDouble() < 0.07 * (double)luckModifier)
                                        {
                                            switch (Game1.random.Next(3))
                                            {
                                                case 0:
                                                    treasures.Add(new Ring(516 + ((Game1.random.NextDouble() < (double)((float)Game1.player.LuckLevel / 11f)) ? 1 : 0)));
                                                    break;
                                                case 1:
                                                    treasures.Add(new Ring(518 + ((Game1.random.NextDouble() < (double)((float)Game1.player.LuckLevel / 11f)) ? 1 : 0)));
                                                    break;
                                                case 2:
                                                    treasures.Add(new Ring(Game1.random.Next(529, 535)));
                                                    break;
                                            }
                                        }
                                        if (Game1.random.NextDouble() < 0.02 * (double)luckModifier)
                                        {
                                            treasures.Add(new StardewValley.Object(166, 1, false, -1, 0));
                                        }
                                        if (Game1.random.NextDouble() < 0.001 * (double)luckModifier)
                                        {
                                            treasures.Add(new StardewValley.Object(74, 1, false, -1, 0));
                                        }
                                        if (Game1.random.NextDouble() < 0.01 * (double)luckModifier)
                                        {
                                            treasures.Add(new StardewValley.Object(127, 1, false, -1, 0));
                                        }
                                        if (Game1.random.NextDouble() < 0.01 * (double)luckModifier)
                                        {
                                            treasures.Add(new StardewValley.Object(126, 1, false, -1, 0));
                                        }
                                        if (Game1.random.NextDouble() < 0.01 * (double)luckModifier)
                                        {
                                            treasures.Add(new Ring(527));
                                        }
                                        if (Game1.random.NextDouble() < 0.01 * (double)luckModifier)
                                        {
                                            treasures.Add(new Boots(Game1.random.Next(504, 514)));
                                        }
                                        if (treasures.Count == 1)
                                        {
                                            treasures.Add(new StardewValley.Object(72, 1, false, -1, 0));
                                        }
                                    }
                                    break;
                            }
                            break;
                    }
                }
                if (treasures.Count == 0)
                {
                    treasures.Add(new StardewValley.Object(685, Game1.random.Next(1, 4) * 5, false, -1, 0));
                }
                if (treasures.Count > 0)
                {
                    Color tint = Color.White;
                    l.overlayObjects[v] = new Chest(Game1.random.Next(0, 1000), new List<Item>() { treasures[ModEntry.myRand.Value.Next(treasures.Count)] }, v, false, 0)
                    {
                        Tint = tint
                    };
                }
            }
        }

19 Source : ViewMethods.cs
with MIT License
from AElfProject

private List<ByteString> GetVictories(List<string> currentMiners)
        {
            var validCandidates = GetValidCandidates();

            List<ByteString> victories;

            Context.LogDebug(() => $"Valid candidates: {validCandidates.Count} / {State.MinersCount.Value}");

            var diff = State.MinersCount.Value - validCandidates.Count;
            // Valid candidates not enough.
            if (diff > 0)
            {
                victories =
                    new List<ByteString>(validCandidates.Select(ByteStringHelper.FromHexString));
                var backups = currentMiners.Where(k => !validCandidates.Contains(k)).ToList();
                if (State.InitialMiners.Value != null)
                {
                    backups.AddRange(
                        State.InitialMiners.Value.Value.Select(k => k.ToHex()).Where(k => !backups.Contains(k)));
                }

                victories.AddRange(backups.OrderBy(p => p)
                    .Take(Math.Min(diff, currentMiners.Count))
                    .Select(ByteStringHelper.FromHexString));
                Context.LogDebug(() => string.Join("\n", victories.Select(v => v.ToHex().Substring(0, 10)).ToList()));
                return victories;
            }

            victories = validCandidates.Select(k => State.CandidateVotes[k])
                .OrderByDescending(v => v.ObtainedActiveVotedVotesAmount).Select(v => v.Pubkey)
                .Take(State.MinersCount.Value).ToList();
            Context.LogDebug(() => string.Join("\n", victories.Select(v => v.ToHex().Substring(0, 10)).ToList()));
            return victories;
        }

19 Source : MiningService.cs
with MIT License
from AElfProject

public async Task<BlockExecutedSet> MineAsync(RequestMiningDto requestMiningDto, List<Transaction> transactions,
            Timestamp blockTime)
        {
            try
            {
                using (var cts = new CancellationTokenSource())
                {
                    var expirationTime = blockTime + requestMiningDto.BlockExecutionTime;
                    if (expirationTime < TimestampHelper.GetUtcNow())
                        cts.Cancel();
                    else
                    {
                        var ts = (expirationTime - TimestampHelper.GetUtcNow()).ToTimeSpan();
                        if (ts.TotalMilliseconds > int.MaxValue)
                        {
                            ts = TimeSpan.FromMilliseconds(int.MaxValue);
                        }

                        cts.CancelAfter(ts);
                    }

                    var block = await GenerateBlock(requestMiningDto.PreviousBlockHash,
                        requestMiningDto.PreviousBlockHeight, blockTime);
                    var systemTransactions = await GenerateSystemTransactions(requestMiningDto.PreviousBlockHash,
                        requestMiningDto.PreviousBlockHeight);
                    _systemTransactionExtraDataProvider.SetSystemTransactionCount(systemTransactions.Count,
                        block.Header);
                    var txTotalCount = transactions.Count + systemTransactions.Count;

                    var pending = txTotalCount > requestMiningDto.TransactionCountLimit
                        ? transactions
                            .Take(requestMiningDto.TransactionCountLimit - systemTransactions.Count)
                            .ToList()
                        : transactions;
                    var blockExecutedSet = await _blockExecutingService.ExecuteBlockAsync(block.Header,
                        systemTransactions, pending, cts.Token);

                    block = blockExecutedSet.Block;
                    await SignBlockAsync(block);
                    Logger.LogInformation($"Generated block: {block.ToDiagnosticString()}, " +
                                          $"previous: {block.Header.PreviousBlockHash}, " +
                                          $"executed transactions: {block.Body.TransactionsCount}, " +
                                          $"not executed transactions {pending.Count + systemTransactions.Count - block.Body.TransactionsCount} ");
                    return blockExecutedSet;
                }
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Failed while mining block.");
                throw;
            }
        }

19 Source : BlockExecutingService.cs
with MIT License
from AElfProject

public async Task<BlockExecutedSet> ExecuteBlockAsync(BlockHeader blockHeader,
            List<Transaction> nonCancellableTransactions)
        {
            _systemTransactionExtraDataProvider.TryGetSystemTransactionCount(blockHeader,
                out var systemTransactionCount);
            return await ExecuteBlockAsync(blockHeader, nonCancellableTransactions.Take(systemTransactionCount),
                nonCancellableTransactions.Skip(systemTransactionCount),
                CancellationToken.None);
        }

19 Source : TxHub.cs
with MIT License
from AElfProject

public async Task<ExecutableTransactionSet> GetExecutableTransactionSetAsync(Hash blockHash, int transactionCount)
        {
            var output = new ExecutableTransactionSet
            {
                PreviousBlockHash = _bestChainHash,
                PreviousBlockHeight = _bestChainHeight
            };

            if (transactionCount <= 0)
            {
                return output;
            }
            
            if (blockHash != _bestChainHash)
            {
                Logger.LogWarning(
                    $"Attempting to retrieve executable transactions while best chain records don't match.");
                return output;
            }

            output.Transactions.AddRange(_validatedTransactions.Values.OrderBy(x => x.EnqueueTime)
                .Take(transactionCount)
                .Select(x => x.Transaction));

            return output;
        }

19 Source : AElfPeerEndpointHelper.cs
with MIT License
from AElfProject

public static bool TryParse(string endpointString, out DnsEndPoint endpoint, 
            int defaultPort = NetworkConstants.DefaultPeerPort)
        {
            endpoint = null;

            if (string.IsNullOrEmpty(endpointString) || endpointString.Trim().Length == 0)
                return false;

            if (defaultPort != -1 && (defaultPort < IPEndPoint.MinPort || defaultPort > IPEndPoint.MaxPort))
                return false;

            string[] values = endpointString.Split(new char[] { ':' });
            string host;
            int port = -1;

            if (values.Length <= 2) 
            {
                // ipv4 or hostname
                host = values[0];

                if (values.Length == 1)
                {
                    port = defaultPort;
                }
                else
                {
                    var parsedPort = GetPort(values[1]);

                    if (parsedPort == 0)
                        return false;

                    port = parsedPort;
                }
            }
            else
            {
                //ipv6
                //could be [a:b:c]:d
                if (values[0].StartsWith("[") && values[values.Length - 2].EndsWith("]"))
                {
                    host = string.Join(":", values.Take(values.Length - 1).ToArray());
                    var parsedPort = GetPort(values[values.Length - 1]);
                    
                    if (parsedPort == 0)
                        return false;
                        
                    port = parsedPort;
                }
                else // [a:b:c] or a:b:c
                {
                    host = endpointString;
                    port = defaultPort;
                }
            }

            if (port == -1)
                return false;

            // we leave semantic replacedysis of the ip/hostname to lower levels.
            endpoint = new AElfPeerEndpoint(host, port);
            
            return true;
        }

19 Source : PaginationViewModel.cs
with MIT License
from AFei19911012

private void PageUpdated(FunctionEventArgs<int> info)
        {
            DataList = TotalDataList.Skip((info.Info - 1) * 10).Take(10).ToList();
        }

19 Source : Extension.cs
with MIT License
from Agenty

public static DataTable FileToTable(this string path, bool heading = true, char delimiter = '\t', int offset = 0, int limit = 100000)
        {
            var table = new DataTable();
            string headerLine = File.ReadLines(path).FirstOrDefault(); // Read the first row for headings
            string[] headers = headerLine.Split(delimiter);
            int skip = 1;
            int num = 1;
            foreach (string header in headers)
            {
                if (heading)
                {
                    table.Columns.Add(header); 
                }
                else
                {
                    table.Columns.Add("Field" + num); // Create fields header if heading is false
                    num++;
                    skip = 0; // Don't skip the first row if heading is false
                }
            }

            foreach (string line in File.ReadLines(path).Skip(skip + offset).Take(limit))
            {
                if (!string.IsNullOrEmpty(line))
                {
                    table.Rows.Add(line.Split(delimiter));
                }
            }
            return table;
        }

19 Source : QueryableExtensions.cs
with Apache License 2.0
from Aguafrommars

public static IQueryable<T> GetPage<T>(this IQueryable<T> query, PageRequest request) where T : clreplaced
        {
            if (request.Skip.HasValue)
            {
                query = query.Skip(request.Skip.Value);
            }

            if (request.Take.HasValue)
            {
                query = query.Take(request.Take.Value);
            }
                
            return query;
        }

19 Source : LinqSample.cs
with The Unlicense
from ahotko

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

19 Source : LinqSample.cs
with The Unlicense
from ahotko

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

19 Source : BundleContainer.cs
with GNU Affero General Public License v3.0
from aianlinb

public virtual byte[] AppendAndSave(Stream newData, Stream originalData) {
            originalData.Seek(offset + 60, SeekOrigin.Begin);
            var OldChunkCompressedSizes = new byte[(entry_count - 1) * 4];
            originalData.Read(OldChunkCompressedSizes, 0, OldChunkCompressedSizes.Length);

            var lastCunkCompressedSize = originalData.ReadByte() | originalData.ReadByte() << 8 | originalData.ReadByte() << 16 | originalData.ReadByte() << 24; //ReadInt32

            var lastCunkDecompressedSize = uncompressed_size - (chunk_size * (entry_count - 1));

            uncompressed_size = (int)(size_decompressed += newData.Length);
            entry_count = uncompressed_size / chunk_size;
            if (uncompressed_size % chunk_size != 0) entry_count++;
            head_size = entry_count * 4 + 48;

            var msToSave = new MemoryStream();
            var bw = new BinaryWriter(msToSave);

            msToSave.Seek(60 + (entry_count * 4), SeekOrigin.Begin);
            var o = new byte[compressed_size - lastCunkCompressedSize];
            originalData.Read(o, 0, o.Length);
            bw.Write(o);

            var lastChunkCompressedData = new byte[lastCunkCompressedSize];
            originalData.Read(lastChunkCompressedData, 0, lastCunkCompressedSize);
            var lastCunkDecompressedData = new byte[lastCunkDecompressedSize + 64];
			_ = OodleLZ_Decompress(lastChunkCompressedData, lastCunkCompressedSize, lastCunkDecompressedData, lastCunkDecompressedSize, 0, 0, 0, IntPtr.Zero, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 0, 3);

            newData.Seek(0, SeekOrigin.Begin);
            compressed_size -= lastCunkCompressedSize;
            var NewChunkCompressedSizes = new int[entry_count - (OldChunkCompressedSizes.Length / 4)];

            var FirstNewDataChunk = new byte[Math.Min(chunk_size - lastCunkDecompressedSize, newData.Length)];
            newData.Read(FirstNewDataChunk, 0, FirstNewDataChunk.Length);
            FirstNewDataChunk = lastCunkDecompressedData.Take(lastCunkDecompressedSize).Concat(FirstNewDataChunk).ToArray();
            var CompressedChunk = new byte[FirstNewDataChunk.Length + 548];
            var CompressedLength = OodleLZ_Compress(encoder, FirstNewDataChunk, FirstNewDataChunk.Length, CompressedChunk, Compression_Level, IntPtr.Zero, 0, 0, IntPtr.Zero, 0);
            compressed_size += NewChunkCompressedSizes[0] = CompressedLength;
            bw.Write(CompressedChunk, 0, CompressedLength);
            for (var i = 1; i < NewChunkCompressedSizes.Length; i++) {
                var size = (i + 1 == NewChunkCompressedSizes.Length) ? uncompressed_size - (chunk_size * (entry_count - 1)) : chunk_size;
                var b = new byte[size];
                newData.Read(b, 0, size);
                var by = new byte[b.Length + 548];
                var l = OodleLZ_Compress(encoder, b, size, by, Compression_Level, IntPtr.Zero, 0, 0, IntPtr.Zero, 0);
                compressed_size += NewChunkCompressedSizes[i] = l;
                bw.Write(by, 0, l);
            }
            size_compressed = compressed_size;

            msToSave.Seek(60, SeekOrigin.Begin);
            bw.Write(OldChunkCompressedSizes);
            for (var i = 0; i < NewChunkCompressedSizes.Length; i++)
                bw.Write(NewChunkCompressedSizes[i]);

            msToSave.Seek(0, SeekOrigin.Begin);
            bw.Write(uncompressed_size);
            bw.Write(compressed_size);
            bw.Write(head_size);
            bw.Write((uint)encoder);
            bw.Write(unknown);
            bw.Write(size_decompressed);
            bw.Write(size_compressed);
            bw.Write(entry_count);
            bw.Write(chunk_size);
            bw.Write(unknown3);
            bw.Write(unknown4);
            bw.Write(unknown5);
            bw.Write(unknown6);

            bw.Flush();
            var result = msToSave.ToArray();
            bw.Close();
            return result;
        }

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

public IEnumerator<T> GetEnumerator()
        {
            return !this._reached_end
                ? this.InternalBuffer.AsEnumerable().GetEnumerator()
                : this.InternalBuffer.Skip(this.CurrentIndex)
                .Concat(this.InternalBuffer.Take(this.CurrentIndex))
                .GetEnumerator();
        }

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from airzero24

public static void ResultFormat(string column1, string column2, string column3, string column4, string column5)
        {
            int column1Width = 7;
            int column2Width = 7;
            int column3Width = 5;
            int column4Width = 25;
            int column5Width = 40;
            int loopCount = 0;

            StringBuilder output = new StringBuilder();

            while (true)
            {
                string col1 = new string(column1.Skip<char>(loopCount * column1Width).Take<char>(column1Width).ToArray()).PadRight(column1Width);
                string col2 = new string(column2.Skip<char>(loopCount * column2Width).Take<char>(column2Width).ToArray()).PadRight(column2Width);
                string col3 = new string(column3.Skip<char>(loopCount * column3Width).Take<char>(column3Width).ToArray()).PadRight(column3Width);
                string col4 = new string(column4.Skip<char>(loopCount * column4Width).Take<char>(column4Width).ToArray()).PadRight(column4Width);
                string col5 = new string(column5.Skip<char>(loopCount * column5Width).Take<char>(column5Width).ToArray()).PadRight(column5Width);

                if (String.IsNullOrWhiteSpace(col1) && String.IsNullOrWhiteSpace(col2) && String.IsNullOrWhiteSpace(col3))
                {
                    break;
                }

                output.AppendFormat("{0} {1} {2} {3} {4}", col1, col2, col3, col4, col5);
                loopCount++;
            }
            Console.WriteLine(output.ToString());
        }

19 Source : BasicTest.cs
with MIT License
from AiursoftWeb

private static async Task Monitor(ClientWebSocket socket)
        {
            var buffer = new ArraySegment<byte>(new byte[2048]);
            while (true)
            {
                var result = await socket.ReceiveAsync(buffer, CancellationToken.None);
                if (result.MessageType == WebSocketMessageType.Text)
                {
                    MessageCount++;
                    var _ = Encoding.UTF8.GetString(buffer.Skip(buffer.Offset).Take(buffer.Count).ToArray())
                        .Trim('\0')
                        .Trim();
                }
                else
                {
                    Console.WriteLine($"[WebSocket Event] Remote wrong message. [{result.MessageType}].");
                    break;
                }
            }
        }

19 Source : MongoDBFileStore.cs
with MIT License
from aishang2015

public async Task<bool> TryCreateDirectoryAsync(string path)
        {
            var fileEnreplacedy = await GetFileEnreplacedyByPath(path);
            if (fileEnreplacedy == null)
            {
                var directoryPathArray = path.Split('/', StringSplitOptions.RemoveEmptyEntries);
                var newArray = directoryPathArray.Take(directoryPathArray.Length - 1);
                var fileinfo = new MongoDBFileStoreEntry
                {
                    Path = path.TrimEnd('/'),
                    DirectoryPath = '/' + string.Join('/', newArray).TrimEnd('/'),
                    Name = directoryPathArray.Last(),
                    LastModifiedUtc = DateTime.Now,
                    IsDirectory = true
                };
                await _mongoRepository.AddAsync(fileinfo);
            }
            return true;
        }

19 Source : EnumerableExtension.cs
with MIT License
from aishang2015

public static IEnumerable<T> PageBy<T>(this IEnumerable<T> enumerable, int page, int size)
        {
            return enumerable.Skip((page - 1) * size).Take(size);
        }

19 Source : ProbeLocator.cs
with MIT License
from AiursoftWeb

private (string siteName, string[] folders, string fileName) SplitToPath(string fullPath)
        {
            if (fullPath == null || fullPath.Length == 0)
            {
                throw new AiurAPIModelException(ErrorType.NotFound, $"Can't get your file download address from path: '{fullPath}'!");
            }
            var paths = SplitStrings(fullPath);
            var fileName = paths.Last();
            var siteName = paths.First();
            var folders = paths.Take(paths.Count() - 1).Skip(1).ToArray();
            return (siteName, folders, fileName);
        }

19 Source : FolderSplitter.cs
with MIT License
from AiursoftWeb

public (string[] folders, string fileName) SplitToFoldersAndFile(string folderNames)
        {
            if (folderNames == null || folderNames.Length == 0)
            {
                throw new AiurAPIModelException(ErrorType.NotFound, "The root folder isn't a file!");
            }
            var foldersWithFileName = SplitToFolders(folderNames);
            var fileName = foldersWithFileName.Last();
            var folders = foldersWithFileName.Take(foldersWithFileName.Count() - 1).ToArray();
            return (folders, fileName);
        }

19 Source : FriendshipController.cs
with MIT License
from AiursoftWeb

[APIProduces(typeof(AiurCollection<FriendDiscovery>))]
        public async Task<IActionResult> DiscoverFriends(int take = 15)
        {
            // Load everything to memory and even functions.
            var users = await _dbContext.Users
                .AsNoTracking()
                .ToListAsync();
            var conversations = await _dbContext.PrivateConversations
                .AsNoTracking()
                .ToListAsync();
            var groups = await _dbContext.GroupConversations
                .Include(t => t.Users)
                .AsNoTracking()
                .ToListAsync();
            var requests = await _dbContext.Requests
                .AsNoTracking()
                .ToListAsync();
            bool AreFriends(string userId1, string userId2)
            {
                var relation = conversations.Any(t => t.RequesterId == userId1 && t.TargetId == userId2);
                if (relation)
                {
                    return true;
                }
                var elation = conversations.Any(t => t.RequesterId == userId2 && t.TargetId == userId1);
                return elation;
            }
            List<string> HisPersonalFriendsId(string userId)
            {
                var personalRelations = conversations
                    .Where(t => t.RequesterId == userId || t.TargetId == userId)
                    .Select(t => userId == t.RequesterId ? t.TargetId : t.RequesterId)
                    .ToList();
                return personalRelations;
            }
            List<int> HisGroups(string userId)
            {
                return groups
                    .Where(t => t.Users.Any(p => p.UserId == userId))
                    .Select(t => t.Id)
                    .ToList();
            }
            bool SentRequest(string userId1, string userId2)
            {
                var relation = requests.Where(t => t.Completed == false).Any(t => t.CreatorId == userId1 && t.TargetId == userId2);
                if (relation)
                {
                    return true;
                }
                var elation = requests.Where(t => t.Completed == false).Any(t => t.TargetId == userId1 && t.CreatorId == userId1);
                return elation;
            }
            var currentUser = await GetKahlaUser();
            var myFriends = HisPersonalFriendsId(currentUser.Id);
            var myGroups = HisGroups(currentUser.Id);
            var calculated = new List<FriendDiscovery>();
            foreach (var user in users)
            {
                if (user.Id == currentUser.Id || AreFriends(user.Id, currentUser.Id))
                {
                    continue;
                }
                var hisFriends = HisPersonalFriendsId(user.Id);
                var hisGroups = HisGroups(user.Id);
                var commonFriends = myFriends.Intersect(hisFriends).Count();
                var commonGroups = myGroups.Intersect(hisGroups).Count();
                if (commonFriends > 0 || commonGroups > 0)
                {
                    calculated.Add(new FriendDiscovery
                    {
                        CommonFriends = commonFriends,
                        CommonGroups = commonGroups,
                        TargetUser = user,
                        SentRequest = SentRequest(currentUser.Id, user.Id)
                    });
                }
            }
            var ordered = calculated
                .OrderByDescending(t => t.CommonFriends)
                .ThenBy(t => t.CommonGroups)
                .Take(take)
                .ToList();
            return this.Protocol(new AiurCollection<FriendDiscovery>(ordered)
            {
                Code = ErrorType.Success,
                Message = "Successfully get your suggested friends."
            });
        }

19 Source : BasicTests.cs
with The Unlicense
from AiursoftWeb

private static async Task Monitor(ClientWebSocket socket)
        {
            var buffer = new ArraySegment<byte>(new byte[2048]);
            while (true)
            {
                var result = await socket.ReceiveAsync(buffer, CancellationToken.None);
                if (result.MessageType == WebSocketMessageType.Text)
                {
                    _messageCount++;
                    string message = Encoding.UTF8.GetString(
                        buffer.Skip(buffer.Offset).Take(buffer.Count).ToArray())
                        .Trim('\0')
                        .Trim();
                    Console.WriteLine(message);
                }
                else
                {
                    Console.WriteLine($"[WebSocket Event] Remote wrong message. [{result.MessageType}].");
                    break;
                }
            }
        }

19 Source : FileType.cs
with GNU General Public License v3.0
from AJMitev

public int GetMatchingNumber(Stream stream)
        {
            stream.Position = 0;

            int counter = 0;
            var buffer = new byte[ByfferDefaultSize];
            stream.Read(buffer, 0, buffer.Length);

            foreach (var bytesArr in this.Bytes)
            {
                var shrinkedBuffer = buffer.Skip(SkipBytes).Take(bytesArr.Length);

                for (int i = counter; i < bytesArr.Length; i++)
                {
                    if (!bytesArr[i].Equals(buffer[i]))
                        break;

                    counter++;
                }
            }

            return counter == 0 ? -1 : counter;
        }

19 Source : FileType.cs
with GNU General Public License v3.0
from AJMitev

private bool DoesMatchWith(byte[] buffer)
        {
            foreach (var bytesArr in this.Bytes)
            {
                if (buffer.Skip(SkipBytes).Take(bytesArr.Length).SequenceEqual(bytesArr)) 
                {
                    return true;
                }
            }
            return false;
        }

19 Source : EnumerableValueFormatter.cs
with MIT License
from akamud

public string Format(object value)
        {
            var enumerable = ConvertOrCastToCollection<object>((IEnumerable)value);

            if (enumerable.Any())
            {
                string postfix = string.Empty;

                if (enumerable.Count > MaxItems)
                {
                    postfix = $", …{enumerable.Count - MaxItems} more…";
                    enumerable = enumerable.Take(MaxItems).ToArray();
                }

                return @$"{{{string.Join(", ", enumerable.Select(item =>
                {
                    var valueFormatter = TestingLibraryOptions.DebugOptions.DefaultValueFormatters
                        .First(x => x.CanHandle(item));
                    return valueFormatter.Format(item);
                }))}{postfix}}

19 Source : PagedList.cs
with MIT License
from aksoftware98

private void PrepareData(IEnumerable<T> data, int page, int pageSize)
        {
            Records = Records ?? new List<T>();
            Records.Clear(); 
            var pageData = data.Skip((page - 1) * pageSize).Take(pageSize);
            Records.AddRange(pageData);

            ItemsCount = data.Count();
            TotalPages = ItemsCount / PageSize;
            if ((ItemsCount % PageSize) > 0)
                TotalPages++; 

        }

19 Source : ExtensionMethods.cs
with GNU General Public License v3.0
from Albo1125

public static IEnumerable<T> PickRandom<T>(this IEnumerable<T> source, int count)
        {
            return new List<T>(source).Shuffle().Take(count);
        }

19 Source : QueryableExtensions.cs
with MIT License
from albyho

public static async Task<Page<T>> GetPageAsync<T>(this IQueryable<T> sourceQuery, PagingInfo pagingInfo, ICollection<T> topQuery = null) where T : clreplaced
        {
            if (sourceQuery == null)
            {
                throw new ArgumentNullException(nameof(sourceQuery));
            }

            sourceQuery = sourceQuery.AsNoTracking();

            var page = new Page<T>();

            // 跳过记录集无记录
            if (topQuery == null || topQuery.Count == 0)
            {
                page.List = await sourceQuery.Skip(pagingInfo.PageIndex * pagingInfo.PageSize).Take(pagingInfo.PageSize).ToListAsync();
                if (!pagingInfo.IsExcludeMetaData)
                {
                    page.TotalItemCount = await sourceQuery.CountAsync();
                }
            }
            else
            {
                // 跳过的记录数
                int topItemCount = topQuery.Count;
                // 跳过的页数,比如一页显示10条,跳过4条、14条或24条,则跳过的页数为0、1或2
                int skipPage = (int)Math.Floor((double)topItemCount / pagingInfo.PageSize);

                // 如果目标页数在跳过的页数范围内,直接从topItems获取
                if (skipPage > pagingInfo.PageIndex)
                {
                    page.List = topQuery.Skip(pagingInfo.PageIndex * pagingInfo.PageSize).Take(pagingInfo.PageSize).ToList();
                    if (!pagingInfo.IsExcludeMetaData)
                    {
                        page.TotalItemCount = await sourceQuery.CountAsync() + topItemCount;
                    }
                }
                else
                {
                    int topSkipCount = skipPage * pagingInfo.PageSize;
                    int topTakeCount = topItemCount % pagingInfo.PageSize;
                    var topItems = topQuery.Skip(topSkipCount).Take(topTakeCount);

                    int sourceSkipCount = (pagingInfo.PageIndex - skipPage) * pagingInfo.PageSize;
                    int sourceTakeCount = pagingInfo.PageSize - topTakeCount;
                    var sourceItems = await sourceQuery.Skip(sourceSkipCount).Take(sourceTakeCount).ToListAsync();

                    page.List = topItems.Concat(sourceItems).ToList();
                    if (!pagingInfo.IsExcludeMetaData)
                    {
                        // 查询集记录数
                        int sourceItemCount = await sourceQuery.CountAsync();
                        page.TotalItemCount = sourceItemCount + topItemCount;
                    }
                }
            }

            page.TotalPageCount = (int)Math.Ceiling(page.TotalItemCount / (double)pagingInfo.PageSize);

            return page;
        }

19 Source : FileHelpers.cs
with MIT License
from albyho

private static bool IsValidFileExtensionAndSignature(string fileName, Stream data, string[] permittedExtensions)
        {
            if (string.IsNullOrEmpty(fileName) || data == null || data.Length == 0)
            {
                return false;
            }

            var ext = Path.GetExtension(fileName).ToLowerInvariant();

            if (string.IsNullOrEmpty(ext) || !permittedExtensions.Contains(ext))
            {
                return false;
            }

            data.Position = 0;

            using (var reader = new BinaryReader(data))
            {
                if (ext.Equals(".txt") || ext.Equals(".csv") || ext.Equals(".prn"))
                {
                    if (_allowedChars.Length == 0)
                    {
                        // Limits characters to ASCII encoding.
                        for (var i = 0; i < data.Length; i++)
                        {
                            if (reader.ReadByte() > sbyte.MaxValue)
                            {
                                return false;
                            }
                        }
                    }
                    else
                    {
                        // Limits characters to ASCII encoding and
                        // values of the _allowedChars array.
                        for (var i = 0; i < data.Length; i++)
                        {
                            var b = reader.ReadByte();
                            if (b > sbyte.MaxValue ||
                                !_allowedChars.Contains(b))
                            {
                                return false;
                            }
                        }
                    }

                    return true;
                }

                // Uncomment the following code block if you must permit
                // files whose signature isn't provided in the _fileSignature
                // dictionary. We recommend that you add file signatures
                // for files (when possible) for all file types you intend
                // to allow on the system and perform the file signature
                // check.
                /*
                if (!_fileSignature.ContainsKey(ext))
                {
                    return true;
                }
                */

                // File signature check
                // --------------------
                // With the file signatures provided in the _fileSignature
                // dictionary, the following code tests the input content's
                // file signature.
                var signatures = _fileSignature[ext];
                var headerBytes = reader.ReadBytes(signatures.Max(m => m.Length));

                return signatures.Any(signature =>
                    headerBytes.Take(signature.Length).SequenceEqual(signature));
            }
        }

19 Source : DataCipher.cs
with MIT License
from AlenToma

public string Decrypt(string cipherText)
        {
            if (!cipherText.IsBase64String())
                return cipherText;
            var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
            var v = Encoding.UTF8.GetString(cipherTextBytesWithSaltAndIv.Take(_Keysize / 8).ToArray());
            if (v != salt256 && v != salt128)
                return cipherText;

            var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((_Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((_Keysize / 8) * 2)).ToArray();
           
            using (var preplacedword = new Rfc2898DeriveBytes(_preplacedPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = preplacedword.GetBytes(_Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.Mode = CipherMode.CBC;
                    symmetricKey.Padding = PaddingMode.PKCS7;
                    symmetricKey.BlockSize = _Keysize;

                    using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream(cipherTextBytes))
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                            {
                                var plainTextBytes = new byte[cipherTextBytes.Length];
                                var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                                memoryStream.Close();
                                cryptoStream.Close();
                                return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                            }
                        }
                    }
                }
            }
        }

19 Source : ByteCipher.cs
with MIT License
from AlenToma

public byte[] Decrypt(byte[] cipherTextBytesWithSaltAndIv)
        {
            if (cipherTextBytesWithSaltAndIv.Length <= 0)
                return cipherTextBytesWithSaltAndIv;
            var v = Encoding.UTF8.GetString(cipherTextBytesWithSaltAndIv.Take(_Keysize / 8).ToArray());
            if (v != salt256 && v != salt128)
                return cipherTextBytesWithSaltAndIv;

            var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((_Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((_Keysize / 8) * 2)).ToArray();

            using (var preplacedword = new Rfc2898DeriveBytes(_preplacedPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = preplacedword.GetBytes(_Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.Mode = CipherMode.CBC;
                    symmetricKey.Padding = PaddingMode.PKCS7;
                    symmetricKey.BlockSize = _Keysize;

                    using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream(cipherTextBytes))
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                            {
                                var plainTextBytes = new byte[cipherTextBytes.Length];
                                var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                                memoryStream.Close();
                                cryptoStream.Close();
                                return plainTextBytes;
                            }
                        }
                    }
                }
            }
        }

19 Source : LinqToSql.cs
with MIT License
from AlenToma

protected object VisitMember(MemberExpression m, bool columnOnly)
        {
            try
            {
                if (m.Expression != null && m.Expression.NodeType == ExpressionType.Constant && (_overridedNodeType == null))
                {
                    VisitConstantFixed(m.Expression as ConstantExpression, m.Member?.Name);
                    return m;
                }
                else if (m.Expression?.ToString().Contains("DisplayClreplaced") ?? false || m.Expression == null)
                {
                    var hasValueAttr = m.ToString().EndsWith(".HasValue");
                    bool isNot = sb.ToString().EndsWith("NOT ");
                    var value = ValuetoSql(Expression.Lambda(m).Compile().DynamicInvoke());
                    var column = value;
                    if (isNot)
                    {
                        var invert = GetInvert();
                        column = $"(CASE WHEN {value} = {boolString.Replace("#", "0T")} THEN {boolString.Replace("#", "0T")} ELSE {boolString.Replace("#", "1T")} END) {boolString.Replace("#", "0")}";
                    }
                    else if (hasValueAttr)
                    {
                        column = $"(CASE WHEN {value} = {boolString.Replace("#", "0T")} THEN {boolString.Replace("#", "0T")} ELSE {boolString.Replace("#", "1T")} END) {boolString.Replace("#", "1")}";
                    }


                    CleanDecoder(column);
                    return m;
                }
                else if (m.Expression != null && (m.Expression.NodeType == ExpressionType.Parameter || (m.ToString().EndsWith(".HasValue") && m.Expression.NodeType == ExpressionType.MemberAccess)) && (_overridedNodeType == null))
                {
                    var hasValueAttr = m.ToString().EndsWith(".HasValue");
                    _overridedNodeType = null;
                    var cl = hasValueAttr ? (m.Expression as MemberExpression).Expression.Type : m.Expression.Type;
                    var prop = DeepCloner.GetFastDeepClonerProperties(cl).First(x => x.Name == (hasValueAttr ? (m.Expression as MemberExpression).Member.Name : m.Member.Name));
                    var name = prop.GetPropertyName();
                    var table = cl.TableName().GetName(DataBaseTypes);
                    var columnName = string.Format("{0}.[{1}]", table, name).CleanValidSqlName(DataBaseTypes);
                    var dataEncode = prop.GetCustomAttribute<DataEncode>();
                    if (columnOnly)
                        return columnName;

                    bool isNot = sb.ToString().EndsWith("NOT ");
                    if (prop.PropertyType.IsEnum && prop.ContainAttribute<Stringify>())
                    {
                        if (!SavedTypes.ContainsKey(prop.FullName))
                            SavedTypes.TryAdd(prop.FullName, prop.PropertyType);
                        columnName += stringyFy.Replace("#", prop.FullName);
                    }
                    if (isNot)
                    {
                        var invert = GetInvert();
                        if (!hasValueAttr)
                            columnName = $"(CASE WHEN {columnName} = {boolString.Replace("#", "0T")} THEN {boolString.Replace("#", "1T")} ELSE {boolString.Replace("#", "0T")} END) {boolString.Replace("#", "0")}";
                        else
                            columnName = $"(CASE WHEN {columnName} IS NULL THEN {boolString.Replace("#", "0T")} ELSE {boolString.Replace("#", "1T")} END) {boolString.Replace("#", "0")}";
                    }
                    else if (hasValueAttr)
                    {
                        columnName = $"(CASE WHEN {columnName} IS NULL THEN {boolString.Replace("#", "0T")} ELSE {boolString.Replace("#", "1T")} END) {boolString.Replace("#", "1")}";
                    }
                    else if (prop.PropertyType == typeof(bool) || prop.PropertyType == typeof(bool?))
                        columnName = columnName + boolString.Replace("#", "1");

                    if (dataEncode != null)
                        columnName = columnName + dataEncodeString.Replace("#", dataEncode.Key + "|" + ((int)dataEncode.KeySize).ToString());
                    sb.Append(columnName);
                    return m;
                }
                else if (m.Expression != null && (m.Expression.NodeType == ExpressionType.MemberAccess))
                {
                    _overridedNodeType = null;
                    var key = string.Join("", m.ToString().Split('.').Take(m.ToString().Split('.').Length - 1));
                    var cl = m.Expression.Type;
                    if (cl.IsInterface)
                    {
                        var pr = (m.Expression as MemberExpression).Expression.Type;
                        var tb = m.Expression.ToString().Split('.').Last();
                        cl = DeepCloner.GetProperty(pr, tb)?.PropertyType ?? cl;

                    }


                    var prop = DeepCloner.GetFastDeepClonerProperties(cl).First(x => x.Name == m.Member.Name);
                    var name = prop.GetPropertyName();
                    var table = cl.TableName();
                    var randomTableName = JoinClauses.ContainsKey(key) ? JoinClauses[key].Item1 : RandomKey();
                    var primaryId = DeepCloner.GetFastDeepClonerProperties(cl).First(x => x.ContainAttribute<PrimaryKey>()).GetPropertyName();
                    var columnName = string.Format("[{0}].[{1}]", randomTableName, name).CleanValidSqlName(DataBaseTypes);
                    if (columnOnly)
                        return columnName;
                    sb.Append(columnName);
                    if (JoinClauses.ContainsKey(key))
                        return m;
                    // Ok lets build inner join 
                    var parentType = (m.Expression as MemberExpression).Expression.Type;
                    var parentTable = parentType.TableName();
                    prop = DeepCloner.GetFastDeepClonerProperties(parentType).FirstOrDefault(x => x.ContainAttribute<ForeignKey>() && x.GetCustomAttribute<ForeignKey>().Type == cl);
                    var v = "";
                    if (prop != null)
                    {
                        v += string.Format("LEFT JOIN {0} {1} ON [{2}].[{3}] = {4}.[{5}]", table.GetName(DataBaseTypes), randomTableName, randomTableName, primaryId, parentTable.GetName(DataBaseTypes), prop.GetPropertyName()).CleanValidSqlName(DataBaseTypes);
                    }
                    else
                    {
                        prop = DeepCloner.GetFastDeepClonerProperties(cl).FirstOrDefault(x => x.ContainAttribute<ForeignKey>() && x.GetCustomAttribute<ForeignKey>().Type == parentType);
                        if (prop != null)
                            v += string.Format("LEFT JOIN {0} {1} ON [{2}].[{3}] = {4}.[{5}]", table.GetName(DataBaseTypes), randomTableName, randomTableName, prop.GetPropertyName(), parentTable.GetName(DataBaseTypes), primaryId).CleanValidSqlName(DataBaseTypes);
                    }

                    if (string.IsNullOrEmpty(v))
                    {
                        sb = sb.Remove(sb.Length - columnName.Length, columnName.Length);
                        CleanDecoder(ValuetoSql(GetValue(m)));
                    }
                    else
                    {
                        JoinClauses.TryAdd(key, new Tuple<string, string>(randomTableName, v));
                    }


                    return m;
                }
                else if (m.Expression != null && _overridedNodeType == ExpressionType.MemberAccess)
                {
                    _overridedNodeType = null;
                    var key = string.Join("", m.ToString().Split('.').Take(m.ToString().Split('.').Length - 1));
                    var cl = m.Expression.Type;
                    if (cl.IsInterface)
                    {
                        var pr = (m.Expression as MemberExpression).Expression.Type.GetActualType();
                        var tb = m.Expression.ToString().Split('.').Last();
                        cl = DeepCloner.GetProperty(pr, tb)?.PropertyType ?? cl;
                    }

                    var prop = DeepCloner.GetFastDeepClonerProperties(cl).First(x => x.Name == m.Member.Name);
                    var table = cl.TableName();
                    var randomTableName = JoinClauses.ContainsKey(key) ? JoinClauses[key].Item1 : RandomKey();
                    var primaryId = DeepCloner.GetFastDeepClonerProperties(cl).First(x => x.ContainAttribute<PrimaryKey>()).GetPropertyName();
                    if (JoinClauses.ContainsKey(key))
                        return m;
                    // Ok lets build inner join 
                    var parentType = (m as MemberExpression).Type.GetActualType();
                    var parentTable = parentType.TableName();
                    prop = DeepCloner.GetFastDeepClonerProperties(parentType).FirstOrDefault(x => x.ContainAttribute<ForeignKey>() && x.GetCustomAttribute<ForeignKey>().Type == cl);
                    var v = "";
                    if (prop != null)
                    {
                        v += string.Format("INNER JOIN {0} {1} ON {2}.[{3}] = [{4}].[{5}]", parentTable.GetName(DataBaseTypes), randomTableName, table.GetName(DataBaseTypes), primaryId, randomTableName, prop.GetPropertyName()).CleanValidSqlName(DataBaseTypes);
                    }
                    else
                    {
                        throw new EnreplacedyException(string.Format("Expression STRUCTURE IS NOT SUPPORTED MEMBER{0} for EnreplacedyWorker", m.Member.Name));
                    }

                    if (!string.IsNullOrEmpty(v))
                        JoinClauses.TryAdd(key, new Tuple<string, string>(randomTableName, v));
                    return m;
                }

            }
            catch
            {
                throw new EnreplacedyException(string.Format("Expression '{0}' is not supported", m.ToString()));
            }

            if (m.Type.IsInternalType() && m.Expression.NodeType == ExpressionType.Call)
            {
                CleanDecoder(ValuetoSql(Expression.Lambda(m).Compile().DynamicInvoke()));
                return m;
            }
            throw new EnreplacedyException(string.Format("The member '{0}' is not supported", m.Member.Name));
        }

19 Source : ExperimentController.cs
with MIT License
from AlexanderFroemmgen

[HttpPost]
        public IActionResult Create([FromBody] ExperimentCreateDto requestData)
        {
            /* Performance statistics */
            Stopwatch sw = new Stopwatch();
            sw.Start();

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (requestData.Parameters.Select(p => p.Name).Distinct().Count() != requestData.Parameters.Count)
            {
                return BadRequest("Parameter names are not unique.");
            }

            if (!requestData.Parameters.All(p => p.Values.All(v => ParameterValidator.IsValid(p.Type, v))))
            {
                return BadRequest("Parameter values are not valid.");
            }

            string errMsg = "";
            string msg = "";
            if (!ExecuteLocalMACIScript(requestData.FileName, ref msg, ref errMsg))
            {
                return new ObjectResult(new 
                {
                    Failed = true,
                    Message = msg,
                    ErrorMessage = errMsg
                });
            }

            // Create the experiment.
            var experiment = new Experiment
            {
                Created = DateTime.UtcNow,
                Script = requestData.Script,
                ScriptInstall = requestData.ScriptInstall,
                Parameters = new List<Parameter>(),
                RequiredCapabilities = requestData.RequiredCapabilities,
                Language = requestData.Language,
                PermutationFilter = requestData.PermutationFilter,
                Repereplacedions = requestData.Repereplacedions,
                RunName = requestData.RunName,
                FileName = requestData.FileName,
                Timeout = 60 // in minutes 
            };

            // Create parameters and parameter values.
            foreach (var parameterDto in requestData.Parameters)
            {
                var experimentParam = new Parameter
                {
                    Name = parameterDto.Name,
                    Type = parameterDto.Type,
                    Purpose = parameterDto.Purpose,
                    Unit = parameterDto.Unit,
                    Experiment = experiment,
                    Values = new List<ParameterValue>()
                };

                experiment.Parameters.Add(experimentParam);

                foreach (var value in parameterDto.Values)
                {
                    experimentParam.Values.Add(new ParameterValue
                    {
                        Parameter = experimentParam,
                        Value = value
                    });
                }
            }

            AddSeedParameter(experiment, requestData.Seeds);

            // Create one ExperimentInstance for each unique combination of parameters.
            var instances = FindAllInstancePermutations(experiment.Parameters);

            TimeSpan ts = sw.Elapsed;
            Console.WriteLine("Generated " + instances.Count() + " experiment instances in " + String.Format("{0:00}:{1:00}:{2:00}",
                ts.Hours, ts.Minutes, ts.Seconds));

            try
            {
                instances = FilterPermutations(instances, experiment.PermutationFilter);
            }
            catch (Exception e)
            {
                return BadRequest(e.Message);
            }

            ts = sw.Elapsed;
            Console.WriteLine("Filtered to " + instances.Count() + " experiment instances in " + String.Format("{0:00}:{1:00}:{2:00}",
                ts.Hours, ts.Minutes, ts.Seconds));

            instances = DuplicateExperimentInstances(instances, requestData.Repereplacedions);

            if (!instances.Any())
            {
                return BadRequest("No experiment instances generated after filtering and duplicating.");
            }

            if(requestData.TestRun)
            {
                instances = instances.Take(1).ToList();
                instances.ForEach(i => i.Priority = 100);
                experiment.RunName = "TEST: " + experiment.RunName;
            }

            experiment.ExperimentInstances = instances;

            // Add everything to the database.
            _context.Add(experiment);
            _context.SaveChanges();


            /* Event logging */
            TimeSpan totalTime = sw.Elapsed;
            _context.Add(new GlobalEventLogMessage
            {
                Message = String.Format("Created Experiment {0:0} with {1:0} instances in {2:00}:{3:00}:{4:00}",
                    experiment.Id,
                    experiment.ExperimentInstances.Count(),
                    totalTime.Hours,
                    totalTime.Minutes,
                    totalTime.Seconds),
                ExperimentId = experiment.Id,
                Time = DateTime.Now,
                Type = GlobalEventLogMessageType.Info,
                ExperimentInstanceId = -1
            });
            _context.SaveChanges();


            /* Create folder and copy relevant files (persistent snapshot) 
             * after storing in database (storing generates the experimentId) */
            CreatePersistentSnapshotFolder(experiment);

            _scalingService.Scale(experiment);

            return new ObjectResult(new
            {
                ExperimentId = experiment.Id,
                ExperimentInstanceId = experiment.ExperimentInstances.First().Id
            });
        }

19 Source : PaginatedList.cs
with MIT License
from AlexanderFroemmgen

public static PaginatedList<T> Create(IEnumerable<T> source, int pageIndex, int pageSize)
        {
            var count = source.Count();
            var items = source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return new PaginatedList<T>(items, count, pageIndex, pageSize);
        }

19 Source : point-of-interest.cs
with MIT License
from AlexChesser

static List<POIDetails> findNearest(double lat, double lng) {
        // a = lat - distances[i][0] 
        // b = lng - distances[i][1] 
        // distance = a + b
        List<POIDetails> poi_details = new List<POIDetails>();
        for(int i = 0; i < distances.Count; i++)
        {
            // get the drviver details value
            // compare against the 3 previous max values
            // throw away if not greater than. 
            poi_details.Add(new POIDetails {
                distance = getDistance(distances[i][0], lat, distances[i][1], lng),
                rating = ratings[i]
            });
            // if the distance isn't in the top three throw it away. 
        }
        return poi_details
            .OrderBy(dd => dd.distance)
            .ThenByDescending(dd => dd.rating)
            .Take(3)
            .ToList();
    }

19 Source : HistoryManager.cs
with MIT License
from alexleen

public void Save(string value)
            {
                HistoricalValue newValue = new HistoricalValue { LastUsage = DateTime.UtcNow, Value = value };

                List<HistoricalValue> values = new List<HistoricalValue> { newValue };

                History history = Read();

                if (history == null)
                {
                    history = new History { Values = values.ToArray() };
                }
                else
                {
                    values.AddRange(history.Values);
                    history.Values = values.Distinct().OrderByDescending(p => p.LastUsage).Take(mLimit).ToArray();
                }

                Save(history);
            }

19 Source : Gomoku.cs
with MIT License
from alexyakunin

private GomokuGameEndingKind GetGameEnding(CharBoard board, GomokuMove lastMove)
        {
            var marker = GetPlayerMarker(lastMove.PlayerIndex);
            int Count(int dr, int dc)
                => Enumerable.Range(0, 5)
                    .Select(i => board[lastMove.Row + dr * i, lastMove.Column + dc * i])
                    .TakeWhile(c => c == marker)
                    .Take(5)
                    .Count();
            int SymmetricCount(int dr, int dc)
                => Count(dr, dc) + Count(-dr, -dc) - 1;
            bool IsWin(int dr, int dc)
                => SymmetricCount(dr, dc) >= 5;

            if (IsWin(0, 1) || IsWin(1, 0) || IsWin(1, 1) || IsWin(-1, 1))
                return GomokuGameEndingKind.Win;
            if (board.Cells.All(c => c != ' '))
                return GomokuGameEndingKind.Draw;
            return GomokuGameEndingKind.None;
        }

19 Source : SampleLauncher.cs
with MIT License
from AliakseiFutryn

static void CheckSingletonInMulreplacedhreadingMode()
		{
			Thread[] threads = new Thread[ThreadsCount];
			Meeting[] meetings = new Meeting[ThreadsCount];
			EventWaitHandle threadsFinishedEvent = new EventWaitHandle(false, EventResetMode.AutoReset);
			using (Barrier startBarrier = new Barrier(ThreadsCount), finishBarrier = new Barrier(ThreadsCount, barrier => threadsFinishedEvent.Set()))
			{
				for (int index = 0; index < ThreadsCount; index++)
				{
					threads[index] = new Thread(threadIndex =>
					{
						// Synchronizes all threads before start.
						startBarrier.SignalAndWait();
						try
						{
							int currentIndex = (int)threadIndex;
							meetings[currentIndex] = currentIndex >= ThreadsCount / 2 ? DoubleCheckedSingleton<Meeting>.Instance : LazySingleton<Meeting>.Instance;
						}
						catch (Exception ex)
						{
							Console.WriteLine(ex.Message);
						}
						finally
						{
							// Synhronizes all threads before finish.
							finishBarrier.SignalAndWait();
						}
					});
					threads[index].Start(index);
				}

				threadsFinishedEvent.WaitOne();
				Meeting lazySingletonInstance = LazySingleton<Meeting>.Instance;
				Meeting doubleCheckedSingletonInstance = DoubleCheckedSingleton<Meeting>.Instance;

				// There is an operation which is responsible for increasing some value of nearly
				// created instances and then it should be compared with all other instances which
				// were created in different threads.
				lazySingletonInstance.ParticipantsCount++;
				doubleCheckedSingletonInstance.ParticipantsCount++;

				Console.WriteLine("The participants count are equal in both instances of singleton: {0}", meetings.Take(ThreadsCount / 2).All(m => m.ParticipantsCount == lazySingletonInstance.ParticipantsCount));
				Console.WriteLine("The participants count are equal in both instances of singleton: {0}", meetings.Skip(ThreadsCount / 2).All(m => m.ParticipantsCount == lazySingletonInstance.ParticipantsCount));
			}
		}

19 Source : ConfigurationResolver.cs
with MIT License
from aliencube

public static string GetBasePath(IConfiguration environmentVariables)
        {
            var location = replacedembly.GetExecutingreplacedembly().Location;
            var segments = location.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries).ToList();
            var basePath = string.Join(Path.DirectorySeparatorChar.ToString(), segments.Take(CountDirectories(segments)));

            if (!OperatingSystem.IsWindows())
            {
                basePath = $"/{basePath}";
            }
#if NETFRAMEWORK
            var scriptRootPath = environmentVariables.GetValue<string>("AzureWebJobsScriptRoot");
            if (!string.IsNullOrWhiteSpace(scriptRootPath))
            {
                basePath = scriptRootPath;
            }
#endif
            return basePath;
        }

19 Source : GridifyExtensionsShould.cs
with MIT License
from alirezanet

[Fact]
      public void ApplyEverything_EmptyGridifyQuery()
      {
         var gq = new GridifyQuery();

         var actual = _fakeRepository.AsQueryable()
            .ApplyFilteringOrderingPaging(gq)
            .ToList();

         var expected = _fakeRepository.Skip(0).Take(GridifyExtensions.DefaultPageSize).ToList();

         replacedert.Equal(expected.Count, actual.Count);
         replacedert.Equal(expected, actual);
         replacedert.True(actual.Any());
      }

19 Source : GridifyExtensionsShould.cs
with MIT License
from alirezanet

[Fact]
      public void ApplyPaging_UsingDefaultValues()
      {
         var gq = new GridifyQuery();
         var actual = _fakeRepository.AsQueryable()
            .ApplyPaging(gq)
            .ToList();

         // just returning first page with default size 
         var expected = _fakeRepository.Take(GridifyExtensions.DefaultPageSize).ToList();

         replacedert.Equal(expected.Count, actual.Count);
         replacedert.Equal(expected, actual);
         replacedert.True(actual.Any());
      }

See More Examples