public void add()
    {
      Assert.Throws<ArgumentNullException>(() => CollectionsExtensions.Add(null, Enumerable.Empty<object>()));
      Assert.Throws<ArgumentNullException>(() => new object[0].Add(null));

      ICollection<string> first = new HashSet<string> {"first"};
      ICollection<string> second = new List<string> {"second"};

      first.Add(second);
      Assert.Equal(2, first.Count);
      Assert.Equal("first", first.ElementAt(0));
      Assert.Equal("second", first.ElementAt(1));
    }
Beispiel #2
0
    static void Main()
    {
        bool found = false;

        int n = int.Parse(Console.ReadLine());

        var numbers = new HashSet<int>(Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse));

        int numOfSubsets = 1 << numbers.Count;

        for (int i = 0; i < numOfSubsets; i++)
        {
            List<int> subset = new List<int>();
            int pos = numbers.Count - 1;
            int b = i;

            while (b > 0)
            {
                if ((b & 1) == 1)
                    subset.Add(numbers.ElementAt<int>(pos));
                b >>= 1;
                pos--;
            }
            if ((subset.Sum() == n) && (subset.Count != 0))
            {
                found = true;
                Console.WriteLine(string.Join(" + ", subset) + " = {0}", n);
            }
        }
        if (!found)
            Console.WriteLine("No matching subsets.");
    }
        public override Unit GetNextTarget(HashSet<Unit> units)
        {
            if (units.Count > 0) {
                return units.ElementAt(0);
            }

            return null;
        }
 static List<HashSet<int>> GetAllSubsets(HashSet<int> s)
 {
     if (s.Count == 0)
         return null;
     s = new HashSet<int>(s);//Copy the set so the original one will not be modified.
     int element = s.ElementAt(0);
     s.Remove(element);
     List<HashSet<int>> list = GetAllSubsetsHelper(element, s);
     return list;
 }
        public void AktualizatorBrzeżnościRogówOdpowiednioJePrzypisuje(int indeksInicjatora,
      BrzeznoscRogu spodziewanaBrzeznoscR1, BrzeznoscRogu spodziewanaBrzeznoscR2,
      BrzeznoscRogu spodziewanaBrzeznoscR3, BrzeznoscRogu spodziewanaBrzeznoscR4, BrzeznoscRogu spodziewanaBrzeznoscR5)
        {
            _komorki = MockKomorek();
             _rogi = MockRogow(_komorki);
             IMapa mapa = MockKlasyMapa(_komorki, _rogi);
             IKomorka inicjator = _komorki.ElementAt(indeksInicjatora);
             var rozdzielacz = new RozdzielaczMorzIJezior(inicjator)
             {
            Nastepnik = new AktualizatorBrzeznosciRogow()
             };

             mapa.ZastosujPrzetwarzanie(rozdzielacz);

             _rogi.ElementAt(0).Dane.Brzeznosc.ShouldEqual(spodziewanaBrzeznoscR1);
             _rogi.ElementAt(1).Dane.Brzeznosc.ShouldEqual(spodziewanaBrzeznoscR2);
             _rogi.ElementAt(2).Dane.Brzeznosc.ShouldEqual(spodziewanaBrzeznoscR3);
             _rogi.ElementAt(3).Dane.Brzeznosc.ShouldEqual(spodziewanaBrzeznoscR4);
             _rogi.ElementAt(4).Dane.Brzeznosc.ShouldEqual(spodziewanaBrzeznoscR5);
        }
    static void Main(string[] args)
    {
        int n = int.Parse(Console.ReadLine());

        var numbers = new HashSet<int>(Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse));

        List<List<int>> unsorted = new List<List<int>>();

        bool found = false;

        int numOfSubsets = 1 << numbers.Count;

        for (int i = 0; i < numOfSubsets; i++)
        {
            List<int> subset = new List<int>();
            int pos = numbers.Count - 1;
            int bitmask = i;

            while (bitmask > 0)
            {
                if ((bitmask & 1) == 1)
                {
                    subset.Add(numbers.ElementAt<int>(pos));
                }
                bitmask >>= 1;
                pos--;
            }
            if ((subset.Sum() == n) && (subset.Count != 0))
            {
                found = true;
                subset.Sort();
                unsorted.Add(subset);

            }
        }

        List<List<int>> results = unsorted.OrderBy(x => x.Count).ThenBy(x => x.ElementAt(0)).ToList();

        if (found)
        {
            foreach (List<int> list in results)
            {
                Console.WriteLine(string.Join(" + ", list) + " = " + n);
            }
        }
        else
        {
            Console.WriteLine("No matching subsets.");
        }

    }
        private void buttonOk_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedItem != null)
            {
                SelectedTable = (ITable)listBox1.SelectedItem;
                HashSet<ITable> tables = new HashSet<ITable>();

                foreach (ListViewItem item in listViewColumns.CheckedItems)
                    tables.Add(((IColumn)item.Tag).Parent);

                StringBuilder sb = new StringBuilder(100);

                for (int i = 0; i < tables.Count; i++)
                {
                    sb.Append(tables.ElementAt(i).Name);

                    if (i < tables.Count - 1)
                        sb.Append(", ");
                }
                if (MessageBox.Show(this, string.Format("Delete all entities currently mapped to this tables [{0}]?", sb), "Delete mapped entities?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    foreach (var table in tables)
                    {
                        var entities = table.MappedEntities().ToList();

                        for (int i = entities.Count - 1; i >= 0; i--)
                        {
                            var entity = entities[i];
                            entity.DeleteSelf();
                        }
                    }
                foreach (ListViewItem item in listViewColumns.CheckedItems)
                {
                    IColumn column = (IColumn)item.Tag;
                    Property newProperty = Controller.MappingLayer.OneToOneEntityProcessor.CreatePropertyFromColumn(column);
                    newProperty.Name = newProperty.Name.GetNextName(Entity.Properties.Select(p => p.Name));
                    Entity.AddProperty(newProperty);
                    newProperty.SetMappedColumn(column);
                }
                //if (checkBoxAddReferences.Checked)
                //{
                //    var mappedEntities = SelectedTable.MappedEntities();

                //    if (mappedEntities.Count() == 1)
                //    {
                //        if (mappedEntities.ElementAt(0).MappedTables().Count() == 1)
                //    }
                //}
            }
            Close();
        }
 static void Main(string[] args)
 {
     String text = "This is a simple text that count unique words . And this is the text that must be checked";
     HashSet<String> words = new HashSet<string>();
     String[] differentWords = text.Split(' ');
     for(int i=0;i<differentWords.Length;i++)
     {
         words.Add(differentWords[i]);
     }
     Console.WriteLine("Here are all the unique words : ");
     for(int i=0;i<words.Count;i++)
     {
         Console.WriteLine(words.ElementAt(i));
     }
 }
Beispiel #9
0
 /// <summary>
 /// Get node collection from dataGridView
 /// </summary>
 /// <returns>HashSet of nodes</returns>
 public HashSet<Node> GetNodes()
 {
     HashSet<Node> Nodes = new HashSet<Node>();
     // Enlist all nodes
     for (int row = 0; row < dataTable.Rows.Count; row++)
         Nodes.Add(new Node((string)dataTable.Rows[row][0], (int)dataTable.Rows[row][1]));
     // Create dependencies
     for (int row = 0; row < dataTable.Rows.Count; row++)
         if (dataTable.Rows[row][2] != null)
             foreach (string dependency in dataTable.Rows[row][2].ToString().Split(separators, StringSplitOptions.RemoveEmptyEntries))
                 Nodes.ElementAt(row).Dependencies.Add(Nodes.Single(new Func<Node, bool>(delegate(Node node)
                 {
                     return node.ID == dependency;
                 })));
     return Nodes;
 }
Beispiel #10
0
        static void Main(string[] args)
        {
            string text = "Example test example list Example is here";
            HashSet<string> uniqueWords = new HashSet<string>();
            string[] storage = text.ToLower().Split(' ');

            for (int i = 0; i < storage.Length; i++)
            {
                uniqueWords.Add(storage[i]);
            }

            for (int i = 0; i < uniqueWords.Count; i++)
            {
                Console.WriteLine(uniqueWords.ElementAt(i));
            }
        }
        public string GetWords()
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            TrollResponse troll = new TrollResponse();
            Random rand = new Random();

            /** choose a text file at random to give to the client **/
            int textFilename = rand.Next(0, 5);
            string text = File.ReadAllText("../../Text/" + textFilename + ".txt");
            /** **/

            /** split text on different punctuations **/
            char[] separators = {'.', ' ', ',', '!', ';', '-'};
            string[] wordsInText = text.Split(separators, StringSplitOptions.RemoveEmptyEntries);
            /** **/

            /** create a set of unique words in the text **/
            HashSet<string> uniqueWords = new HashSet<string>(StringComparer.CurrentCultureIgnoreCase);
            foreach (string word in wordsInText)
            {
                uniqueWords.Add(word);
            }
            /** **/

            int len = uniqueWords.Count;

            troll.Text = text;

            /** if there is only one unique word in text exclude word list will be empty **/
            if (len == 1)
            {
                return serializer.Serialize(troll);
            }
            /** **/

            /** select words to be excluded from count at random **/
            int excludeLen = rand.Next(0, len - 1);
            HashSet<string> excludeList = new HashSet<string>();
            for (int i = 0; i < excludeLen; i++)
            {
                excludeList.Add(uniqueWords.ElementAt(rand.Next(0 , len - 1)));
            }
            troll.Exclude = excludeList.ToArray();
            /** **/

            return serializer.Serialize(troll);
        }
Beispiel #12
0
        public ListBookings(Welcome welcomeForm, OdbcConnection odbcConnection, HashSet<BookingInformation> bookings)
            : this()
        {
            objectWelcomeForm = welcomeForm;
            objectOdbcConnection = odbcConnection;
            bookingsListView.Columns.Add("Guest ID");
            bookingsListView.Columns.Add("First Name");
            bookingsListView.Columns.Add("Last Name");
            bookingsListView.Columns.Add("Phone");
            bookingsListView.Columns.Add("CheckIn Date");
            bookingsListView.Columns.Add("CheckOut Date");
            bookingsListView.Columns.Add("Room Number");
            bookingsListView.Columns.Add("Booking Status");

            bookingsListView.Columns[0].Width = 100;
            bookingsListView.Columns[1].Width = 125;
            bookingsListView.Columns[2].Width = 125;
            bookingsListView.Columns[3].Width = 100;
            bookingsListView.Columns[4].Width = 80;
            bookingsListView.Columns[5].Width = 80;
            bookingsListView.Columns[6].Width = 80;
            bookingsListView.Columns[7].Width = 100;

            //bookingsListBox.Items.Add(lv);
            for(int i= 0; i<bookings.Count; i++)
            {
                string[] listColumns = new string[8];
                listColumns[0] = bookings.ElementAt(i).bookedGuest.guestId;
                listColumns[1] = bookings.ElementAt(i).bookedGuest.firstName;
                listColumns[2] = bookings.ElementAt(i).bookedGuest.lastName;
                listColumns[3] = bookings.ElementAt(i).bookedGuest.phone;
                listColumns[4] = bookings.ElementAt(i).checkInDate.ToShortDateString();
                listColumns[5] = bookings.ElementAt(i).checkOutDate.ToShortDateString();
                listColumns[6] = bookings.ElementAt(i).bookedRoom.roomNumber;
                listColumns[7] = bookings.ElementAt(i).status;
                ListViewItem li = new ListViewItem(listColumns);
                if (i % 2 == 0)
                {
                    li.BackColor = Color.Gainsboro;
                }
                bookingsListView.Items.Add(li);
            }
        }
 static void Main(string[] args)
 {
     int arr0 = 1, arr1 = 2;
     List<long> listArr0 = new List<long>();
     List<long> f2 = new List<long>();
     List<long> f3 = new List<long>();
     listArr0.Add(arr0);
     f2.Add(arr1);
     f3.Add(arr1);
     // do utre nema go smetne tva sus 1 000 000 + tova toq long prevurta-> taka 4e go praa do 50
     for(int i=1;i<50;i++)
     {
         listArr0.Add(((2*listArr0.ElementAt(i-1))+3));
         f2.Add(((3*f2.ElementAt(i-1))+1));
         f3.Add(((2*f3.ElementAt(i-1))-1));
     }
     // obedinenie
     HashSet<long> obedinenie = new HashSet<long>();
     for(int i=0;i<50;i++)
     {
         obedinenie.Add(listArr0.ElementAt(i));
         obedinenie.Add(f3.ElementAt(i));
     }
     //se4enie
     HashSet<long> sechenie = new HashSet<long>();
     for(int i=0;i<50;i++)
     {
         if(listArr0.Contains(f3.ElementAt(i)))
         {
             sechenie.Add(f3.ElementAt(i));
         }
     }
     Console.WriteLine("Obedinenie : ");
     for(int i=0;i<obedinenie.Count;i++)
     {
         Console.WriteLine(" " + obedinenie.ElementAt(i) + " ");
     }
     Console.WriteLine("Se4enie : ");
     for(int i=0;i<sechenie.Count;i++)
     {
         Console.WriteLine(" " + sechenie.ElementAt(i) + " ");
     }
 }
Beispiel #14
0
        /// <summary>
        /// Метод возвращает массив, описывающий ритм
        /// </summary>
        /// <param name="segmentsCount">Количество долей в такте (количество нот и пауз)</param>
        /// <param name="notesCount">Количество звучащих нот</param>
        /// <returns></returns>
        public static int[] GetRhythm(int segmentsCount, int notesCount)
        {           
            HashSet<int> set = new HashSet<int>();
            for (int i = 0; i < segmentsCount; i++)
            {
                set.Add(i);
            }

            int[] rhythm = new int[segmentsCount];
            Random rand = new Random();

            for (int i = 0; i < notesCount; i++)
            {
                int pos = rand.Next(0, segmentsCount);
                int position = set.ElementAt(pos);
                rhythm[position] = 1;

                set.Remove(position);
                segmentsCount--;
            }

            return rhythm;
        }
Beispiel #15
0
        public Chunk(Vector3 position)
        {
            this.BlockPositions = new Block[ChunkSize, ChunkSize, ChunkSize];
            this.Position = position * ChunkSize;

            this.uniqueBlocks = new HashSet<Block>();
            this.uniqueBlocks.Add(new Block("checkerboard"));
            this.uniqueBlocks.Add(new Block("stone"));

            Random rnd = new Random();
            for (int x = 0; x < ChunkSize; x++)
            {
                for (int z = 0; z < ChunkSize; z++)
                {
                    int maxY = rnd.Next(1, 4);
                    for (int y = 0; y <= maxY; y++)
                    {
                        this.BlockPositions[x, y, z] = uniqueBlocks.ElementAt(0);
                    }
                }
            }

            this.Mesh = GenerateMesh();

            this.Effects = new HashSet<Effect>();

            foreach (Block b in this.uniqueBlocks)
            {
                BasicEffect effect = new BasicEffect(Game1.Instance.GraphicsDevice);
                effect.TextureEnabled = true;
                effect.Texture = b.Texture;

                this.Effects.Add(effect);
                b.Effects.Add(effect);
            }
        }
 static List<HashSet<int>> GetAllSubsetsHelper(int n, HashSet<int> s)
 {
     List<HashSet<int>> list = new List<HashSet<int>>();
     if (s.Count == 0)
     {
         list.Add(new HashSet<int>());
         HashSet<int> withN = new HashSet<int>();
         withN.Add(n);
         list.Add(withN);
         return list;
     }
     int element = s.ElementAt(0);
     s.Remove(element);
     list = GetAllSubsetsHelper(element,s);
     List<HashSet<int>> secondList = new List<HashSet<int>>();
     for(int i = 0;i<list.Count;i++)
     {
         HashSet<int> newSet = new HashSet<int>(list.ElementAt<HashSet<int>>(i));
         newSet.Add(n);
         secondList.Add(newSet);
     }
     list.AddRange(secondList);
     return list;
 }
        public void AktualizatorBrzeżnościKomórekOdpowiednioPrzypisujeBrzeżnościKomórek(int indeksInicjatora,
      BrzeznoscKomorki spodziewanaBrzeznoscK1, BrzeznoscKomorki spodziewanaBrzeznoscK2,
      BrzeznoscKomorki spodziewanaBrzeznoscK3, BrzeznoscKomorki spodziewanaBrzeznoscK4, BrzeznoscKomorki spodziewanaBrzeznoscK5)
        {
            _komorki = MockKomorek();
            IMapa mapa = MockKlasyMapa(_komorki);
            IKomorka inicjator = _komorki.ElementAt(indeksInicjatora);
            var rozdzielacz = new RozdzielaczMorzIJezior(inicjator)
            {
               Nastepnik = new AktualizatorBrzeznosciKomorek()
            };

            mapa.ZastosujPrzetwarzanie(rozdzielacz);

            _komorki.ElementAt(0).Dane.Brzeznosc.ShouldEqual(spodziewanaBrzeznoscK1);
            _komorki.ElementAt(1).Dane.Brzeznosc.ShouldEqual(spodziewanaBrzeznoscK2);
            _komorki.ElementAt(2).Dane.Brzeznosc.ShouldEqual(spodziewanaBrzeznoscK3);
            _komorki.ElementAt(3).Dane.Brzeznosc.ShouldEqual(spodziewanaBrzeznoscK4);
            _komorki.ElementAt(4).Dane.Brzeznosc.ShouldEqual(spodziewanaBrzeznoscK5);
        }
Beispiel #18
0
        public ArrayList manageCpuApp(String file, String cpu_app_stat)
        {
            ArrayList ret = new ArrayList();
            ArrayList ret2 = new ArrayList();
            int countLine = CPU_cores;

            string[] cpu_app_stats = File.ReadAllLines(file + cpu_app_stat);

            bool inLoop = false;
            for (int i = 0; i < cpu_app_stats.Length; i++)
            {

                if (cpu_app_stats[i].Contains("+++"))
                {
                    inLoop = true;
                    continue;
                }

                if (cpu_app_stats[i].Trim().Equals(""))
                {
                    inLoop = false;

                    //check cpu num match
                    int len1 = ret.Count;
                    HashSet<string> cpuSets = new HashSet<string>();
                    for (int b = 0; b < len1; b++)
                    {
                        string[] str = ret[b].ToString().Split(' ');
                        string cpuNum = str[38];
                        cpuSets.Add(cpuNum);
                    }

                    Dictionary<string, int[]> match = new Dictionary<string, int[]>();
                    //initial match
                    for (int c = 0; c < cpuSets.Count; c++)
                    {
                        match[cpuSets.ElementAt<string>(c)] = new int[] { 0, 0 };
                    }

                    for (int c = 0; c < cpuSets.Count; c++)
                    {
                        string cpuType = cpuSets.ElementAt<string>(c);

                        for (int d = 0; d < ret.Count; d++)
                        {
                            string[] str = ret[d].ToString().Split(' ');
                            string cpuNum = str[38];
                            if (cpuNum.Equals(cpuType))
                            {
                                int[] s = new int[2];
                                s[0] = int.Parse(str[13]);
                                s[1] = int.Parse(str[14]);
                                match[cpuType][0] += s[0];
                                match[cpuType][1] += s[1];
                            }
                        }
                    }

                    for (int a = 0; a < 8; a++)
                    {
                        if (match.ContainsKey(a.ToString()))
                        {
                            // ret2.Add(match[a.ToString()][0] + " " + match[a.ToString()][1]);
                string s = match[a.ToString()][0] + " " + match[a.ToString()][1];
                ret2.Add(s);
                        }
                        else
                        {
                            ret2.Add("0");
                        }
                    }

                    ret.Clear();

                    continue;
                }

                if (inLoop)
                {
                    ret.Add(cpu_app_stats[i]);
                }
            }

            return ret2;
        }
        public void RozdzielaczMorzIJeziorOdpowiednioPrzypisujeTypyDlaDwóchInicjatorów()
        {
            _komorki = MockKomorek();
             IMapa mapa = MockKlasyMapa(_komorki);
             IKomorka inicjator1 = _komorki.ElementAt(0);
             IKomorka inicjator2 = _komorki.ElementAt(4);
             IPrzetwarzaczMapy rozdzielacz = new RozdzielaczMorzIJezior(new IKomorka[]{inicjator1, inicjator2});

             mapa.ZastosujPrzetwarzanie(rozdzielacz);

             _komorki.ElementAt(0).Dane.Typ.ShouldEqual(TypKomorki.Morze);
             _komorki.ElementAt(1).Dane.Typ.ShouldEqual(TypKomorki.Morze);
             _komorki.ElementAt(2).Dane.Typ.ShouldEqual(TypKomorki.Lad);
             _komorki.ElementAt(3).Dane.Typ.ShouldEqual(TypKomorki.Lad);
             _komorki.ElementAt(4).Dane.Typ.ShouldEqual(TypKomorki.Morze);
        }
 public ClusterNode ElementAt(int index)
 {
     return(nodes.ElementAt(index));
 }
Beispiel #21
0
        public void Run(IMaze maze)
        {
            if (maze == null)
            {
                throw new ArgumentNullException(nameof(maze));
            }

            // Start with one cell marked as visited.  Pick a random non-visited cell and create a path of cells until
            // we get to a visited cell.  Carve out a path through the path to the visited cell, then repeat until all
            // cells are visited.  If a path loops around reset the path at the beginning of the loop.

            var allCells       = maze.AllCells;
            var visitedCells   = new HashSet <Cell>();
            var unvisitedCells = new HashSet <Cell>(allCells);
            var path           = new List <CellWall>();

            var firstVisitedCell = unvisitedCells.ElementAt(_random.Next(0, unvisitedCells.Count));

            visitedCells.Add(firstVisitedCell);
            unvisitedCells.Remove(firstVisitedCell);

            var firstCellInPath = unvisitedCells.ElementAt(_random.Next(0, unvisitedCells.Count));
            var currentCell     = firstCellInPath;

            while (unvisitedCells.Any())
            {
                var walls = currentCell.CellWalls;
                var wall  = walls[_random.Next(0, walls.Count)];
                if (visitedCells.Contains(wall.GetOtherCell(currentCell)))
                {
                    // Carve out the path
                    var firstCell = firstCellInPath;
                    foreach (var wallToOpen in path)
                    {
                        wallToOpen.IsPassable = true;
                        visitedCells.Add(firstCell);
                        unvisitedCells.Remove(firstCell);
                        firstCell = wallToOpen.GetOtherCell(firstCell);
                    }

                    wall.IsPassable = true;
                    visitedCells.Add(firstCell);
                    unvisitedCells.Remove(firstCell);
                    path.Clear();

                    // Choose a new starting cell
                    if (unvisitedCells.Any())
                    {
                        firstCellInPath = unvisitedCells.ElementAt(_random.Next(0, unvisitedCells.Count));
                        currentCell     = firstCellInPath;
                    }
                    else
                    {
                        break;
                    }
                }
                else if (firstCellInPath == wall.GetOtherCell(currentCell))
                {
                    // Looped back to the beginning so clear the whole path
                    path.Clear();
                    currentCell = wall.GetOtherCell(currentCell);
                }
                else
                {
                    var pathIndex = path.Select((pathWall, index) => new { pathWall, index })
                                    .Where(x => x.pathWall.GetOtherCell(currentCell) == wall.GetOtherCell(currentCell))
                                    .Select(x => (int?)x.index)
                                    .FirstOrDefault();

                    if (pathIndex != null)
                    {
                        // Path looped back to itself
                        for (var x = path.Count - 1; x > pathIndex; x--)
                        {
                            path.RemoveAt(x);
                        }
                    }
                    else
                    {
                        path.Add(wall);
                    }

                    currentCell = wall.GetOtherCell(currentCell);
                }
            }
        }
Beispiel #22
0
        private static Dictionary <int, byte> GetColors(int width, int height, ref int[,] labels, int[,] borders)
        {
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    int basePoint = labels[x, y];

                    if (borders[x, y] == 1 && basePoint != 0)
                    {
                        int curPoint = 0;

                        if (x > 0)
                        {
                            curPoint = labels[x - 1, y];
                            if (curPoint != 0 && curPoint != basePoint)
                            {
                                UniteColors(width, height, ref labels, basePoint, curPoint);
                                continue;
                            }
                        }
                        if (x > 0 && y > 0)
                        {
                            curPoint = labels[x - 1, y - 1];
                            if (curPoint != 0 && curPoint != basePoint)
                            {
                                UniteColors(width, height, ref labels, basePoint, curPoint);
                                continue;
                            }
                        }
                        if (y > 0)
                        {
                            curPoint = labels[x, y - 1];
                            if (curPoint != 0 && curPoint != basePoint)
                            {
                                UniteColors(width, height, ref labels, basePoint, curPoint);
                                continue;
                            }
                        }
                        if (x < width - 1 && y > 0)
                        {
                            curPoint = labels[x + 1, y - 1];
                            if (curPoint != 0 && curPoint != basePoint)
                            {
                                UniteColors(width, height, ref labels, basePoint, curPoint);
                                continue;
                            }
                        }
                        if (x < width - 1)
                        {
                            curPoint = labels[x + 1, y];
                            if (curPoint != 0 && curPoint != basePoint)
                            {
                                UniteColors(width, height, ref labels, basePoint, curPoint);
                                continue;
                            }
                        }
                        if (x < width - 1 && y < height - 1)
                        {
                            curPoint = labels[x + 1, y + 1];
                            if (curPoint != 0 && curPoint != basePoint)
                            {
                                UniteColors(width, height, ref labels, basePoint, curPoint);
                                continue;
                            }
                        }
                        if (y < height - 1)
                        {
                            if (labels[x, y + 1] != 0 && labels[x, y + 1] != basePoint)
                            {
                                UniteColors(width, height, ref labels, basePoint, curPoint);
                                continue;
                            }
                        }
                        if (x > 0 && y < height - 1)
                        {
                            curPoint = labels[x - 1, y + 1];
                            if (curPoint != 0 && curPoint != basePoint)
                            {
                                UniteColors(width, height, ref labels, basePoint, curPoint);
                                continue;
                            }
                        }
                    }
                }
            }

            var hashSet = new HashSet <int>();

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    hashSet.Add(labels[x, y]);
                }
            }

            var  colors   = new Dictionary <int, byte>();
            byte curColor = 0;

            for (int i = 0; i < hashSet.Count; i++)
            {
                int hashElement = hashSet.ElementAt(i);
                colors.Add(hashElement, (hashElement == 0) ? (byte)255 : curColor);
                curColor += 20;
                if (curColor > 230)
                {
                    curColor = 0;
                }
            }

            return(colors);
        }
Beispiel #23
0
 public Cluster GetSubCluster(int index)
 {
     return(_subClusters.ElementAt(index));
 }
Beispiel #24
0
        public string RandomAdverb(bool capitalize = false)
        {
            string s = AdverbList.ElementAt(Random.Next(0, AdverbList.Count));

            return(capitalize ? Capitalize(s) : s);
        }
        /**
         * Call this function to make the computer play a move.
         */
        private void BotMove()
        {
            // TODO - Change this function so the computer can play against you

            // Enumerate through the grid, check for open spots
            HashSet<Tuple<int, int>> possibleMoves = new HashSet<Tuple<int, int>>();
            for (int i = 0; i < GAME_GRID_ROWS_COUNT; i++)
            {
                for (int j = 0; j < GAME_GRID_COLUMNS_COUNT; j++)
                {
                    if (gameGrid.GetGrid(i, j) == EMPTY_VALUE)
                    {
                        possibleMoves.Add(Tuple.Create(i, j));
                    }
                }
            }

            // Check if there are possible moves
            if (possibleMoves.Count == 0)
            {
                // No possible moves, game is a tie
                isGameOver = true;
                ShowPopup("Tie Game!", 90);
            }
            else
            {
                // Randomly choose a move
                int moveIndex = (new Random()).Next(possibleMoves.Count);
                Tuple<int, int> move = possibleMoves.ElementAt(moveIndex);
                gameGrid.SetGrid(move.Item1, move.Item2, BOT_VALUE);
            }
        }
Beispiel #26
0
        private void Simconnect_OnRecvSimobjectDataBytypeAsync(SimConnect sender, SIMCONNECT_RECV_SIMOBJECT_DATA_BYTYPE data)
        {
            // Must be general SimObject information
            switch (data.dwRequestID)
            {
            case (uint)DATA_REQUESTS.FLIGHT_STATUS:
            {
                var flightStatus = data.dwData[0] as FlightStatusStruct?;

                if (flightStatus.HasValue)
                {
                    logger.LogDebug("Get Aircraft status");
                    AircraftStatusUpdated?.Invoke(this, new AircraftStatusUpdatedEventArgs(
                                                      new AircraftStatus
                        {
                            //SimTime = flightStatus.Value.SimTime,
                            //SimRate = flightStatus.Value.SimRate,
                            Latitude            = flightStatus.Value.Latitude,
                            Longitude           = flightStatus.Value.Longitude,
                            Altitude            = flightStatus.Value.Altitude,
                            AltitudeAboveGround = flightStatus.Value.AltitudeAboveGround,
                            Pitch             = flightStatus.Value.Pitch,
                            Bank              = flightStatus.Value.Bank,
                            Heading           = flightStatus.Value.MagneticHeading,
                            TrueHeading       = flightStatus.Value.TrueHeading,
                            GroundSpeed       = flightStatus.Value.GroundSpeed,
                            IndicatedAirSpeed = flightStatus.Value.IndicatedAirSpeed,
                            VerticalSpeed     = flightStatus.Value.VerticalSpeed,
                            FuelTotalQuantity = flightStatus.Value.FuelTotalQuantity,
                            IsOnGround        = flightStatus.Value.IsOnGround == 1,
                            StallWarning      = flightStatus.Value.StallWarning == 1,
                            OverspeedWarning  = flightStatus.Value.OverspeedWarning == 1,
                            IsAutopilotOn     = flightStatus.Value.IsAutopilotOn == 1,
                            IsApHdgOn         = flightStatus.Value.IsApHdgOn == 1,
                            ApHeading         = flightStatus.Value.ApHdg,
                            IsApNavOn         = flightStatus.Value.IsApNavOn == 1,
                            IsApAprOn         = flightStatus.Value.IsApAprOn == 1,
                            IsApAltOn         = flightStatus.Value.IsApAltOn == 1,
                            ApAltitude        = flightStatus.Value.ApAlt,
                            Transponder       = flightStatus.Value.Transponder.ToString().PadLeft(4, '0'),
                            FreqencyCom1      = flightStatus.Value.Com1,
                            FreqencyCom2      = flightStatus.Value.Com2,
                        }));
                }
                else
                {
                    // Cast failed
                    logger.LogError("Cannot cast to FlightStatusStruct!");
                }
            }
            break;

            case (uint)DATA_REQUESTS.TOGGLE_VALUE_DATA:
            {
                var result = new Dictionary <TOGGLE_VALUE, string>();
                lock (lockLists)
                {
                    if (data.dwDefineCount != genericValues.Count)
                    {
                        logger.LogError("Incompatible array count {actual}, expected {expected}. Skipping received data", data.dwDefineCount, genericValues.Count);
                        return;
                    }

                    var dataArray = data.dwData[0] as GenericValuesStruct?;

                    if (!dataArray.HasValue)
                    {
                        logger.LogError("Invalid data received");
                        return;
                    }

                    for (int i = 0; i < data.dwDefineCount; i++)
                    {
                        var    genericValue = genericValues.ElementAt(i);
                        int    decimals     = eventLib.GetDecimals(genericValue);
                        double toggleValue  = Math.Round(dataArray.Value.Get(i), decimals);
                        result.Add(genericValue, toggleValue.ToString("F" + decimals.ToString()));
                    }
                }

                GenericValuesUpdated?.Invoke(this, new ToggleValueUpdatedEventArgs(result));
            }
            break;
            }
        }
Beispiel #27
0
        public string RandomWord(bool capitalize = false)
        {
            string s = Random.Next(0, 2) == 0 ? List.ElementAt(Random.Next(0, List.Count)).Item1 : List.ElementAt(Random.Next(0, List.Count)).Item2;

            return(capitalize ? Capitalize(s) : s);
        }
Beispiel #28
0
    /** Get a random element from the set. */
    public int GetRandom()
    {
        int n = rand.Next(hashSet.Count);

        return(hashSet.ElementAt(n));
    }
        /// <summary>
        /// Exports a Rebar Coupler,
        /// </summary>
        /// <param name="exporterIFC">The exporter.</param>
        /// <param name="coupler">The RebarCoupler element.</param>
        /// <param name="productWrapper">The product wrapper.</param>
        public static void ExportCoupler(ExporterIFC exporterIFC, RebarCoupler coupler, ProductWrapper productWrapper)
        {
            if (coupler == null)
            {
                return;
            }

            FamilySymbol familySymbol = ExporterCacheManager.Document.GetElement(coupler.GetTypeId()) as FamilySymbol;

            if (familySymbol == null)
            {
                return;
            }

            ElementId categoryId = CategoryUtil.GetSafeCategoryId(coupler);

            IFCFile       file         = exporterIFC.GetFile();
            IFCAnyHandle  ownerHistory = ExporterCacheManager.OwnerHistoryHandle;
            Options       options      = GeometryUtil.GetIFCExportGeometryOptions();;
            string        ifcEnumType;
            IFCExportType exportType = ExporterUtil.GetExportType(exporterIFC, coupler, out ifcEnumType);

            using (IFCTransaction tr = new IFCTransaction(file))
            {
                FamilyTypeInfo currentTypeInfo = ExporterCacheManager.TypeObjectsCache.Find(coupler.GetTypeId(), false, exportType);
                bool           found           = currentTypeInfo.IsValid();
                if (!found)
                {
                    string typeGUID            = GUIDUtil.CreateGUID(familySymbol);
                    string typeName            = NamingUtil.GetIFCName(familySymbol);
                    string typeObjectType      = NamingUtil.CreateIFCObjectName(exporterIFC, familySymbol);
                    string applicableOccurance = NamingUtil.GetObjectTypeOverride(familySymbol, typeObjectType);
                    string typeDescription     = NamingUtil.GetDescriptionOverride(familySymbol, null);
                    string typeElemId          = NamingUtil.CreateIFCElementId(familySymbol);

                    HashSet <IFCAnyHandle> propertySetsOpt = new HashSet <IFCAnyHandle>();

                    GeometryElement exportGeometry = familySymbol.get_Geometry(options);

                    BodyData            bodyData            = null;
                    BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true, ExportOptionsCache.ExportTessellationLevel.ExtraLow);
                    bodyData = BodyExporter.ExportBody(exporterIFC, coupler, categoryId, ElementId.InvalidElementId, exportGeometry, bodyExporterOptions, null);

                    List <IFCAnyHandle> repMap = new List <IFCAnyHandle>();
                    IFCAnyHandle        origin = ExporterUtil.CreateAxis2Placement3D(file);;
                    repMap.Add(IFCInstanceExporter.CreateRepresentationMap(file, origin, bodyData.RepresentationHnd));

                    IFCAnyHandle styleHandle = FamilyExporterUtil.ExportGenericType(exporterIFC, exportType, ifcEnumType, typeGUID, typeName,
                                                                                    typeDescription, applicableOccurance, propertySetsOpt, repMap, typeElemId, typeName, coupler, familySymbol);

                    if (!IFCAnyHandleUtil.IsNullOrHasNoValue(styleHandle))
                    {
                        currentTypeInfo.Style = styleHandle;
                        ExporterCacheManager.TypeObjectsCache.Register(coupler.GetTypeId(), false, exportType, currentTypeInfo);
                    }
                }

                int nCouplerQuantity = coupler.GetCouplerQuantity();
                if (nCouplerQuantity <= 0)
                {
                    return;
                }

                ISet <IFCAnyHandle> createdRebarCouplerHandles = new HashSet <IFCAnyHandle>();
                string origInstanceName = NamingUtil.GetNameOverride(coupler, NamingUtil.GetIFCName(coupler));

                for (int idx = 0; idx < nCouplerQuantity; idx++)
                {
                    string instanceGUID        = GUIDUtil.CreateSubElementGUID(coupler, idx);
                    string instanceName        = NamingUtil.GetNameOverride(coupler, origInstanceName + ": " + idx);
                    string objectType          = NamingUtil.CreateIFCObjectName(exporterIFC, coupler);
                    string instanceObjectType  = NamingUtil.GetObjectTypeOverride(coupler, objectType);
                    string instanceDescription = NamingUtil.GetDescriptionOverride(coupler, null);
                    string instanceElemId      = NamingUtil.CreateIFCElementId(coupler);
                    string instanceTag         = NamingUtil.GetTagOverride(coupler, NamingUtil.CreateIFCElementId(coupler));

                    IFCAnyHandle style = currentTypeInfo.Style;
                    if (IFCAnyHandleUtil.IsNullOrHasNoValue(style))
                    {
                        return;
                    }

                    IList <IFCAnyHandle> repMapList = GeometryUtil.GetRepresentationMaps(style);
                    if (repMapList == null)
                    {
                        return;
                    }
                    if (repMapList.Count == 0)
                    {
                        return;
                    }

                    IList <IFCAnyHandle> shapeReps        = new List <IFCAnyHandle>();
                    IFCAnyHandle         contextOfItems3d = exporterIFC.Get3DContextHandle("Body");
                    ISet <IFCAnyHandle>  representations  = new HashSet <IFCAnyHandle>();
                    representations.Add(ExporterUtil.CreateDefaultMappedItem(file, repMapList[0], XYZ.Zero));
                    IFCAnyHandle shapeRep = RepresentationUtil.CreateBodyMappedItemRep(exporterIFC, coupler, categoryId, contextOfItems3d, representations);
                    shapeReps.Add(shapeRep);

                    IFCAnyHandle productRepresentation = IFCInstanceExporter.CreateProductDefinitionShape(exporterIFC.GetFile(), null, null, shapeReps);

                    Transform trf = coupler.GetCouplerPositionTransform(idx);

                    using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, coupler, trf, null))
                    {
                        IFCAnyHandle instanceHandle = null;
                        instanceHandle = IFCInstanceExporter.CreateGenericIFCEntity(Common.Enums.IFCEntityType.IfcMechanicalFastener, file, instanceGUID, ownerHistory,
                                                                                    instanceName, instanceDescription, instanceObjectType, setter.LocalPlacement, productRepresentation, instanceTag);

                        if (ExporterCacheManager.ExportOptionsCache.ExportAs4)
                        {
                            // In IFC4 NominalDiameter and NominalLength attributes have been deprecated. PredefinedType attribute was added.
                            IFCAnyHandleUtil.SetAttribute(instanceHandle, "PredefinedType", Revit.IFC.Export.Toolkit.IFC4.IFCMechanicalFastenerType.USERDEFINED);
                        }
                        else
                        {
                            IFCAnyHandleUtil.SetAttribute(instanceHandle, "NominalDiameter", familySymbol.get_Parameter(BuiltInParameter.COUPLER_WIDTH).AsDouble());
                            IFCAnyHandleUtil.SetAttribute(instanceHandle, "NominalLength", familySymbol.get_Parameter(BuiltInParameter.COUPLER_LENGTH).AsDouble());
                        }

                        createdRebarCouplerHandles.Add(instanceHandle);

                        productWrapper.AddElement(coupler, instanceHandle, setter, null, true);
                    }
                }

                string couplerGUID = GUIDUtil.CreateGUID(coupler);

                if (nCouplerQuantity > 1)
                {
                    // Create a group to hold all of the created IFC entities, if the coupler aren't already in an assembly.
                    // We want to avoid nested groups of groups of couplers.
                    if (coupler.AssemblyInstanceId == ElementId.InvalidElementId)
                    {
                        string revitObjectType = exporterIFC.GetFamilyName();
                        string name            = NamingUtil.GetNameOverride(coupler, revitObjectType);
                        string description     = NamingUtil.GetDescriptionOverride(coupler, null);
                        string objectType      = NamingUtil.GetObjectTypeOverride(coupler, revitObjectType);

                        IFCAnyHandle rebarGroup = IFCInstanceExporter.CreateGroup(file, couplerGUID,
                                                                                  ownerHistory, name, description, objectType);

                        productWrapper.AddElement(coupler, rebarGroup);

                        IFCInstanceExporter.CreateRelAssignsToGroup(file, GUIDUtil.CreateGUID(), ownerHistory,
                                                                    null, null, createdRebarCouplerHandles, null, rebarGroup);
                    }
                }
                else
                {
                    // We will update the GUID of the one created element to be the element GUID.
                    // This will allow the IfcGUID parameter to be use/set if appropriate.
                    ExporterUtil.SetGlobalId(createdRebarCouplerHandles.ElementAt(0), couplerGUID);
                }

                tr.Commit();
            }
        }
Beispiel #30
0
        /// <summary>
        /// Exports a Rebar, AreaReinforcement or PathReinforcement to IFC ReinforcingBar.
        /// </summary>
        /// <param name="exporterIFC">The exporter.</param>
        /// <param name="element">The element.</param>
        /// <param name="productWrapper">The product wrapper.</param>
        public static void Export(ExporterIFC exporterIFC, Element element, ProductWrapper productWrapper)
        {
            ISet <DelayedProductWrapper> createdRebars = new HashSet <DelayedProductWrapper>();

            if (element is Rebar)
            {
                createdRebars = ExportRebar(exporterIFC, element, productWrapper);
            }
            else if (element is AreaReinforcement)
            {
                AreaReinforcement areaReinforcement = element as AreaReinforcement;
                IList <ElementId> rebarIds          = areaReinforcement.GetRebarInSystemIds();

                Document doc = areaReinforcement.Document;
                foreach (ElementId id in rebarIds)
                {
                    Element rebarInSystem = doc.GetElement(id);
                    ISet <DelayedProductWrapper> newlyCreatedRebars = ExportRebar(exporterIFC, rebarInSystem, productWrapper);
                    if (newlyCreatedRebars != null)
                    {
                        createdRebars.UnionWith(newlyCreatedRebars);
                    }
                }
            }
            else if (element is PathReinforcement)
            {
                PathReinforcement pathReinforcement = element as PathReinforcement;
                IList <ElementId> rebarIds          = pathReinforcement.GetRebarInSystemIds();

                Document doc = pathReinforcement.Document;
                foreach (ElementId id in rebarIds)
                {
                    Element rebarInSystem = doc.GetElement(id);
                    ISet <DelayedProductWrapper> newlyCreatedRebars = ExportRebar(exporterIFC, rebarInSystem, productWrapper);
                    if (newlyCreatedRebars != null)
                    {
                        createdRebars.UnionWith(newlyCreatedRebars);
                    }
                }
            }
            else if (element is RebarContainer)
            {
                int            itemIndex      = 1;
                RebarContainer rebarContainer = element as RebarContainer;
                foreach (RebarContainerItem rebarContainerItem in rebarContainer)
                {
                    ISet <DelayedProductWrapper> newlyCreatedRebars = ExportRebar(exporterIFC, rebarContainerItem, rebarContainer, itemIndex, productWrapper);
                    if (newlyCreatedRebars != null)
                    {
                        itemIndex += createdRebars.Count;
                        createdRebars.UnionWith(newlyCreatedRebars);
                    }
                }
            }

            if (createdRebars != null && createdRebars.Count != 0)
            {
                string guid = GUIDUtil.CreateGUID(element);

                // Create a group to hold all of the created IFC entities, if the rebars aren't already in an assembly or a group.
                // We want to avoid nested groups of groups of rebars.
                bool relateToLevel     = true;
                bool groupRebarHandles = (createdRebars.Count != 1);
                foreach (DelayedProductWrapper delayedProductWrapper in createdRebars)
                {
                    if (ElementIsContainedInAssembly(delayedProductWrapper.RebarElement))
                    {
                        groupRebarHandles = false;
                        relateToLevel     = false;
                        break;
                    }
                }

                ISet <IFCAnyHandle> createdRebarHandles = new HashSet <IFCAnyHandle>();
                foreach (DelayedProductWrapper delayedProductWrapper in createdRebars)
                {
                    IFCAnyHandle currentRebarHandle = delayedProductWrapper.ElementHandle;
                    productWrapper.AddElement(delayedProductWrapper.RebarElement, currentRebarHandle, delayedProductWrapper.LevelInfo, null, relateToLevel);
                    createdRebarHandles.Add(currentRebarHandle);
                }

                if (createdRebars.Count > 1)
                {
                    if (groupRebarHandles)
                    {
                        // Check the intended IFC entity or type name is in the exclude list specified in the UI
                        Common.Enums.IFCEntityType elementClassTypeEnum = Common.Enums.IFCEntityType.IfcGroup;
                        if (!ExporterCacheManager.ExportOptionsCache.IsElementInExcludeList(elementClassTypeEnum))
                        {
                            IFCFile file = exporterIFC.GetFile();
                            using (IFCTransaction tr = new IFCTransaction(file))
                            {
                                IFCAnyHandle ownerHistory    = ExporterCacheManager.OwnerHistoryHandle;
                                string       revitObjectType = NamingUtil.GetFamilyAndTypeName(element);
                                string       name            = NamingUtil.GetNameOverride(element, revitObjectType);
                                string       description     = NamingUtil.GetDescriptionOverride(element, null);
                                string       objectType      = NamingUtil.GetObjectTypeOverride(element, revitObjectType);

                                IFCAnyHandle rebarGroup = IFCInstanceExporter.CreateGroup(file, guid,
                                                                                          ownerHistory, name, description, objectType);

                                productWrapper.AddElement(element, rebarGroup);

                                IFCInstanceExporter.CreateRelAssignsToGroup(file, GUIDUtil.CreateGUID(), ownerHistory,
                                                                            null, null, createdRebarHandles, null, rebarGroup);

                                tr.Commit();
                            }
                        }
                    }
                }
                else
                {
                    // We will update the GUID of the one created IfcReinforcingElement to be the element GUID.
                    // This will allow the IfcGUID parameter to be use/set if appropriate.
                    ExporterUtil.SetGlobalId(createdRebarHandles.ElementAt(0), guid);
                }
            }
        }
 private HashSet<IRog> MockRogow(HashSet<IKomorka> komorki)
 {
     var r1 = new Rog{ Punkt = new Punkt()};
      var r2 = new Rog{ Punkt = new Punkt()};
      var r3 = new Rog{ Punkt = new Punkt()};
      var r4 = new Rog{ Punkt = new Punkt()};
      var r5 = new Rog{ Punkt = new Punkt()};
      r1.BliskieRogi = new List<IRog> { r2, r3 };
      r2.BliskieRogi = new List<IRog> { r1, r3, r4 };
      r3.BliskieRogi = new List<IRog> { r1, r2, r5 };
      r4.BliskieRogi = new List<IRog> { r2, r5 };
      r5.BliskieRogi = new List<IRog> { r3, r4 };
      r1.Komorki = new List<IKomorka> {komorki.ElementAt(0), komorki.ElementAt(1)};
      r2.Komorki = new List<IKomorka> {komorki.ElementAt(1), komorki.ElementAt(2)};
      r3.Komorki = new List<IKomorka> {komorki.ElementAt(1), komorki.ElementAt(3)};
      r4.Komorki = new List<IKomorka> {komorki.ElementAt(2), komorki.ElementAt(4)};
      r5.Komorki = new List<IKomorka> {komorki.ElementAt(3), komorki.ElementAt(4)};
      komorki.ElementAt(0).Rogi = new List<IRog> {r1};
      komorki.ElementAt(1).Rogi = new List<IRog> {r1, r2, r3};
      komorki.ElementAt(2).Rogi = new List<IRog> {r2, r4};
      komorki.ElementAt(3).Rogi = new List<IRog> {r3, r5};
      komorki.ElementAt(4).Rogi = new List<IRog> {r4, r5};
      komorki.ElementAt(0).Punkt.Sasiedzi = komorki.ElementAt(0).Rogi.Select(r => r.Punkt).ToList();
      komorki.ElementAt(1).Punkt.Sasiedzi = komorki.ElementAt(1).Rogi.Select(r => r.Punkt).ToList();
      komorki.ElementAt(2).Punkt.Sasiedzi = komorki.ElementAt(2).Rogi.Select(r => r.Punkt).ToList();
      komorki.ElementAt(3).Punkt.Sasiedzi = komorki.ElementAt(3).Rogi.Select(r => r.Punkt).ToList();
      komorki.ElementAt(4).Punkt.Sasiedzi = komorki.ElementAt(4).Rogi.Select(r => r.Punkt).ToList();
      r1.Punkt.Sasiedzi = r1.BliskieRogi.Select(b => b.Punkt).Union(r1.Komorki.Select(k => k.Punkt)).ToList();
      r2.Punkt.Sasiedzi = r2.BliskieRogi.Select(b => b.Punkt).Union(r2.Komorki.Select(k => k.Punkt)).ToList();
      r3.Punkt.Sasiedzi = r3.BliskieRogi.Select(b => b.Punkt).Union(r3.Komorki.Select(k => k.Punkt)).ToList();
      r4.Punkt.Sasiedzi = r4.BliskieRogi.Select(b => b.Punkt).Union(r4.Komorki.Select(k => k.Punkt)).ToList();
      r5.Punkt.Sasiedzi = r5.BliskieRogi.Select(b => b.Punkt).Union(r5.Komorki.Select(k => k.Punkt)).ToList();
      return new HashSet<IRog>{r1, r2, r3, r4, r5};
 }
 /// <summary>
 /// Get the specific outer boundary (index of vertices)
 /// </summary>
 /// <param name="fIdx">the index face</param>
 /// <returns>return index of vertices</returns>
 public IList <int> IndexOuterboundOfFaceAt(int fIdx)
 {
     return(facesColl[_mergedFaceList.ElementAt(fIdx)].indexOuterBoundary);
 }
    public override void OnInspectorGUI()
    {
        m_Object.Update();

        GUILayout.Label("slotElementList", EditorStyles.boldLabel);

        SlotDataAsset[] slotElementList = GetSlotDataAssetArray();

        GUILayout.BeginHorizontal();
        if (GUILayout.Button("Order by Name"))
        {
            canUpdate = false;

            List <SlotDataAsset> SlotDataAssetTemp = slotElementList.ToList();

            //Make sure there's no invalid data
            for (int i = 0; i < SlotDataAssetTemp.Count; i++)
            {
                if (SlotDataAssetTemp[i] == null)
                {
                    SlotDataAssetTemp.RemoveAt(i);
                    i--;
                }
            }

            SlotDataAssetTemp.Sort((x, y) => x.name.CompareTo(y.name));

            for (int i = 0; i < SlotDataAssetTemp.Count; i++)
            {
                SetSlotDataAsset(i, SlotDataAssetTemp[i]);
            }
        }

        if (GUILayout.Button("Update List"))
        {
            isDirty   = true;
            canUpdate = false;
        }
        if (GUILayout.Button("Remove Duplicates"))
        {
            HashSet <SlotDataAsset> Slots = new HashSet <SlotDataAsset>();

            foreach (SlotDataAsset osa in slotElementList)
            {
                Slots.Add(osa);
            }

            m_SlotDataAssetCount.intValue = Slots.Count;
            for (int i = 0; i < Slots.Count; i++)
            {
                SetSlotDataAsset(i, Slots.ElementAt(i));
            }
            isDirty   = true;
            canUpdate = false;
        }

        GUILayout.EndHorizontal();

        GUILayout.Space(20);
        Rect dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));

        GUI.Box(dropArea, "Drag Slots here");
        GUILayout.Space(20);


        for (int i = 0; i < m_SlotDataAssetCount.intValue; i++)
        {
            GUILayout.BeginHorizontal();

            SlotDataAsset result = EditorGUILayout.ObjectField(slotElementList[i], typeof(SlotDataAsset), true) as SlotDataAsset;

            if (GUI.changed && canUpdate)
            {
                SetSlotDataAsset(i, result);
            }

            if (GUILayout.Button("-", GUILayout.Width(20.0f)))
            {
                canUpdate = false;
                RemoveSlotDataAssetAtIndex(i);
            }

            GUILayout.EndHorizontal();

            if (i == m_SlotDataAssetCount.intValue - 1)
            {
                canUpdate = true;

                if (isDirty)
                {
                    slotLibrary.UpdateDictionary();
                    isDirty = false;
                }
            }
        }

        DropAreaGUI(dropArea);

        if (GUILayout.Button("Add SlotDataAsset"))
        {
            AddSlotDataAsset(null);
        }

        if (GUILayout.Button("Clear List"))
        {
            m_SlotDataAssetCount.intValue = 0;
        }

        if (GUILayout.Button("Remove Invalid Slot Data"))
        {
            RemoveInvalidSlotDataAsset(slotElementList);
        }

        m_Object.ApplyModifiedProperties();
    }
Beispiel #34
0
        /**
         * Conversion de un automata AFN a uno AFD por el
         * metodo de subconjuntos
         * @param afn AFN
         */
        public void conversionAFN(Automata afn)
        {
            try
            {
                //se crea una estructura vacia
                Automata automata = new Automata();
                //se utiliza una cola como la estructura para guardar los subconjuntos a analizar
                List <HashSet <Estado> > cola = new List <HashSet <Estado> >();
                //se crea un nuevo estado inicial
                Estado inicial = new Estado(0);
                automata.setEstadoInicial(inicial);
                automata.addEstados(inicial);


                //el algoritmo empieza con el e-Closure del estado inicial del AFN
                HashSet <Estado> array_inicial = eClosure(afn.getEstadoInicial());
                //si el primer e-closure contiene estados de aceptacion hay que agregarlo
                foreach (Estado aceptacion in afn.getEstadosAceptacion())
                {
                    if (array_inicial.Contains(aceptacion))
                    {
                        automata.addEstadosAceptacion(inicial);
                    }
                }

                //lo agregamos a la pila
                cola.Add(array_inicial);
                //variable temporal para guardar el resultado todos los subconjuntos creados
                List <HashSet <Estado> > temporal = new List <HashSet <Estado> >();
                //se utilizan esetos indices para saber el estado actuales y anterior
                int indexEstadoInicio = 0;
                int counter           = 0;
                while (counter < cola.Count())
                {
                    //actual subconjunto
                    HashSet <Estado> actual = cola.ElementAt(counter);
                    //se recorre el subconjunto con cada simbolo del alfabeto del AFN
                    HashSet <Object> simbolo = new HashSet <Object>();
                    simbolo = (afn.getAlfabeto());
                    for (int i = 2; i < simbolo.Count(); i++)
                    {
                        //se realiza el move con el subconjunto
                        HashSet <Estado> move_result = move(actual, simbolo.ElementAt(i).ToString());

                        HashSet <Estado> resultado = new HashSet <Estado>();
                        //e-Closure con cada estado del resultado del move y
                        //se guarda en un solo array (merge)
                        foreach (Estado e in move_result)
                        {
                            resultado = (eClosure(e));
                        }

                        Estado anterior = (Estado)automata.getEstados().ElementAt(indexEstadoInicio);

                        /*Si el subconjunto ya fue creado una vez, solo se agregan
                         * transiciones al automata*/
                        if (temporal.Contains(resultado))
                        {
                            List <Estado> array_viejo  = automata.getEstados();
                            Estado        estado_viejo = anterior;
                            //se busca el estado correspondiente y se le suma el offset
                            Estado estado_siguiente = array_viejo.ElementAt(temporal.IndexOf(resultado) + 1);
                            estado_viejo.setTransiciones(new Transicion(estado_viejo, estado_siguiente, simbolo.ElementAt(i).ToString()));
                        }
                        //si el subconjunto no existe, se crea un nuevo estado
                        else
                        {
                            temporal.Add(resultado);
                            cola.Add(resultado);

                            Estado nuevo = new Estado(temporal.IndexOf(resultado) + 1);
                            anterior.setTransiciones(new Transicion(anterior, nuevo, simbolo.ElementAt(i).ToString()));
                            automata.addEstados(nuevo);
                            //se verifica si el estado tiene que ser de aceptacion
                            foreach (Estado aceptacion in afn.getEstadosAceptacion())
                            {
                                if (resultado.Contains(aceptacion))
                                {
                                    automata.addEstadosAceptacion(nuevo);
                                }
                            }
                        }
                    }
                    indexEstadoInicio++;
                    counter++;
                }

                this.afd = automata;
                this.afd.setTipo("AFD");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Beispiel #35
0
        public static void TestPTMOutput()
        {
            List <Modification> variableModifications = new List <Modification>();
            List <Modification> fixedModifications    = new List <Modification>();

            ModificationMotif.TryGetMotif("S", out ModificationMotif motif);
            variableModifications.Add(new Modification(_originalId: "resMod", _modificationType: "HaHa", _target: motif, _locationRestriction: "Anywhere.", _chemicalFormula: ChemicalFormula.ParseFormula("H")));

            var proteinList = new List <Protein> {
                new Protein("MNNNSKQQQ", "accession")
            };
            var protease = new Protease("CustomProtease", CleavageSpecificity.Full, null, null, new List <DigestionMotif> {
                new DigestionMotif("K", null, 1, null)
            });

            ProteaseDictionary.Dictionary.Add(protease.Name, protease);

            Dictionary <Modification, ushort> modsDictionary = new Dictionary <Modification, ushort>
            {
                { variableModifications.Last(), 1 }
            };

            DigestionParams digestionParams = new DigestionParams(protease: protease.Name, maxMissedCleavages: 0, minPeptideLength: 1);

            var modPep = proteinList.First().Digest(digestionParams, fixedModifications, variableModifications).Last();
            HashSet <PeptideWithSetModifications> value = new HashSet <PeptideWithSetModifications> {
                modPep
            };
            PeptideWithSetModifications compactPeptide1 = value.First();

            Assert.AreEqual("QQQ", value.First().FullSequence);//this might be base

            var firstProtDigest = proteinList.First().Digest(digestionParams, fixedModifications, variableModifications).ToList();
            HashSet <PeptideWithSetModifications> value2 = new HashSet <PeptideWithSetModifications> {
                firstProtDigest[0]
            };
            PeptideWithSetModifications compactPeptide2 = value2.First();

            Assert.AreEqual("MNNNSK", value2.First().FullSequence);//this might be base

            HashSet <PeptideWithSetModifications> value2mod = new HashSet <PeptideWithSetModifications> {
                firstProtDigest[1]
            };
            PeptideWithSetModifications compactPeptide2mod = value2mod.Last();

            Assert.AreEqual("MNNNS[HaHa:resMod on S]K", value2mod.Last().FullSequence);//this might be base

            HashSet <PeptideWithSetModifications> value3 = new HashSet <PeptideWithSetModifications> {
                firstProtDigest[2]
            };
            PeptideWithSetModifications compactPeptide3 = value3.First();

            Assert.AreEqual("NNNSK", value3.First().FullSequence);//this might be base
            HashSet <PeptideWithSetModifications> value3mod = new HashSet <PeptideWithSetModifications> {
                firstProtDigest[3]
            };

            PeptideWithSetModifications compactPeptide3mod = value3mod.Last();

            Assert.AreEqual("NNNS[HaHa:resMod on S]K", value3mod.Last().FullSequence);//this might be base

            var peptideList = new HashSet <PeptideWithSetModifications>();

            foreach (var protein in proteinList)
            {
                foreach (var peptide in protein.Digest(digestionParams, new List <Modification>(), variableModifications))
                {
                    peptideList.Add(peptide);
                }
            }

            MsDataScan jdfk = new MsDataScan(new MzSpectrum(new double[] { 1 }, new double[] { 1 }, false), 0, 1, true, Polarity.Positive, double.NaN, null, null, MZAnalyzerType.Orbitrap, double.NaN, null, null, "scan=1", double.NaN, null, null, double.NaN, null, DissociationType.AnyActivationType, 0, null);
            Ms2ScanWithSpecificMass ms2scan = new Ms2ScanWithSpecificMass(jdfk, 2, 0, "File", new CommonParameters());

            Tolerance fragmentTolerance = new AbsoluteTolerance(0.01);

            var match1 = new PeptideSpectralMatch(peptideList.ElementAt(0), 0, 10, 0, ms2scan, digestionParams, new List <MatchedFragmentIon>())
            {
            };

            match1.SetFdrValues(0, 0, 0, 0, 0, 0, 0, 0);
            var match2 = new PeptideSpectralMatch(peptideList.ElementAt(1), 0, 10, 0, ms2scan, digestionParams, new List <MatchedFragmentIon>())
            {
            };

            match2.SetFdrValues(0, 0, 0, 0, 0, 0, 0, 0);
            var match3 = new PeptideSpectralMatch(peptideList.ElementAt(1), 0, 10, 0, ms2scan, digestionParams, new List <MatchedFragmentIon>())
            {
            };

            match3.SetFdrValues(0, 0, 0, 0, 0, 0, 0, 0);

            List <PeptideSpectralMatch> psms = new List <PeptideSpectralMatch>
            {
                match1,
                match2,
                match3
            };

            psms.ForEach(p => p.ResolveAllAmbiguities());

            ProteinParsimonyEngine engine = new ProteinParsimonyEngine(psms, true, new CommonParameters(), new List <string> {
                "ff"
            });
            var cool          = (ProteinParsimonyResults)engine.Run();
            var proteinGroups = cool.ProteinGroups;

            ProteinScoringAndFdrEngine f = new ProteinScoringAndFdrEngine(proteinGroups, psms, false, false, true, new CommonParameters(), new List <string>());

            f.Run();

            Assert.AreEqual("#aa5[resMod on S,info:occupancy=0.67(2/3)];", proteinGroups.First().ModsInfo[0]);
        }
Beispiel #36
0
    public override void OnInspectorGUI()
    {
        m_Object.Update();
        serializedObject.Update();

        GUILayout.Label("overlayList", EditorStyles.boldLabel);


        OverlayDataAsset[] overlayElementList = GetOverlayDataArray();
        GUILayout.Space(30);
        GUILayout.Label("Overlays reduced " + scaleAdjust.intValue + " time(s)");
        GUILayout.BeginHorizontal();

        if (scaleAdjust.intValue > 0)
        {
            if (GUILayout.Button("Resolution +"))
            {
                ScaleUpTextures();

                isDirty   = true;
                canUpdate = false;
                scaleAdjust.intValue--;
            }
        }

        if (GUILayout.Button("Resolution -"))
        {
            ScaleDownTextures();

            isDirty   = true;
            canUpdate = false;
            scaleAdjust.intValue++;
        }


        GUILayout.EndHorizontal();

        GUILayout.Space(20);


        GUILayout.BeginHorizontal();
        compress.boolValue = GUILayout.Toggle(compress.boolValue ? true : false, " Compress Textures");

        readWrite.boolValue = GUILayout.Toggle(readWrite.boolValue ? true : false, " Read/Write");

        if (GUILayout.Button(" Apply"))
        {
            ConfigureTextures();

            isDirty   = true;
            canUpdate = false;
        }

        GUILayout.EndHorizontal();

        GUILayout.Space(20);


        GUILayout.BeginHorizontal();
        if (GUILayout.Button("Order by Name"))
        {
            canUpdate = false;

            List <OverlayDataAsset> OverlayDataTemp = overlayElementList.ToList();

            //Make sure there's no invalid data
            for (int i = 0; i < OverlayDataTemp.Count; i++)
            {
                if (OverlayDataTemp[i] == null)
                {
                    OverlayDataTemp.RemoveAt(i);
                    i--;
                }
            }

            OverlayDataTemp.Sort((x, y) => x.name.CompareTo(y.name));

            for (int i = 0; i < OverlayDataTemp.Count; i++)
            {
                SetOverlayData(i, OverlayDataTemp[i]);
            }
        }

        if (GUILayout.Button("Update List"))
        {
            isDirty   = true;
            canUpdate = false;
        }
        if (GUILayout.Button("Remove Duplicates"))
        {
            HashSet <OverlayDataAsset> Overlays = new HashSet <OverlayDataAsset>();

            foreach (OverlayDataAsset oda in overlayElementList)
            {
                Overlays.Add(oda);
            }

            m_OverlayDataCount.intValue = Overlays.Count;
            for (int i = 0; i < Overlays.Count; i++)
            {
                SetOverlayData(i, Overlays.ElementAt(i));
            }
            isDirty   = true;
            canUpdate = false;
        }
        GUILayout.EndHorizontal();

        GUILayout.Space(20);
        Rect dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));

        GUI.Box(dropArea, "Drag Overlays here");
        GUILayout.Space(20);


        for (int i = 0; i < m_OverlayDataCount.intValue; i++)
        {
            GUILayout.BeginHorizontal();

            var result = EditorGUILayout.ObjectField(overlayElementList[i], typeof(OverlayDataAsset), true) as OverlayDataAsset;

            if (GUI.changed && canUpdate)
            {
                SetOverlayData(i, result);
            }

            if (GUILayout.Button("-", GUILayout.Width(20.0f)))
            {
                canUpdate = false;
                RemoveOverlayDataAtIndex(i);
            }

            GUILayout.EndHorizontal();

            if (i == m_OverlayDataCount.intValue - 1)
            {
                canUpdate = true;

                if (isDirty)
                {
                    overlayLibrary.UpdateDictionary();
                    isDirty = false;
                }
            }
        }

        DropAreaGUI(dropArea);

        if (GUILayout.Button("Add OverlayData"))
        {
            AddOverlayData(null);
        }

        if (GUILayout.Button("Clear List"))
        {
            m_OverlayDataCount.intValue = 0;
        }


        m_Object.ApplyModifiedProperties();
        serializedObject.ApplyModifiedProperties();
    }
Beispiel #37
0
        /** Get a random element from the set. */
        public int GetRandom()
        {
            int index = new Random().Next(0, set.Count);

            return(set.ElementAt(index));
        }
Beispiel #38
0
        private void nomeAnexos_DoubleClick(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(nomeAnexos.Text))
            {
                int selInicio = nomeAnexos.SelectionStart;
                int selFim = nomeAnexos.Text.IndexOf(";", selInicio);
                int selTamanho = selFim - selInicio;

                string nome = nomeAnexos.Text.Substring(selInicio, selTamanho);

                nomeAnexos.SelectionStart = selInicio;
                nomeAnexos.SelectionLength = selTamanho;

                string[] listArq = nomeAnexos.Text.Split(';');
                int listCount = 0;
                int count = 0;
                int listCountInicio = 0;
                int listCountFim = 0;

                foreach (string arq in listArq)
                {
                    listCountFim += arq.Trim().Length + 2;
                    if (arq.Contains(nome) && listCountInicio <= selInicio && listCountFim > selInicio)
                    {
                        nome = arq.Trim();
                        selInicio = listCountInicio;
                        break;
                    }
                    listCountInicio = listCountFim;
                }

                if (control == 1)
                {
                    if(nome.Contains(".sac")) nome = gerenciaServlet.recuperaNomeOriginalArquivo(nome);
                    System.Diagnostics.Process.Start(caminho + nome);
                }
                else
                {
                    HashSet<string> files = new HashSet<string>();

                    if(CriptoFiles != null) foreach(string path in CriptoFiles) files.Add(path);
                    if(PlainFiles != null) foreach(string path in PlainFiles) files.Add(path);

                    foreach (string file in files)
                    {
                        if (file.Contains(nome) && count == selInicio)
                        {
                            nome = files.ElementAt(listCount);
                            break;
                        }

                        count += gerenciaServlet.retornaNome(file).Length + 2;
                        listCount++;
                    }

                    System.Diagnostics.Process.Start(nome);
                }

            }
        }
Beispiel #39
0
 public Pattern GetPattern(int index)
 {
     return(_cluster.ElementAt(index));
 }
Beispiel #40
0
        /// <summary>
        /// Searches the player's current location, their inventory, and their
        /// clothes for a thing with the specified name.
        /// </summary>
        /// <param name="name">the name of the thing</param>
        /// <returns>a thing with the specified name, if it is found; null if none is found</returns>
        private static Thing findThingNamed(string name)
        {
            HashSet<Thing> itemsFound = new HashSet<Thing>();
            foreach (Thing item in GetTopMostVisibleContainer(player.GetLocation()).GetVisibleRecursiveContents()) {
                if (item.IsNamed(name)) {
                    itemsFound.Add(item); }
            }
            foreach (Thing item in player.GetRecursiveContents()) {
                if (item.IsNamed(name)) {
                    itemsFound.Add(item); }
            }

            if (itemsFound.Count == 0) {
                return null; }
            else if (itemsFound.Count == 1) {
                return itemsFound.ElementAt(0); }
            else {
                Console.WriteLine("The specified name is ambiguous. Try being more specific?");
                Console.Write(">>> ");
                return findThingNamed(Console.ReadLine()); }
        }
    //Needs K_CollisionSet to be relative to the (0,0) cell!
    private HashSet <Vector2Int> getMainMapKMaxMinCells(TileObject[,] mainMap, ITypeGrid TypeGrid, int kMinStep, int kMaxStep, Vector2Int startCell, float percBacktrack)
    {
        HashSet <Vector2Int> UnionCollisionSet = new HashSet <Vector2Int>();

        if (K_CollisionSet == null || K_CollisionSet.Length == 0)
        {
            ErrorManager.ManageError(ErrorManager.Error.HARD_ERROR, "No collision set for the main map has been built.");
        }

        int i      = 0;
        int width  = mainMap.GetLength(0);
        int height = mainMap.GetLength(1);

        //Ensure same cells in minimum kMinStep steps: EVERYTHING IS WRT ORIGIN CELL
        while (i <= kMinStep)
        {
            foreach (Vector2Int p in K_CollisionSet[i])
            {
                UnionCollisionSet.Add(p);
            }

            i++;
        }

        //Ensure one or more paths from kMinStep up to kMaxStep: WE DON'T USE IT. IF USE IT CONSIDER WRT TO ORIGIN
        if (kMaxStep > kMinStep)
        {
            HashSet <Vector2Int> toBacktrack   = new HashSet <Vector2Int>();
            HashSet <Vector2Int> nextBacktrack = new HashSet <Vector2Int>();
            foreach (Vector2Int p in K_CollisionSet[kMaxStep])
            {
                Vector2Int x = p + startCell;
                if (Utility.in_bounds_General(x, width, height))
                {
                    toBacktrack.Add(x);
                }
            }

            if (toBacktrack.Count > 0)
            {
                int toRemove = (int)((1 - percBacktrack) * (float)toBacktrack.Count);


                //remove from toBacktrack in order to have percbacktrack elements in the set
                for (i = 0; i < toRemove; i++)
                {
                    toBacktrack.Remove(toBacktrack.ElementAt(pRNG_Alias.Next(0, toBacktrack.Count)));
                }

                UnionCollisionSet.UnionWith(toBacktrack);

                //backtrack and reconstruct the paths
                for (i = 0; i < kMaxStep - kMinStep; i++)
                {
                    foreach (Vector2Int v in toBacktrack)
                    {
                        HashSet <Vector2Int> a      = new HashSet <Vector2Int>(Utility.getAllNeighbours_General(v, TypeGrid, width, height));
                        HashSet <Vector2Int> TmpSet = new HashSet <Vector2Int>(K_CollisionSet[kMaxStep - i - 1]);
                        TmpSet.IntersectWith(a);

                        if (TmpSet.Count == 1)
                        {
                            UnionCollisionSet.UnionWith(TmpSet);
                            nextBacktrack.UnionWith(TmpSet);
                        }
                    }

                    foreach (Vector2Int v in toBacktrack)
                    {
                        if (!nextBacktrack.Contains(v))
                        {
                            HashSet <Vector2Int> a      = new HashSet <Vector2Int>(Utility.getAllNeighbours_General(v, TypeGrid, width, height));
                            HashSet <Vector2Int> TmpSet = new HashSet <Vector2Int>(K_CollisionSet[kMaxStep - i - 1]);
                            TmpSet.IntersectWith(a);
                            TmpSet.Except(UnionCollisionSet);

                            Vector2Int e = TmpSet.ElementAt(pRNG_Alias.Next(0, TmpSet.Count));
                            UnionCollisionSet.Add(e);
                            nextBacktrack.Add(e);
                        }
                    }
                    toBacktrack = new HashSet <Vector2Int>(nextBacktrack);
                }
            }
        }

        return(UnionCollisionSet);
    }
        public override void Update(UpdateState state)
        {
            var _3d = FSOEnvironment.Enable3D;

            base.Update(state);
            bool rotated = false;

            if (!Master.TVisible || !UIScreen.Current.Visible || !state.ProcessMouseEvents)
            {
                ScrollWheelInvalid = true;
            }

            if (!FSOEnvironment.SoftwareKeyboard)
            {
                if (!state.WindowFocused)
                {
                    ScrollWheelInvalid = true;
                }
                else if (ScrollWheelInvalid)
                {
                    LastMouseWheel     = state.MouseState.ScrollWheelValue;
                    ScrollWheelInvalid = false;
                }
                if (state.WindowFocused && state.MouseState.ScrollWheelValue != LastMouseWheel)
                {
                    var diff = state.MouseState.ScrollWheelValue - LastMouseWheel;
                    Master.TargetZoom  = Master.TargetZoom + diff / 1600f;
                    LastMouseWheel     = state.MouseState.ScrollWheelValue;
                    Master.TargetZoom  = Math.Max(MinZoom, Math.Min(Master.TargetZoom, MaxZoom));
                    Master.UserModZoom = true;
                    ZoomFreezeTime     = (10 * FSOEnvironment.RefreshRate) / 60;
                }
            }

            MiceDown = new HashSet <int>(MiceDown.Intersect(state.MouseStates.Select(x => x.ID)));

            int transitionTo = -2;

            if (MiceDown.Count == 0)
            {
                if (Mode != -1)
                {
                    transitionTo = -1;
                }
            }
            else if (MiceDown.Count == 1)
            {
                if (Mode == -1)
                {
                    transitionTo = 0;
                }
                if (Mode == 2)
                {
                    transitionTo = 1;
                }
            }
            else if (MiceDown.Count >= 2)
            {
                //cannot possibly be a touch
                if (Mode < 2)
                {
                    transitionTo = 2;
                }
                if (Mode == -1)
                {
                    Mode = 0;
                }
            }

            switch (Mode)
            {
            case -1:
                if (transitionTo == 0)
                {
                    var mouse = state.MouseStates.FirstOrDefault(x => x.ID == MiceDown.First());
                    if (mouse != null)
                    {
                        TapPoint      = new Point(mouse.MouseState.X, mouse.MouseState.Y);
                        MiceDownTimer = 0;
                        Mode          = 0;
                    }
                }
                break;

            case 0:
            case 1:
                if (transitionTo == 2)
                {
                    //register the first distance between the two taps
                    var m1 = state.MouseStates.FirstOrDefault(x => x.ID == MiceDown.ElementAt(0));
                    var m2 = state.MouseStates.FirstOrDefault(x => x.ID == MiceDown.ElementAt(1));
                    BaseVector = (new Point(m2.MouseState.X, m2.MouseState.Y) - new Point(m1.MouseState.X, m1.MouseState.Y)).ToVector2();
                    StartScale = Master.TargetZoom;
                    if (_3d)
                    {
                        LastAngleX = null;
                    }

                    //scroll anchor should change to center of two touches without drastically changing scroll
                    TapPoint = (new Point(m2.MouseState.X / 2, m2.MouseState.Y / 2) + new Point(m1.MouseState.X / 2, m1.MouseState.Y / 2));

                    Mode = 2;
                }
                else
                {
                    if (Mode == 0)
                    {
                        ScrollVelocity = new Vector2();
                        if (transitionTo == -1)
                        {
                            Mode = -1;
                            Master.Click(GetScaledPoint(TapPoint), state);
                        }
                        else
                        {
                            var mouse = state.MouseStates.FirstOrDefault(x => x.ID == MiceDown.First());
                            var time  = FSOEnvironment.SoftwareKeyboard ? ((TAP_TIMER * FSOEnvironment.RefreshRate) / 60) : 0;
                            if ((TapPoint - new Point(mouse.MouseState.X, mouse.MouseState.Y)).ToVector2().Length() > TAP_POINT_DIST)
                            {
                                Mode = 1;     //become a scroll
                            }
                            else if (++MiceDownTimer > time)
                            {
                                Mode = 3;
                                Master.Click(GetScaledPoint(TapPoint), state);
                            }
                        }
                    }
                    if (Mode == 1)
                    {
                        if (transitionTo == -1)
                        {
                            //release our scroll velocity
                            Mode = -1;
                        }
                        else
                        {
                            var mouse  = state.MouseStates.FirstOrDefault(x => x.ID == MiceDown.First());
                            var newTap = new Point(mouse.MouseState.X, mouse.MouseState.Y);
                            ScrollVelocity = (newTap - TapPoint).ToVector2();
                            TapPoint       = newTap;
                        }
                    }
                }
                break;

            case 2:
                if (transitionTo != -2)
                {
                    //release rotation gesture. todo.
                }
                if (transitionTo == 1)
                {
                    //go back to being a normal scroll
                    //again, anchor should change to single point without drastic scroll change
                    var mouse = state.MouseStates.FirstOrDefault(x => x.ID == MiceDown.First());
                    TapPoint = new Point(mouse.MouseState.X, mouse.MouseState.Y);
                    Mode     = 1;
                }
                else if (transitionTo == -1)
                {
                    Mode = -1;
                }
                else if (transitionTo == -2)
                {
                    var m1     = state.MouseStates.FirstOrDefault(x => x.ID == MiceDown.ElementAt(0));
                    var m2     = state.MouseStates.FirstOrDefault(x => x.ID == MiceDown.ElementAt(1));
                    var vector = (new Point(m2.MouseState.X, m2.MouseState.Y) - new Point(m1.MouseState.X, m1.MouseState.Y)).ToVector2();
                    var newTap = (new Point(m2.MouseState.X / 2, m2.MouseState.Y / 2) + new Point(m1.MouseState.X / 2, m1.MouseState.Y / 2));
                    ScrollVelocity = (newTap - TapPoint).ToVector2();
                    TapPoint       = newTap;

                    Master.TargetZoom  = (vector.Length() / BaseVector.Length()) * StartScale;
                    Master.UserModZoom = true;

                    //clockwise if dot product b against a rotated 90 degrees clockwise is positive
                    var a = BaseVector;
                    var b = vector;
                    a.Normalize(); b.Normalize();
                    var clockwise = ((-a.Y) * b.X + a.X * b.Y) > 0;
                    var angle     = (float)Math.Acos(Vector2.Dot(a, b));
                    RotateAngle = (clockwise) ? angle : -angle;

                    if (_3d)
                    {
                        var rcState = Master.Rotate;
                        if (LastAngleX != null)
                        {
                            float rot = rcState.RotationX - (float)DirectionUtils.Difference(RotateAngle, LastAngleX.Value);
                            if (!float.IsNaN(rot))
                            {
                                rcState.RotationX = rot;
                            }
                        }
                        LastAngleX         = RotateAngle;
                        rcState.RotationY += ScrollVelocity.Y / 200;
                        ScrollVelocity     = Vector2.Zero;
                    }
                    else
                    {
                        if (Math.Abs(RotateAngle) > Math.PI / 8)
                        {
                            Master.TargetZoom = StartScale;
                        }
                    }
                }
                break;

            case 3:
                if (transitionTo == -1)
                {
                    Mode = -1;
                }
                break;
            }
            if (Mode != 2 && RotateAngle != 0 && !_3d)
            {
                if (Math.Abs(RotateAngle) > Math.PI / 4)
                {
                    //confirmed
                    var screen = ((IGameScreen)GameFacade.Screens.CurrentUIScreen);
                    if (RotateAngle > 0)
                    {
                        screen.Rotation = (screen.Rotation + 1) % 4;
                    }
                    else
                    {
                        screen.Rotation = (screen.Rotation + 3) % 4;
                    }

                    HITVM.Get().PlaySoundEvent(UISounds.ObjectRotate);
                    rotated = true;
                }
                RotateAngle = 0;
            }
            ScrollVelocityHistory.Insert(0, ScrollVelocity);
            if (ScrollVelocityHistory.Count > 5)
            {
                ScrollVelocityHistory.RemoveAt(ScrollVelocityHistory.Count - 1);
            }
            if (transitionTo == -1)
            {
                //ScrollVelocity = LastValidScrollVelocity / UpdatesSinceDraw;
                if (ScrollVelocityHistory.Count > 1)
                {
                    int total = 0;
                    ScrollVelocity = new Vector2();
                    for (int i = 1; i < ScrollVelocityHistory.Count; i++)
                    {
                        total++;
                        ScrollVelocity += ScrollVelocityHistory[i];
                    }
                    ScrollVelocity /= total;
                }
                ScrollVelocityHistory.Clear();
            }

            if (Mode == -1)
            {
                ScrollVelocity *= 0.95f * Math.Min(ScrollVelocity.Length(), 1);
                if (Master.TargetZoom < 1.25f && ZoomFreezeTime == 0 && !_3d)
                {
                    Master.UserModZoom = true;
                    float snapZoom = 1f;
                    float dist     = 200f;
                    foreach (var snappable in SnapZooms)
                    {
                        var newDist = Math.Abs(Master.TargetZoom - snappable);
                        if (newDist < dist)
                        {
                            dist     = newDist;
                            snapZoom = snappable;
                        }
                    }
                    if (dist > 0)
                    {
                        var move = snapZoom - Master.TargetZoom;
                        if (move != 0)
                        {
                            if (move > 0)
                            {
                                Master.TargetZoom += 0.01f;
                            }
                            else
                            {
                                Master.TargetZoom -= 0.01f;
                            }
                        }
                        if (move * (snapZoom - Master.TargetZoom) < 0)
                        {
                            Master.TargetZoom = snapZoom;
                        }
                    }
                }
                if (ZoomFreezeTime > 0)
                {
                    ZoomFreezeTime--;
                }
            }
            if (ScrollVelocity.Length() > 0.001f)
            {
                Master.Scroll(-ScrollVelocity / (Master.TargetZoom * 128));
            }

            UpdatesSinceDraw++;
        }
        /// <summary>
        /// temporarily flips joints to remove cycles
        /// </summary>
        private void RemoveGraphCycles()
        {
            HashSet<GraphNode> tempGraph = new HashSet<GraphNode>(RobotNodes.Values.ToArray());
            while (tempGraph.Count > 0)
            {
                bool hasFinished = false;
                while (!hasFinished)//remove all sources from tempGraph. A source is a node with no parents
                {
                    hasFinished = true;
                    GraphNode tempNode;

                    for (int i = 0; i < tempGraph.Count;i++ )
                    {
                        tempNode = tempGraph.ElementAt(i);
                        if(!tempGraph.Overlaps(tempNode.ParentNodes))
                        {
                            tempGraph.Remove(tempNode);
                            hasFinished = false;
                            i--;
                        }
                    }
                }
                hasFinished = false;
                while (!hasFinished)//remove all sinks from the graph. A sink is a node with no children
                {
                    hasFinished = true;
                    GraphNode tempNode;
                    for (int i = 0; i < tempGraph.Count; i++)
                    {
                        tempNode = tempGraph.ElementAt(i);
                        if(!tempGraph.Overlaps(tempNode.ChildNodes))
                        {
                            tempGraph.Remove(tempNode);
                            hasFinished = false;
                            i--;
                        }
                    }
                }

                if (tempGraph.Count > 0) //If nodes are left, they must be in a cycle, so flip joints to fix
                {
                    foreach (GraphNode tempNode in tempGraph)
                    {
                        if (tempNode.Equals(RobotNodes[0]) || tempNode.ParentNodes.Count > 1)
                        {
                            List<GraphNode> tempList = tempNode.ParentNodes.ToList();
                            foreach (GraphNode g in tempList)
                            {
                                if (tempGraph.Contains(g))
                                {
                                    tempNode.FlipJoint(g);
                                }

                            }
                            break;
                        }

                    }
                }

            }
        }
        // forced static
        private static Bgr extractPointColor(Point p, Mat input)
        {
            HashSet<Bgr> nearbyColors = new HashSet<Bgr>();

            for (int i = p.X - Constants.AREA_SHIFT; i <= p.X + Constants.AREA_SHIFT; i++)
            {
                for (int j = p.Y - Constants.AREA_SHIFT; j <= p.Y + Constants.AREA_SHIFT; j++)
                {
                    if (i >= 0 && i < input.Width)
                    {
                        if (j >= 0 && j < input.Height)
                        {

                            nearbyColors.Add(new Bgr(input.GetData(j, i)[0], input.GetData(j, i)[1], input.GetData(j, i)[2]));
                        }
                    }
                }
            }

            // check the whiteness of nearby pixels, use the less whiteness pixel as edge color
            double maxWhiteness = 0; // check max
            int index = 0;
            int maxIndex = 0;
            foreach (Bgr c in nearbyColors)
            {
                double whiteness = Metrics.Whiteness(c);
                if (whiteness > maxWhiteness)
                {
                    maxWhiteness = whiteness;
                    maxIndex = index;
                }
                index++;
            }

            //Color ccolor = Color.FromArgb((int)color.Red, (int)color.Green, (int)color.Blue);

            return nearbyColors.ElementAt(maxIndex);
        }
        private void Crossover(Individual[] generation, Individual[] extendedGeneration, int[] probabilities)
        {
            Random random = new Random(Guid.NewGuid().GetHashCode());

            for (int i = 0; i < extendedGeneration.Length; i += 2)
            {
                CrossoverOperator(SelectParents(), (extendedGeneration[i], extendedGeneration[i + 1]));
            }

            (Individual FirstParent, Individual SecondParent) SelectParents()
            {
                Individual first  = generation[probabilities[random.Next(0, probabilities.Length)]];
                Individual second = first;

                while (first == second)
                {
                    second = generation[probabilities[random.Next(0, probabilities.Length)]];
                }

                return(first, second);
            }

            void CrossoverOperator((Individual FirstParent, Individual SecondParent) parents, (Individual FirstChild, Individual SecondChild) childs)
            {
                Individual firstParent  = parents.FirstParent;
                Individual secondParent = parents.SecondParent;

                double firstParentFitness  = firstParent.Fitness;
                double secondParentFitness = secondParent.Fitness;

                Individual better;
                Individual worse;

                if (firstParentFitness < secondParentFitness)
                {
                    better = firstParent;
                    worse  = secondParent;
                }
                else
                {
                    better = secondParent;
                    worse  = firstParent;
                }

                double chanceToSelectBetter = worse.Fitness / (firstParentFitness + secondParentFitness);

                byte[] firstKey  = childs.FirstChild.Key;
                byte[] secondKey = childs.SecondChild.Key;

                HashSet <byte> left = CloneByteAlphabet;
                var            used = _marksArrayPool.Rent(_alphabetLength);

                FillKey(firstKey);

                left = CloneByteAlphabet;
                for (int i = 0; i < used.Length; i++)
                {
                    used[i] = false;
                }

                FillKey(secondKey);

                _marksArrayPool.Return(used, true);

                void FillKey(byte[] key)
                {
                    for (int i = 0; i < _alphabetLength; i++)
                    {
                        bool u_1 = used[better.Key[i]];
                        bool u_2 = used[worse.Key[i]];
                        byte value;

                        if ((u_1 && !u_2) || (u_2 && !u_1))
                        {
                            value = u_2 ? better.Key[i] : worse.Key[i];
                        }
                        else if (!u_1 && !u_2)
                        {
                            value = random.NextDouble() < chanceToSelectBetter ? better.Key[i] : worse.Key[i];
                        }
                        else
                        {
                            value = left.ElementAt(random.Next(0, left.Count));
                        }

                        key[i]      = value;
                        used[value] = true;
                        left.Remove(value);
                    }
                }
            }
        }
        /// <summary>
        /// 遊技台のデータ取得
        /// </summary>
        /// <param name="tenpoInfoList"></param>
        /// <param name="slotMachineSearchNames"></param>
        /// <param name="aimMachineInfo"></param>
        /// <returns></returns>
        public async Task GetSlotDataAsync(List <TenpoInfo> tenpoInfoList, List <string> slotMachineSearchNames, List <AimMachineInfo> aimMachineInfo)
        {
            SlotPlayDataCollection = new HashSet <SlotPlayData>();
            AimMachineCollection   = new HashSet <SlotPlayData>();

            _tenpoInfoList          = tenpoInfoList;
            _slotMachineSearchNames = slotMachineSearchNames;
            _aimMachineList         = aimMachineInfo;

            //foreach (var tempo in _tenpoInfoList.Where(x => x.TenpoUri.ToString() == "https://daidata.goraggio.com/100247/"))
            foreach (var tempo in _tenpoInfoList)
            {
                //初期化
                _floorSearchUri.Clear();
                _slotDataUri.Clear();

                //一旦置いとく
                //var slotMachineStartNo = tempo.SlotMachineStartNo;
                //var slotMachineEndNo = tempo.SlotMachineEndNo;
                //var slotMachineNumbers = Enumerable.Range(slotMachineStartNo, slotMachineEndNo - slotMachineStartNo + 1);
                var slotMachineNumbers = Enumerable.Empty <int>();

                if (_slotMachineSearchNames != null)
                {
                    //指定した台が店舗に存在するか確かめられるURIを作成
                    var floorSearchUri = _slotMachineSearchNames.Select(slotMachineSearchName => new Uri($"{tempo.TenpoUri.ToString()}unit_list?model={slotMachineSearchName}"));
                    _floorSearchUri.AddRange(await floorSearchUri.GetExistUriAsync(_httpClient));

                    //指定した台が無ければ次の店舗の検索をする
                    if (!_floorSearchUri.Any())
                    {
                        continue;
                    }

                    try
                    {
                        var floorStreamTasks = _floorSearchUri.Select(floorUri => _httpClient.GetStreamAsync(floorUri));
                        var streamResponses  = await Task.WhenAll(floorStreamTasks);

                        //取得したソースを解析
                        var floorAnalyseTasks = streamResponses.Select(response => _analysisHTML.AnalyseFloorAsync(response));
                        var slotMachineNumbersForSlotModels = await Task.WhenAll(floorAnalyseTasks);

                        //リストの平準化
                        slotMachineNumbers = slotMachineNumbersForSlotModels.SelectMany(x => x);
                        //slotMachineNumbers = Enumerable.Repeat(532, 1);
                    }
                    catch
                    {
                        //指定した台が無ければ次の店舗の検索をする
                        continue;
                    }
                }

                try
                {
                    //遊技台の情報があるURIを作成する
                    var month       = $"{_dataDate.Month:D2}";
                    var day         = $"{_dataDate.Day:D2}";
                    var slotDataUri = slotMachineNumbers
                                      .Select(slotMachineNumber => new Uri(
                                                  $"{tempo.TenpoUri.ToString()}detail?unit={slotMachineNumber}&target_date={_dataDate.Year}-{month}-{day}"));
                    _slotDataUri.AddRange(await slotDataUri.GetExistUriAsync(_httpClient));

                    //存在するURI内のソースを取得
                    var slotDataStreamTasks = _slotDataUri
                                              .Select(uri => _httpClient.GetStreamAsync(uri));
                    var streamResponses = await Task.WhenAll(slotDataStreamTasks);

                    //取得したソースを解析
                    var slotDataAnalyseTasks =
                        streamResponses.Select((response, index)
                                               => _analysisHTML.AnalyseAsync(response, tempo, _slotMachineSearchNames, _aimMachineList, _slotDataUri.ElementAt(index)));
                    var analysisSlotData = await Task.WhenAll(slotDataAnalyseTasks);

                    //解析したデータをコレクションに追加
                    SlotPlayDataCollection.AddRange(analysisSlotData.Where(x => x != null));

                    //狙い目の台をコレクションに追加
                    AimMachineCollection.AddRange(SlotPlayDataCollection.Where(x => x.Status != null));
                    foreach (var slotData in SlotPlayDataCollection)
                    {
                        //if (slotData.Title.Contains("凱旋"))
                        //{
                        //    //前日G数 + 初当たりG数(または現在のスタート回数)が1504G+10G(ペナ考慮)を超えていればリセットされている
                        //    var isReset = slotData.FinalStartCountYesterDay + firstStartCount > 1504 + 10;

                        //    //リセットされているかつ初当たりまで1024Gを超えていたら高設定確定
                        //    if (isReset)
                        //    {
                        //        //当選履歴がない場合はこの判断ができないはずなので除外
                        //        //10Gはペナ考慮
                        //        if (firstStartCount > 1024 + 10 && slotData.IsPublicWinningHistory)
                        //        {
                        //            //高設定であれば追加する
                        //            slotData.Status = "456確定";
                        //            AimMachineCollection.Add(slotData);
                        //        }
                        //        else if (slotData.ARTCount + slotData.BigBonusCount + slotData.RegulerBonusCount == 0)
                        //        {
                        //            //リセット確定の場合は当日未当選の台のみを追加する
                        //            AimMachineCollection.Add(slotData);
                        //        }
                        //    }
                        //}
                        //else
                        //{
                        //狙い目の台をコレクションに追加

                        //}
                    }
                }
                catch (Exception e)
                {
                    var check  = _floorSearchUri;
                    var check2 = _slotDataUri;

                    //他に何があるんやろうか
                    throw;
                }
            }
        }
        public void RozdzielaczMorzIJeziorOdpowiednioPrzypisujeTypy(int indeksInicjatora,
         TypKomorki spodziewanyTypK1, TypKomorki spodziewanyTypK2,
         TypKomorki spodziewanyTypK3, TypKomorki spodziewanyTypK4, TypKomorki spodziewanyTypK5)
        {
            _komorki = MockKomorek();
             IMapa mapa = MockKlasyMapa(_komorki);
             IKomorka inicjator = _komorki.ElementAt(indeksInicjatora);
             IPrzetwarzaczMapy rozdzielacz = new RozdzielaczMorzIJezior(inicjator);

             mapa.ZastosujPrzetwarzanie(rozdzielacz);

             _komorki.ElementAt(0).Dane.Typ.ShouldEqual(spodziewanyTypK1);
             _komorki.ElementAt(1).Dane.Typ.ShouldEqual(spodziewanyTypK2);
             _komorki.ElementAt(2).Dane.Typ.ShouldEqual(spodziewanyTypK3);
             _komorki.ElementAt(3).Dane.Typ.ShouldEqual(spodziewanyTypK4);
             _komorki.ElementAt(4).Dane.Typ.ShouldEqual(spodziewanyTypK5);
        }
Beispiel #48
0
    public void goToState(State state)
    {
        Debug.Log("goto: " + state);
        gameState = state;
        switch (state)
        {
        case State.d1Turn:
            Debug.Log("d1turn");
            centerCameraOnDetective(1);
            message.PopUp("Detective 1's turn...", "Ok");
            break;

        case State.d2Turn:
            Debug.Log("d2turn");
            centerCameraOnDetective(2);
            message.PopUp("Detective 2's turn...", "Ok");
            break;

        case State.d3Turn:
            Debug.Log("d3turn");
            centerCameraOnDetective(3);
            message.PopUp("Detective 3's turn...", "Ok");
            break;

        case State.dLoss:
            Debug.Log("dloss");
            message.PopUp("Detectives lose...", "Reset game");
            gameLogic.GameBoard.reset();
            break;

        case State.dWin:
            Debug.Log("dwin");
            message.PopUp("Detectives win!", "Reset game");
            break;

        case State.mrXTurn:
            Debug.Log("mrxTurn");
            //gameState = State.mrXTurn;
            HashSet <Node> possibleMoves = gameLogic.GetPossibleMoves(0, gameLogic.GameBoard);
            Node           destination   = possibleMoves.ElementAt(new System.Random().Next(possibleMoves.Count));
            //Node destination = MinMax.minMax(gameLogic, 0, 1).Players[0].Location;
            Debug.Log("mr x moving, from " + gameLogic.GameBoard.Players[0].Location.Id + " to " + destination.Id);
            moveMrX(destination.gameObject);
            ++turnCount;
            Debug.Log("turncount: " + turnCount);
            if (turnCount == 3)
            {
                gameLogic.GameBoard.Players[0].renderer.enabled = true;
                turnCount = 0;
            }
            else
            {
                gameLogic.GameBoard.Players[0].renderer.enabled = false;
            }
            goToNextTurn();

            break;

        default:
            Debug.Log("default");
            break;
        }
    }
        public void WyrównywaczTerenuWodyOdpowiednioModyfikujeWysokosc(string wodne, float minWys)
        {
            _komorki = MockKomorek();
             _rogi = MockRogow(_komorki);
             IMapa mapa = MockKlasyMapa(_komorki, _rogi);
             _komorki.ToList().ForEach(k => k.Dane.Podloze = Podloze.Ziemia);
             _komorki.ToList().ForEach(k => k.Dane.Typ = TypKomorki.Lad);
             for (int i = 0; i < 5; ++i) // wysokość punktu = jego numer
             {
            _komorki.ElementAt(i).Punkt.Wysokosc = i + 1;
            _rogi.ElementAt(i).Punkt.Wysokosc = i + 1;
             }
             IEnumerable<int> indeksyWodnych = wodne.Split(';').Select(n => int.Parse(n) - 1);
             foreach (int indeks in indeksyWodnych)
            _komorki.ElementAt(indeks).Dane.Podloze = Podloze.Woda;

             mapa.ZastosujPrzetwarzanie(new WyrownywaczTerenuWody(minWys));

             List<IKomorka> doSprawdzenia = _komorki.Where((k, indeks) => indeksyWodnych.Contains(indeks)).ToList();
             doSprawdzenia.ForEach(k => k.Punkt.Wysokosc.ShouldEqual(minWys));
             // niepotrzebne? doSprawdzenia.ForEach(ds => ds.Rogi.ToList().ForEach(r => r.Punkt.Wysokosc.ShouldEqual(minWys)));
        }
        //Old version of method 'ExecuteSetOperation':
        public static DFA <C, List <State <S> > > ExecuteSetOperationOld <C, S>(List <DFA <C, S> > automataList, BooleanOperation boolOp)
        {
            int noAutomata = automataList.Count;

            //Give every state in each automaton 'Q' in 'automataList' a unique id between '0' and 'Q.Count' (included and excluded):
            foreach (DFA <C, S> D in automataList)
            {
                D.Enumerate();
            }

            //Array, thats i-th component contains the number of states of 'automataList[i]':
            int[] automataSizes = new int[noAutomata];
            for (int i = 0; i < noAutomata; i++)
            {
                automataSizes[i] = automataList[i].Q.Count;
            }

            //Stores references to all states of product-automaton, that have already been created:
            Array Q_reference_array = Array.CreateInstance(typeof(State <List <State <S> > >), automataSizes);

            //Initialize all five components (Q,Sigma,delta,q_0,F) of the resulting automaton:
            HashSet <State <List <State <S> > > > Q = new HashSet <State <List <State <S> > > >();
            HashSet <C> Sigma = automataList[0].Sigma;
            Dictionary <TwoTuple <State <List <State <S> > >, C>, State <List <State <S> > > > delta = new Dictionary <TwoTuple <State <List <State <S> > >, C>, State <List <State <S> > > >();
            HashSet <State <List <State <S> > > > F = new HashSet <State <List <State <S> > > >();

            List <State <S> > q_0_as_list = new List <State <S> >();

            foreach (DFA <C, S> D in automataList)
            {
                q_0_as_list.Add(D.q_0);
            }

            //Initialize workset with the initial state [q_0_1, q_0_2, ...]:
            HashSet <List <State <S> > > W = new HashSet <List <State <S> > >();

            W.Add(q_0_as_list);

            while (W.Count > 0)
            {
                //Pick 'q = [q_1,q_2,...]' from 'W' and add it to 'Q'.
                //Mark in 'Q_reference_array', that 'q' has been added, by referencing it at the position determined by the id's of the states 'q_1', 'q_2', ... respectively:
                List <State <S> > q_list = W.ElementAt(0);
                W.Remove(q_list);

                int[] indices_q = new int[noAutomata];
                for (int i = 0; i < noAutomata; i++)
                {
                    indices_q[i] = q_list[i].id;
                }

                State <List <State <S> > > q;
                if (Q_reference_array.GetValue(indices_q) == null)
                {
                    q = new State <List <State <S> > >(q_list);
                    Q_reference_array.SetValue(q, indices_q);
                }
                else
                {
                    q = (State <List <State <S> > >)Q_reference_array.GetValue(indices_q);
                }
                Q.Add(q);

                //Add q to F if it is accepting
                bool[] q_acceptance_array = new bool[noAutomata];
                for (int i = 0; i < noAutomata; i++)
                {
                    q_acceptance_array[i] = automataList[i].F.Contains(q_list[i]);
                }
                if (boolOp.IsTrueForInterpretation(q_acceptance_array))
                {
                    F.Add(q);
                }

                //Determine, where transitions out of 'q' need to go:
                foreach (C c in Sigma)
                {
                    //Determine 'q_new = delta(q, c)' and its id-array ('indices'):
                    List <State <S> > q_new_list = new List <State <S> >();
                    int[]             indices    = new int[noAutomata];
                    for (int i = 0; i < noAutomata; i++)
                    {
                        State <S> q_temp;
                        TwoTuple <State <S>, C> tuple = new TwoTuple <State <S>, C>(q_list[i], c);
                        if (!automataList[i].delta.TryGetValue(tuple, out q_temp))
                        {
                            return(null); //TODO: throw proper exception rather than returning null
                        }
                        q_new_list.Add(q_temp);
                        indices[i] = q_temp.id;
                    }

                    //If not yet in there, add 'q_new' to 'Q':
                    State <List <State <S> > > q_new;
                    if (Q_reference_array.GetValue(indices) == null)
                    {
                        q_new = new State <List <State <S> > >(q_new_list);
                        Q_reference_array.SetValue(q_new, indices);
                        W.Add(q_new_list);
                    }
                    else
                    {
                        q_new = (State <List <State <S> > >)Q_reference_array.GetValue(indices);
                    }

                    //Add new transition to 'delta':
                    TwoTuple <State <List <State <S> > >, C> key = new TwoTuple <State <List <State <S> > >, C>(q, c);
                    delta.Add(key, q_new);
                }
            }

            //Determine id-array of initial state:
            int[] indices_q_0 = new int[noAutomata];
            for (int i = 0; i < noAutomata; i++)
            {
                indices_q_0[i] = automataList[i].q_0.id;
            }

            State <List <State <S> > > q_0 = (State <List <State <S> > >)Q_reference_array.GetValue(indices_q_0);

            //Return new DFA composed of calculated sets:
            return(new DFA <C, List <State <S> > >(Q, Sigma, delta, q_0, F));
        }
        private DataFlowAnalysisResult <TAnalysisResult, TAbstractAnalysisValue> Run(ControlFlowGraph cfg, DataFlowAnalysisResult <TAnalysisResult, TAbstractAnalysisValue> seedResultOpt)
        {
            var resultBuilder = new DataFlowAnalysisResultBuilder <TAnalysisData>();

            // Add each basic block to the result.
            foreach (var block in cfg.Blocks)
            {
                resultBuilder.Add(block);
            }

            var worklist = new Queue <BasicBlock>();
            var pendingBlocksNeedingAtLeastOnePass = new HashSet <BasicBlock>(cfg.Blocks);
            var entry = GetEntry(cfg);

            // Are we computing the analysis data from scratch?
            if (seedResultOpt == null)
            {
                // Initialize the input of the initial block
                // with the default abstract value of the domain.
                UpdateInput(resultBuilder, entry, AnalysisDomain.Bottom);
            }
            else
            {
                // Initialize the input and output of every block
                // with the previously computed value.
                foreach (var block in cfg.Blocks)
                {
                    UpdateInput(resultBuilder, block, GetInputData(seedResultOpt[block]));
                }
            }

            // Add the block to the worklist.
            worklist.Enqueue(entry);

            while (worklist.Count > 0 || pendingBlocksNeedingAtLeastOnePass.Count > 0)
            {
                // Get the next block to process
                // and its associated result.
                var block = worklist.Count > 0 ? worklist.Dequeue() : pendingBlocksNeedingAtLeastOnePass.ElementAt(0);
                var needsAtLeastOnePass = pendingBlocksNeedingAtLeastOnePass.Remove(block);

                // Get the outputs of all predecessor blocks of the current block.
                var inputs = GetPredecessors(block).Select(b => GetOutput(resultBuilder[b]));

                // Merge all the outputs to get the new input of the current block.
                var input = AnalysisDomain.Merge(inputs);

                // Merge might return one of the original input values if only one of them is a valid non-null value.
                if (inputs.Any(i => ReferenceEquals(input, i)))
                {
                    input = AnalysisDomain.Clone(input);
                }

                // Temporary workaround due to lack of *real* CFG
                // TODO: Remove the below if statement once we move to compiler's CFG
                // https://github.com/dotnet/roslyn-analyzers/issues/1567
                if (block.Kind == BasicBlockKind.Exit &&
                    OperationVisitor.MergedAnalysisDataAtReturnStatements != null)
                {
                    input = AnalysisDomain.Merge(input, OperationVisitor.MergedAnalysisDataAtReturnStatements);
                }

                // Compare the previous input with the new input.
                if (!needsAtLeastOnePass)
                {
                    int compare = AnalysisDomain.Compare(GetInput(resultBuilder[block]), input);

                    // The newly computed abstract values for each basic block
                    // must be always greater or equal than the previous value
                    // to ensure termination.
                    Debug.Assert(compare <= 0, "The newly computed abstract value must be greater or equal than the previous one.");

                    // Is old input value >= new input value
                    if (compare >= 0)
                    {
                        continue;
                    }
                }

                // The newly computed value is greater than the previous value,
                // so we need to update the current block result's
                // input values with the new ones.
                UpdateInput(resultBuilder, block, AnalysisDomain.Clone(input));

                // Flow the new input through the block to get a new output.
                var output = Flow(OperationVisitor, block, input);

                // Compare the previous output with the new output.
                if (!needsAtLeastOnePass)
                {
                    int compare = AnalysisDomain.Compare(GetOutput(resultBuilder[block]), output);

                    // The newly computed abstract values for each basic block
                    // must be always greater or equal than the previous value
                    // to ensure termination.
                    Debug.Assert(compare <= 0, "The newly computed abstract value must be greater or equal than the previous one.");

                    // Is old output value >= new output value ?
                    if (compare >= 0)
                    {
                        continue;
                    }
                }

                // The newly computed value is greater than the previous value,
                // so we need to update the current block result's
                // output values with the new ones.
                UpdateOutput(resultBuilder, block, output);

                // Since the new output value is different than the previous one,
                // we need to propagate it to all the successor blocks of the current block.
                EnqueueRange(worklist, GetSuccessors(block));
            }

            return(resultBuilder.ToResult(ToResult, OperationVisitor.GetStateMap(),
                                          OperationVisitor.GetPredicateValueKindMap(), OperationVisitor.GetMergedDataForUnhandledThrowOperations(),
                                          cfg, OperationVisitor.ValueDomain.UnknownOrMayBeValue));
        }
Beispiel #52
0
        private static async void getMessage(object sender, MessageEventArgs e)
        {
            // Console.WriteLine(e.Message.Text.ToString());

            if (e.Message.Type != MessageType.Text)
            {
                await client.DeleteMessageAsync(e.Message.Chat.Id, e.Message.MessageId);

                //  await client.SendTextMessageAsync(e.Message.Chat.Id, "U+1F601");
                //    await client.KickChatMemberAsync(e.Message.Chat.Id, e.Message.From.Id/*, untilDate: DateTime.Now.AddHours(1)*/);
            }

            Console.WriteLine(e.Message.Type.ToString());
            if (e.Message.Type == MessageType.Document)
            {
                Document d = e.Message.Document;
                Console.WriteLine(d.FileName);
                Console.WriteLine(d.FileId.Length);
                if (!IdFiles.Contains(d.FileName))
                {
                    IdFiles.Add(d.FileId);
                }
            }
            if (e.Message.Type == MessageType.Text)
            {
                if (e.Message.Text.Equals("/addCat"))
                {
                    categories_list.Add(new Categories(categories_list.Last().ID + 1, "вейп"));
                    AddCategorie(categories_list.Last());
                }
                if (e.Message.Text.Equals("/addGood"))
                {
                    goods_list.Add(new Goods(goods_list.Last().ID + 1, "same", 12.33, 1));
                    AddGoods(goods_list.Last());
                }
                if (e.Message.Text.Equals("/start"))
                {
                    using (SQLiteConnection conn = new SQLiteConnection(string.Format($"Data Source=TestDB.db")))
                    {
                        conn.Open();
                        SQLiteCommand command;

                        try
                        {
                            command = new SQLiteCommand("INSERT INTO User (Login, Name, Surname, Login_id) VALUES(@login, @name, @surname, @login_id);", conn);
                            command.Parameters.Add(new SQLiteParameter("login_id", e.Message.Chat.Id));
                            string tmp = e.Message.Chat.Username;
                            if (String.IsNullOrEmpty(tmp))
                            {
                                tmp = String.Empty;
                            }
                            command.Parameters.Add(new SQLiteParameter("@login", tmp));
                            tmp = e.Message.Chat.FirstName;
                            if (String.IsNullOrEmpty(tmp))
                            {
                                tmp = String.Empty;
                            }
                            command.Parameters.Add(new SQLiteParameter("@name", tmp));
                            tmp = e.Message.Chat.LastName;
                            if (String.IsNullOrEmpty(tmp))
                            {
                                tmp = String.Empty;
                            }
                            command.Parameters.Add(new SQLiteParameter("@surname", tmp));

                            command.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }

                    e.Message.Text = "/categories";
                }
                if (e.Message.Text.Equals("/categories"))
                {
                    var keyboardMarkup = new InlineKeyboardMarkup(GetInlineKeyboard_Categories());
                    client.SendTextMessageAsync(e.Message.Chat.Id, e.Message.Text, replyMarkup: keyboardMarkup);
                }
                if (e.Message.Text.Equals("/files"))
                {
                    foreach (var item in IdFiles)
                    {
                        client.SendDocumentAsync(e.Message.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(item));
                    }
                }

                if (e.Message.Text.Equals("/test"))
                {
                    client.SendDocumentAsync(e.Message.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(IdFiles.ElementAt(1)), GetInfoAboutFIle(IdFiles.ElementAt(1)));
                    //client.StopReceiving();
                }
            }
        }
Beispiel #53
0
        private static Dictionary<int, byte> GetColors(int width, int height, ref int[,] labels, int[,] borders)
        {
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    int basePoint = labels[x, y];

                    if (borders[x, y] == 1 && basePoint != 0)
                    {
                        int curPoint = 0;

                        if (x > 0)
                        {
                            curPoint = labels[x - 1, y];
                            if (curPoint != 0 && curPoint != basePoint)
                            {
                                UniteColors(width, height, ref labels, basePoint, curPoint);
                                continue;
                            }
                        }
                        if (x > 0 && y > 0)
                        {
                            curPoint = labels[x - 1, y - 1];
                            if (curPoint != 0 && curPoint != basePoint)
                            {
                                UniteColors(width, height, ref labels, basePoint, curPoint);
                                continue;
                            }
                        }
                        if (y > 0)
                        {
                            curPoint = labels[x, y - 1];
                            if (curPoint != 0 && curPoint != basePoint)
                            {
                                UniteColors(width, height, ref labels, basePoint, curPoint);
                                continue;
                            }
                        }
                        if (x < width - 1 && y > 0)
                        {
                            curPoint = labels[x + 1, y - 1];
                            if (curPoint != 0 && curPoint != basePoint)
                            {
                                UniteColors(width, height, ref labels, basePoint, curPoint);
                                continue;
                            }
                        }
                        if (x < width - 1)
                        {
                            curPoint = labels[x + 1, y];
                            if (curPoint != 0 && curPoint != basePoint)
                            {
                                UniteColors(width, height, ref labels, basePoint, curPoint);
                                continue;
                            }
                        }
                        if (x < width - 1 && y < height - 1)
                        {
                            curPoint = labels[x + 1, y + 1];
                            if (curPoint != 0 && curPoint != basePoint)
                            {
                                UniteColors(width, height, ref labels, basePoint, curPoint);
                                continue;
                            }
                        }
                        if (y < height - 1)
                        {
                            if (labels[x, y + 1] != 0 && labels[x, y + 1] != basePoint)
                            {
                                UniteColors(width, height, ref labels, basePoint, curPoint);
                                continue;
                            }
                        }
                        if (x > 0 && y < height - 1)
                        {
                            curPoint = labels[x - 1, y + 1];
                            if (curPoint != 0 && curPoint != basePoint)
                            {
                                UniteColors(width, height, ref labels, basePoint, curPoint);
                                continue;
                            }
                        }
                    }
                }
            }

            var hashSet = new HashSet<int>();

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    hashSet.Add(labels[x, y]);
                }
            }

            var colors = new Dictionary<int, byte>();
            byte curColor = 0;
            for (int i = 0; i < hashSet.Count; i++)
            {
                int hashElement = hashSet.ElementAt(i);
                colors.Add(hashElement, (hashElement == 0) ? (byte)255 : curColor);
                curColor += 20;
                if (curColor > 230)
                {
                    curColor = 0;
                }
            }

            return colors;
        }
        /// <summary>
        /// Получает интенсивности потоков для каждой из систем в сети
        /// </summary>
        /// <param name="S">Массив номеров базовых систем </param>
        /// <param name="F">Массив номеров дивайдеров</param>
        /// <param name="J">Массив номеров интеграторов</param>
        /// <param name="Lambda0">ИНтенсивность входящего потока</param>
        /// <param name="Theta">Матрица передачи</param>
        /// <returns>Словарь, в котором ключ - вектор перемещений, а значение - вектор интенсвиностей для входящего потока
        /// в базовые системы и дивайдеры (S_1, S_2, ...S_LS, F_1, F_2, ..., F_LF) </returns>
        public static Dictionary <string, double[]> InputRates(int[] S, int[] F, int[] J, double Lambda0, RoutingMatrix Theta)
        {
            //Словарь с элементами (вектор перемещений; вектор интенсивостей)
            Dictionary <string, double[]> rates = new Dictionary <string, double[]>();


            //Первый этап - Решение уравнения потока для требований
            //Размерность СЛАУ
            int n = F.Length + S.Length;
            int k = 0; //0-фрагменты
            //Перенумерация интенсивностей происходит по порядку
            //сначала для БС, а затем для дивайдеров:
            //lambda(S1) = lambda(1), ..., lambda(SL_S) =  lambda(L_S)
            //lambda (F1) = lambda(L_S), ... lambdA(FL_F) = lambda(L_F+L_S)
            Matrix A = new Matrix(n, n);

            double[] b = new double[n];

            //Нумерация базовых систем и интеграторов
            //базовых систем и дивайдеров
            int[] SF = new int[S.Length + F.Length];
            int[] SJ = new int[S.Length + F.Length];
            for (int i = 0; i < S.Length; i++)
            {
                SF[i] = S[i];
                SJ[i] = S[i];
            }
            for (int i = 0; i < F.Length; i++)
            {
                SF[i + S.Length] = F[i];
                SJ[i + S.Length] = J[i];
            }


            for (int j = 0; j < A.CountRow; j++)
            {
                for (int i = 0; i < A.CountColumn; i++)
                {
                    A[j, i] = Theta[k, SJ[i], SF[j]];
                    if (i == j)
                    {
                        A[i, j]--;
                    }
                }
                //Поток требований из источника
                b[j] = -Lambda0 * Theta[k, 0, SF[j]];
            }

            rates.Add("0", Computation.Gauss(A, b));
            HashSet <string> UnknownRates = new HashSet <string>();

            UnknownRates.Add("0");

            //Пока множество не пусто
            while (UnknownRates.Count != 0)
            {
                string v = UnknownRates.ElementAt(0);
                UnknownRates.Remove(v);
                //Проверяю поток в дивайдер
                for (k = 0; k < F.Length; k++)
                {
                    //Если есть поток в k-ый дивайдер, то определяю итенсивности для
                    //вектора перемещений (v,k)
                    int indexFk = Array.IndexOf(SF, F[k]);

                    if (rates[v][indexFk] > 0)
                    {
                        A.Initialize();
                        b.Initialize();

                        for (int j = 0; j < A.CountRow; j++)
                        {
                            for (int i = 0; i < SF.Length; i++)
                            {
                                A[j, i] = Theta[k + 1, SJ[i], SF[j]];
                                if (i == j)
                                {
                                    A[i, j]--;
                                }
                            }
                            //Поток требований в БС и дивайдер (в интегратор поток требований идти не может)
                            b[j] = -rates[v][indexFk] * Theta[k + 1, F[k], SF[j]];
                        }

                        string new_v = v + "," + (k + 1).ToString();
                        rates.Add(new_v, Computation.Gauss(A, b));
                        UnknownRates.Add(new_v);
                    }
                }
            }
            return(rates);
        }
    protected override void LoadData()
    {
        TimeSpan loading_time = Wrap.MeasureTime(delegate() {
            base.LoadData();

            // training data
            training_data = double.IsNaN(rating_threshold)
                                ? ItemData.Read(training_file, user_mapping, item_mapping, file_format == ItemDataFileFormat.IGNORE_FIRST_LINE)
                                : ItemDataRatingThreshold.Read(training_file, rating_threshold, user_mapping, item_mapping, file_format == ItemDataFileFormat.IGNORE_FIRST_LINE);

            // test data
            if (test_ratio == 0)
            {
                if (test_file != null)
                {
                    test_data = double.IsNaN(rating_threshold)
                                                ? ItemData.Read(test_file, user_mapping, item_mapping, file_format == ItemDataFileFormat.IGNORE_FIRST_LINE)
                                                : ItemDataRatingThreshold.Read(test_file, rating_threshold, user_mapping, item_mapping, file_format == ItemDataFileFormat.IGNORE_FIRST_LINE);
                }
            }
            else
            {
                var split     = new PosOnlyFeedbackSimpleSplit <PosOnlyFeedback <SparseBooleanMatrix> >(training_data, test_ratio);
                training_data = split.Train[0];
                test_data     = split.Test[0];
            }

            if (user_prediction)
            {
                // swap file names for test users and candidate items
                var ruf              = test_users_file;
                var rif              = candidate_items_file;
                test_users_file      = rif;
                candidate_items_file = ruf;

                // swap user and item mappings
                var um       = user_mapping;
                var im       = item_mapping;
                user_mapping = im;
                item_mapping = um;

                // transpose training and test data
                training_data = training_data.Transpose();

                // transpose test data
                if (test_data != null)
                {
                    test_data = test_data.Transpose();
                }
            }

            if (recommender is MyMediaLite.ItemRecommendation.ItemRecommender)
            {
                ((ItemRecommender)recommender).Feedback = training_data;
            }

            // test users
            if (test_users_file != null)
            {
                test_users = user_mapping.ToInternalID(File.ReadLines(Path.Combine(data_dir, test_users_file)).ToArray());
            }
            else
            {
                test_users = test_data != null ? test_data.AllUsers : training_data.AllUsers;
            }

            // if necessary, perform user sampling
            if (num_test_users > 0 && num_test_users < test_users.Count)
            {
                var old_test_users = new HashSet <int>(test_users);
                var new_test_users = new int[num_test_users];
                for (int i = 0; i < num_test_users; i++)
                {
                    int random_index  = MyMediaLite.Random.GetInstance().Next(old_test_users.Count - 1);
                    new_test_users[i] = old_test_users.ElementAt(random_index);
                    old_test_users.Remove(new_test_users[i]);
                }
                test_users = new_test_users;
            }

            // candidate items
            if (candidate_items_file != null)
            {
                candidate_items = item_mapping.ToInternalID(File.ReadLines(Path.Combine(data_dir, candidate_items_file)).ToArray());
            }
            else if (all_items)
            {
                candidate_items = Enumerable.Range(0, item_mapping.InternalIDs.Max() + 1).ToArray();
            }

            if (candidate_items != null)
            {
                eval_item_mode = CandidateItems.EXPLICIT;
            }
            else if (in_training_items)
            {
                eval_item_mode = CandidateItems.TRAINING;
            }
            else if (in_test_items)
            {
                eval_item_mode = CandidateItems.TEST;
            }
            else if (overlap_items)
            {
                eval_item_mode = CandidateItems.OVERLAP;
            }
            else
            {
                eval_item_mode = CandidateItems.UNION;
            }
        });

        Console.Error.WriteLine(string.Format(CultureInfo.InvariantCulture, "loading_time {0,0:0.##}", loading_time.TotalSeconds));
        Console.Error.WriteLine("memory {0}", Memory.Usage);
    }
Beispiel #56
0
 private void GetNewFrontier()
 {
     currentNode       = frontier.ElementAt(Random.Range(0, frontier.Count));
     currentNodeParent = currentNode.Parent;
     visitedNodes.Add(currentNode);
 }
Beispiel #57
0
        //Validate that the we are using valid colors and set appropriate defaults if not.
        private void CheckForInvalidColorData()
        {
            // check for sane default colors when first rendering it
            HashSet<Color> validColors = new HashSet<Color>();
            validColors.AddRange(TargetNodes.SelectMany(x => ColorModule.getValidColorsForElementNode(x, true)));

            //Validate Color 1
            if (validColors.Any() &&
                (!validColors.Contains(_data.Color1.ToArgb()) || !_data.ColorGradient1.GetColorsInGradient().IsSubsetOf(validColors)))
            {
                Color1 = validColors.First();
                ColorGradient1 = new ColorGradient(validColors.First());
            }

            //Validate color 2
            if (validColors.Any() &&
                (!validColors.Contains(_data.Color2.ToArgb()) || !_data.ColorGradient2.GetColorsInGradient().IsSubsetOf(validColors)))
            {
                if (validColors.Count > 1)
                {
                    Color2 = validColors.ElementAt(1);
                    ColorGradient2 = new ColorGradient(validColors.ElementAt(1));
                } else
                {
                    Color2 = validColors.First();
                    ColorGradient2 = new ColorGradient(validColors.First());
                }
            }
        }
Beispiel #58
0
        private void butonOlustur()
        {
            var dizi = new HashSet <int>(); //aynı elemanın birden fazla eklenmemesi ve eklenenlerin sadece int tipinde
            var rnd  = new Random();

            while (dizi.Count != 16)       //eleman sayısı 16 olana kadar ekle
            {
                dizi.Add(rnd.Next(1, 17)); //1 - 17 arası sayı üret ve diziye ekle
            }



            //butonların oluşturulması

            Button btn1 = new Button();

            btn1.Style  = this.Resources["ButtonStyleSon"] as Style; //buton stilinin butona aktarılması
            btn1.Width  = 100;
            btn1.Height = 100;
            //btn1.Content = dizi.ElementAt(0).ToString();

            btn1.Click += new RoutedEventHandler(btnClick_Click); //tıklandığında ne yapılması isteniyorsa
            btn1.Tag    = dizi.ElementAt(0);                      // tag ına diziye rastgele atılmış sayılardan 0ncı elemanını at
            h01.Children.Add(btn1);                               //1 nolu hücreye bu butonu yerleştir

            //bu sayede hücrelerde aynı butonlar oluşturuluyor ama tag ları rastgele geliyor
            //gelen rastgele tag lara görede resim getireceğiz

            Button btn2 = new Button();

            btn2.Style  = this.Resources["ButtonStyleSon"] as Style;
            btn2.Width  = 100;
            btn2.Height = 100;
            //btn2.Content = dizi.ElementAt(1).ToString();
            btn2.Tag    = dizi.ElementAt(1);
            btn2.Click += new RoutedEventHandler(btnClick_Click);
            h02.Children.Add(btn2);

            Button btn3 = new Button();

            btn3.Style  = this.Resources["ButtonStyleSon"] as Style;
            btn3.Width  = 100;
            btn3.Height = 100;
            //btn3.Content = dizi.ElementAt(2).ToString();

            btn3.Tag    = dizi.ElementAt(2);
            btn3.Click += new RoutedEventHandler(btnClick_Click);
            h03.Children.Add(btn3);

            Button btn4 = new Button();

            btn4.Style   = this.Resources["ButtonStyleSon"] as Style;
            btn4.Width   = 100;
            btn4.Height  = 100;
            btn4.Content = dizi.ElementAt(3).ToString();
            btn4.Tag     = dizi.ElementAt(3);
            btn4.Click  += new RoutedEventHandler(btnClick_Click);
            h04.Children.Add(btn4);

            Button btn5 = new Button();

            btn5.Style   = this.Resources["ButtonStyleSon"] as Style;
            btn5.Width   = 100;
            btn5.Height  = 100;
            btn5.Content = dizi.ElementAt(4).ToString();
            btn5.Tag     = dizi.ElementAt(4);
            btn5.Click  += new RoutedEventHandler(btnClick_Click);
            h05.Children.Add(btn5);

            Button btn6 = new Button();

            btn6.Style   = this.Resources["ButtonStyleSon"] as Style;
            btn6.Width   = 100;
            btn6.Height  = 100;
            btn6.Content = dizi.ElementAt(5).ToString();
            btn6.Tag     = dizi.ElementAt(5);
            btn6.Click  += new RoutedEventHandler(btnClick_Click);
            h06.Children.Add(btn6);

            Button btn7 = new Button();

            btn7.Style   = this.Resources["ButtonStyleSon"] as Style;
            btn7.Width   = 100;
            btn7.Height  = 100;
            btn7.Content = dizi.ElementAt(6).ToString();
            btn7.Tag     = dizi.ElementAt(6);
            btn7.Click  += new RoutedEventHandler(btnClick_Click);
            h07.Children.Add(btn7);

            Button btn8 = new Button();

            btn8.Style   = this.Resources["ButtonStyleSon"] as Style;
            btn8.Width   = 100;
            btn8.Height  = 100;
            btn8.Content = dizi.ElementAt(7).ToString();
            btn8.Tag     = dizi.ElementAt(7);
            btn8.Click  += new RoutedEventHandler(btnClick_Click);
            h08.Children.Add(btn8);

            Button btn9 = new Button();

            btn9.Style  = this.Resources["ButtonStyleSon"] as Style;
            btn9.Width  = 100;
            btn9.Height = 100;

            btn9.Tag    = dizi.ElementAt(8);
            btn9.Click += new RoutedEventHandler(btnClick_Click);
            h09.Children.Add(btn9);

            Button btn10 = new Button();

            btn10.Style  = this.Resources["ButtonStyleSon"] as Style;
            btn10.Width  = 100;
            btn10.Height = 100;
            btn10.Tag    = dizi.ElementAt(9);
            btn10.Click += new RoutedEventHandler(btnClick_Click);
            h10.Children.Add(btn10);

            Button btn11 = new Button();

            btn11.Style   = this.Resources["ButtonStyleSon"] as Style;
            btn11.Width   = 100;
            btn11.Height  = 100;
            btn11.Content = dizi.ElementAt(8).ToString();
            btn11.Tag     = dizi.ElementAt(10);
            btn11.Click  += new RoutedEventHandler(btnClick_Click);
            h11.Children.Add(btn11);

            Button btn12 = new Button();

            btn12.Style  = this.Resources["ButtonStyleSon"] as Style;
            btn12.Width  = 100;
            btn12.Height = 100;
            btn12.Tag    = dizi.ElementAt(11);
            btn12.Click += new RoutedEventHandler(btnClick_Click);
            h12.Children.Add(btn12);

            Button btn13 = new Button();

            btn13.Style  = this.Resources["ButtonStyleSon"] as Style;
            btn13.Width  = 100;
            btn13.Height = 100;
            btn13.Tag    = dizi.ElementAt(12);
            btn13.Click += new RoutedEventHandler(btnClick_Click);
            h13.Children.Add(btn13);

            Button btn14 = new Button();

            btn14.Style  = this.Resources["ButtonStyleSon"] as Style;
            btn14.Width  = 100;
            btn14.Height = 100;
            btn14.Tag    = dizi.ElementAt(13);
            btn14.Click += new RoutedEventHandler(btnClick_Click);
            h14.Children.Add(btn14);

            Button btn15 = new Button();

            btn15.Style  = this.Resources["ButtonStyleSon"] as Style;
            btn15.Width  = 100;
            btn15.Height = 100;
            btn15.Tag    = dizi.ElementAt(14);
            btn15.Click += new RoutedEventHandler(btnClick_Click);
            h15.Children.Add(btn15);

            Button btn16 = new Button();

            btn16.Style  = this.Resources["ButtonStyleSon"] as Style;
            btn16.Width  = 100;
            btn16.Height = 100;
            btn16.Tag    = dizi.ElementAt(15);
            btn16.Click += new RoutedEventHandler(btnClick_Click);

            h16.Children.Add(btn16);

            //oyunun başında gösterilen kızgın troll resimlerinin oluşturulması
            Image img1x = new Image();

            img1x.Source = new BitmapImage(new Uri("troller/kizgintroll.png", UriKind.RelativeOrAbsolute));
            img1x.Height = 100;
            img1x.Width  = 100;

            Image img2x = new Image();

            img2x.Source = new BitmapImage(new Uri("troller/kizgintroll.png", UriKind.RelativeOrAbsolute));
            img2x.Height = 100;
            img2x.Width  = 100;
            int[] hangiGrid = new int[2];


            //kizgin trolleri göster
            Grid btngr1 = btn1.Parent as Grid; //btn1 in bulunduğu grid i öğreniyoruz

            //sanırım buradaki butonun bulunduğu grid i öğrenmek gereksiz olmuş sonra düzelitilecek

            if (btn1.Tag.ToString() == "5") //btn1 butonun tagı 5 ise
            {
                btngr1.Children.Add(img1x); //btn1 in bulunduğu gride resmi ekle
                hangiGrid[0] = 1;           //hangi gride koydumuzu diziye atıyoruz ki kontrolünü yapabilelim. bu griddeki butona tıklarsa yanacak
            }
            else if (btn1.Tag.ToString() == "16")
            {
                btngr1.Children.Add(img2x);
                hangiGrid[1] = 1;
            }



            Grid btngr2 = btn2.Parent as Grid;

            if (btn2.Tag.ToString() == "5")
            {
                btngr2.Children.Add(img1x);
                hangiGrid[0] = 2;
            }
            else if (btn2.Tag.ToString() == "16")
            {
                btngr2.Children.Add(img2x);
                hangiGrid[1] = 2;
            }


            Grid btngr3 = btn3.Parent as Grid;

            if (btn3.Tag.ToString() == "5")
            {
                btngr3.Children.Add(img1x);
                hangiGrid[0] = 3;
            }
            else if (btn3.Tag.ToString() == "16")
            {
                btngr3.Children.Add(img2x);
                hangiGrid[1] = 3;
            }

            Grid btngr4 = btn4.Parent as Grid;

            if (btn4.Tag.ToString() == "5")
            {
                btngr4.Children.Add(img1x);
                hangiGrid[0] = 4;
            }
            else if (btn4.Tag.ToString() == "16")
            {
                btngr4.Children.Add(img2x);
                hangiGrid[1] = 4;
            }

            Grid btngr5 = btn5.Parent as Grid;

            if (btn5.Tag.ToString() == "5")
            {
                btngr5.Children.Add(img1x);
                hangiGrid[0] = 5;
            }
            else if (btn5.Tag.ToString() == "16")
            {
                btngr5.Children.Add(img2x);
                hangiGrid[1] = 5;
            }

            Grid btngr6 = btn6.Parent as Grid;

            if (btn6.Tag.ToString() == "5")
            {
                btngr6.Children.Add(img1x);
                hangiGrid[0] = 6;
            }
            else if (btn6.Tag.ToString() == "16")
            {
                btngr6.Children.Add(img2x);
                hangiGrid[1] = 6;
            }

            Grid btngr7 = btn7.Parent as Grid;

            if (btn7.Tag.ToString() == "5")
            {
                btngr7.Children.Add(img1x);
                hangiGrid[0] = 7;
            }
            else if (btn7.Tag.ToString() == "16")
            {
                btngr7.Children.Add(img2x);
                hangiGrid[1] = 7;
            }

            Grid btngr8 = btn8.Parent as Grid;

            if (btn8.Tag.ToString() == "5")
            {
                btngr8.Children.Add(img1x);
                hangiGrid[0] = 8;
            }
            else if (btn8.Tag.ToString() == "16")
            {
                btngr8.Children.Add(img2x);
                hangiGrid[1] = 8;
            }

            Grid btngr9 = btn9.Parent as Grid;

            if (btn9.Tag.ToString() == "5")
            {
                btngr9.Children.Add(img1x);
                hangiGrid[0] = 9;
            }
            else if (btn9.Tag.ToString() == "16")
            {
                btngr9.Children.Add(img2x);
                hangiGrid[1] = 9;
            }

            Grid btngr10 = btn10.Parent as Grid;

            if (btn10.Tag.ToString() == "5")
            {
                btngr10.Children.Add(img1x);
                hangiGrid[0] = 10;
            }
            else if (btn10.Tag.ToString() == "16")
            {
                btngr10.Children.Add(img2x);
                hangiGrid[1] = 10;
            }

            Grid btngr11 = btn11.Parent as Grid;

            if (btn11.Tag.ToString() == "5")
            {
                btngr11.Children.Add(img1x);
                hangiGrid[0] = 11;
            }
            else if (btn11.Tag.ToString() == "16")
            {
                btngr11.Children.Add(img2x);
                hangiGrid[1] = 11;
            }

            Grid btngr12 = btn12.Parent as Grid;

            if (btn12.Tag.ToString() == "5")
            {
                btngr12.Children.Add(img1x);
                hangiGrid[0] = 12;
            }
            else if (btn12.Tag.ToString() == "16")
            {
                btngr12.Children.Add(img2x);
                hangiGrid[1] = 12;
            }

            Grid btngr13 = btn13.Parent as Grid;

            if (btn13.Tag.ToString() == "5")
            {
                btngr13.Children.Add(img1x);
                hangiGrid[0] = 13;
            }
            else if (btn13.Tag.ToString() == "16")
            {
                btngr13.Children.Add(img2x);
                hangiGrid[1] = 13;
            }

            Grid btngr14 = btn14.Parent as Grid;

            if (btn14.Tag.ToString() == "5")
            {
                btngr14.Children.Add(img1x);
                hangiGrid[0] = 14;
            }
            else if (btn14.Tag.ToString() == "16")
            {
                btngr14.Children.Add(img2x);
                hangiGrid[1] = 14;
            }

            Grid btngr15 = btn15.Parent as Grid;

            if (btn15.Tag.ToString() == "5")
            {
                btngr15.Children.Add(img1x);
                hangiGrid[0] = 15;
            }
            else if (btn15.Tag.ToString() == "16")
            {
                btngr15.Children.Add(img2x);
                hangiGrid[1] = 15;
            }

            Grid btngr16 = btn16.Parent as Grid;

            if (btn16.Tag.ToString() == "5")
            {
                btngr16.Children.Add(img1x);
                hangiGrid[0] = 16;
            }
            else if (btn16.Tag.ToString() == "16")
            {
                btngr16.Children.Add(img2x);
                hangiGrid[1] = 16;
            }

            //grid isimlerini bir diziye atıyoruz
            Grid[] gridisim = { btngr1, btngr2, btngr3, btngr4, btngr5, btngr6, btngr7, btngr8, btngr9, btngr10, btngr11, btngr12, btngr13, btngr14, btngr15, btngr16 };
            sureRec.Visibility  = Visibility.Visible;
            bittiTxt.Visibility = Visibility.Visible;
            sureTxt2.Visibility = Visibility.Visible;
            bittiTxt.Text       = "Kızgın trollerin yerini unutma!";

            int gostersure = 3; //kızgın trollerin yerini gösterme süresi

            gostertimer.Start();
            gostertimer.Interval = TimeSpan.FromSeconds(1); //1saniye
            gostertimer.Tick    += (s, e) =>
            {
                gostersure = gostersure - 1;

                sureTxt2.Text = gostersure.ToString();
                if (gostersure == 0)                            //süre bittiğinde
                {
                    gostertimer.Stop();                         //timerı durdur
                    sureRec.Visibility  = Visibility.Collapsed; //
                    bittiTxt.Visibility = Visibility.Collapsed;
                    sureTxt2.Visibility = Visibility.Collapsed;
                    //kizgin trolleri kapat
                    for (int i = 0; i < 16; i++) //teker teker gridleri kontrol edip hangisindeyse resmi siliyoruz / kapatıyoruz
                    {
                        if (hangiGrid[0] == i + 1)
                        {
                            gridisim[i].Children.Remove(img1x);
                        }

                        if (hangiGrid[1] == i + 1)
                        {
                            gridisim[i].Children.Remove(img2x);
                        }
                    }
                }
            };
        }
        // admin deletearea x y z radius
        public override bool HandleCommand(ulong userId, string[] words)
        {
            HashSet<IMyEntity> entities = new HashSet<IMyEntity>();
            HashSet<IMyEntity> entitiesToConfirm = new HashSet<IMyEntity>();
            HashSet<IMyEntity> entitiesConnected = new HashSet<IMyEntity>();
            HashSet<IMyEntity> entitiesFound = new HashSet<IMyEntity>();
            Wrapper.GameAction(() =>
            {
                MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid);
            });

            foreach (IMyEntity entity in entities)
            {
                if (!(entity is IMyCubeGrid))
                    continue;

                IMyCubeGrid grid = (IMyCubeGrid)entity;
                MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder(grid);
                if (gridBuilder == null)
                    continue;

                bool found = false;
                foreach (MyObjectBuilder_CubeBlock block in gridBuilder.CubeBlocks)
                {
                    if (block.TypeId == typeof(MyObjectBuilder_Beacon))
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                    entitiesToConfirm.Add(grid);
            }

            CubeGrids.GetGridsUnconnected(entitiesFound, entitiesToConfirm);

            foreach (IMyEntity entity in entitiesFound)
            {
                CubeGridEntity gridEntity = (CubeGridEntity)GameEntityManager.GetEntity(entity.EntityId);
                if (gridEntity == null)
                {
                    Log.Info("A found entity gridEntity was null!");
                    continue;
                }
                Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) at {2} with no beacon.", gridEntity.Name, entity.EntityId, General.Vector3DToString(entity.GetPosition())));
            }

            for(int r = entitiesFound.Count - 1; r >= 0; r--)
            {
                //MyAPIGateway.Entities.RemoveEntity(entity);
                IMyEntity entity = entitiesFound.ElementAt(r);
                CubeGridEntity gridEntity = new CubeGridEntity((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder(), entity);
                gridEntity.Dispose();
            }

            Communication.SendPrivateInformation(userId, string.Format("Removed {0} grids with no beacons", entitiesFound.Count));

            return true;
        }
        public int GetRandom()
        {
            var index = random.Next(0, set.Count);

            return(set.ElementAt(index));
        }