public int ModifLikeProduit(List<string> aData)
 {
     DataSet DsJson = new DataSet();
     MyCo NewCo = new MyCo();
     NewCo.UpdateLikeProduit(aData.IndexOf(aData.Last()).ToString(),aData.Last(),ref DsJson);
     return aData.IndexOf(aData.Last());
 }
Example #2
0
        public void HandleInput(List<Keys> input)
        {
            if (input.IndexOf(Keys.Left) > -1)
            {
                MoveLeftIfPossible();
            }

            if (input.IndexOf(Keys.Right) > -1)
            {
                MoveRightIfPossible();
            }

            if (input.IndexOf(Keys.PageDown) > -1)
            {
                field.RotateBlockRight();
            }

            if (input.IndexOf(Keys.PageUp) > -1)
            {
                field.RotateBlockLeft();
            }

            if (input.IndexOf(Keys.Space) > -1)
            {
                field.FixBlock();
            }
        }
        public static List<Scraper> GetScrapers(bool allowIgnored = false)
        {
            loadScrapers();

            List<string> scraperPriorities = new List<string>(EmulatorsCore.Options.ReadOption(o => o.ScraperPriorities).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
            List<string> ignoredScraperIds = new List<string>();
            if (!allowIgnored)
            {
                ignoredScraperIds.AddRange(EmulatorsCore.Options.ReadOption(o => o.IgnoredScrapers).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
            }

            List<Scraper> scrapers = new List<Scraper>();
            foreach (Scraper scraper in allScrapers)
            {
                if (allowIgnored || !ignoredScraperIds.Contains(scraper.IdString))
                {
                    if (!scraperPriorities.Contains(scraper.IdString))
                        scraperPriorities.Add(scraper.IdString);
                    scrapers.Add(scraper);
                }
            }

            scrapers.Sort((Scraper s, Scraper t) =>
            {
                return scraperPriorities.IndexOf(s.IdString).CompareTo(scraperPriorities.IndexOf(t.IdString));
            });
            return scrapers;
        }
Example #4
0
        public bool IsValid(string s)
        {
            List<char> lefts = new List<char>() { '(', '[', '{' };
            List<char> rights = new List<char>() { ')', ']', '}' };

            Stack<char> charStack = new Stack<char>();
            foreach (char c in s)
            {

                if (lefts.IndexOf(c) > -1)
                {
                    charStack.Push(c);
                }
                else
                {
                    if (charStack.Count == 0)
                    {
                        return false;
                    }
                    char pop = charStack.Pop();
                    if (lefts.IndexOf(pop) == rights.IndexOf(c))
                    {
                        continue;
                    }
                    return false;
                }
            }
            if (charStack.Count != 0) return false;

            return true;
        }
    public List<float> AssignWidthToPoints(List<Vertex> path, float minWidth)
    {
        List<float> sumOfPointNeighb = new List<float>();
        float totalSum = 0;
        float maxSum = 0;
        foreach (Vertex v in path)
        {
            sumOfPointNeighb.Add(ftm.GetSumFromNeighbourhood(v.x, v.z, 2 * (int)minWidth));
            totalSum += sumOfPointNeighb[path.IndexOf(v)];
            if(sumOfPointNeighb[path.IndexOf(v)] > maxSum){
                maxSum = sumOfPointNeighb[path.IndexOf(v)];
            }
        }
        float averageSum = totalSum / sumOfPointNeighb.Count;

        List<float> finalWidthValues = new List<float>();
        //Debug.Log("-------------");
        foreach (float f in sumOfPointNeighb)
        {
            float value = minWidth + minWidth/2 * (maxSum - f) / maxSum;
            finalWidthValues.Add(value);
            //Debug.Log(value);
            //finalWidthValues.Add(minWidth);
        }

        return finalWidthValues;
    }
Example #6
0
 public int ambiguous(string[] dictionary)
 {
     List<string> list = new List<string>();
     List<int> count = new List<int>();
     int res = 0;
     for (int a = 0; a < dictionary.Length; a++)
     {
         if (!list.Contains(dictionary[a]))
         {
             list.Add(dictionary[a]);
             count.Add(1);
         }
         else
             count[list.IndexOf(dictionary[a])]++;
         for (int b = 0; b < dictionary.Length; b++)
         {
             string temp = dictionary[a] + dictionary[b];
             if (a == b)
                 continue;
             if (!list.Contains(temp))
             {
                 list.Add(temp);
                 count.Add(1);
             }
             else
                 count[list.IndexOf(temp)]++;
         }
     }
     for (int c = 0; c < count.Count; c++)
     {
         if (count[c] > 1)
             res++;
     }
     return res;
 }
        void Start()
        {
            if (instance != null)
                throw new Exception("Error: multiple LocationGraphs present");
            instance = this;

            locations = new List<Location>();

            Component[] components = this.gameObject.GetComponents(typeof(Edge));
            Edge[] edges = new Edge[components.Length];
            for (int i = 0; i < components.Length; i++) {
                edges[i] = (Edge) components[i];

                if (!locations.Contains(edges[i].one))
                    locations.Add(edges[i].one);
                if (!locations.Contains(edges[i].two))
                    locations.Add(edges[i].two);
            }

            graph = new bool[locations.Count, locations.Count];
            for (int i = 0; i < graph.GetLength(0); i++) {
                for (int j = 0; j < graph.GetLength(1); j++) {
                    graph[i,j] = inverse;
                }
            }

            foreach (Edge edge in edges) {
                int indexOne = locations.IndexOf(edge.one);
                int indexTwo = locations.IndexOf(edge.two);

                graph[indexOne, indexTwo] = !inverse;
                graph[indexTwo, indexOne] = !inverse;
            }
        }
Example #8
0
        void InitDB(String strCmpactDBFilePath, DbInteractiveArgs InitSqliteArgs)
        {
            try
            {
                DbInteractiveArgs args = InitSqliteArgs;
                args.Database = strCmpactDBFilePath;
                args.ThisDbConnection.ConnectionString = String.Format("data source={0}", strCmpactDBFilePath);

                bool b = this.Connect(args);
                if (b)
                {
                    List <String> AllTableNames = GetAllTableNames(args);
                    int           nIndex        = -1;
                    nIndex = (int)AllTableNames?.IndexOf(DefaultTable);
                    int nUpperIndex = (int)AllTableNames?.IndexOf(DefaultTable.ToUpper());
                    if (nIndex == -1 && nUpperIndex == -1)
                    {
                        CreateKeyValueTable(DefaultTable, args);
                    }

                    Console.WriteLine("已经成功连接数据库");
                }
                else
                {
                    Console.WriteLine("未能连接数据库");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
		public void Update(List<Hearthstone.Card> cards, bool reset)
		{
			try
			{
				if(reset)
				{
					_animatedCards.Clear();
					ItemsControl.Items.Clear();
				}
				var newCards = new List<Hearthstone.Card>();
				foreach(var card in cards)
				{
					var existing = _animatedCards.FirstOrDefault(x => AreEqualForList(x.Card, card));
					if(existing == null)
						newCards.Add(card);
					else if(existing.Card.Count != card.Count || existing.Card.HighlightInHand != card.HighlightInHand)
					{
						var highlight = existing.Card.Count != card.Count;
						existing.Card.Count = card.Count;
						existing.Card.HighlightInHand = card.HighlightInHand;
						existing.Update(highlight).Forget();
					}
					else if(existing.Card.IsCreated != card.IsCreated)
						existing.Update(false).Forget();
				}
				var toUpdate = new List<AnimatedCard>();
				foreach(var aCard in _animatedCards)
				{
					if(!cards.Any(x => AreEqualForList(x, aCard.Card)))
						toUpdate.Add(aCard);
				}
				var toRemove = new List<Tuple<AnimatedCard, bool>>();
				foreach(var card in toUpdate)
				{
					var newCard = newCards.FirstOrDefault(x => x.Id == card.Card.Id);
					toRemove.Add(new Tuple<AnimatedCard, bool>(card, newCard == null));
					if(newCard != null)
					{
						var newAnimated = new AnimatedCard(newCard);
						_animatedCards.Insert(_animatedCards.IndexOf(card), newAnimated);
						ItemsControl.Items.Insert(_animatedCards.IndexOf(card), newAnimated);
						newAnimated.Update(true).Forget();
						newCards.Remove(newCard);
					}
				}
				foreach(var card in toRemove)
					RemoveCard(card.Item1, card.Item2);
				foreach(var card in newCards)
				{
					var newCard = new AnimatedCard(card);
					_animatedCards.Insert(cards.IndexOf(card), newCard);
					ItemsControl.Items.Insert(cards.IndexOf(card), newCard);
					newCard.FadeIn(!reset).Forget();
				}
			}
			catch(Exception e)
			{
				Log.Error(e);
			}
		}
Example #10
0
		//We currently don't clean White Text, Small Text, Hidden Columns, Rows
		private List<ContentType> RemoveUnsupportedElements(List<ContentType> elementsToClean)
		{
			int index = elementsToClean.IndexOf(ContentType.WhiteText);
			if (index != -1)
			{
				elementsToClean.Remove(elementsToClean[index]);
			}

			index = elementsToClean.IndexOf(ContentType.SmallText);
			if (index != -1)
			{
				elementsToClean.Remove(elementsToClean[index]);
			}

			index = elementsToClean.IndexOf(ContentType.HiddenColumn);
			if (index != -1)
			{
				elementsToClean.Remove(elementsToClean[index]);
			}

			index = elementsToClean.IndexOf(ContentType.HiddenRow);
			if (index != -1)
			{
				elementsToClean.Remove(elementsToClean[index]);
			}

			index = elementsToClean.IndexOf(ContentType.HiddenSheet);
			if (index != -1)
			{
					elementsToClean.Remove(elementsToClean[index]);
			}

			return elementsToClean;
		}
Example #11
0
        static void Main()
        {
            Console.WriteLine("Enter some text to see how many times each word appears:");
            string text = Console.ReadLine();
            string[] textSplitted = text.Split(',', ' ');

            List<string> words = new List<string>();
            List<int> counter = new List<int>();

            for (int i = 0; i < textSplitted.Length; i++)
            {
                string currentWord = textSplitted[i];
                if (currentWord != "")
                {
                    if (words.IndexOf(currentWord) == -1)
                    {
                        words.Add(currentWord);
                        counter.Add(1);
                    }
                    else
                    {
                        int index = words.IndexOf(currentWord);
                        counter[index]++;
                    }
                }
            }

            Console.WriteLine("Letters : Appearances");
            for (int i = 0; i < words.Count; i++)
            {
                Console.WriteLine("{0} - {1}", words[i], counter[i]);
            }
        }
Example #12
0
        public static List<Notices> GetAllNotices(string link)
        {
            string htmlPage = "";
            List<string> NoticeTitles = new List<string>();
            List<string> NoticeDates = new List<string>();
            List<string> NoticeUrl = new List<string>();

            List<Notices> Notices = new List<Notices>();

            using(var client = new WebClient())
            {
                Uri weblink = new Uri(link, UriKind.Absolute);
                htmlPage = client.DownloadString(weblink);
            }

            NoticeTitles = PatternHelper.GetNoticeTitle(htmlPage);
            NoticeDates = PatternHelper.GetNoticeDate(htmlPage);
            NoticeUrl = PatternHelper.GetNoticeLink(htmlPage);

            foreach(var item in NoticeTitles)
            {
                Notices.Add(new Notices {
                    Title = item,
                    Date = NoticeDates[NoticeTitles.IndexOf(item)],
                    Url = NoticeUrl[NoticeTitles.IndexOf(item)]
                });
            }

            return Notices;
        }
Example #13
0
 static void ComputeDistinctStrands(string[] strands, ref int cDistinctStrands, ref string concatenatedDistinctStrands, ref int[] permuation)
     {
     List<string> distinct = new List<string>();
     foreach (string strand in strands)
         {
         if (distinct.IndexOf(strand) < 0)
             distinct.Add(strand);
         } 
     //
     StringBuilder builder = new StringBuilder();
     foreach (string s in distinct)
         {
         if (builder.Length > 0)
             builder.Append('+');
         builder.Append(s);
         }
     concatenatedDistinctStrands = builder.ToString();
     cDistinctStrands = distinct.Count;
     //
     permuation = new int[strands.Length];
     for (int i = 0; i < strands.Length; i++)
         {
         permuation[i] = distinct.IndexOf(strands[i]) + 1;
         }
     }
Example #14
0
    public static void Main()
    {
        List <int> ll = new List<int>();
        string t1;
        int idx1;
        int idx2;
        int ent1;
        int ent2;

        for(int i = 1; i <= 10; i++) {
            ll.Add(i);
        }
        foreach(int i in ll)
            Console.Write("{0} ", i);
        Console.WriteLine();
        while(true) {
            t1 = Console.ReadLine();
            if(t1 == "-999")
                break;
            string[] t2 = t1.Split(' ');
            ent1 = Convert.ToInt32(t2[0]);
            ent2 = Convert.ToInt32(t2[1]);
            idx1 = ll.IndexOf(ent1);
            idx2 = ll.IndexOf(ent2);
            ll.RemoveAt(idx1);
            ll.Insert(idx1, ent2);
            ll.RemoveAt(idx2);
            ll.Insert(idx2, ent1);
            foreach(int i in ll)
                Console.Write("{0} ", i);
            Console.WriteLine();
        }
    }
Example #15
0
        public void HandleInput(List<Keys> input)
        {
            if (input.IndexOf(Keys.Left) > -1)
            {
                field.Move(Movement.Left);
            }

            if (input.IndexOf(Keys.Right) > -1)
            {
                field.Move(Movement.Right);
            }

            if (input.IndexOf(Keys.Space) > -1)
            {
                //field.FixBlock();
            }

            if (input.IndexOf(Keys.PageDown) > -1)
            {
                field.Move(Movement.RotateClockwise);
            }

            if (input.IndexOf(Keys.Delete) > -1)
            {
                field.Move(Movement.RotateCounterClockwise);
            }
        }
        //public PlayerSprite testRemotePlayer = new PlayerSprite();

        public GameContentManager(string localPlayer, List<string> allPlayers, BomberGame game)
        {
            Game = game;
            isGameEnded = false;
            Sprites = new List<Sprite>();
            RemotePlayers = new List<PlayerSprite>();
            LocalPlayer = new PlayerSprite();
            LocalPlayer.GameContentManager = this;
            LocalPlayer.PlayerID = localPlayer;
            int localPlayerNumber = allPlayers.IndexOf(localPlayer);
            LocalPlayer.PlayerIndex = localPlayerNumber;
            LocalPlayer.Controller = new PlayerController();
            LocalPlayer.Controller.Player = LocalPlayer;
            Sprites.Add(LocalPlayer);
            foreach (string s in allPlayers)
            {
                if (s != localPlayer)
                {
                    PlayerSprite player = new PlayerSprite();
                    player.GameContentManager = this;
                    player.PlayerID = s;
                    int playerNumber = allPlayers.IndexOf(s);
                    player.PlayerIndex = playerNumber;
                    Sprites.Add(player);
                    RemotePlayers.Add(player);
                }
            }
        }
Example #17
0
        /// <summary>
        /// Tries to implement the Get [] semantics, but it cuts corners like crazy.
        /// Specifically, it relies on the knowledge that the only Gets used are
        /// keyed on PrincipalID, Email, and FirstName+LastName.
        /// </summary>
        /// <param name="fields"></param>
        /// <param name="values"></param>
        /// <returns></returns>
        public UserAccountData[] Get(string[] fields, string[] values)
        {
            List<string> fieldsLst = new List<string>(fields);
            if (fieldsLst.Contains("PrincipalID"))
            {
                int i = fieldsLst.IndexOf("PrincipalID");
                UUID id = UUID.Zero;
                if (UUID.TryParse(values[i], out id))
                    if (m_DataByUUID.ContainsKey(id))
                        return new UserAccountData[] { m_DataByUUID[id] };
            }
            if (fieldsLst.Contains("FirstName") && fieldsLst.Contains("LastName"))
            {
                int findex = fieldsLst.IndexOf("FirstName");
                int lindex = fieldsLst.IndexOf("LastName");
                if (m_DataByName.ContainsKey(values[findex] + " " + values[lindex]))
                    return new UserAccountData[] { m_DataByName[values[findex] + " " + values[lindex]] };
            }
            if (fieldsLst.Contains("Email"))
            {
                int i = fieldsLst.IndexOf("Email");
                if (m_DataByEmail.ContainsKey(values[i]))
                    return new UserAccountData[] { m_DataByEmail[values[i]] };
            }

            // Fail
            return new UserAccountData[0];
        }
Example #18
0
		List<byte> CreateInputBytes(List<byte> messageBytes)
		{
			var bytes = new List<byte>();
			var previousByte = new byte();
			messageBytes.RemoveRange(0, messageBytes.IndexOf(0x7E) + 1);
			messageBytes.RemoveRange(messageBytes.IndexOf(0x3E), messageBytes.Count - messageBytes.IndexOf(0x3E));
			foreach (var b in messageBytes)
			{
				if ((b == 0x7D) || (b == 0x3D))
				{ previousByte = b; continue; }
				if (previousByte == 0x7D)
				{
					previousByte = new byte();
					if (b == 0x5E)
					{ bytes.Add(0x7E); continue; }
					if (b == 0x5D)
					{ bytes.Add(0x7D); continue; }
				}
				if (previousByte == 0x3D)
				{
					previousByte = new byte();
					if (b == 0x1E)
					{ bytes.Add(0x3E); continue; }
					if (b == 0x1D)
					{ bytes.Add(0x3D); continue; }
				}
				bytes.Add(b);
			}
			return bytes;
		}
Example #19
0
        //Plays an animation from a given list of Texture2D's
        public void Animate(List<Texture2D> textures, float time, float animationRate)
        {
            //Keep track of the elapsed time
            if (animationTime == null)
            {
                animationTime = time;
            }
            else
            {
                animationTime += time;
            }

            //The given animation rate determines when we switch to the next texture in the list
            if (animationTime > animationRate / textures.Count)
            {
                //Switch to the next texture in the list, or the first texture if we're at the end.
                if (textures.IndexOf(texture) < textures.Count - 1)
                {
                    texture = textures[textures.IndexOf(texture) + 1];
                }
                else
                {
                    texture = textures[0];
                }

                //Reset the elapsed time
                animationTime = 0;
            }
        }
Example #20
0
        public void HandleInput(List<Keys> input)
        {
            if (input.IndexOf(Keys.Left) > -1)
            {
                MoveLeftIfPossible();
            }

            if (input.IndexOf(Keys.Right) > -1)
            {
                MoveRightIfPossible();
            }

            if (input.IndexOf(Keys.Space) > -1)
            {
                field.FixBlock();
            }
            if (input.IndexOf(Keys.A) > -1)
            {
                currentBlock.RotateLeft();
            }

            if (input.IndexOf(Keys.D) > -1)
            {
                currentBlock.RotateRight();
            }
        }
    static void Main()
    {
        string number = Console.ReadLine();

        List<string> digits = new List<string>();

        for (char i = 'A'; i <= 'Z'; i++)
            digits.Add(i.ToString());

        for (char i = 'a'; i <= 'f'; i++)
            for (char j = 'A'; j <= 'Z'; j++)
                digits.Add(i.ToString() + j.ToString());

        if (number.Length == 1)
        {
            Console.WriteLine(digits.IndexOf(number[0].ToString()));
            return;
        }

        long result = 0, pow = 0;

        for (int i = number.Length - 1; i >= 0; i--)
        {
            // Example with number aFG...

            string left = number[i - 1].ToString(); // Found: F
            string right = number[i].ToString(); // Found: G

            if (i - 2 >= 0 && char.IsLower(number[i - 2])) // Check: aFG
            {
                left = number[i - 2] + "" + number[i - 1]; // Correct numbers: aF and G
                i--;
            }

            int index = digits.IndexOf(left + right); // Finds only numbers from type aF, bG, pL, etc...

            if (index != -1)
            {
                // Found one number
                result += index * (long)Math.Pow(168, pow++);
            }
            else
            {
                // There are two numbers, example: FG => calculates its values
                result += digits.IndexOf(right) * (long)Math.Pow(168, pow++) +
                          digits.IndexOf(left) * (long)Math.Pow(168, pow++);
            }

            i--;

            if (i - 1 == 0)
            {
                // Only one number left
                result += digits.IndexOf(number[0].ToString()) * (long)Math.Pow(168, pow);
                break;
            }
        }

        Console.WriteLine(result);
    }
Example #22
0
 public static long Jump(Dictionary<int, List<int>> cluspos, long currentpos, List<int> peaks, int[] peakclus, ref int nextvalue, ref int currentposs)
 {
     long startpos = currentpos / 2;
     int pos = (int)startpos / 512;
     if (nextvalue < peaks[currentposs])
         nextvalue = peaks[currentposs];
     if(nextvalue - pos > 0)
     {
         if(nextvalue - pos < 50)//pretty close
         {
             pos = nextvalue;
         }
     }
     else
     {
         currentposs++;
     }
     int index = peaks.IndexOf(pos);
     
     if (index != -1)
     {
         index = peakclus[index];
         Random r = new Random();
         if (r.Next(0, 100) > 25)//25% jump
         {
             int random = r.Next(0, cluspos[index].Count);
             int loc = cluspos[index][random];
             currentposs = peaks.IndexOf(loc);
             return (long)(loc * 512 * 2);
         }
     }
     return currentpos;
 }
Example #23
0
        public EditCustomerInformationModel(Customer customer, IEnumerable<Country> countries)
        {
            Firstname = customer.Firstname;
            Lastname = customer.Lastname;
            Email = customer.Email;
            //Birthday = customer.Birthday ?? DateTime.MinValue;
            SelectedGenderType = (int) customer.Gender;

            AvailableCountries = countries.Select(x => new SelectListItem { Selected = x.Name.Trim() == customer.Country.Trim(), Text = x.Name.Trim(), Value = x.Name.Trim() }).ToList();
            AvailableCountries.Insert(0, new SelectListItem { Selected = false, Text = "I'd rather not say", Value = string.Empty });

            Genders = new List<SelectListItem>();
            Genders.Add(new SelectListItem { Selected = false, Text = "I'd rather not say", Value = "0" });
            Genders.Add(new SelectListItem { Selected = false, Text = GenderTypeEnum.Male.ToString(), Value = ((int)GenderTypeEnum.Male).ToString() });
            Genders.Add(new SelectListItem { Selected = false, Text = GenderTypeEnum.Female.ToString(), Value = ((int)GenderTypeEnum.Female).ToString() });

            SelectedBirthDate = (customer.Birthday.HasValue) ? customer.Birthday.Value.Day : 0;
            SelectedBirthMonth = (customer.Birthday.HasValue) ? customer.Birthday.Value.Month : 0;
            SelectedBirthYear = (customer.Birthday.HasValue) ? customer.Birthday.Value.Year : 1970;

            BirthDate = new List<SelectListItem>{ new SelectListItem { Selected = false, Text = "Day", Value = "0" } };
            BirthDate.AddRange(Enumerable.Range(1, 31).Select(x => new SelectListItem { Selected = x == SelectedBirthDate, Text = x.ToString(), Value = x.ToString() }).ToList());

            var months = new List<string> { "Month", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
            BirthMonth = new List<SelectListItem>();
            months.ForEach(x => BirthMonth.Add(new SelectListItem { Selected = months.IndexOf(x) == SelectedBirthMonth, Text = x, Value = months.IndexOf(x).ToString() }));
        }
Example #24
0
        static void Main()
        {
            Console.WriteLine("Enter some text to see how many times each letter appears:");
            string text = Console.ReadLine();

            List<char> letters = new List<char>();
            List<int> counter = new List<int>();

            for (int i = 0; i < text.Length; i++)
            {
                char currentLetter = text[i];
                if (currentLetter != ' ')
                {
                    if (letters.IndexOf(currentLetter) == -1)
                    {
                        letters.Add(currentLetter);
                        counter.Add(1);
                    }
                    else
                    {
                        int index = letters.IndexOf(currentLetter);
                        counter[index]++;
                    }
                }
            }

            Console.WriteLine("Letters : Appearances");
            for (int i = 0; i < letters.Count; i++)
            {
                Console.WriteLine("{0} - {1}", letters[i], counter[i]);
            }
        }
        static bool count(int currentSum, int targetSum, int amountNums, int currentNumber, int prevNumber, List<int> subSetSum0, List<int> set, bool isFristPass)
        {
            if (currentSum + currentNumber == targetSum)
            {
                set[set.IndexOf(currentNumber)] = 0;
                subSetSum0.Add(currentNumber);
                return true;
            }
            else
            {
                for (int i = amountNums; i > 0; i--)
                {
                    if (count(currentSum + currentNumber, targetSum, i - 1, set[i - 1], currentNumber, subSetSum0, set, false) == true)
                    {
                        try
                        {
                            set[set.IndexOf(currentNumber)] = 0;
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            return false;
                        }
                        subSetSum0.Add(currentNumber);
                        if (isFristPass == false)
                            return true;
                    }

                }
            }

            return false;
        }
Example #26
0
        internal static List<Block> CheckPostImport(List<Block> ret)
        {
            if (ret == null) return null;

            var lastImport = ret.LastOrDefault(r => r is Model.Import);
            var firstNonImport = ret.FirstOrDefault(r => !(r is Model.Import));

            if (lastImport == null || firstNonImport == null)
            {
                return ret;
            }

            var lix = ret.IndexOf(lastImport);
            var fnix = ret.IndexOf(firstNonImport);

            if (lix != -1 && fnix != -1)
            {
                if (fnix < lix)
                {
                    for (int i = fnix; i < ret.Count; i++)
                    {
                        if (ret[i] is Model.Import)
                        {
                            Current.RecordWarning(ErrorType.Parser, ret[i], "@import should appear before any other statements.  Statement will be moved.");
                        }
                    }
                }
            }

            return ret;
        }
Example #27
0
        static void Main()
        {
            Console.WriteLine("Enter a word:");
            string word = Console.ReadLine();

            List<string> words = new List<string> {
                             ".NET",
                             "CLR",
                             "namespace"
                             };

            List<string> explanations = new List<string> {
                                    "platform for applications from Microsoft",
                                    "managed execution environment for .NET",
                                    "hierarchical organization of classes"
                                    };

            if (words.IndexOf(word) != -1)
            {
                Console.WriteLine("{0} - {1}", word, explanations[words.IndexOf(word)]);
            }
            else
            {
                Console.WriteLine("Sorry, but there is no description of this word!");
            }
        }
Example #28
0
 public int GetGameScore(List<Frame> frames)
 {
     AddTwoSinteticRolls(frames);
     var gameFrames = frames.Take(10).ToList();
     var simpeRollsSum = gameFrames.Where(frame => frame.IsSimple).Sum(frame => frame.FrameSum);
     var spareRollsSum = gameFrames.Where(frame => frame.IsSpare).Sum(frame => frame.FrameSum + frames[frames.IndexOf(frame) + 1].FirstRoll);
     var strikeRollsSum = gameFrames.Where(frame => frame.IsStrike).SelectMany(frame => frames.Skip(frames.IndexOf(frame)).Take(3)).Sum(frame => frame.FrameSum);
     return simpeRollsSum + spareRollsSum + strikeRollsSum;
 }
Example #29
0
    public static void Main (string[] args) {
      var list = new List<Enum1> { Enum1.Value0, Enum1.Value1, Enum1.Value0, (Enum1)3 };

      Console.WriteLine(list.IndexOf(Enum1.Value0));
      Console.WriteLine(list.IndexOf(Enum1.Value1));
      Console.WriteLine(list.IndexOf((Enum1)2));

      // Other overloads not implemented yet
    }
Example #30
0
 private static void AddResult(List<int> numbers, List<int> result, int i)
 {
     if (numbers.IndexOf(i) > -1)
     {
         result.Add(i);
         numbers.RemoveRange(0, numbers.IndexOf(i) + 1);
         AddResult(numbers, result, i);
     }
 }
        static void Main(string[] args)
        {
            string text = Console.ReadLine();
            List<string> letters = new List<string>();
            for (char i = 'A'; i <= 'Z'; i++)
            {
                letters.Add(i.ToString());
            }
            for (char j = 'a'; j <= 'f'; j++)
            {
                for (char i = 'A'; i <= 'Z'; i++)
                {
                    letters.Add(j.ToString() + i);
                }
            }

            int power = 0;
            BigInteger result = 0;
            string concatenation = "";
            int index = 0;
            for (int i = text.Length - 1; i >= 0; i--)
            {
                if (i > 0)
                {
                    if (char.IsUpper(text[i]) && char.IsLower(text[i - 1]))
                    {
                        concatenation = text[i - 1].ToString() + text[i];
                        index = letters.IndexOf(concatenation);
                        if (index >= 0)
                        {
                            result = Power(power) * index + result;
                            power++;
                            concatenation = "";
                            i--;
                        }

                    }
                    else
                    {

                        index = letters.IndexOf(text[i].ToString());
                        result = Power(power) * index + result;
                        power++;

                    }
                }

                else if (i == 0)
                {
                    index = letters.IndexOf(text[i].ToString());
                    result = Power(power) * index + result;
                    power++;
                }

            }
            Console.WriteLine(result);
        }
Example #32
0
        public bool IsSubscriptionRegistered(Type serviceDelegateType)
        {
            if (localSharedInterfaceTypes?.IndexOf(serviceDelegateType) >= 0)
            {
                return(true);
            }

            if (manualManagedServiceInterfaceTypes != null &&
                manualManagedServiceInterfaceTypes.Contains(serviceDelegateType))
            {
                return(true);
            }

            return(false);
        }
Example #33
0
 public static void AddRayMarchingShape(RayMarchingShape shape)
 {
     if (_shapes?.IndexOf(shape) < 0)
     {
         _shapes.Add(shape);
     }
 }
Example #34
0
        protected override void RankSeriesEpisodeSubtitleMatch(SubtitleInfo subtitleSearch, List <string> languages)
        {
            subtitleSearch.MatchPercentage = 100;
            int languageRank = languages?.IndexOf(subtitleSearch.Language) ?? -1;

            if (languageRank >= 0)
            {
                subtitleSearch.LanguageMatchRank = languageRank;
            }
        }
Example #35
0
 public static Dictionary <string, ControlData> SelectableSourceOptions(
     SiteSettings ss, IEnumerable <string> columns, string labelType = null, List <string> order = null)
 {
     return(columns.ToDictionary(
                columnName => columnName,
                columnName => SelectableOptionsControlData(
                    ss: ss,
                    columnName: columnName,
                    labelType: labelType,
                    order: order?.IndexOf(columnName))));
 }
Example #36
0
        /// <summary>
        /// Ranks movie subtitle matches.
        /// </summary>
        /// <param name="subtitleSearch">Subtitle search result</param>
        protected virtual void RankMovieSubtitleMatch(SubtitleInfo subtitleSearch, List <string> languages)
        {
            int matchPct = 0;

            var match = _regexTitleYear.Match(CleanMovieTitle(subtitleSearch.Name));

            if (match.Success && (match.Groups["title"].Value.Equals(subtitleSearch.MediaTitle, StringComparison.InvariantCultureIgnoreCase) ||
                                  match.Groups["title"].Value.StartsWith(subtitleSearch.MediaTitle, StringComparison.InvariantCultureIgnoreCase)))
            {
                if (subtitleSearch.Year.HasValue && int.TryParse(match.Groups["year"].Value, out int subYear) && subYear == subtitleSearch.Year.Value)
                {
                    matchPct = BASE_YEAR_MATCH_PCT;
                }
                else if (!subtitleSearch.Year.HasValue || string.IsNullOrEmpty(match.Groups["year"].Value))
                {
                    matchPct = BASE_MATCH_PCT;
                }
            }

            match = _regexMultiPartVideo.Match(subtitleSearch.Name);
            if (match.Success)
            {
                if (!string.IsNullOrEmpty(match.Groups["disc"].Value) && subtitleSearch.MediaFiles.Count > 1)
                {
                    matchPct += MULTIFILE_MATCH_PCT;
                }
                else if (!string.IsNullOrEmpty(match.Groups["disc"].Value) && subtitleSearch.MediaFiles.Count == 1)
                {
                    return;
                }
            }
            else if (subtitleSearch.MediaFiles.Count == 1)
            {
                matchPct += MULTIFILE_MATCH_PCT;
            }
            else if (subtitleSearch.MediaFiles.Count > 1)
            {
                return;
            }

            matchPct = CompareMediaFiles(subtitleSearch, matchPct);
            subtitleSearch.MatchPercentage = Math.Min(matchPct, 100);

            int languageRank = languages?.IndexOf(subtitleSearch.Language) ?? -1;

            if (languageRank >= 0)
            {
                subtitleSearch.LanguageMatchRank = languageRank;
            }
        }
Example #37
0
 public static Dictionary <string, ControlData> SelectableOptions(
     Context context,
     SiteSettings ss,
     IEnumerable <string> columns,
     string labelType    = null,
     List <string> order = null)
 {
     return(columns
            .Distinct()
            .ToDictionary(
                columnName => columnName,
                columnName => SelectableOptionsControlData(
                    context: context,
                    ss: ss?.GetJoinedSs(columnName),
                    columnName: columnName,
                    labelType: labelType,
                    order: order?.IndexOf(columnName))));
 }
Example #38
0
        private static RouteSheet SeparateStartData(List <List <string> > prototype, bool isWeekend)
        {
            var arrayDataBuffer = prototype?.FirstOrDefault()
                                  ?.FirstOrDefault(p => !string.IsNullOrEmpty(p))
                                  ?.Split(' ');
            var nullStringElement  = prototype?.FirstOrDefault(l => l.All(a => string.IsNullOrEmpty(a)));
            var nullStringPosition = prototype?.IndexOf(nullStringElement);
            var fullNameRow        = prototype.Count > (nullStringPosition ?? 0) + 1
                            ? prototype.ElementAt((nullStringPosition ?? 0) + 1)
                            : new List <string> {
                "Ошибочный формат файла"
            };
            var fullName  = fullNameRow.FirstOrDefault(f => f.Trim(' ').Length > 1);
            var shortName = arrayDataBuffer.Length > 1
                          ? arrayDataBuffer[0]
                          : "Ошибочный формат файла";

            return(new RouteSheet(shortName, fullName, isWeekend));
        }
Example #39
0
        public static string ToSpecId(this EcmaDesc desc, List <string> knownTypeParamsOnType = null, List <string> knownTypeParamsOnMember = null)
        {
            if (desc == null)
            {
                return(null);
            }
            var typeStr = string.IsNullOrEmpty(desc.Namespace) ? desc.TypeName : desc.Namespace + "." + desc.TypeName;

            if (desc.GenericTypeArgumentsCount > 0)
            {
                var typeparameterPart = string.Join(",", desc.GenericTypeArguments.Select(ta =>
                {
                    var i = knownTypeParamsOnType?.IndexOf(ta.TypeName);
                    if (i.HasValue && i.Value >= 0)
                    {
                        return($"`{i.Value}");
                    }
                    i = knownTypeParamsOnMember?.IndexOf(ta.TypeName);
                    if (i.HasValue && i.Value >= 0)
                    {
                        return($"``{i.Value}");
                    }
                    return(ta.ToSpecId(knownTypeParamsOnType, knownTypeParamsOnMember));
                }));
                typeStr = string.Format("{0}{{{1}}}", typeStr, typeparameterPart);
            }
            if (desc.ArrayDimensions?.Count > 0)
            {
                for (int i = 0; i < desc.ArrayDimensions?.Count; i++)
                {
                    typeStr = typeStr + "[]";
                }
            }
            if (desc.DescModifier == EcmaDesc.Mod.Pointer)
            {
                typeStr += "*";
            }
            if (desc.NestedType != null)
            {
                typeStr += ("." + desc.NestedType.ToSpecId(knownTypeParamsOnType, knownTypeParamsOnMember));
            }
            return(typeStr);
        }
Example #40
0
        private void Replace <T>(ref List <T> list, T oldValue, T newValue)
        {
            if (oldValue != null && newValue != null)
            {
                var index = list?.IndexOf(oldValue) ?? -1;

                if (index >= 0)
                {
                    list[index] = newValue;
                }
                else
                {
                    Add(ref list, newValue);
                }
            }
            else if (oldValue != null)
            {
                Remove(ref list, oldValue);
            }
            else if (newValue != null)
            {
                Add(ref list, newValue);
            }
        }
Example #41
0
        static void Main(string[] args)
        {
            List <string> localCerts = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.pfx").ToList();

            if (localCerts.Count > 0)
            {
                Console.WriteLine("Which certificate to use?");
                foreach (string localCert in localCerts)
                {
                    Console.WriteLine("{0}.{1}", localCerts.IndexOf(localCert), localCert.Remove(0, localCert.LastIndexOf(@"\") + 1).Replace(".pfx", String.Empty));
                }
                int index = Convert.ToInt32(Console.ReadLine());
                cert    = new X509Certificate2(localCerts[index]);
                subject = cert.Subject.Replace("CN=", String.Empty);
            }
            else
            {
                Console.WriteLine("No certificates found");
                Console.ReadKey();
                return;
            }

            while (true)
            {
                Console.Write("IP: ");
                host = Console.ReadLine();
                Console.Write("PORT: ");
                port   = Convert.ToInt32(Console.ReadLine());
                client = new TcpClient();
                try
                {
                    client.Connect(host, port);  //подключение клиента
                    stream = client.GetStream(); // получаем поток
                    BinaryFormatter             formatter = new BinaryFormatter();
                    Task                        task      = Task.Run(() => ReceiveMessage());
                    Dictionary <string, object> data      = new Dictionary <string, object>();
                    data.Add("command", "authReq");
                    data.Add("subject", subject);
                    formatter.Serialize(stream, data);

                    while (true)
                    {
                        string command = Console.ReadLine();
                        data.Clear();
                        switch (command)
                        {
                        default:
                        {
                            Console.WriteLine("Unknown command");
                            break;
                        }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    Disconnect();
                }
            }
        }
Example #42
0
 /// <summary>
 /// Determines the index of a specific item in the container.
 /// </summary>
 /// <param name="item">The element to locate in this element.</param>
 /// <returns>
 /// The index of <paramref name="item" /> if found in the list; otherwise, -1.
 /// </returns>
 public int IndexOf(IElement item) => Elements?.IndexOf(item) ?? -1;
Example #43
0
 /// <summary>
 /// 検索
 /// </summary>
 /// <param name="item"></param>
 /// <returns></returns>
 public int IndexOf(NakoException item)
 {
     return(_list.IndexOf(item));
 }
Example #44
0
        /*
         * public float GetDistanceFromPoint(int wpIdx, int subWpIdx, Vector3 curPos){	//for creep, not in used yet
         *      List<Vector3> subList=GetWP(wpIdx);
         *      float dist=Vector3.Distance(curPos, subList[subWpIdx]);
         *      for(int i=subWpIdx; i<subList.Count-1; i++){
         *              dist+=Vector3.Distance(subList[i], subList[i+1]);
         *      }
         *      for(int i=wpIdx+1; i<wpSecList.Count; i++){
         *              dist+=Vector3.Distance(wpSecList[i-1].GetExitPoint(), wpSecList[i].GetEntryPoint());
         *              if(wpSecList[i].isPlatform){
         *                      List<Vector3> subPath=wpSecList[i].wpList;
         *                      for(int n=1; n<subPath.Count; n++) dist+=Vector3.Distance(subPath[n-1], subPath[n]);
         *              }
         *      }
         *      return dist;
         * }
         */



        public void RemoveBlockedEntry(Path prevP)
        {
            blockedEntryPoint[prevPath.IndexOf(prevP)] = false;
        }
Example #45
0
 /// <summary>
 /// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1" />.
 /// </summary>
 /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1" />.</param>
 /// <returns>
 /// The index of <paramref name="item" /> if found in the list; otherwise, -1.
 /// </returns>
 public int IndexOf(Attribute item) => _attributes?.IndexOf(item) ?? -1;
Example #46
0
        public void Run(object data)
        {
            while (true)
            {
                //this.LastErrorMessage = null;

                List <Page> pages = new List <Page>();

                try
                {
                    //dashboards
                    List <Page> dashboards = GetDashboards();

                    //WriteLog("Download dashboards", dashboards.Count.ToString());

                    foreach (Page page in dashboards)
                    {
                        this.CurrentPage = page;
                        this.Progress    = "Dashboard: " + (dashboards.IndexOf(page) + 1).ToString() + " of " + dashboards.Count;

                        try
                        {
                            this.DownloadWebPage(page);
                        }
                        catch (Exception ex)
                        {
                            this.LastErrorMessage = ex.Message;

                            Thread.Sleep(this.PageDelay);

                            continue;
                        }

                        this.TotalSize += page.HtmlContent.Length;
                        this.AmountPages++;

                        pages.AddRange(this.OnDashboardLoaded(page));

                        Thread.Sleep(this.PageDelay);
                    }

                    //WriteLog("Process pages", pages.Count.ToString());
                }
                catch (Exception ex)
                {
                    if (this.CurrentPage != null)
                    {
                        //clear labels
                        for (int i = 0; i < pages.Count; i++)
                        {
                            //lock (Labels)
                            //{
                            //    Labels[pages[i].DashboardURL] = string.Empty;
                            //}

                            DBHelpers.SaveLabel(this.Code, pages[i].DashboardURL, string.Empty);
                        }

                        this.LastErrorMessage = string.Format("Failed page: {0};{1}",
                                                              this.GetUrlByDocNumber(this.CurrentPage.DocNumber,
                                                                                     this.CurrentPage.PageNumber,
                                                                                     this.CurrentPage.DashboardID),
                                                              ex.Message);

                        //MessageBox.Show(ex.Message + this.CurrentPage.ToString() + ex.StackTrace);
                    }
                    else
                    {
                        this.LastErrorMessage = ex.Message;
                        //MessageBox.Show(ex.Message + ex.StackTrace);
                    }

                    this.WaitNextUpdate(true);

                    continue;
                }

                try
                {
                    //pages
                    for (int i = 0; i < pages.Count; i++)
                    {
                        Page page = pages[i];

                        this.CurrentPage = page;
                        this.Progress    = "Article: " + (i + 1).ToString() + " of " + pages.Count;

                        this.ProcessPage(pages[0], page);

                        this.TotalSize += page.HtmlContent.Length;
                        this.AmountPages++;

                        while (page.NeedLoadNextPage)
                        {
                            page.PageNumber++;

                            if (page.PageNumber > 5000)
                            {
                                break;
                            }

                            page.URL = GetUrlByDocNumber(page.DocNumber, page.PageNumber, page.DashboardID);

                            this.CurrentPage = page;

                            this.ProcessPage(pages[0], page);

                            if (page.URL != page.RedirectURL) //avoid cycles
                            {
                                break;
                            }

                            this.TotalSize += page.HtmlContent.Length;
                            this.AmountPages++;

                            Thread.Sleep(this.PageDelay);
                        }

                        Thread.Sleep(this.PageDelay);
                    }

                    //WriteLog("Site " + Code + " sleep to ", DateTime.Now.Add(this.SiteDelay).ToString());

                    //this.SaveLabels();

                    this.WaitNextUpdate(false);
                }
                catch (Exception ex)
                {
                    //WriteLog("Exception in site " + Code, ex.Message + ex.StackTrace);
                    //WriteLog("Site " + Code + " sleep to ", DateTime.Now.Add(this.SiteDelay).ToString());

                    if (this.CurrentPage != null)
                    {
                        //clear labels
                        for (int i = pages.IndexOf(this.CurrentPage); i < pages.Count; i++)
                        {
                            //lock (Labels)
                            //{
                            //    Labels[pages[i].DashboardURL] = string.Empty;
                            //}

                            DBHelpers.SaveLabel(this.Code, pages[i].DashboardURL, string.Empty);
                        }

                        this.LastErrorMessage = string.Format("Failed page: {0};{1}",
                                                              this.GetUrlByDocNumber(this.CurrentPage.DocNumber,
                                                                                     this.CurrentPage.PageNumber,
                                                                                     this.CurrentPage.DashboardID),
                                                              ex.Message);

                        //MessageBox.Show(ex.Message + this.CurrentPage.ToString() + ex.StackTrace);
                    }
                    else
                    {
                        this.LastErrorMessage = ex.Message;

                        //MessageBox.Show(ex.Message + ex.StackTrace);
                    }

                    this.WaitNextUpdate(true);
                }
            }
        }
        static void Main(string[] args)
        {
            /*this version take only 66 points! => ToDo must be fix.*/
            List <string> sheduleLessons = Console.ReadLine().Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
            List <string> clearSpace     = new List <string>();

            foreach (var item in sheduleLessons)
            {
                var temp = item.Trim();
                clearSpace.Add(temp);
            }

            string commands = Console.ReadLine();

            while (commands != "course start")
            {
                List <string> splitCommands = commands.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
                string        command       = splitCommands[0];
                if (command == "Add")
                {
                    string lessons = splitCommands[1];
                    if (!clearSpace.Contains(lessons))
                    {
                        clearSpace.Add(lessons);
                    }
                }
                if (command == "Insert")
                {
                    //Insert:Arrays:0
                    string lessons = splitCommands[1];
                    var    index   = int.Parse(splitCommands[2]);
                    if (!clearSpace.Contains(lessons) && index >= 0 && index < clearSpace.Count)
                    {
                        clearSpace.Insert(index, lessons);
                    }
                }
                if (command == "Remove")
                {
                    string lessons = splitCommands[1];
                    if (clearSpace.Contains(lessons))
                    {
                        clearSpace.Remove(lessons);
                    }
                }
                if (command == "Swap")
                {
                    var first  = splitCommands[1];
                    var second = splitCommands[2];

                    if (clearSpace.Contains(first) && clearSpace.Contains(second))
                    {
                        var indexFirst  = clearSpace.IndexOf(first);
                        var indexSecond = clearSpace.IndexOf(second);
                        var lenght      = clearSpace.Count();
                        //Console.WriteLine(lenght);
                        for (int i = 0; i < lenght; i++)
                        {
                            if (i == indexFirst)
                            {
                                clearSpace.Insert(indexFirst, second);
                                clearSpace = clearSpace.Distinct().ToList();
                            }
                            if (i == indexSecond)
                            {
                                clearSpace.Insert(indexSecond, first);
                                clearSpace = clearSpace.Distinct().ToList();
                            }
                        }
                    }
                }
                if (command == "Exercise")
                {
                    string lessons = splitCommands[1];
                    if (!clearSpace.Contains(lessons))
                    {
                        clearSpace.Add(lessons + "-Exercise");
                    }
                }
                commands = Console.ReadLine();
            }
            var count = 1;

            for (int i = 0; i < clearSpace.Count; i++)
            {
                Console.WriteLine($"{count}.{clearSpace[i]}");
                count++;
            }
            //Console.WriteLine(string.Join("\n", clearSpace));


            //Console.WriteLine(string.Join("\n", shedulelessons));
        }
Example #48
0
        /// <summary>
        /// Ranks movie subtitle matches.
        /// </summary>
        /// <param name="subtitleSearch">Subtitle search result</param>
        protected virtual void RankSeriesEpisodeSubtitleMatch(SubtitleInfo subtitleSearch, List <string> languages)
        {
            int    matchPct   = 0;
            string seriesName = null;
            var    match      = _regexDoubleEpisode.Match(subtitleSearch.Name);

            if (match.Success)
            {
                if (int.TryParse(match.Groups["seasonnum"].Value, out var season) &&
                    int.TryParse(match.Groups["episodenum"].Value, out var episode) && int.TryParse(match.Groups["endepisodenum"].Value, out var endEpisode))
                {
                    if (season == subtitleSearch.Season && episode <= subtitleSearch.Episode && endEpisode >= subtitleSearch.Episode)
                    {
                        seriesName = match.Groups["series"].Value;
                    }
                    else
                    {
                        return;
                    }
                }
            }
            else
            {
                match = _regexEpisode.Match(subtitleSearch.Name);
                if (match.Success)
                {
                    if (int.TryParse(match.Groups["seasonnum"].Value, out var season) && int.TryParse(match.Groups["episodenum"].Value, out var episode))
                    {
                        if (season == subtitleSearch.Season && episode == subtitleSearch.Episode)
                        {
                            seriesName = match.Groups["series"].Value;
                        }
                        else
                        {
                            return;
                        }
                    }
                }
            }

            if (!string.IsNullOrEmpty(seriesName))
            {
                var cleanName = CleanSeriesTitle(seriesName);
                match = _regexTitleYear.Match(cleanName);
                if (match.Success && match.Groups["title"].Value.Equals(subtitleSearch.MediaTitle, StringComparison.InvariantCultureIgnoreCase) ||
                    match.Groups["title"].Value.StartsWith(subtitleSearch.MediaTitle, StringComparison.InvariantCultureIgnoreCase))
                {
                    if (subtitleSearch.Year.HasValue && int.TryParse(match.Groups["year"].Value, out int subYear) && subYear == subtitleSearch.Year.Value)
                    {
                        matchPct = BASE_YEAR_MATCH_PCT;
                    }
                    else if (!subtitleSearch.Year.HasValue || string.IsNullOrEmpty(match.Groups["year"].Value))
                    {
                        matchPct = BASE_MATCH_PCT;
                    }
                }
                else if (!match.Success && cleanName.Equals(subtitleSearch.MediaTitle, StringComparison.InvariantCultureIgnoreCase) ||
                         cleanName.StartsWith(subtitleSearch.MediaTitle, StringComparison.InvariantCultureIgnoreCase))
                {
                    matchPct = BASE_MATCH_PCT;
                }
            }

            matchPct = CompareMediaFiles(subtitleSearch, matchPct);
            subtitleSearch.MatchPercentage = Math.Min(matchPct, 100);

            int languageRank = languages?.IndexOf(subtitleSearch.Language) ?? -1;

            if (languageRank >= 0)
            {
                subtitleSearch.LanguageMatchRank = languageRank;
            }
        }
Example #49
0
 public int IndexOf(T item)
 {
     return _internalList.IndexOf(item);
 }
        private static List <Mesh> GetMeshes(SrdFile srd, List <Material> materials)
        {
            var meshList = new List <Mesh>();

            //var treBlocks = srd.Blocks.Where(b => b is TreBlock).ToList();
            var sklBlocks = srd.Blocks.Where(b => b is SklBlock).ToList();
            var mshBlocks = srd.Blocks.Where(b => b is MshBlock).ToList();
            var vtxBlocks = srd.Blocks.Where(b => b is VtxBlock).ToList();

            // For debugging
            //var vtxNameList = new List<string>();
            //var mshNameList = new List<string>();
            //foreach (VtxBlock vtx in vtxBlocks)
            //{
            //    vtxNameList.Add((vtx.Children[0] as RsiBlock).ResourceStringList[0]);
            //}
            //foreach (MshBlock msh in mshBlocks)
            //{
            //    mshNameList.Add((msh.Children[0] as RsiBlock).ResourceStringList[0]);
            //}

            // Iterate through each VTX block simultaneously and extract the data we need
            var extractedData = new List <MeshData>();

            foreach (MshBlock msh in mshBlocks)
            {
                var vtx          = vtxBlocks.Where(b => (b.Children[0] as RsiBlock).ResourceStringList[0] == msh.VertexBlockName).First() as VtxBlock;
                var vtxResources = vtx.Children[0] as RsiBlock;

                // Extract position data
                using BinaryReader positionReader = new BinaryReader(new MemoryStream(vtxResources.ExternalData[0]));
                var curVertexList   = new List <Vector3>();
                var curNormalList   = new List <Vector3>();
                var curTexcoordList = new List <Vector2>();
                var curWeightList   = new List <float>();

                foreach (var section in vtx.VertexDataSections)
                {
                    positionReader.BaseStream.Seek(section.StartOffset, SeekOrigin.Begin);
                    for (int vNum = 0; vNum < vtx.VertexCount; ++vNum)
                    {
                        long oldPos = positionReader.BaseStream.Position;
                        switch (vtx.VertexDataSections.IndexOf(section))
                        {
                        case 0:     // Vertex/Normal data (and Texture UV for boneless models)
                        {
                            Vector3 vertex;
                            vertex.X = positionReader.ReadSingle() * -1.0f;                 // X
                            vertex.Y = positionReader.ReadSingle();                         // Y
                            vertex.Z = positionReader.ReadSingle();                         // Z
                            curVertexList.Add(vertex);

                            Vector3 normal;
                            normal.X = positionReader.ReadSingle() * -1.0f;                 // X
                            normal.Y = positionReader.ReadSingle();                         // Y
                            normal.Z = positionReader.ReadSingle();                         // Z
                            curNormalList.Add(normal);

                            if (vtx.VertexDataSections.Count == 1)
                            {
                                Console.WriteLine($"Mesh type: {vtx.MeshType}");
                                Vector2 texcoord;
                                texcoord.X = float.PositiveInfinity;
                                texcoord.X = positionReader.ReadSingle();                   // U
                                while (float.IsNaN(texcoord.X) || !float.IsFinite(texcoord.X))
                                {
                                    texcoord.X = positionReader.ReadSingle();
                                }
                                texcoord.Y = positionReader.ReadSingle();                   // V, invert for non-glTF exports
                                while (float.IsNaN(texcoord.Y) || !float.IsFinite(texcoord.Y))
                                {
                                    texcoord.Y = positionReader.ReadSingle();
                                }

                                if (float.IsNaN(texcoord.X) || float.IsNaN(texcoord.Y) || Math.Abs(texcoord.X) > 1 || Math.Abs(texcoord.Y) > 1)
                                {
                                    Console.WriteLine($"INVALID UVs DETECTED!");
                                }
                                curTexcoordList.Add(texcoord);
                            }
                        }
                        break;

                        case 1:                                                           // Bone weights?
                        {
                            var weightsPerVert = (section.SizePerVertex / sizeof(float)); // TODO: Is this always 8?
                            for (int wNum = 0; wNum < weightsPerVert; ++wNum)
                            {
                                curWeightList.Add(positionReader.ReadSingle());
                            }
                        }
                        break;

                        case 2:     // Texture UVs (only for models with bones)
                        {
                            Vector2 texcoord;
                            texcoord.X = positionReader.ReadSingle();                       // U
                            texcoord.Y = positionReader.ReadSingle();                       // V, invert for non-glTF exports
                            curTexcoordList.Add(texcoord);
                        }
                        break;

                        default:
                            Console.WriteLine($"WARNING: Unknown vertex sub-block index {vtx.VertexDataSections.IndexOf(section)} is present in VTX block {vtxBlocks.IndexOf(vtx)}!");
                            break;
                        }

                        // Skip data we don't currently use, though I may add support for this data later
                        long remainingBytes = section.SizePerVertex - (positionReader.BaseStream.Position - oldPos);
                        positionReader.BaseStream.Seek(remainingBytes, SeekOrigin.Current);
                    }
                }

                // Extract index data
                using BinaryReader indexReader = new BinaryReader(new MemoryStream(vtxResources.ExternalData[1]));
                var curIndexList = new List <ushort[]>();
                while (indexReader.BaseStream.Position < indexReader.BaseStream.Length)
                {
                    ushort[] indices = new ushort[3];
                    for (int i = 0; i < 3; ++i)
                    {
                        ushort index = indexReader.ReadUInt16();
                        // We need to reverse the order of the indices to prevent the normals
                        // from becoming permanently flipped due to the clockwise/counter-clockwise
                        // order of the indices determining the face's direction
                        indices[3 - (i + 1)] = index;
                    }
                    curIndexList.Add(indices);
                }

                // Add the extracted data to our list
                extractedData.Add(new MeshData(curVertexList, curNormalList, curTexcoordList, curIndexList, vtx.BindBoneList, curWeightList));
            }

            // Now that we've extracted the data we need, convert it to Assimp equivalents
            for (int d = 0; d < extractedData.Count; ++d)
            {
                MeshData meshData     = extractedData[d];
                var      msh          = mshBlocks[d] as MshBlock;
                var      mshResources = msh.Children[0] as RsiBlock;

                Mesh mesh = new Mesh()
                {
                    Name          = mshResources.ResourceStringList[0],
                    PrimitiveType = PrimitiveType.Triangle,
                    MaterialIndex = materials.IndexOf(materials.Where(m => m.Name == msh.MaterialName).First()),
                };

                // Add vertices
                foreach (var vertex in meshData.Vertices)
                {
                    Vector3D vec3D = new Vector3D(vertex.X, vertex.Y, vertex.Z);
                    mesh.Vertices.Add(vec3D);
                }

                // Add normals
                foreach (var normal in meshData.Normals)
                {
                    Vector3D vec3D = new Vector3D(normal.X, normal.Y, normal.Z);
                    mesh.Normals.Add(vec3D);
                }

                // Add UVs
                mesh.UVComponentCount[0]          = 2;
                mesh.TextureCoordinateChannels[0] = new List <Vector3D>();
                foreach (var uv in meshData.Texcoords)
                {
                    Vector3D vec3D = new Vector3D(uv.X, uv.Y, 0.0f);
                    mesh.TextureCoordinateChannels[0].Add(vec3D);
                }

                // Add faces
                foreach (var indexArray in meshData.Indices)
                {
                    Face face = new Face();

                    foreach (ushort index in indexArray)
                    {
                        face.Indices.Add(index);
                    }

                    mesh.Faces.Add(face);
                }

                // Add bones
                foreach (string boneName in meshData.Bones)
                {
                    var boneInfoList = (sklBlocks.First() as SklBlock).BoneInfoList;

                    var matchingBone = boneInfoList.Where(b => b.BoneName == boneName).First();

                    Bone bone = new Bone();
                    bone.Name = boneName;

                    mesh.Bones.Add(bone);
                }

                // Add weights to those bones
                int weightsPerVert = (meshData.Weights.Count / meshData.Vertices.Count);
                for (int vNum = 0; vNum < meshData.Vertices.Count; ++vNum)
                {
                    for (int wNum = 0; wNum < weightsPerVert; ++wNum)
                    {
                        // Make sure the bone actually exists
                        if (mesh.BoneCount <= (wNum % weightsPerVert))
                        {
                            break;
                        }

                        VertexWeight vWeight;
                        vWeight.VertexID = vNum;
                        vWeight.Weight   = meshData.Weights[wNum + (vNum * weightsPerVert)];
                        mesh.Bones[wNum % weightsPerVert].VertexWeights.Add(vWeight);
                    }
                }

                meshList.Add(mesh);
            }

            return(meshList);
        }
Example #51
0
 public int IndexOf(T item)
 {
     EnsureNotDisposed();
     EnsureReadAccess();
     return(_list.IndexOf(item));
 }
Example #52
0
        public static Path GetNextShortestPath(Path path, bool bypass = false)                  //get the nearest path to destination from the path nextPath
        {
            List <int> list = new List <int>();

            for (int i = 0; i < completePathList.Count; i++)                            //get all potential path
            {
                if (completePathList[i].Contains(path))
                {
                    list.Add(i);
                }
            }

            float shortestDist = Mathf.Infinity; int shortestIdx = 0; int tgtIdx = 0;

            bool hasValidPath = false;

            for (int j = 0; j < list.Count; j++)
            {
                bool        isPathValid = true;
                List <Path> cPath       = completePathList[list[j]];

                int idx = cPath.IndexOf(path) + 1; float dist = 0;

                for (int i = idx; i < cPath.Count; i++)
                {
                    if (!bypass)
                    {
                        isPathValid = !cPath[i].IsBlocked() & (i > 0 & !cPath[i].IsEntryBlocked(cPath[i - 1]));
                        if (!isPathValid)
                        {
                            break;
                        }
                    }

                    int nextPathIdx1 = 0;
                    if (cPath[i - 1].HasBranchingPlatformEnd())
                    {
                        nextPathIdx1 = cPath[i - 1].nextPath.IndexOf(cPath[i]);
                        dist        += cPath[i - 1].GetDistance(false, nextPathIdx1, bypass);
                    }
                    dist += Vector3.Distance(cPath[i - 1].GetLastWP(nextPathIdx1), cPath[i].GetFirstWP());

                    int nextPathIdx2 = 0;
                    if (cPath[i].HasBranchingPlatformEnd() && i < cPath.Count - 1)
                    {
                        nextPathIdx2 = cPath[i].nextPath.IndexOf(cPath[i + 1]);
                    }
                    dist += cPath[i].GetDistance(false, nextPathIdx2, bypass);
                }

                if (isPathValid && dist < shortestDist)
                {
                    hasValidPath = true; shortestDist = dist; shortestIdx = list[j]; tgtIdx = idx;
                }
            }

            if (completePathList[shortestIdx][tgtIdx] == path)
            {
                return(null);
            }

            if (!hasValidPath)
            {
                return(null);
            }

            return(completePathList[shortestIdx][tgtIdx]);
        }
Example #53
0
 public int IndexOf(T item)
 {
     return(m_List?.IndexOf(item) ?? -1);
 }
Example #54
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="inclusionStates"></param>
        /// <param name="addresses"></param>
        /// <returns></returns>
        public Bundle[] BundlesFromAddresses(bool inclusionStates, params string[] addresses)
        {
            List <Transaction> trxs = FindTransactionObjectsByAddresses(addresses);
            // set of tail transactions
            List <string> tailTransactions    = new List <string>();
            List <string> nonTailBundleHashes = new List <string>();

            foreach (var trx in trxs)
            {
                // Sort tail and nonTails
                if (trx.CurrentIndex == 0)
                {
                    tailTransactions.Add(trx.CurlHash());
                }
                else
                {
                    if (nonTailBundleHashes.IndexOf(trx.Bundle) == -1)
                    {
                        nonTailBundleHashes.Add(trx.Bundle);
                    }
                }
            }

            List <Transaction> bundleObjects =
                FindTransactionObjectsByBundle(nonTailBundleHashes.ToArray());

            foreach (var trx in bundleObjects)
            {
                // Sort tail and nonTails
                if (trx.CurrentIndex == 0)
                {
                    var hash = trx.CurlHash();
                    if (tailTransactions.IndexOf(hash) == -1)
                    {
                        tailTransactions.Add(hash);
                    }
                }
            }

            List <Bundle> finalBundles = new List <Bundle>();
            var           tailTxArray  = tailTransactions.ToArray();

            // If inclusionStates, get the confirmation status
            // of the tail transactions, and thus the bundles
            GetInclusionStatesResponse gisr = null;

            if (tailTxArray.Length != 0 && inclusionStates)
            {
                gisr = GetLatestInclusion(tailTxArray);
                if (gisr?.States == null || gisr.States.Count == 0)
                {
                    throw new IllegalStateException(Constants.GET_INCLUSION_STATE_RESPONSE_ERROR);
                }
            }

            GetInclusionStatesResponse finalInclusionStates = gisr;

            try
            {
                Parallel.ForEach(tailTxArray, tailTx =>
                {
                    try
                    {
                        GetBundleResponse bundleResponse = GetBundle(tailTx);
                        Bundle gbr = new Bundle(bundleResponse.Transactions,
                                                bundleResponse.Transactions.Count);
                        if (gbr.Transactions != null)
                        {
                            if (inclusionStates)
                            {
                                bool thisInclusion = false;
                                if (finalInclusionStates != null)
                                {
                                    thisInclusion = finalInclusionStates.States[tailTxArray.ToList().IndexOf(tailTx)];
                                }

                                foreach (var t in gbr.Transactions)
                                {
                                    t.Persistence = thisInclusion;
                                }
                            }

                            finalBundles.Add(gbr);
                        }

                        // If error returned from getBundle, simply ignore it because the bundle was most likely incorrect
                    }
                    catch (ArgumentException)
                    {
                        Log.Warn(Constants.GET_BUNDLE_RESPONSE_ERROR);
                    }
                });
            }
            catch (AggregateException)
            {
                return(null);
            }

            finalBundles.Sort();
            Bundle[] returnValue = new Bundle[finalBundles.Count];
            for (int i = 0; i < finalBundles.Count; i++)
            {
                returnValue[i] = new Bundle(finalBundles[i].Transactions,
                                            finalBundles[i].Transactions.Count);
            }

            return(returnValue);
        }
Example #55
0
 public int IndexOf(string item)
 {
     return(values.IndexOf(item));
 }
 public int IndexOf(BonsaiNode child)
 {
     return(children.IndexOf(child));
 }
Example #57
0
        /// <summary>
        /// Schedule data WITH pending changes
        /// </summary>
        /// <param name="withPending"></param>
        /// <returns></returns>
        public static List <Person> AllData(bool withPending = true)
        {
            List <Person> results = CurrentData.ToList();

            if (!withPending)
            {
                return(results);
            }

            foreach (Tuple <Person, Edit> personChange in PendingPersonChanges)
            {
                Person matchingPerson = results.Find(p => p.Username == personChange.Item1.Username);
                if (personChange.Item2 == Edit.Add)
                {
                    results.Add(personChange.Item1);
                }
                else if (personChange.Item2 == Edit.Delete)
                {
                    results.Remove(personChange.Item1);
                }
                else if (personChange.Item2 == Edit.Overwrite)
                {
                    Person newPerson = personChange.Item1;
                    newPerson.TimeBlocks.AddRange(matchingPerson.GetShifts());
                    int index = results.IndexOf(matchingPerson);
                    results.Remove(matchingPerson);
                    results.Insert(index, newPerson);
                }
                else if (personChange.Item2 == Edit.Merge)
                {
                    if (matchingPerson != null)
                    {
                        matchingPerson.TimeBlocks.AddRange(personChange.Item1.GetShifts());
                    }
                    else
                    {
                        results.Add(personChange.Item1);
                    }
                }
            }

            foreach (Tuple <Shift, Person, Edit> shiftChange in PendingShiftChanges)
            {
                Person matchingPerson = results.Find(p => p.Username == shiftChange.Item2.Username);
                Shift  matchingShift  = matchingPerson.GetShifts().Find(p => p.StartTime == shiftChange.Item1.StartTime &&
                                                                        p.EndTime == shiftChange.Item1.EndTime);
                if (shiftChange.Item3 == Edit.Add)
                {
                    matchingPerson.TimeBlocks.Add(shiftChange.Item1);
                }
                else if (shiftChange.Item3 == Edit.Delete)
                {
                    matchingPerson.TimeBlocks.Remove(matchingShift);
                }
                else if (shiftChange.Item3 == Edit.Overwrite)
                {
                    matchingPerson.TimeBlocks.Remove(matchingShift);
                    matchingPerson.TimeBlocks.Add(shiftChange.Item1);
                }
            }

            return(results);
        }
Example #58
0
 private int GetSelectedIndexByKey(List<Tuple<string, string>> dataSource, string key)
 {
     var result = dataSource?.IndexOf(dataSource?.Where(r => r.Item1 == key).FirstOrDefault());
     return result ?? -1;
 }
Example #59
0
    private void AdvanceToNextMonth()
    {
        var curIndex = _months.IndexOf(_currentMonth);

        _currentMonth = curIndex == _months.Count - 1 ? _months[0] : _months[curIndex + 1];
    }
Example #60
0
        static void Script(string parseFile)
        {
            string text       = File.ReadAllText(parseFile);
            string scriptName = Path.GetFileName(parseFile);

            string compiledDirectory = Path.Combine(Constants.WorkingDirectory, "compiled");

            string compiledName = scriptName + Constants.COMPILED_FILETYPE;

            Rule[] generatedRules = null;
#if DEBUG == false
            try
            {
#endif
            generatedRules = Parser.ParseText(text);
            for (int i = 0; i < generatedRules.Length; i++)
            {
                Console.WriteLine($"Rule \"{generatedRules[i].Name}\":");
                generatedRules[i].Print();
            }
#if DEBUG == false
        }
        catch (SyntaxErrorException ex)
        {
            Log.Write(ex.Message, ConsoleColor.DarkRed);
            return;
        }
#endif
            Workshop workshop = new Workshop(generatedRules);

            Section();
            if (!Directory.Exists(compiledDirectory))
            {
                Directory.CreateDirectory(compiledDirectory);
            }
            Workshop prev = null;
            if (File.Exists(Path.Combine(compiledDirectory, compiledName)))
            {
                try
                {
                    Stream stream = File.Open(Path.Combine(compiledDirectory, compiledName), FileMode.Open);

                    var formatter = new BinaryFormatter();
                    prev = formatter.Deserialize(stream) as Workshop;

                    stream.Close();

                    Log.Write($"A previously compiled version of \"{scriptName}\" was found.");
                    Log.Write("Rules:");

                    int maxlength = prev.Rules.Length.ToString().Length;
                    for (int i = 0; i < prev.Rules.Length; i++)
                    {
                        Log.Colors(new ColorMod($"{i}{new string(' ', maxlength - i.ToString().Length)}", ConsoleColor.Gray), new ColorMod(": " + prev.Rules[i].Name));
                    }

                    Log.Write("Press [Y] to update the current workshop ruleset based off the changes since the last compilation. The workshop code must be the same as the rules above.");
                    Log.Write("Press [N] to regenerate the script. This requires the workshop's ruleset to be empty.");
                    if (!YorN())
                    {
                        prev = null;
                    }
                }
                catch (Exception ex)
                {
                    Log.Write($"Found previous compiled version of \"{scriptName}\", but failed to load it:", ConsoleColor.Black, ConsoleColor.Yellow);
                    Log.Write(ex.ToString());
                }
            }

            List <Rule> previousRules = prev?.Rules.ToList();

            List <int> deleteRules        = new List <int>();
            List <RuleAction> ruleActions = new List <RuleAction>();

            // Remove old rules
            if (previousRules != null)
            {
                for (int i = previousRules.Count - 1; i >= 0; i--)
                {
                    if (!generatedRules.Contains(previousRules[i]))
                    {
                        InputLog.Write($"Deleting rule \"{previousRules[i].Name}\"");
                        deleteRules.Add(i);
                        previousRules.RemoveAt(i);
                    }
                }
            }

            int numberOfRules = 0;

            for (int i = 0; i < generatedRules.Length; i++)
            {
                if (previousRules != null && generatedRules[i] == previousRules.ElementAtOrDefault(i))
                {
                    return;
                }

                var previousIndex = previousRules?.IndexOf(generatedRules[i]) ?? -1;

                if (previousIndex == -1)
                {
                    // Create new rule

                    InputLog.Write($"Creating rule \"{generatedRules[i].Name}\"");
                    ruleActions.Add(new RuleAction(generatedRules[i], i, true));
                }
                else if (previousIndex != i)
                {
                    // Move existing rule
                    InputLog.Write($"Moving rule \"{generatedRules[i].Name}\" from #{previousIndex} to #{i}.");
                    ruleActions.Add(new RuleAction(generatedRules[i], previousIndex, i));
                    numberOfRules++;
                }
                else
                {
                    InputLog.Write($"Doing nothing to rule \"{generatedRules[i].Name}\"");
                    ruleActions.Add(new RuleAction(generatedRules[i], i, false));
                    numberOfRules++;
                }
            }

            Log.Write("To setup the input for the generation, leave then re-enter the Settings/Workshop menu in Overwatch.", ConsoleColor.Black, ConsoleColor.Cyan);
            if (prev == null)
            {
                Log.Write("No previous workshop state loaded, make sure that there are no rules in the workshop.");
            }
            Log.Write("It is recommended to save a backup preset before starting the input.", ConsoleColor.Black, ConsoleColor.Yellow);
            Log.Write("If input is incorrect or fails, increase the step wait times in the config.");
            Log.Write("During generation, you can press ctrl+c to cancel.");
            if (Config.StopInput)
            {
                Log.Write("The stopinput option in the config is set to true. During generation any user input sent to the Overwatch window will be ignored." +
                          " After generation if you can't interact with the Overwatch window, start the executable directly then type \"fixinput\".", ConsoleColor.Black, ConsoleColor.Gray);
            }
            Log.Write("Press Enter to start input.");

            List <int> breakAt = null;

            var parameters = Regex.Matches(Console.ReadLine(), @"-([a-z]+)(=(.*))?");
            foreach (Match match in parameters)
            {
                string paramName = match.Groups[1].Value;
                string value     = match.Groups.Count == 4 ? match.Groups[3].Value : null;

                List <int> targetRules = null;

                if (value != null)
                {
                    targetRules = new List <int>();
                    string[] rulesToDo = value.Split(',');

                    foreach (string ruleToDo in rulesToDo)
                    {
                        if (int.TryParse(ruleToDo, out int set))
                        {
                            targetRules.Add(set);
                        }
                    }
                }

                else if (paramName == "break")
                {
                    breakAt = targetRules;
                }
                else
                {
                    Log.Write($"Unknown parameter {paramName}");
                }
            }

            while ((InputSim.OverwatchProcess = Process.GetProcessesByName("Overwatch").FirstOrDefault()) == null)
            {
                Log.Write("No Overwatch window found, press enter to recheck.");
                Console.ReadLine();
            }

            // Generate rules
            try
            {
                Console.CancelKeyPress += Console_CancelKeyPress;
                InputSim.CancelToken    = CancelSource.Token;

                if (Config.StopInput)
                {
                    InputSim.EnableWindow(false);
                }

                InputSim.Press(Keys.Tab, Wait.Short);

                // Delete rules
                int selectedRule = -1;
                foreach (var remove in deleteRules)
                {
                    selectedRule = RuleNav(selectedRule, remove);

                    InputSim.Press(Keys.Space, Wait.Short);
                    InputSim.Press(Keys.Tab, Wait.Short);
                    InputSim.Press(Keys.Right, Wait.Short);
                    InputSim.Press(Keys.Space, Wait.Long);

                    selectedRule = -1;
                }

                // Move and add rules.
                int index = 0;
                foreach (var action in ruleActions)
                {
                    if (breakAt != null && breakAt.Contains(index))
                    {
                        Debugger.Break();
                    }

                    if (action.RuleActionType == RuleActionType.Add)
                    {
                        selectedRule = ResetRuleNav(selectedRule);

                        action.Rule.Input(numberOfRules, action.RuleIndex);
                        numberOfRules++;
                        action.Exists = true;

                        var conflicting = ruleActions.Where(v => v != null &&
                                                            v.Exists &&
                                                            action.NewIndex <= v.RuleIndex &&
                                                            !ReferenceEquals(action, v));
                        foreach (var conflict in conflicting)
                        {
                            conflict.RuleIndex += 1;
                        }
                    }
                    if (action.RuleIndex != action.NewIndex)
                    {
                        selectedRule = RuleNav(selectedRule, action.RuleIndex);

                        InputSim.Press(Keys.Left, Wait.Short, 2);
                        if (index < action.RuleIndex)
                        {
                            InputSim.Press(Keys.Space, Wait.Short, selectedRule - action.NewIndex);
                        }

                        InputSim.Press(Keys.Right, Wait.Short, 2);

                        selectedRule = index;

                        var conflicting = ruleActions.Where(v => v != null &&
                                                            v.Exists &&
                                                            action.NewIndex <= v.RuleIndex && v.RuleIndex <= action.RuleIndex &&
                                                            !ReferenceEquals(action, v));
                        foreach (var conflict in conflicting)
                        {
                            conflict.RuleIndex += 1;
                        }

                        action.RuleIndex = action.NewIndex;
                    }

                    index++;
                }

                selectedRule = ResetRuleNav(selectedRule);

                InputSim.EnableWindow(true);

                Log.Write("Input completed.");
                Log.Write("Press [Y] to save the current workshop state. Only do this if the input was sucessful.");
                Log.Write("Press [N] to discard the saved workshop state. The next generation will requre the workshop state to be the same as before the last input.");
                if (YorN())
                {
                    Stream saveStream = File.Open(Path.Combine(compiledDirectory, compiledName), FileMode.Create);

                    var saveFormatter = new BinaryFormatter();
                    saveFormatter.Serialize(saveStream, workshop);

                    saveStream.Close();
                }
            }
            catch (OperationCanceledException)
            {
                Log.Write("Generation canceled.");
            }
            finally
            {
                InputSim.EnableWindow(true);
            }
        }