Example #1
1
        /// <summary>
        /// Locates the changes between the prior and post state of the modules..
        /// </summary>
        /// <param name="modules_prior">List of the available modules prior to the update.</param>
        /// <param name="modules_post">List of the available modules after the update.</param>
        private void PrintChanges(List<CkanModule> modules_prior, List<CkanModule> modules_post)
        {
            var prior = new HashSet<CkanModule>(modules_prior, new NameComparer());
            var post = new HashSet<CkanModule>(modules_post, new NameComparer());


            var added = new HashSet<CkanModule>(post.Except(prior, new NameComparer()));
            var removed = new HashSet<CkanModule>(prior.Except(post, new NameComparer()));


            var unchanged = post.Intersect(prior);//Default compare includes versions
            var updated = post.Except(unchanged).Except(added).Except(removed).ToList();

            // Print the changes.
            user.RaiseMessage("Found {0} new modules, {1} removed modules and {2} updated modules.", added.Count(), removed.Count(), updated.Count());

            if (added.Count > 0)
            {
                PrintModules("New modules [Name (CKAN identifier)]:", added);
            }

            if (removed.Count > 0)
            {
                PrintModules("Removed modules [Name (CKAN identifier)]:", removed);
            }

            if (updated.Count > 0)
            {
                PrintModules("Updated modules [Name (CKAN identifier)]:", updated);
            }
        }
Example #2
0
        public bool run()
        {
            var triangleNumbers = new HashSet<long>();
            var pentagonalNumbers = new HashSet<long>();
            var hexagonalNumbers = new HashSet<long>();
            for (var n = 1L; ; n++)
            {
                long v1 = n * (n + 1) / 2;
                long v2 = n * (3 * n - 1) / 2;
                long v3 = n * (2 * n - 1);
                triangleNumbers.Add(v1);
                pentagonalNumbers.Add(v2);
                hexagonalNumbers.Add(v3);

                if ((pentagonalNumbers.Contains(v1) && hexagonalNumbers.Contains(v1)) ||
                    (triangleNumbers.Contains(v2) && hexagonalNumbers.Contains(v2)) ||
                    (triangleNumbers.Contains(v3) && pentagonalNumbers.Contains(v3)))
                {
                    {
                        if (triangleNumbers.Intersect(pentagonalNumbers)
                                .Intersect(hexagonalNumbers).Count() == 3)
                        {
                            break;
                        }
                    }
                }
            }

            var result =
                triangleNumbers.Intersect(pentagonalNumbers)
                    .Intersect(hexagonalNumbers).OrderBy(v => v).Last();

            return result == 1533776805;
        }
Example #3
0
    static void Main(string[] args)
    {
        int[] input = Console.ReadLine().Split(' ')
            .Select(int.Parse).ToArray();

        int firstSetCount = input.First();
        int secondSetCount = input.Last();

        HashSet<int> firstSet = new HashSet<int>();
        HashSet<int> secondSet = new HashSet<int>();

        for (int i = 0; i < firstSetCount; i++)
        {
            firstSet.Add(int.Parse(Console.ReadLine()));
        }

        for (int i = 0; i < secondSetCount; i++)
        {
            secondSet.Add(int.Parse(Console.ReadLine()));
        }

        List<int> intersect = firstSet.Intersect(secondSet).ToList();

        intersect.ForEach(a => Console.Write(a + " "));
    }
Example #4
0
        public static void Main(string[] args)
        {
            var setSizes =
                Console.ReadLine()
                    .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(int.Parse)
                    .ToArray();

            var firstSet = new HashSet<int>();
            var secondSet = new HashSet<int>();

            for (int i = 0; i < setSizes[0]; i++)
            {
                firstSet.Add(int.Parse(Console.ReadLine()));
            }

            for (int i = 0; i < setSizes[1]; i++)
            {
                secondSet.Add(int.Parse(Console.ReadLine()));
            }

            var resultSet = firstSet.Intersect(secondSet);

            Console.WriteLine(string.Join(" ", resultSet));
        }
		public void UpdateReservedWordsInDialect()
		{
			var reservedDb = new HashSet<string>();
			var configuration = TestConfigurationHelper.GetDefaultConfiguration();
			var dialect = Dialect.Dialect.GetDialect(configuration.Properties);
			var connectionHelper = new ManagedProviderConnectionHelper(configuration.Properties);
			connectionHelper.Prepare();
			try
			{
				var metaData = dialect.GetDataBaseSchema(connectionHelper.Connection);
				foreach (var rw in metaData.GetReservedWords())
				{
					reservedDb.Add(rw.ToLowerInvariant());
				}
			}
			finally
			{
				connectionHelper.Release();
			}

			var sf = (ISessionFactoryImplementor) configuration.BuildSessionFactory();
			SchemaMetadataUpdater.Update(sf);
			var match = reservedDb.Intersect(sf.Dialect.Keywords);
			Assert.That(match, Is.EquivalentTo(reservedDb));
		}
Example #6
0
        public static void Main()
        {
            HashSet<int> mySet = new HashSet<int>();
            mySet.Add(10);
            mySet.Add(11);
            mySet.Add(12);
            mySet.Add(13);
            mySet.Add(19);
            mySet.Add(14);
            mySet.Add(15);

            HashSet<int> myOtherSet = new HashSet<int>();
            myOtherSet.Add(10);
            myOtherSet.Add(11);
            myOtherSet.Add(12);
            myOtherSet.Add(13);
            myOtherSet.Add(14);
            myOtherSet.Add(15);
            myOtherSet.Add(16);

            //var union = mySet.Union(myOtherSet);

            //foreach (var item in union)
            //{
            //    Console.WriteLine(item);
            //}

            var intersect = mySet.Intersect(myOtherSet);

            foreach (var item in intersect)
            {
                Console.WriteLine(item);
            }
        }
Example #7
0
        public static double simularity(HashSet<string> setA, HashSet<string> setB)
        {
            double interCount = setA.Intersect(setB).Count();
            if (interCount == 0) return 0;

            double unionCount = setA.Union(setB).Count();
            return interCount / unionCount;
        }
Example #8
0
        /// <summary>
        /// Does intersect using hash sets.
        /// </summary>
        /// <param name="list1"></param>
        /// <param name="list2"></param>
        /// <param name="toLower"></param>
        /// <param name="factor"></param>
        /// <returns></returns>
        public static bool HashSetIntersects(IEnumerable<string> list1, IEnumerable<string> list2, bool toLower, int factor)
        {
            var set1 = new HashSet<string>(list1);
            var set2 = new HashSet<string>(list2);

            if (toLower)
            {
                return set1.Select(x => x.ToLower()).Intersect(set2.Select(x => x.ToLower())).Count() >= factor;
            }

            return set1.Intersect(set2).Count() >= factor;
        }
        public void TestRecognizeSpirals()
        {
            Bitmap b = MakeBitmap(100, 100, (Graphics g) =>
                {
                    int top = 20;
                    int bottom = 75;

                    for (int i = 20; i <= 60; i += 10 )
                    {
                        g.DrawLine(Pens.Black, i, top, i, bottom);

                        if (i != 80) {
                            if ((i / 10) % 2 == 0) {
                                top += 10;
                                g.DrawLine(Pens.Black, i, bottom, i + 10, bottom);
                            }
                            else {
                                bottom -= 10;
                                g.DrawLine(Pens.Black, i, top, i + 10, top);
                            }
                        }
                    }

                    g.FillPolygon(Brushes.Black, new Point[] {
                        new Point(30, 20),
                        new Point(80, 20),
                        new Point(80, 45) });
                    g.DrawPolygon(Pens.Black, new Point[] {  //Make sure that we draw the borders too
                        new Point(30, 20),
                        new Point(80, 20),
                        new Point(80, 45) });

                    g.FillPolygon(Brushes.Black, new Point[] {
                        new Point(30, 80),
                        new Point(80, 80),
                        new Point(80, 55) });
                    g.DrawPolygon(Pens.Black, new Point[] {
                        new Point(30, 80),
                        new Point(80, 80),
                        new Point(80, 55) });
                });

            HashSet<Rectangle> expected = new HashSet<Rectangle>();
            HashSet<Rectangle> blobs = new HashSet<Rectangle>(from blob in MangaParser.Graphics.Raster.Graphics.IdentifyBlobs(b)
                                                              select blob.BoundingBox);

            expected.Add(new Rectangle(20, 20, 51, 56));
            expected.Add(new Rectangle(30, 20, 51, 26));
            expected.Add(new Rectangle(30, 55, 51, 26));

            Assert.AreEqual(expected.Count, blobs.Intersect(expected).Count());
        }
Example #10
0
    /// <summary>
    /// 创建一个简单路由规则
    /// </summary>
    /// <param name="name">规则名称</param>
    /// <param name="urlPattern">URL 模式</param>
    /// <param name="routeValues">静态/默认路由值</param>
    /// <param name="queryKeys">可用于 QueryString 的参数</param>
    internal SimpleRouteRule( string name, string urlPattern, IDictionary<string, string> routeValues, string[] queryKeys )
    {
      Name = name;

      if ( queryKeys == null )
      {
        LimitedQueries = false;
        queryKeys = new string[0];
      }
      else
        LimitedQueries = true;

      DataTokens = new RouteValueDictionary();


      var match = urlPatternRegex.Match( urlPattern );

      if ( !match.Success )
        throw new FormatException( "URL模式格式不正确" );

      _paragraphes = match.Groups["paragraph"].Captures.Cast<Capture>().Select( c => c.Value ).ToArray();

      _urlPattern = urlPattern;
      _staticValues = new Dictionary<string, string>( routeValues, StringComparer.OrdinalIgnoreCase );


      _routeKeys = new HashSet<string>( _staticValues.Keys, StringComparer.OrdinalIgnoreCase );

      _dynamics = new HashSet<string>( _paragraphes.Where( p => p.StartsWith( "{" ) && p.EndsWith( "}" ) ).Select( p => p.Substring( 1, p.Length - 2 ) ), StringComparer.OrdinalIgnoreCase );



      foreach ( var key in _dynamics )
      {
        if ( _routeKeys.Contains( key ) )
          throw new FormatException( "URL模式格式不正确,包含重复的动态参数名或动态参数名与预设路由键重复" );


        _routeKeys.Add( key );
      }

      if ( _routeKeys.Intersect( queryKeys, StringComparer.OrdinalIgnoreCase ).Any() )
        throw new FormatException( "URL模式格式不正确,动态参数或预设路由键与可选查询字符串名重复" );

      _queryKeys = new HashSet<string>( queryKeys, StringComparer.OrdinalIgnoreCase );

      _allKeys = new HashSet<string>( _routeKeys, StringComparer.OrdinalIgnoreCase );
      _allKeys.UnionWith( _queryKeys );

    }
        public static void Main(string[] args)
        {
            HashSet<int> first = new HashSet<int>();
            first.Add(1);
            first.Add(2);
            first.Add(3);

            Console.Write("First set: ");
            foreach (var item in first)
            {
                Console.Write(item.Key + " ");
            }

            Console.WriteLine();

            HashSet<int> second = new HashSet<int>();
            second.Add(4);
            second.Add(1);
            second.Remove(1);

            Console.Write("Second set: ");
            foreach (var item in second)
            {
                Console.Write(item.Key + " ");
            }

            Console.WriteLine();

            first.Union(second);

            Console.Write("Sets union: ");
            foreach (var item in first)
            {
                Console.Write(item.Key + " ");
            }

            Console.WriteLine();

            //second.Add(1);

            first.Intersect(second);

            Console.Write("Sets intersection: ");
            foreach (var item in first)
            {
                Console.Write(item.Key + " ");
            }

            Console.WriteLine();
        }
    public IEnumerable<Person> GetMatchesByKeysAndTown(string[] param)
    {
        var matchedPersons = names[param[0]];
        HashSet<Person> result = new HashSet<Person>(matchedPersons);
        
        for (int i = 1; i < param.Length; i++)
        {
            matchedPersons = names[param[i]];
            var hashedSet = new HashSet<Person>(matchedPersons);
            result = new HashSet<Person>(result.Intersect(hashedSet));
        }

        return result;
    }
        protected override void InternalHandle(Output result, string args, DependencyGraph graph)
        {
            var projctsFiltered = FilterLibs(graph, args);

            IDictionary<Library, int> components;
            graph.StronglyConnectedComponents(out components);

            var circularDependencies = components.Select(c => new { Proj = c.Key, Group = c.Value })
                .GroupBy(c => c.Group)
                .Where(g => g.Count() > 1);

            bool found = false;
            foreach (var g in circularDependencies)
            {
                var libs = g.Select(i => i.Proj)
                    .ToList();

                var projsSet = new HashSet<Library>(libs);

                if (!projsSet.Intersect(projctsFiltered)
                    .Any())
                    continue;

                found = true;

                libs.Sort(Library.NaturalOrdering);

                result.AppendLine("Circular dependency:");
                result.IncreaseIndent();

                foreach (var lib in libs)
                {
                    var proj = lib as Project;
                    if (proj != null)
                        result.AppendLine("{0} (project path: {1})", GetName(proj), proj.ProjectPath);
                    else
                        result.AppendLine(GetName(lib));
                }

                result.DecreaseIndent();
                result.AppendLine();
            }

            if (!found)
                result.AppendLine("No circular dependency found");
        }
        public void HashSetShouldIntersectElementCorrectly()
        {
            var set1 = new HashSet<int>();
            var set2 = new HashSet<int>();
            set1.Add(1);
            set1.Add(2);
            set1.Add(3);

            set2.Add(1);
            set2.Add(5);
            set2.Add(6);

            var intersect = set1.Intersect(set2);

            Assert.IsTrue(intersect.Find(1));
            Assert.AreEqual(1, intersect.Count);
        }
        public static void Main()
        {
            var firstSet = new HashSet<int>();
            var secondSet = new HashSet<int>();
            firstSet.Add(1);
            firstSet.Add(2);
            firstSet.Add(7);
            secondSet.Add(7);
            secondSet.Add(13);
            secondSet.Add(19);
            firstSet.Remove(2);

            var unionSet = firstSet.Union(secondSet);
            Console.WriteLine("Union set = {0}", unionSet);

            var intersectSet = firstSet.Intersect(secondSet);
            Console.WriteLine("Intersect set = {0}", intersectSet);
        }
        public async Task OptionsViewModel_ReconcilePlatformsWithBackendAsync_ReturnsInvalidPlatforms()
        {
            int numberOfPlatforms = 6;
            var serverPlatformNames = new string[] { "valid1", "valid2" };
            var apiPort = ApiPortWhichReturnsPlatforms(serverPlatformNames);

            var invalidLocalPlatforms = (from n in Enumerable.Range(1, numberOfPlatforms)
                                 select new TargetPlatform { Name = string.Format("invalid{0}", n), Selected = n % 2 == 0 })
                                 .ToList();

            var viewModel = new TestableOptionsViewModel(apiPort, invalidLocalPlatforms);

            var result = await viewModel.ReconcilePlatformsWithBackendAsync();

            var localHash = new HashSet<TargetPlatform>(invalidLocalPlatforms);
            var resultHash = new HashSet<TargetPlatform>(result);

            Assert.IsTrue(localHash.Intersect(resultHash).Count() == localHash.Count);
        }
Example #17
0
        static void Main(string[] args)
        {
            int[] dimentions =
                Console.ReadLine().Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();

            HashSet<int> set1= new HashSet<int>();
            HashSet<int> set2 = new HashSet<int>();

            for (int i = 0; i < dimentions[0]; i++)
            {
                set1.Add(int.Parse(Console.ReadLine()));
            }
            for (int i = 0; i < dimentions[1]; i++)
            {
                set2.Add(int.Parse(Console.ReadLine()));
            }

            Console.WriteLine(string.Join(" ",set1.Intersect(set2)));
        }
            protected override void Push(IEnumerable<ParameterExpression> variables)
            {
                var newEnv = new HashSet<ParameterExpression>(variables);
                var subst = new Dictionary<ParameterExpression, ParameterExpression>();

                foreach (var env in _env)
                {
                    if (env.Overlaps(newEnv))
                    {
                        foreach (var p in newEnv.Intersect(env))
                        {
                            subst[p] = Expression.Parameter(p.Type, p.Name);
                        }
                    }
                }

                _env.Push(newEnv);
                _subst.Push(subst);
            }
        static void Main(string[] args)
        {
            HashSet<string> hashSet = new HashSet<string>();

            hashSet.Add("ooo");
            hashSet.Add("qqq");
            hashSet.Add("ppp");
            hashSet.Add("iii");

            foreach (var item in hashSet.Items)
            {
                Console.WriteLine(item);
            }

            hashSet.Remove("iii");
            Console.WriteLine("\nCount after removal: {0}", hashSet.Count);


            Console.WriteLine();
            Console.WriteLine(hashSet.Find("ppp"));


            HashSet<string> secondHashSet = new HashSet<string>();
            secondHashSet.Add("www");
            secondHashSet.Add("qqq");
            secondHashSet.Add("yyy");
            secondHashSet.Add("ooo");

            Console.WriteLine("\nUnion: ");
            HashSet<string> union = hashSet.Union(secondHashSet);
            foreach (var item in union.Items)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("\nIntersection: ");
            HashSet<string> intersection = hashSet.Intersect(secondHashSet);
            foreach (var item in intersection.Items)
            {
                Console.WriteLine(item);
            }
        }
		public static void MenuSelectFacesWithColor()
		{
			foreach(pb_Object pb in pbUtil.GetComponents<pb_Object>(Selection.transforms))
			{
				HashSet<Color> cols = new HashSet<Color>();
				
				foreach(pb_Face f in pb.SelectedFaces)
				{
					foreach(int i in f.distinctIndices)
						cols.Add(pb.colors[i]);
				}

				pb_Face[] faces = System.Array.FindAll(pb.faces, x => cols.Intersect(pbUtil.ValuesWithIndices(pb.colors, x.distinctIndices)).Count() > 0);

				pb.SetSelectedFaces(faces);
				if(pb_Editor.instance)
					pb_Editor.instance.UpdateSelection();
				
				EditorWindow.FocusWindowIfItsOpen(typeof(SceneView));
			}
		}
Example #21
0
        static void Main()
        {
            HashSet<string> testTable = new HashSet<string>();

            testTable.Add("stoicho");
            testTable.Add("peicho");
            testTable.Add("koicho");
            testTable.Add("koicho");
            testTable.Add("koicho");
            testTable.Add("nacho");
            testTable.Add("bochko");
            testTable.Add("zuza");
            testTable.Add("ko");

            //foreach (var key in testTable)
            //{
            //    Console.WriteLine(key);

            //}

            HashSet<string> testTable2 = new HashSet<string>();
            testTable2.Add("gosho");
             testTable2.Add("stoicho");
            testTable2.Add("peicho");
            testTable2.Add("koicho");
             testTable2.Add("asen");
            testTable2.Add("peicho");
            testTable2.Add("toshkata");

            //testTable.Union(testTable2);

            var testTable3 = testTable.Intersect(testTable2);

            foreach (var key in testTable3)
            {
                Console.WriteLine(key);

            }
        }
Example #22
0
        static void Main(string[] args)
        {
            int NewNumber = 10000000;

            int[] FirstArray = new int[NewNumber];

            int[] SecondArray = new int[NewNumber];

            int[] ThirdArray = new int[NewNumber];

            FirstArray[0] = 1;

            SecondArray[0] = 2;

            ThirdArray[0] = 2;

            for (int i = 1; i < NewNumber; i++)
            {
                FirstArray[i] = 2 * FirstArray[i - 1] + 3;
                SecondArray[i] = 3 * SecondArray[i - 1] + 1;
                ThirdArray[i] = 2 * ThirdArray[i - 1] - 1;
            }

            HashSet<int> hash1 = new HashSet<int>(FirstArray);

            HashSet<int> hash2 = new HashSet<int>(SecondArray);

            HashSet<int> hash3 = new HashSet<int>(ThirdArray);

            HashSet<int> Union1 = new HashSet<int>(hash1.Union(hash2));

            HashSet<int> Union2 = new HashSet<int>(hash2.Intersect(hash3));

            foreach (var item in Union2)
            {
                Console.WriteLine(item);
            }
        }
Example #23
0
        public bool IsConnected()
        {
            HashSet<Point> allPathablePoints = new HashSet<Point>();
            foundPathablePoints = new HashSet<Point>();

            for (int i = 0; i < thisMap.Width; i++)
            {
                for (int j = 0; j < thisMap.Height; j++)
                {
                    if(CountsAsWalkable(thisMap.getCell(i, j)))
                        allPathablePoints.Add(new Point(i, j));
                }
            }

            if(allPathablePoints.Count() == 0)
                return true;

            Stack<Point> workNodes = new Stack<Point>();

            workNodes.Push(allPathablePoints.First());

            while (workNodes.Count() > 0)
            {
                var thisNode = workNodes.Pop();
                if (CountsAsWalkable(thisMap.getCell(thisNode.x, thisNode.y)))
                {
                    foundPathablePoints.Add(thisNode);
                    var neighbours = Get4WayNeighbours(thisNode);
                    foreach (var p in neighbours)
                        workNodes.Push(p);
                }
            }

            if (allPathablePoints.Intersect(foundPathablePoints).Count() == allPathablePoints.Count())
                return true;

            return false;
        }
Example #24
0
        public static void Main()
        {
            try
            {
                HashSet<int> hashSet = new HashSet<int>();

                hashSet.Add(1);
                hashSet.Add(5);
                hashSet.Add(2);
                hashSet.Add(33);
                Console.WriteLine("Count is : {0}", hashSet.Count);

                hashSet.Remove(2);
                Console.WriteLine("Count is : {0}", hashSet.Count);

                Console.WriteLine(hashSet.Find(5));
                Console.WriteLine(hashSet.Contains(5));

                int[] numArray = new int[] { 5, 11, 33 };
                int[] array = numArray;
                hashSet.UnionWith(array);
                Console.WriteLine("Count is : {0}", hashSet.Count);

                int[] numArray1 = new int[] { 5, 11, 22 };
                int[] array2 = numArray1;
                hashSet.Intersect(array2);
                Console.WriteLine("Count is : {0}", hashSet.Count);

                hashSet.Clear();
                Console.WriteLine("Count is : {0}", hashSet.Count);
                Console.WriteLine(hashSet.Find(5));
            }
            catch (ArgumentException aex)
            {
                Console.WriteLine(aex.Message);
            }
        }
Example #25
0
        static void Main(string[] args)
        {
            int numberOfEdges = int.Parse(Console.ReadLine());

            HashSet<int> parents = new HashSet<int>();
            HashSet<int> childrens = new HashSet<int>();
            for (int i = 0; i < numberOfEdges; i++)
            {
                string[] current = Console.ReadLine().Split();
                parents.Add(int.Parse(current[0]));
                childrens.Add(int.Parse(current[1]));
            }

            IEnumerable<int> result = parents.Intersect(childrens);
            foreach (var item in result)
            {
                childrens.Remove(item);
            }

            int[] forPrint = childrens.ToArray();
            Array.Sort(forPrint);

            Console.WriteLine(string.Join("\n", forPrint));
        }
Example #26
0
        static void Main(string[] args)
        {
            int number = 100000;

           
            int[] arr1 = new int[number];
            int[] arr2 = new int[number];
            int[] arr3 = new int[number];

            arr1[0] = 1;
            arr2[0] = 2;
            arr3[0] = 2;

            for (int i = 1; i < number; i++)
            {
                arr1[i] = 2 * arr1[i - 1] + 3;
                arr2[i] = 3 * arr2[i - 1] + 1;
                arr3[i] = 2 * arr3[i - 1] - 1;
            }

            HashSet<int> hash1 = new HashSet<int>(arr1);
            HashSet<int> hash2 = new HashSet<int>(arr2);
            HashSet<int> hash3 = new HashSet<int>(arr3);
            HashSet<int> Union1 = new HashSet<int>(hash1.Union(hash2)); 
            HashSet<int> Union2 = new HashSet<int>(hash2.Intersect(hash3));


        

            foreach (var item in Union2)
            {
                Console.WriteLine(item);
            }


        }
        public override bool HandleCommand(ulong userId, string[] words)
        {
            bool showConcealed = true;
            if (words.Length > 0 && words[0].ToLower() == "revealed")
                showConcealed = false;

            if (showConcealed)
            {
                HashSet<IMyEntity> entities = new HashSet<IMyEntity>();
                Wrapper.GameAction(() =>
                {
                    MyAPIGateway.Entities.GetEntities(entities);
                });

                Communication.SendPrivateInformation(userId, "==== Concealed Entities ===");
                int count = 0;
                foreach (IMyEntity entity in entities)
                {
                    if (!(entity is IMyCubeGrid))
                        continue;

                    if (entity.InScene)
                        continue;

                    IMyCubeGrid grid = (IMyCubeGrid)entity;
                    long ownerId = 0;
                    string ownerName = "";
                    if (grid.BigOwners.Count > 0)
                    {
                        ownerId = grid.BigOwners.First();
                        ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name;
                    }

                    if (ownerName == "")
                        ownerName = "No one";

                    Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition())));
                    count++;
                }

                Communication.SendPrivateInformation(userId, string.Format("Total concealed entities: {0}", count));
            }
            else
            {
                HashSet<IMyEntity> entities = new HashSet<IMyEntity>();
                Wrapper.GameAction(() =>
                {
                    MyAPIGateway.Entities.GetEntities(entities);
                });

                Communication.SendPrivateInformation(userId, "==== Revealed Entities ===");
                Communication.SendPrivateInformation(userId, "==== Unconnected Entities ===");
                HashSet<IMyEntity> entitiesFound = new HashSet<IMyEntity>();
                CubeGrids.GetGridsUnconnected(entitiesFound, entities);
                int count = 0;
                List<IMySlimBlock> slimBlocks = new List<IMySlimBlock>();
                foreach (IMyEntity entity in entitiesFound)
                {
                    if (!(entity is IMyCubeGrid))
                        continue;

                    if (!entity.InScene)
                        continue;

                    IMyCubeGrid grid = (IMyCubeGrid)entity;
                    long ownerId = 0;
                    string ownerName = "";
                    if (grid.BigOwners.Count > 0)
                    {
                        ownerId = grid.BigOwners.First();
                        ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name;
                    }

                    if (ownerName == "")
                        ownerName = "No one";

                    grid.GetBlocks(slimBlocks, null);
                    Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4} BlockCount: {5}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition()), slimBlocks.Count));
                    slimBlocks.Clear();
                    count++;
                }

                Communication.SendPrivateInformation(userId, string.Format("Total unconnected revealed entities: {0}", count));

                Communication.SendPrivateInformation(userId, "==== Connected Entities ===");
                HashSet<IMyEntity> connectedFound = new HashSet<IMyEntity>();
                CubeGrids.GetConnectedGrids(connectedFound);
                Console.WriteLine("Here: {0} : {1} {2}", connectedFound.Intersect(entitiesFound).Count(), entitiesFound.Count, connectedFound.Count);
                count = 0;
                slimBlocks.Clear();
                foreach (IMyEntity entity in connectedFound)
                {
                    if (!(entity is IMyCubeGrid))
                        continue;

                    if (entitiesFound.Contains(entity))
                        continue;

                    if (!entity.InScene)
                        continue;

                    if (CubeGrids.GetRecursiveGridList((IMyCubeGrid)entity).Count < 2)
                        continue;

                    IMyCubeGrid grid = (IMyCubeGrid)entity;
                    long ownerId = 0;
                    string ownerName = "";
                    if (grid.BigOwners.Count > 0)
                    {
                        ownerId = grid.BigOwners.First();
                        ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name;
                    }

                    if (ownerName == "")
                        ownerName = "No one";

                    grid.GetBlocks(slimBlocks, null);
                    Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4} BlockCount: {5} Connections: {6}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition()), slimBlocks.Count, CubeGrids.GetRecursiveGridList(grid).Count));
                    //Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4} BlockCount: {5} Connections: {6}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition()), slimBlocks.Count));
                    slimBlocks.Clear();
                    count++;
                }

                Communication.SendPrivateInformation(userId, string.Format("Total connected revealed entities: {0}", count));

            }

            return true;
        }
Example #28
0
        public void HashSetWithBuiltInComparer_HashSetContainsNotUsed()
        {
            IEnumerable<string> input1 = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "a" };
            IEnumerable<string> input2 = new[] { "A" };

            Assert.Equal(Enumerable.Empty<string>(), input1.Intersect(input2));
            Assert.Equal(Enumerable.Empty<string>(), input1.Intersect(input2, null));
            Assert.Equal(Enumerable.Empty<string>(), input1.Intersect(input2, EqualityComparer<string>.Default));
            Assert.Equal(new[] { "a" }, input1.Intersect(input2, StringComparer.OrdinalIgnoreCase));

            Assert.Equal(Enumerable.Empty<string>(), input2.Intersect(input1));
            Assert.Equal(Enumerable.Empty<string>(), input2.Intersect(input1, null));
            Assert.Equal(Enumerable.Empty<string>(), input2.Intersect(input1, EqualityComparer<string>.Default));
            Assert.Equal(new[] { "A" }, input2.Intersect(input1, StringComparer.OrdinalIgnoreCase));
        }
Example #29
0
        public CreeperGameState GetGameState(CreeperColor playerTurn)
        {
            if (TeamCount(playerTurn, PieceType.Peg) == 0 || TeamCount(playerTurn.Opposite(), PieceType.Peg) == 0)
            {
                return CreeperGameState.Draw;
            }

            bool gameOver = false;
            bool stackEmpty = false;
            Stack<AIBoardNode> stack = new Stack<AIBoardNode>();
            HashSet<AIBoardNode> foundTiles = new HashSet<AIBoardNode>();
            HashSet<AIBoardNode> endTiles = new HashSet<AIBoardNode>();
            Position start = (playerTurn == CreeperColor.Fire) ? _WhiteStart : _BlackStart;
            Position end = (playerTurn == CreeperColor.Fire) ? _WhiteEnd : _BlackEnd;
            AIBoardNode winTile1 = TileBoard[end.Row - 1, end.Column];
            AIBoardNode winTile2 = TileBoard[end.Row, IsValidPosition(end.Row, end.Column - 1, PieceType.Tile)? end.Column - 1: end.Column + 1];
            if (winTile1.Color == playerTurn) endTiles.Add(winTile1);
            if (winTile2.Color == playerTurn) endTiles.Add(winTile2);

            if (!endTiles.Any())
            {
                return CreeperGameState.Unfinished;
            }

            AIBoardNode currentTile = TileBoard[start.Row, start.Column];
            IEnumerable<AIBoardNode> neighbors = GetNeighbors(currentTile, playerTurn);
            while (!stackEmpty && !(currentTile.Row == end.Row && currentTile.Column == end.Column))
            {
                foreach (AIBoardNode neighbor in neighbors)
                {
                    if (!foundTiles.Contains(neighbor))
                    {
                        stack.Push(neighbor);
                    }
                }

                foundTiles.UnionWith(neighbors);
                if (foundTiles.Intersect(endTiles).Any())
                {
                    gameOver = true;
                    break;
                }

                if (stack.Any())
                {
                    currentTile = stack.Pop();
                }
                else
                {
                    stackEmpty = true;
                }

                neighbors = GetNeighbors(currentTile, playerTurn);
            }

            return gameOver ? CreeperGameState.Complete : CreeperGameState.Unfinished;
        }
Example #30
0
        private void UpdateContextMenu()
        {
            var projects = projectMonitor.GetProjects();
              var updatedProjects = projectMonitor.GetUpdatedProjects();
              var editedProjects = projectMonitor.GetEditedProjects();
              var update = notifyIcon.ContextMenu.MenuItems[3];
              var upload = notifyIcon.ContextMenu.MenuItems[4];
              var view = notifyIcon.ContextMenu.MenuItems[5];
              var curNames = new HashSet<string>(from item in update.MenuItems.Cast<MenuItem>() select item.Text);
              var newNames = new HashSet<string>(from p in projects select p.name);
              var updNames = new HashSet<string>(from p in updatedProjects select p.name);
              var editNames = new HashSet<string>(from p in editedProjects select p.name);
              var writeNames = new HashSet<string>(from p in projects where p.can_write select p.name);

              for (int i = update.MenuItems.Count - 1; i >= 0; i--) {
            MenuItem item = update.MenuItems[i];
            if (!newNames.Contains(item.Text)) {
              update.MenuItems.Remove(item);
            } else {
              item.Checked = updNames.Contains(item.Text);
            }
              }

              for (int i = view.MenuItems.Count - 1; i >= 0; i--) {
            MenuItem item = view.MenuItems[i];
            if (!newNames.Contains(item.Text)) {
              view.MenuItems.Remove(item);
            }
              }

              const string readOnlySuffix = " (read-only)";
              for (int i = upload.MenuItems.Count - 1; i >= 0; i--) {
            MenuItem item = upload.MenuItems[i];
            string projName = item.Text;
            if (projName.EndsWith(readOnlySuffix)) {
              projName = projName.Substring(0, projName.Length - readOnlySuffix.Length);
            }
            if (!newNames.Contains(projName)) {
              upload.MenuItems.Remove(item);
            } else {
              bool canWrite = writeNames.Contains(projName);
              item.Enabled = canWrite;
              item.Checked = canWrite && editNames.Contains(projName);
              item.Text = projName + (canWrite ? "" : readOnlySuffix);
            }
              }

              foreach (var project in projects) {
            if (!curNames.Contains(project.name)) {
              var curProject = project; // closure issues
              var item = new MenuItem(project.name, CreateUpdateProjectHandler(curProject)) {
            Checked = updNames.Contains(project.name),
            RadioCheck = true
              };
              update.MenuItems.Add(item);
              item = new MenuItem(project.name + (project.can_write ? "" : readOnlySuffix),
                              CreateUploadProjectHandler(curProject)) {
            Enabled = project.can_write,
            Checked = project.can_write && editNames.Contains(project.name),
            RadioCheck = true
              };
              upload.MenuItems.Add(item);
              item = new MenuItem(project.name, CreateViewProjectHistoryHandler(curProject));
              view.MenuItems.Add(item);
            }
              }

              var updateAll = notifyIcon.ContextMenu.MenuItems[7];
              updateAll.Text = "Update All" + (updNames.Count > 0 ? String.Format(" ({0})", updNames.Count) : "");

              var uploadAll = notifyIcon.ContextMenu.MenuItems[8];
              int uploadable = writeNames.Intersect(editNames).Count();
              uploadAll.Text = "Upload All" + (uploadable > 0 ? String.Format(" ({0})", uploadable) : "");
              uploadAll.Enabled = writeNames.Count > 0;

              update.Enabled = upload.Enabled = updateAll.Enabled = view.Enabled = projects.Count > 0;

              // Hide the loading indicator and show others
              notifyIcon.Icon = updNames.Count > 0 || uploadable > 0 ? notifyIconUpdate : notifyIconBase;
              notifyIcon.Text = "SciGit\n";

              if (projectMonitor.syncing > 0) {
            notifyIcon.Icon = notifyIconLoading;
            notifyIcon.Text += "Syncing projects...";
              } else if (updNames.Count > 0) {
            notifyIcon.Text += "Project updates available.";
              } else if (uploadable > 0) {
            notifyIcon.Text += "Local changes awaiting upload.";
              } else {
            notifyIcon.Text += "All projects up to date.";
              }

              for (int i = 3; i <= 8; i++) {
            notifyIcon.ContextMenu.MenuItems[i].Visible = true;
              }
              notifyIcon.ContextMenu.MenuItems[9].Visible = false;
        }