public void Cloner_Collection_HashSet()
        {
            //Arrange

            IEnumerable <Test2> test2List = new HashSet <Test2>
            {
                new Test2 {
                    Name = "Name11"
                },
                new Test2 {
                    Name = "Name12"
                }
            };


            //Act

            var cloner = ClonerBase.Create(test2List.GetType());
            var clone  = (HashSet <Test2>)cloner.Clone(test2List);

            //Assert

            Assert.IsTrue(clone != null &&
                          clone != test2List &&
                          clone.GetType() == test2List.GetType() &&
                          clone.Count == 2 &&
                          clone.Any(x => x.Name == "Name11") &&
                          clone.Any(x => x.Name == "Name12"));
        }
Exemple #2
0
        /// <inheritdoc/>
        public void WriteField <TBufferWriter>(ref Writer <TBufferWriter> writer, uint fieldIdDelta, Type expectedType, HashSet <T> value) where TBufferWriter : IBufferWriter <byte>
        {
            if (ReferenceCodec.TryWriteReferenceField(ref writer, fieldIdDelta, expectedType, value))
            {
                return;
            }

            writer.WriteFieldHeader(fieldIdDelta, expectedType, value.GetType(), WireType.TagDelimited);

            if (value.Comparer != EqualityComparer <T> .Default)
            {
                _comparerCodec.WriteField(ref writer, 0, typeof(IEqualityComparer <T>), value.Comparer);
            }

            Int32Codec.WriteField(ref writer, 1, typeof(int), value.Count);

            uint innerFieldIdDelta = 1;

            foreach (var element in value)
            {
                _fieldCodec.WriteField(ref writer, innerFieldIdDelta, CodecElementType, element);
                innerFieldIdDelta = 0;
            }

            writer.WriteEndObject();
        }
    {   // hashsets are used for unique data!!!
        static void Main(string[] args)
        {
            HashSet <int> MyHashSet  = new HashSet <int>();
            HashSet <int> NewHashSet = new HashSet <int>();

            MyHashSet.Add(1);
            MyHashSet.Add(2);
            MyHashSet.Add(3);
            MyHashSet.Add(4);
            MyHashSet.Add(5);

            MyHashSet.Add(5);

            NewHashSet.Add(4);

            Console.WriteLine(MyHashSet.Count);
            // printed 5 instead of six because i added 5 twice!
            Console.WriteLine("=====================");
            foreach (int i in MyHashSet)
            {
                Console.WriteLine(i);
            }
            // five was only printed once even though I included it twice

            Console.WriteLine("Did i put 5 in here? {0}", MyHashSet.Contains(5));

            int[] HashArry = MyHashSet.ToArray();

            Console.WriteLine(string.Join(", ", MyHashSet));

            Console.WriteLine(MyHashSet.GetType());
            Console.WriteLine(MyHashSet.Overlaps(NewHashSet));
            Console.WriteLine(MyHashSet.Average());
            // string[] CastTest = MyHashSet.Cast<string>();
        }
    public static HashSet <T> SetCapacity <T>(this HashSet <T> hs, int capacity)
    {
        var initialize = hs.GetType().GetMethod("Initialize", Flags);

        initialize.Invoke(hs, new object[] { capacity });
        return(hs);
    }
Exemple #5
0
        static long CountMemory(HashSet <T> set, int sizeOfT)
        {
            int bytes = IntPtr.Size * 6 + 4 * 4;             // size of HashSet<T> itself

            if (HashSet_buckets == null)
            {
                HashSet_buckets = set.GetType().GetField("m_buckets", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
            }

            int arrayLength = 0;

            if (HashSet_buckets != null)
            {
                int[] buckets = (int[])HashSet_buckets.GetValue(set);
                if (buckets != null)
                {
                    arrayLength = buckets.Length;
                }
            }
            else
            {
                arrayLength = MathEx.NextPowerOf2(set.Count) - 1;                 // guess array length
            }
            if (arrayLength != 0)
            {
                bytes += IntPtr.Size * 6;                 // overhead of the two arrays in HashSet
                bytes += arrayLength * (sizeOfT + 12);    // size of the buckets, cached hashcodes, "next" indexes and T data
            }

            return(bytes);
        }
        public void Methods_Ignored()
        {
            var set = new HashSet <int>();

            set.GetHashCode();
            set.Equals(items);
            set.GetType();
            set.Contains(5);
        }
Exemple #7
0
        public void CanAggregateIntoHashSet()
        {
            HashSet <int> set = from i in INT_SOURCE
                                orderby Distinct
                                group i by ToHashSet into s
                                select s;

            set.GetType().Should().Be <HashSet <int> >();
        }
Exemple #8
0
        public void CanSelectDistinct()
        {
            HashSet <int> distinctItems = from i in INT_SOURCE
                                          orderby Distinct
                                          group i by ToHashSet into set
                                          select set;

            distinctItems.GetType().Should().Be <HashSet <int> >();
            distinctItems.Should().ContainInOrder(1, 9, 4, 5, 0, 8, 7);
        }
 /// <summary>
 /// Our replacement loop
 /// </summary>
 /// <param name="list">The Asteroid collection</param>
 /// <param name="writer">The stream used by the Asteroid.SerializeBytes() method.</param>
 public static void Serialize_Asteroids(ref HashSet <Asteroid> list, ref BinaryWriter writer)
 {
     if (PatchWriteWorld.Debug)
     {
         Log($"In Serialize_Asteroids:\nHashSet:{list.GetType().FullDescription()}\n\tCount:{list.Count}");
         Log($"BinaryWriter:{writer.GetType().FullDescription()}");
     }
     foreach (Asteroid a in list)
     {
         a.SerializeBytes(ref writer);
     }
 }
Exemple #10
0
        public void ShouldAssignArrayToNativeSet()
        {
            var        intSet = new HashSet <int>();
            SinTDArray array  = new SinTDArray();

            array.elementType = SinTDInstance.GetSinTDType("i32");
            ISet <int> test = (HashSet <int>)array.AssignValuesToNativeType(new int[1] {
                1
            }, intSet.GetType());

            Assert.AreEqual(1, test.Count);
            Assert.AreEqual(1, test.ElementAt(0));
        }
        public void OnGUI()
        {
            PropertyEditor.Get(_resources.GetType(), null)
            .FirstEditor
            .EditWithGUILayout(new GUIContent("Resources"), _resources, _metadata.Enter("Resources", null));

            if (GUILayout.Button("Write To Disk"))
            {
                const string outputPath = "Assets/FullInspector2/Modules/EditorImagesManager/Editor/fiEditorImages.cs";
                File.WriteAllText(outputPath, BuildFile(_resources));
                AssetDatabase.Refresh();
            }
        }
Exemple #12
0
 public static void Serialize(HashSet <BaseTalent> t, IGenericWriter writer)
 {
     if (t == null)
     {
         writer.WriteEncodedInt(0);
     }
     else
     {
         writer.WriteEncodedInt(t.Count);
         foreach (BaseTalent talent in t)
         {
             Write(t.GetType(), BaseTalent.TalentTypes, writer);
             writer.WriteEncodedInt(talent.Level);
         }
     }
 }
Exemple #13
0
        public async Task TestHomogeneousTypeSafeSet()
        {
            var expected = new HashSet <string> {
                "test", "123"
            };
            var writer = CreateGraphBinaryWriter();
            var reader = CreateGraphBinaryReader();
            var serializationStream = new MemoryStream();

            await writer.WriteValueAsync(expected, serializationStream, false);

            serializationStream.Position = 0;
            var actual = await reader.ReadValueAsync <HashSet <string> >(serializationStream, false);

            Assert.Equal(expected, actual);
            Assert.Equal(expected.GetType(), actual.GetType());
        }
Exemple #14
0
        public virtual void TestHashSetOfString()
        {
            Object        obj  = "";
            ISet <String> coll = new HashSet <String>();

            MethodInfo addMethod = coll.GetType().GetMethod("Add", new Type[] { typeof(String) });

            fixture = new CollectionSetterCommand();
            fixture.ObjectFuture = null;
            fixture.Parent       = coll;
            fixture.AddMethod    = addMethod;
            fixture.Obj          = obj;
            fixture.AfterPropertiesSet();
            fixture.Execute(null);

            Assert.AreEqual(1, coll.Count);
            Assert.AreEqual(obj, coll.ElementAt(0));
        }
        private static void SaveSet <T>(XmlWriter writer, HashSet <T> items, string key)
        {
            writer.WriteStartElement(PROPERTY_ID);
            writer.WriteAttributeString(KEY_ID, key);
            writer.WriteAttributeString(TYPE_ID, items.GetType().Name);

            T[] sorted = new T[items.Count];
            items.CopyTo(sorted, 0);
            Array.Sort(sorted);

            foreach (T item in sorted)
            {
                writer.WriteStartElement(ITEM_ID);
                writer.WriteString(item.ToString());
                writer.WriteEndElement(); // Item
            }

            writer.WriteEndElement(); // Property
        }
        public void Serialize_HashSetWithComparer()
        {
            var source1 = new HashSet <string>(new CaseInsensitiveStringEquality());

            source1.Add("one");
            source1.Add("two");
            source1.Add("three");
            var deserialized = OrleansSerializationLoop(environment.Serializer, environment.DeepCopier, source1);

            Assert.IsAssignableFrom(source1.GetType(), deserialized); //Type is wrong after round-trip of string hash set with comparer
            var result = deserialized as HashSet <string>;

            Assert.Equal(source1.Count, result.Count); //Count is wrong after round-trip of string hash set with comparer
#pragma warning disable xUnit2017                      // Do not use Contains() to check if a value exists in a collection
            foreach (var key in source1)
            {
                Assert.True(result.Contains(key)); //key is missing after round-trip of string hash set with comparer
            }
            Assert.True(result.Contains("One"));   //Comparer is wrong after round-trip of string hash set with comparer
#pragma warning restore xUnit2017                  // Do not use Contains() to check if a value exists in a collection
        }
Exemple #17
0
        /// <inheritdoc/>
        public HashSet <T> DeepCopy(HashSet <T> input, CopyContext context)
        {
            if (context.TryGetCopy <HashSet <T> >(input, out var result))
            {
                return(result);
            }

            if (input.GetType() != typeof(HashSet <T>))
            {
                return(context.DeepCopy(input));
            }

            result = new HashSet <T>(input.Comparer);
            context.RecordCopy(input, result);
            foreach (var item in input)
            {
                result.Add(_copier.DeepCopy(item, context));
            }

            return(result);
        }
Exemple #18
0
        protected override Expression VisitTypeBinary(TypeBinaryExpression node)
        {
            var expression = Visit(node.Expression);

            if (expression.Type != node.Expression.Type)
            {
                HashSet <int>            typeDbIds = null;
                Expression <Func <int> > x         = () => typeDbIds.Count;
                ModelType.TryGetNotAbstractIncludingDerivedTypeDbIds(new string[] { node.TypeOperand.FullName }, out typeDbIds);

                Expression typePropAccess = Expression.MakeMemberAccess(
                    expression,
                    typeof(TDbEntity).GetProperty(nameof(IDbEntity.Type), BindingFlags.Instance | BindingFlags.Public));

                return(Expression.Call(
                           Expression.Constant(typeDbIds),
                           typeDbIds.GetType().GetMethod(nameof(HashSet <int> .Contains)),
                           typePropAccess));
            }

            return(base.VisitTypeBinary(node));
        }
Exemple #19
0
        public void QueryFilterCustomPareter()
        {
            using (var container = new RhetosTestContainer())
            {
                var repository = container.Resolve <Common.DomRepository>();

                var items = new[]
                {
                    new TestFilter.SimpleItem {
                        Name = "si0"
                    },
                    new TestFilter.SimpleItem {
                        Name = "si1"
                    },
                    new TestFilter.SimpleItem {
                        Name = "si2"
                    },
                    new TestFilter.SimpleItem {
                        Name = "si3"
                    },
                };
                repository.TestFilter.SimpleItem.Insert(items);

                var filter = new HashSet <string>(new[] { "si0", "si1" });

                var ids   = items.Select(item => item.ID).ToList();
                var query = repository.TestFilter.SimpleItem.Query();

                var directFilterImplementation = repository.TestFilter.SimpleItem.Filter(query, filter).Where(item => ids.Contains(item.ID));
                Assert.AreEqual("si0, si1", TestUtility.DumpSorted(directFilterImplementation, item => item.Name));

                var genericWithExplicitFilterType = repository.TestFilter.SimpleItem.Load(filter, filter.GetType()).Where(item => ids.Contains(item.ID));
                Assert.AreEqual("si0, si1", TestUtility.DumpSorted(genericWithExplicitFilterType, item => item.Name));

                var genericWithImplicitFilterType = repository.TestFilter.SimpleItem.Load(filter).Where(item => ids.Contains(item.ID));
                Assert.AreEqual("si0, si1", TestUtility.DumpSorted(genericWithImplicitFilterType, item => item.Name));

                var legacyFilterMethod = repository.TestFilter.SimpleItem.Filter(filter).Where(item => ids.Contains(item.ID));
                Assert.AreEqual("si0, si1", TestUtility.DumpSorted(legacyFilterMethod, item => item.Name));
            }
        }
Exemple #20
0
        public void RecursiveJavaScriptSerializerArray()
        {
            var list = SampleModel.CreateListSampleWithCircularReference().ToList();
            var jss  = new JavaScriptSerializer();

            jss.RegisterConverters(new[] { new ControlledSerializationJsonConverter(new[] { list.GetType() }, 50, true, false) });
            var json = jss.Serialize(list);

            if (json != @"[{""Number"":1,""Name"":""a"",""Child"":{""Number"":2,""Name"":""b"",""Child"":{""Number"":3,""Name"":""c""}}}]")
            {
                throw new ApplicationException("List serialization doesn't work. Case 1");
            }

            var array = SampleModel.CreateListSampleWithCircularReference().ToArray();
            var jss2  = new JavaScriptSerializer();

            jss2.RegisterConverters(new[] { new ControlledSerializationJsonConverter(new[] { array.GetType() }, 50, true, false) });
            var json2 = jss.Serialize(array);

            if (json2 != @"[{""Number"":1,""Name"":""a"",""Child"":{""Number"":2,""Name"":""b"",""Child"":{""Number"":3,""Name"":""c""}}}]")
            {
                throw new ApplicationException("List serialization doesn't work. Case 2");
            }

            var hashSet = new HashSet <SampleModel>(SampleModel.CreateListSampleWithCircularReference().ToArray());
            var jss3    = new JavaScriptSerializer();

            jss3.RegisterConverters(new[] { new ControlledSerializationJsonConverter(new[] { hashSet.GetType() }, 50, true, false) });
            var json3 = jss.Serialize(hashSet);

            if (json3 != @"[{""Number"":1,""Name"":""a"",""Child"":{""Number"":2,""Name"":""b"",""Child"":{""Number"":3,""Name"":""c""}}}]")
            {
                throw new ApplicationException("List serialization doesn't work. Case 3");
            }

            var arrayList = new ArrayList(SampleModel.CreateListSampleWithCircularReference().ToArray());
            var jss4      = new JavaScriptSerializer();

            jss4.RegisterConverters(new[] { new ControlledSerializationJsonConverter(new[] { arrayList.GetType() }, 50, true, false) });
            var json4 = jss.Serialize(arrayList);

            if (json4 != @"[{""Number"":1,""Name"":""a"",""Child"":{""Number"":2,""Name"":""b"",""Child"":{""Number"":3,""Name"":""c""}}}]")
            {
                throw new ApplicationException("List serialization doesn't work. Case 3");
            }
        }
Exemple #21
0
 public void ShouldAssignArrayToNativeSet()
 {
     var intSet = new HashSet<int>();
     SinTDArray array = new SinTDArray();
     array.elementType = SinTDInstance.GetSinTDType("i32");
     ISet<int> test = (HashSet<int>)array.AssignValuesToNativeType(new int[1] { 1 }, intSet.GetType());
     Assert.AreEqual(1, test.Count);
     Assert.AreEqual(1, test.ElementAt(0));
 }
Exemple #22
0
 static void Imprimir(HashSet<String> t)
 {
     Console.WriteLine("tipo: {0}", t.GetType().Name);
     Console.WriteLine("quantidade de elementos: {0}", t.Count);
 }
Exemple #23
0
        public void ShouldAssignArrayOfSetsToNative()
        {
            var intArray = new int[1][];

            intArray[0] = new int[1] {
                2
            };
            ISet <int>[] setArray = new HashSet <int>[1] {
                new HashSet <int> {
                    1
                }
            };
            SinTDArray innerArray = new SinTDArray();

            innerArray.elementType = SinTDInstance.GetSinTDType("i32");
            SinTDArray outerArray = new SinTDArray();

            outerArray.elementType = innerArray;
            HashSet <int>[] test = (HashSet <int>[])outerArray.AssignValuesToNativeType(intArray, setArray.GetType());
            Assert.IsAssignableFrom <HashSet <int> >(test[0]);
            Assert.AreEqual(2, test[0].ElementAt(0));
        }
Exemple #24
0
 public void ShouldAssignLSetOfArraysToNative()
 {
     var intArray = new int[1][];
     intArray[0] = new int[1] { 2 };
     ISet<int[]> arraySet = new HashSet<int[]> { new int[1] { 1 } };
     SinTDArray innerArray = new SinTDArray();
     innerArray.elementType = SinTDInstance.GetSinTDType("i32");
     SinTDArray outerArray = new SinTDArray();
     outerArray.elementType = innerArray;
     ISet<int[]> test = (HashSet<int[]>)outerArray.AssignValuesToNativeType(intArray, arraySet.GetType());
     Assert.IsAssignableFrom<int[]>(test.ElementAt(0));
     Assert.AreEqual(2, test.ElementAt(0)[0]);
 }
Exemple #25
0
        public void ShouldAssignLSetOfArraysToNative()
        {
            var intArray = new int[1][];

            intArray[0] = new int[1] {
                2
            };
            ISet <int[]> arraySet = new HashSet <int[]> {
                new int[1] {
                    1
                }
            };
            SinTDArray innerArray = new SinTDArray();

            innerArray.elementType = SinTDInstance.GetSinTDType("i32");
            SinTDArray outerArray = new SinTDArray();

            outerArray.elementType = innerArray;
            ISet <int[]> test = (HashSet <int[]>)outerArray.AssignValuesToNativeType(intArray, arraySet.GetType());

            Assert.IsAssignableFrom <int[]>(test.ElementAt(0));
            Assert.AreEqual(2, test.ElementAt(0)[0]);
        }
Exemple #26
0
 public void ShouldAssignArrayOfSetsToNative()
 {
     var intArray = new int[1][];
     intArray[0] = new int[1] { 2 };
     ISet<int>[] setArray = new HashSet<int>[1] { new HashSet<int> { 1 } };
     SinTDArray innerArray = new SinTDArray();
     innerArray.elementType = SinTDInstance.GetSinTDType("i32");
     SinTDArray outerArray = new SinTDArray();
     outerArray.elementType = innerArray;
     HashSet<int>[] test = (HashSet<int>[])outerArray.AssignValuesToNativeType(intArray, setArray.GetType());
     Assert.IsAssignableFrom<HashSet<int>>(test[0]);
     Assert.AreEqual(2, test[0].ElementAt(0));
 }
Exemple #27
0
        public static void testvector()
        {
            Dictionary <string, string> testdict = new Dictionary <string, string>()
            {
                { "1", "1" },
                { "2", "1" },
                { "3", "2" },
                { "4", "3" },
                { "5", "5" },
                { "6", "8" },
            };

            Console.WriteLine(ObjectPropertyPrinter.PrintProperty(testdict.GetType(), testdict));

            HashSet <string> testhashset = new HashSet <string>()
            {
                "12", "123", "ad", "fd", "qwe", "23",
            };

            Console.WriteLine(ObjectPropertyPrinter.PrintProperty(testhashset.GetType(), testhashset));

            List <int> testlist = new List <int>()
            {
                1, 2, 10, 2, 5, 9, 22, 14, 16,
            };

            Console.WriteLine(ObjectPropertyPrinter.PrintProperty(testlist.GetType(), testlist));

            LinkedList <int> testlinkedlist = new LinkedList <int>(testlist);

            Console.WriteLine(ObjectPropertyPrinter.PrintProperty(testlinkedlist.GetType(), testlinkedlist));

            Queue <string> testq = new Queue <string>(testhashset);

            Console.WriteLine(ObjectPropertyPrinter.PrintProperty(testq.GetType(), testq));

            Stack <int> tests = new Stack <int>(testlist);

            Console.WriteLine(ObjectPropertyPrinter.PrintProperty(tests.GetType(), tests));

            SortedDictionary <string, string> testsd = new SortedDictionary <string, string>(testdict);

            Console.WriteLine(ObjectPropertyPrinter.PrintProperty(testsd.GetType(), testsd));

            SortedList <int, int> testsl = new SortedList <int, int>()
            {
                { 1, 10 },
                { 10, 1 },
                { 55, 5 },
                { 5, 55 },
                { 1000, 101 },
                { 101, 1001 },
            };

            Console.WriteLine(ObjectPropertyPrinter.PrintProperty(testsl.GetType(), testsl));


            Console.WriteLine(ObjectPropertyPrinter.PrintProperty <int>(1));

            Dictionary <string, Dictionary <string, string> > test2dict = new Dictionary <string, Dictionary <string, string> > ();

            test2dict.Add("test2", testdict);
            Console.WriteLine(ObjectPropertyPrinter.PrintProperty(test2dict.GetType(), test2dict));

            Dictionary <string, Dictionary <string, Dictionary <string, string> > > test3dict = new Dictionary <string, Dictionary <string, Dictionary <string, string> > > ();

            test3dict.Add("test3", test2dict);
            Console.WriteLine(ObjectPropertyPrinter.PrintProperty(test3dict.GetType(), test3dict));

            List <Dictionary <string, string> > testldict = new List <Dictionary <string, string> > ();

            testldict.Add(testdict);
            Console.WriteLine(ObjectPropertyPrinter.PrintProperty(testldict.GetType(), testldict));

            object o = new object();

            Console.WriteLine(ObjectPropertyPrinter.PrintProperty(o.GetType(), o));
        }