예제 #1
0
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj))
            {
                return(false);
            }
            if (ReferenceEquals(this, obj))
            {
                return(true);
            }
            EffectiveProfile prof = obj as EffectiveProfile;

            if (prof != null)
            {
                IStructuralEquatable eqProfile = prof._profileData;
                return
                    (eqProfile.Equals(_profileData,
                                      StructuralComparisons.StructuralEqualityComparer));
            }
            return(false);
        }
예제 #2
0
    public static void Main()
    {
        var rate1 = Tuple.Create("New York", .014505, -.1042733,
                                 .0354833, .093644, .0290792);
        var rate2 = Tuple.Create("Unknown City", .014505, -.1042733,
                                 .0354833, .093644, .0290792);
        var rate3 = Tuple.Create("Unknown City", .014505, -.1042733,
                                 .0354833, .093644, .029079);
        var rate4 = Tuple.Create("San Francisco", -.0332858, -.0512803,
                                 .0662544, .0728964, .0491912);
        IStructuralEquatable eq = rate1;

        // Compare first tuple with remaining two tuples.
        Console.WriteLine("{0} = ", rate1.ToString());
        Console.WriteLine("   {0} : {1}", rate2,
                          eq.Equals(rate2, new RateComparer <string, double, double, double, double, double>()));
        Console.WriteLine("   {0} : {1}", rate3,
                          eq.Equals(rate3, new RateComparer <string, double, double, double, double, double>()));
        Console.WriteLine("   {0} : {1}", rate4,
                          eq.Equals(rate4, new RateComparer <string, double, double, double, double, double>()));
    }
예제 #3
0
        private void HandleOperationEvent(object sender, EventArgs args)
        {
            CallbackValues = null;

            switch (args)
            {
            case BrowseEventArgs oeArgs:
            {
                CallbackValues = (OperationCallbackType.Browse, oeArgs.EventType, oeArgs.Descriptor.InstanceName, oeArgs.Descriptor.ServiceType, oeArgs.Descriptor.Domain, oeArgs.Descriptor.InterfaceIndex);
                break;
            }

            case RegistrationEventArgs oeArgs:
            {
                CallbackValues = (OperationCallbackType.Register, oeArgs.EventType, oeArgs.Descriptor.InstanceName, oeArgs.Descriptor.ServiceType, oeArgs.Descriptor.Domain, oeArgs.Descriptor.InterfaceIndex);
                break;
            }

            case ResolveEventArgs oeArgs:
            {
                byte[] trBytes = null;
                if (oeArgs.TxtRecords != null)
                {
                    var trb = new TxtRecordBuilder(oeArgs.TxtRecords);
                    trBytes = trb.GetBytes();
                }

                CallbackValues = (OperationCallbackType.Resolve, oeArgs.FullName, oeArgs.HostName, oeArgs.Port, trBytes, oeArgs.InterfaceIndex);
                break;
            }

            case LookupEventArgs oeArgs:
            {
                CallbackValues = (OperationCallbackType.Lookup, oeArgs.EventType, oeArgs.HostName, oeArgs.IPAddress, oeArgs.Ttl, oeArgs.InterfaceIndex);
                break;
            }
            }

            _manualResetEvent.Set();
        }
예제 #4
0
        public void TestCompareByMinElement()
        {
            int[][] array =
            {
                new[] { 1, -2, 3 },
                new[] { 0,  2,13, 4 },
                new[] { 1,3 },
                new[] { 14 }
            };
            int[][] testArray =
            {
                new[] { 1, -2, 3 },
                new[] { 0,  2,13, 4 },
                new[] { 1,3 },
                new[] {14 },
            };
            Task2Refatored.ArraySort.Sort(array, new CompareRowsByMinInc());

            IStructuralEquatable arrays = array;

            Assert.AreEqual(arrays.Equals(testArray, StructuralComparisons.StructuralEqualityComparer), true);
        }
        static void Main()
        {
            var comparer = new CompoundEqualityComparer();

            comparer.Add(new AbsoluteValueEqualityComparer());
            comparer.Add(StringComparer.OrdinalIgnoreCase);

            IStructuralEquatable a = ("abc", 10, 'x');
            IStructuralEquatable b = ("ABC", 10, 'x');
            IStructuralEquatable c = ("abc", -10, 'x');
            IStructuralEquatable d = ("abc", 10, 'X');
            IStructuralEquatable e = ("def", 10, 'x');
            IStructuralEquatable f = ("abc", 20, 'x');
            IStructuralEquatable g = ("abc", 10, 'y');

            Console.WriteLine(a.Equals(b, comparer)); // True: string comparisons are case-insensitive
            Console.WriteLine(a.Equals(c, comparer)); // True: int comparisons are sign-insensitive
            Console.WriteLine(a.Equals(d, comparer)); // False: char comparisons are case-sensitive
            Console.WriteLine(a.Equals(e, comparer)); // False: we don't just ignore the string value
            Console.WriteLine(a.Equals(f, comparer)); // False: we don't just ignore the int value
            Console.WriteLine(a.Equals(g, comparer)); // False: we don't just ignore the char value
        }
예제 #6
0
        public static bool OperarorMultiply_PositiveTests()
        {
            Polynom first       = new Polynom(25, 89, -54, 0, 3, 17);
            Polynom second      = new Polynom(42, 17, 22);
            Polynom multiplyRes = new Polynom(1050, 4163, -205, 1040, -1062, 765, 355, 374);

            int[] check = new int[multiplyRes.Length()];
            for (int i = 0; i < multiplyRes.Length(); i++)
            {
                check[i] = multiplyRes.Coefficents[i];
            }
            Polynom third = first * second;

            int[] check2 = new int[third.Length()];
            for (int i = 0; i < third.Length(); i++)
            {
                check2[i] = third.Coefficents[i];
            }
            IStructuralEquatable a = check;

            return(a.Equals(check2, StructuralComparisons.StructuralEqualityComparer));
        }
예제 #7
0
        static bool DiffXml(string windiffpath, string file1, string file2)
        {
            string tempfolder = Path.GetTempPath();

            string outfile1 = GetSemiUniqueFileName(Path.Combine(tempfolder, Path.GetFileNameWithoutExtension(file1)), ".xml");

            if (!CleanFile(file1, outfile1))
            {
                return(false);
            }

            string outfile2 = GetSemiUniqueFileName(Path.Combine(tempfolder, Path.GetFileNameWithoutExtension(file2)), ".xml");

            if (!CleanFile(file2, outfile2))
            {
                return(false);
            }

            bool diff;

            byte[] buf1 = File.ReadAllBytes(outfile1);
            byte[] buf2 = File.ReadAllBytes(outfile2);

            IStructuralEquatable eqa1 = buf1;

            diff = !eqa1.Equals(buf2, StructuralComparisons.StructuralEqualityComparer);


            if (_DontDiffIfEqual || diff)
            {
                if (_WinDiff)
                {
                    Console.WriteLine($"Diffing: '{file1}' and '{file2}'");
                    System.Diagnostics.Process.Start(windiffpath, $"\"{outfile1}\" \"{outfile2}\"");
                }
            }

            return(diff);
        }
예제 #8
0
        public static bool OperarorPlus_PositiveTests()
        {
            Polynom first   = new Polynom(25, 89, -54, 0, 3, 17);
            Polynom second  = new Polynom(42, 17, 22);
            Polynom plusRes = new Polynom(67, 106, -32, 0, 3, 17);

            int[] check = new int[plusRes.Length()];
            for (int i = 0; i < plusRes.Length(); i++)
            {
                check[i] = plusRes.Coefficents[i];
            }
            Polynom third = first + second;

            int[] check2 = new int[third.Length()];
            for (int i = 0; i < third.Length(); i++)
            {
                check2[i] = third.Coefficents[i];
            }
            IStructuralEquatable a = check;

            return(a.Equals(check2, StructuralComparisons.StructuralEqualityComparer));
        }
예제 #9
0
        /// <inheritdoc />
        public int GetHashCode(object obj)
        {
            IEqualityComparerContracts.GetHashCode(obj);

            // if there is a comparer registered for the type then use that
            IEqualityComparer comparer;

            if (this.comparerPerType.TryGetValue(obj.GetType(), out comparer))
            {
                return(comparer.GetHashCode(obj));
            }

            // check if the type is structurally equatable, and if so pass this comparer as the structural comparer
            IStructuralEquatable structuralEquatable = obj as IStructuralEquatable;

            if (structuralEquatable != null)
            {
                return(structuralEquatable.GetHashCode(this));
            }

            // otherwise fall back on regular hashcode
            return(obj.GetHashCode());
        }
        public void SortBubblesort_decreaseMaxAbs_Test()
        {
            int[][] jaggedArray =
            {
                new [] { -61, 3,  0 },
                new [] {   5, 2, 45 },
                null,
                new [] {  10, 46 }
            };

            int[][] decreaseMaxAbsInRowResult =
            {
                new [] { -61, 3,  0 },
                new [] {  10,46 },
                new [] {   5, 2, 45 },
                null
            };

            Sort.BubbleSort(jaggedArray, decreaseMaxAbsInRow);
            IStructuralEquatable arrays = jaggedArray;

            Assert.AreEqual(arrays.Equals(decreaseMaxAbsInRowResult, StructuralComparisons.StructuralEqualityComparer), true);
        }
예제 #11
0
        public void Initialize(List <ConversationPage> _openedConnection, int[] nr, int _mynumber)
        {
            istnieje = false;
            idx      = 0;
            myNumber = _mynumber;
            //nr_z_sel_item = Int32.Parse(selected);
            conversationConnections = _openedConnection;
            //openedConnections.Add(new ChatPage(idx, nr));

            foreach (ConversationPage chatPage in conversationConnections)
            {
                IStructuralEquatable se1 = chatPage.conversation_numbers;
                if (se1.Equals(nr, StructuralComparisons.StructuralEqualityComparer))
                {
                    istnieje = true;
                }                                                                                         // tu jest blad pewnie cos takiego jak converstation_numbers jst
            }
            if (istnieje == true)
            {
                foreach (ConversationPage convPage in conversationConnections)
                {
                    IStructuralEquatable se1 = convPage.conversation_numbers;
                    if (se1.Equals(nr, StructuralComparisons.StructuralEqualityComparer))
                    {
                        idx = conversationConnections.IndexOf(convPage);
                    }
                }
                _mainFrame.Navigate(conversationConnections[idx]);
            }
            else
            {
                ConversationPage strona = new ConversationPage(nr, myNumber);
                conversationConnections.Add(strona);
                idx = conversationConnections.IndexOf(strona);
                _mainFrame.Navigate(conversationConnections[idx]); //Bug wyswietlil idx 1
            }
        }
예제 #12
0
파일: equals2.cs 프로젝트: zhimaqiao51/docs
    public static void Main()
    {
        Tuple <string, int, double, double>[] temperatures =
        { Tuple.Create("New York, NY",        4, 61.0, 43.0),
          Tuple.Create("Chicago, IL",     2, 34.0, 18.0),
          Tuple.Create("Newark, NJ",      4, 61.0, 43.0),
          Tuple.Create("Boston, MA",      6, 77.0, 59.0),
          Tuple.Create("Detroit, MI",     9, 74.0, 53.0),
          Tuple.Create("Minneapolis, MN", 8, 81.0, 61.0) };
        // Compare each item with every other item for equality.
        for (int ctr = 0; ctr < temperatures.Length; ctr++)
        {
            IStructuralEquatable temperatureInfo = temperatures[ctr];
            for (int ctr2 = ctr + 1; ctr2 < temperatures.Length; ctr2++)
            {
                Console.WriteLine("{0} = {1}: {2}",
                                  temperatureInfo, temperatures[ctr2],
                                  temperatureInfo.Equals(temperatures[ctr2],
                                                         new Item3And4Comparer <string, int, double, double>()));
            }

            Console.WriteLine();
        }
    }
예제 #13
0
        private void buttonAuth_Click(object sender, EventArgs e)
        {
            AES256 AES = new AES256();
            string hashString = null; byte[] encryptedBytes = null;

            // 비밀번호 암호화
            hashString     = Convert.ToBase64String(SHA512.Create().ComputeHash(Encoding.UTF8.GetBytes(CommonData.HashSalt + textBoxAuthPassword.Text)));
            encryptedBytes = AES.EncryptByte(Encoding.UTF8.GetBytes(hashString + textBoxAuthPassword.Text));

            // 정보 로드 및 배열 비교 준비
            byte[] loadData         = File.ReadAllBytes(Path.Combine(Application.StartupPath, CommonData.Folder, CommonData.PasswordFile));
            IStructuralEquatable SE = loadData;

            // 배열 서로 비교
            if (SE.Equals(encryptedBytes, StructuralComparisons.StructuralEqualityComparer))
            {
                MessageBox.Show("정상적으로 인증되었습니다.", "알림", MessageBoxButtons.OK, MessageBoxIcon.Information);
                groupBoxAuth.Enabled = false; groupBoxChange.Enabled = true;
            }
            else
            {
                MessageBox.Show("로그인에 실패하였습니다.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
예제 #14
0
        private static bool ByteArrayCompare(byte[] a1, byte[] a2)
        {
            IStructuralEquatable eqa1 = a1;

            return(!eqa1.Equals(a2, StructuralComparisons.StructuralEqualityComparer));
        }
예제 #15
0
        public void SelectDirectory()
        {
            string stream = folderDialog.OpenFolder();

            if (!stream.Equals(String.Empty))
            {
                Progress = 0;
                ClassVMs = new ObservableCollection <ImageClassVM>();

                db = new Database.ApplicationContext();
                var dir = Directory.GetFiles(stream);
                Images = new ObservableCollection <ImageVM>();
                List <string> fileNames = new List <string>();

                foreach (var file in dir)
                {
                    bool flag     = false;
                    var  fileInfo = new FileInfo(file);

                    foreach (var img in db.Images)
                    {
                        if (fileInfo.FullName == img.Path)
                        {
                            var code1 = ConvertImageToByteArray(fileInfo.FullName);
                            IStructuralEquatable equ = code1;
                            var code2 = img.Details.Image;
                            if (equ.Equals(code2, EqualityComparer <object> .Default))
                            {
                                img.count++;

                                db.SaveChanges();
                                Images.Add(new ImageVM(fileInfo.FullName, fileInfo.Name, img.Confidence, img.ClassName));

                                flag = true;
                                Progress++;

                                dispatcher.BeginInvoke(new Action(() =>
                                {
                                    if (ClassVMs.Count() > 0)
                                    {
                                        bool flag1 = false;
                                        foreach (var imgClass in ClassVMs)
                                        {
                                            if (imgClass.Type == img.ClassName)
                                            {
                                                imgClass.Count++;
                                                flag1 = true;
                                                break;
                                            }
                                        }
                                        if (!flag1)
                                        {
                                            ClassVMs.Add(new ImageClassVM(img.ClassName, 1));
                                        }
                                    }
                                    else
                                    {
                                        ClassVMs.Add(new ImageClassVM(img.ClassName, 1));
                                    }
                                }));
                                break;
                            }
                        }
                    }

                    if (!flag)
                    {
                        Images.Add(new ImageVM(fileInfo.FullName, fileInfo.Name));
                        fileNames.Add(fileInfo.FullName);
                    }
                }

                imageRecognizer = new ImageRecognizer(fileNames, new ForResults(this));
            }
        }
예제 #16
0
        public bool CompareByteArrays(byte[] byteArrayOne, byte[] byteArrayTwo)
        {
            IStructuralEquatable equalsArray = byteArrayOne;

            return(equalsArray.Equals(byteArrayTwo, StructuralComparisons.StructuralEqualityComparer));
        }
 public static T[] CastAsArray <T>(this IStructuralEquatable equatable)
 {
     return((T[])equatable);
 }
예제 #18
0
        public static void ModelCompare(BinaryModelBase wr, BinaryModelBase ok, string indent = "")
        {
            var type      = wr.GetType();
            var modelType = typeof(BinaryModelBase);
            var wrKeys    = wr.BinMap.Keys;
            var okKeys    = ok.BinMap.Keys;

            for (var i = 0; i < wrKeys.Length; i++)
            {
                var wrEntry = wr.BinMap.Get(wrKeys[i]).Item2;
                var key     = wrKeys[i];
                if (okKeys.Contains(key))
                {
                    var okEntry = ok.BinMap.Get(key).Item2;
                    if (wrEntry.Length != okEntry.Length)
                    {
                        Debug.WriteLine(
                            "{8}[0x{0,8:X8}][{7,4}] Different content length. A[{3},{5}]: {1}; B[{4},{6}]: {2}",
                            wrKeys[i], wrEntry.Length, okEntry.Length, wrEntry.PropertyName,
                            okEntry.PropertyName, wrEntry.ClassName, okEntry.ClassName, wrEntry.BlockNum, indent);
                    }
                    else
                    {
                        var wrData = wr.Binary.ReadBytes(wrKeys[i], wrEntry.Length.Value);
                        var okData = ok.Binary.ReadBytes(wrKeys[i], wrEntry.Length.Value);
                        IStructuralEquatable eqa1 = wrData;
                        if (!eqa1.Equals(okData, StructuralComparisons.StructuralEqualityComparer))
                        {
                            int?   blockNum;
                            string wrValue;
                            string okValue;
                            if (wr is HashEntry)
                            {
                                var wrhe = (HashEntry)wr;
                                var okhe = (HashEntry)ok;
                                switch (wrEntry.PropertyName)
                                {
                                case "BlockHash":
                                    wrValue = wrhe.BlockHash.ToHex();
                                    okValue = okhe.BlockHash.ToHex();
                                    break;

                                case "Status":
                                    wrValue = wrhe.Status.ToString();
                                    okValue = okhe.Status.ToString();
                                    break;

                                case "NextBlock":
                                    wrValue = wrhe.NextBlock.ToString(CultureInfo.InvariantCulture);
                                    okValue = okhe.NextBlock.ToString(CultureInfo.InvariantCulture);
                                    break;

                                default:
                                    throw new NotSupportedException(wrEntry.PropertyName);
                                }
                                blockNum = wrhe.Block;
                            }
                            else
                            {
                                blockNum = wrEntry.BlockNum;
                                wrValue  = wrEntry.ClassName;
                                okValue  = okEntry.ClassName;
                            }

                            Debug.WriteLine("{6}[0x{0,8:X8}][{2,4}] Different data: {1} ({3}) vs {4} ({5})", wrKeys[i],
                                            wrEntry.PropertyName, blockNum, wrValue, okEntry.PropertyName, okValue,
                                            indent);
                            var pi = type.GetProperty(wrEntry.PropertyName);
                            switch (wrEntry.PropertyName)
                            {
                            case "TopTable":
                            {
                                var wrTable = ((StfsPackage)wr).TopTable;
                                var okTable = ((StfsPackage)ok).TopTable;
                                if (wrTable.EntryCount != okTable.EntryCount)
                                {
                                    Debug.WriteLine("  -- Different entry count --");
                                }
                                else
                                {
                                    for (var j = 0; j < wrTable.EntryCount; j++)
                                    {
                                        ModelCompare(wrTable.Entries[j], okTable.Entries[j], "  ");
                                    }
                                    Debug.WriteLine("{0} {1}", wrTable.AllocatedBlockCount, okTable.AllocatedBlockCount);
                                }
                            }
                            break;

                            case "Table":
                            {
                                var wrTable = ((StfsPackage)wr).TopTable.Tables[int.Parse(wrEntry.ClassName)];
                                var okTable = ((StfsPackage)ok).TopTable.Tables[int.Parse(wrEntry.ClassName)];
                                if (wrTable.EntryCount != okTable.EntryCount)
                                {
                                    Debug.WriteLine("  -- Different entry count --");
                                }
                                else
                                {
                                    for (var j = 0; j < wrTable.EntryCount; j++)
                                    {
                                        ModelCompare(wrTable.Entries[j], okTable.Entries[j], "  ");
                                    }
                                }
                            }
                            break;

                            case "FileTable":
                            {
                                for (var j = 0; j < 64; j++)
                                {
                                    var addr = key + j * 0x40;
                                    var wrfe = ModelFactory.GetModel <FileEntry>(wr.Binary, addr);
                                    var okfe = ModelFactory.GetModel <FileEntry>(ok.Binary, addr);
                                    ModelCompare(wrfe, okfe, "  ");
                                }
                            }
                            break;

                            default:
                                if (pi != null && modelType.IsAssignableFrom(pi.PropertyType))
                                {
                                    var wrProperty = pi.GetValue(wr, null) as BinaryModelBase;
                                    var okProperty = pi.GetValue(ok, null) as BinaryModelBase;
                                    ModelCompare(wrProperty, okProperty, indent + "  ");
                                }
                                break;
                            }
                        }
                    }
                }
                else
                {
                    Debug.WriteLine("{4}[0x{0,8:X8}][{2,4}] Missing data. {1} ({3})", wrKeys[i], wrEntry.PropertyName,
                                    wrEntry.BlockNum, wrEntry.ClassName, indent);
                }
            }
        }
        public static bool ByteArrayCompare(this byte[] a1, byte[] a2)
        {
            IStructuralEquatable eqa1 = a1;

            return(eqa1.Equals(a2, StructuralComparisons.StructuralEqualityComparer));
        }
예제 #20
0
        public static bool ValidateHeader(string[] header, int recordNumber, string resourceType)
        {
            bool correctHeader = false;
            IStructuralEquatable actualHeader = header;

            string[] expectedFormHeader = { "Id", "Name*", "Description*", "Resource_Type*", "URL*", "Topic*", "Organizational_Unit*", "Location_State*", "Location_County", "Location_City",
                                            "Location_Zip" };

            string[] expectedOrganizationHeader = { "Id",           "Name*",        "Description*", "Resource_Type*", "URL*",        "Topic*",                  "Organizational_Unit*", "Location_State*", "Location_County", "Location_City",
                                                    "Location_Zip", "Org_Address*", "Phone*",       "Overview",       "Specialties", "Eligibility_Information", "Qualifications",       "Business_Hours",  "Resource_Category" };

            string[] expectedArticleHeader = { "Id",           "Name*", "Description*", "Resource_Type*", "Topic*", "Organizational_Unit*", "Location_State*", "Location_County", "Location_City",
                                               "Location_Zip", "Overview" };

            string[] expectedVideoHeader = { "Id",           "Name*",             "Description*", "Resource_Type*", "URL*", "Topic*", "Organizational_Unit*", "Location_State*", "Location_County", "Location_City",
                                             "Location_Zip", "Resource_Category", "Overview" };

            string[] expectedAdditionalReadingHeader = { "Id", "Name*", "Resource_Type*", "URL*", "Topic*", "Organizational_Unit*", "Location_State*", "Location_County", "Location_City",
                                                         "Location_Zip" };

            string[] expectedOrganizationReviewHeader = { "Organization*", "Reviewer_Full_Name*", "Reviewer_Title", "Review_Text*", "Reviewer_Image_URL" };

            string[] expectedArticleContentsHeader = { "Article*", "Section_Headline", "Section_Content" };

            string[] expectedRelatedLinkHeader = { "Id", "Name*", "Description*", "Resource_Type*", "URL*", "Topic*", "Organizational_Unit*", "Location_State*", "Location_County", "Location_City",
                                                   "Location_Zip" };
            try
            {
                if (resourceType == Constants.FormResourceType)
                {
                    correctHeader = HeaderValidation(header, expectedFormHeader, Constants.FormResourceType);
                }

                else if (resourceType == Constants.OrganizationResourceType)
                {
                    correctHeader = HeaderValidation(header, expectedOrganizationHeader, Constants.OrganizationResourceType);
                }

                else if (resourceType == Constants.ArticleResourceType)
                {
                    correctHeader = HeaderValidation(header, expectedArticleHeader, Constants.ArticleResourceType);
                }

                else if (resourceType == Constants.ArticleContent)
                {
                    correctHeader = HeaderValidation(header, expectedArticleContentsHeader, Constants.ArticleContent);
                }

                else if (resourceType == Constants.VideoResourceType)
                {
                    correctHeader = HeaderValidation(header, expectedVideoHeader, Constants.VideoResourceType);
                }

                else if (resourceType == Constants.AdditionalReadingResourceType)
                {
                    correctHeader = HeaderValidation(header, expectedAdditionalReadingHeader, Constants.AdditionalReadingResourceType);
                }

                else if (resourceType == Constants.OrganizationReview)
                {
                    correctHeader = HeaderValidation(header, expectedOrganizationReviewHeader, Constants.OrganizationReview);
                }

                else if (resourceType == Constants.RelatedLinkResourceType)
                {
                    correctHeader = HeaderValidation(header, expectedRelatedLinkHeader, Constants.RelatedLinkResourceType);
                }
            }
            catch (Exception ex)
            {
                InsertTopics.ErrorLogging(ex, recordNumber);
            }
            return(correctHeader);
        }
예제 #21
0
        public static void Show()
        {
            // StructuralEqualityComparer
            {
                object[] a1 = { "string", 123, true };
                object[] a2 = { "string", 123, true };

                Console.WriteLine(a1 == a2);                         // False
                Console.WriteLine(a1.Equals(a2));                    // False

                IStructuralEquatable se1 = a1;

                Console.WriteLine(se1.Equals(a2, StructuralComparisons.StructuralEqualityComparer));   // True
            }
            // Clone
            {
                StringBuilder[] builders = new StringBuilder[5];
                builders[0] = new StringBuilder("builder1");
                builders[1] = new StringBuilder("builder2");
                builders[2] = new StringBuilder("builder3");

                StringBuilder[] builders2    = builders;
                StringBuilder[] shallowClone = (StringBuilder[])builders.Clone();

                builders.Dump();
                builders2.Dump();

                (builders[0] == builders2[0]).Dump("Comparing first element of each array");
            }
            // Create
            {
                // Via C#'s native syntax:

                int[] myArray = { 1, 2, 3 };
                int   first   = myArray[0];
                int   last    = myArray[myArray.Length - 1];

                // Using GetValue/SetValue:

                // Create a string array 2 elements in length:
                Array a = Array.CreateInstance(typeof(string), 2);
                a.SetValue("hi", 0);                            //  → a[0] = "hi";
                a.SetValue("there", 1);                         //  → a[1] = "there";
                a.Dump();
                string s = (string)a.GetValue(0);               //  → s = a[0];
                s.Dump();

                // We can also cast to a C# array as follows:
                string[] cSharpArray = (string[])a;
                string   s2          = cSharpArray[0];
                s2.Dump();
            }
            // Search
            {
                string[] names = { "Rodney", "Jack", "Jill", "Jane" };

                Array.Find(names, n => n.Contains("a")).Dump();    // Returns first matching element
                Array.FindAll(names, n => n.Contains("a")).Dump(); // Returns all matching elements

                // Equivalent in LINQ:

                names.FirstOrDefault(n => n.Contains("a")).Dump();
                names.Where(n => n.Contains("a")).Dump();
            }
            // Sort
            {
                int[] numbers = { 3, 2, 1 };
                Array.Sort(numbers);
                numbers.Dump("Simple sort");

                numbers = new[] { 3, 2, 1 };
                string[] words = { "three", "two", "one" };
                Array.Sort(numbers, words);
                new { numbers, words }.Dump("Parallel sort");

                // Sort such that odd numbers come first:
                numbers = new[] { 1, 2, 3, 4, 5 };
                Array.Sort(numbers, (x, y) => x % 2 == y % 2 ? 0 : x % 2 == 1 ? -1 : 1);
                numbers.Dump();
            }
            // ConvertAll
            {
                float[] reals  = { 1.3f, 1.5f, 1.8f };
                int[]   wholes = Array.ConvertAll(reals, r => Convert.ToInt32(r));

                wholes.Dump();
            }
        }
예제 #22
0
 // Return whether node input meta data matches the given dimensions
 static protected bool DimEquals(NodeMetadata metadata, IStructuralEquatable x)
 {
     return(x.Equals(metadata.Dimensions, StructuralComparisons.StructuralEqualityComparer));
 }
예제 #23
0
        /// <inheritdoc/>
        public bool Equals(T x, T y)
        {
            Type type = typeof(T);

            // Null?
            if (!type.IsValueType || (type.IsGenericType && type.GetGenericTypeDefinition().IsAssignableFrom(NullableTypeInfo)))
            {
                if (Object.Equals(x, default(T)))
                {
                    return(Object.Equals(y, default(T)));
                }

                if (Object.Equals(y, default(T)))
                {
                    return(false);
                }
            }

            // Implements IEquatable<T>?
            IEquatable <T> equatable = x as IEquatable <T>;

            if (equatable != null)
            {
                return(equatable.Equals(y));
            }

            // Implements IComparable<T>?
            IComparable <T> comparableGeneric = x as IComparable <T>;

            if (comparableGeneric != null)
            {
                try
                {
                    return(comparableGeneric.CompareTo(y) == 0);
                }
                catch
                {
                    // Some implementations of IComparable<T>.CompareTo throw exceptions in
                    // certain situations, such as if x can't compare against y.
                    // If this happens, just swallow up the exception and continue comparing.
                }
            }

            // Implements IComparable?
            IComparable comparable = x as IComparable;

            if (comparable != null)
            {
                try
                {
                    return(comparable.CompareTo(y) == 0);
                }
                catch
                {
                    // Some implementations of IComparable.CompareTo throw exceptions in
                    // certain situations, such as if x can't compare against y.
                    // If this happens, just swallow up the exception and continue comparing.
                }
            }

            // Dictionaries?
            var dictionariesEqual = this.CheckIfDictionariesAreEqual(x, y);

            if (dictionariesEqual.HasValue)
            {
                return(dictionariesEqual.GetValueOrDefault());
            }

            // Sets?
            var setsEqual = this.CheckIfSetsAreEqual(x, y, type);

            if (setsEqual.HasValue)
            {
                return(setsEqual.GetValueOrDefault());
            }

            // Enumerable?
            var enumerablesEqual = this.CheckIfEnumerablesAreEqual(x, y);

            if (enumerablesEqual.HasValue)
            {
                if (!enumerablesEqual.GetValueOrDefault())
                {
                    return(false);
                }

                // Array.GetEnumerator() flattens out the array, ignoring array ranks and lengths
                Array xArray = x as Array;
                Array yArray = y as Array;
                if (xArray != null && yArray != null)
                {
                    // new object[2,1] != new object[2]
                    if (xArray.Rank != yArray.Rank)
                    {
                        return(false);
                    }

                    // new object[2,1] != new object[1,2]
                    for (int i = 0; i < xArray.Rank; i++)
                    {
                        if (xArray.GetLength(i) != yArray.GetLength(i))
                        {
                            return(false);
                        }
                    }
                }
                return(true);
            }

            // Implements IStructuralEquatable?
            IStructuralEquatable structuralEquatable = x as IStructuralEquatable;

            if (structuralEquatable != null && structuralEquatable.Equals(y, new TypeErasedEqualityComparer(this.innerComparerFactory())))
            {
                return(true);
            }

            //// Implements IEquatable<typeof(y)>?
            //Type iequatableY = typeof(IEquatable<>).MakeGenericType(new Type[] { y.GetType() });
            //if (iequatableY.IsAssignableFrom(x.GetType()))
            //{
            //    MethodInfo equalsMethod = iequatableY.GetDeclaredMethod(nameof(IEquatable<T>.Equals));
            //    return (bool)equalsMethod.Invoke(x, new object[] { y });
            //}

            //// Implements IComparable<typeof(y)>?
            //Type icomparableY = typeof(IComparable<>).MakeGenericType(new Type[] { y.GetType() });
            //if (icomparableY.IsAssignableFrom(x.GetType())))
            //{
            //    MethodInfo compareToMethod = icomparableY.GetDeclaredMethod(nameof(IComparable<T>.CompareTo));
            //    try
            //    {
            //        return (int)compareToMethod.Invoke(x, new object[] { y }) == 0;
            //    }
            //    catch
            //    {
            //        // Some implementations of IComparable.CompareTo throw exceptions in
            //        // certain situations, such as if x can't compare against y.
            //        // If this happens, just swallow up the exception and continue comparing.
            //    }
            //}

            // Last case, rely on object.Equals
            return(Object.Equals(x, y));
        }
예제 #24
0
파일: AWD.cs 프로젝트: escape209/AWDio
        public static int Extract(string inFile, string outDir, bool convert)
        {
            var fs = new FileStream(inFile, FileMode.Open);
            var br = new BinaryReader(fs);

            if (br.ReadInt32() != Sec1Tag)
            {
                return(1);
            }
            int unk0    = br.ReadInt32();
            int ctrSize = br.ReadInt32();

            br.BaseStream.Position = 0;
            byte[] buf      = br.ReadBytes(ctrSize);
            var    platUuid = buf.AsSpan(0x18, 0x10).ToArray();
            int    pName    = BitConverter.ToInt32(buf, 0x30);
            int    nameLen  = (Array.IndexOf(buf, (byte)0x00, pName, 12) - pName) + 1;
            string nameStr  = Encoding.ASCII.GetString(buf, pName, nameLen);
            int    dataPos  = BitConverter.ToInt32(buf, 0x28);

            Directory.CreateDirectory(outDir);
            int    pos      = (int)(br.BaseStream.Position = pName + (int)Math.Ceiling((float)((nameStr.Length + 3) / 4)) * 4);
            string txthPath = Path.Combine(outDir, ".txth");

            File.CreateText(txthPath).Close();
            string codecStr = "codec = " + (Enumerable.SequenceEqual(platUuid, psUuid) ? "PSX" : "PCM16LE");

            File.WriteAllLines(txthPath, new string[] { codecStr, "channels = @0x1D$1", "sample_rate = @0x10", "start_offset = 0x100", "interleave = 0x1000", "num_samples = data_size" });
            var tempDir = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()));

            while (pos < dataPos)
            {
                int trkUuidPos = BitConverter.ToInt32(buf, pos);
                if (trkUuidPos <= 0 || trkUuidPos > br.BaseStream.Length)
                {
                    break;
                }
                int    trkNamePos = BitConverter.ToInt32(buf, pos + 4);
                int    trkNameLen = (Array.IndexOf(buf, (byte)0x00, trkNamePos, 16) - trkNamePos) + 1;
                byte[] trkHdrBuf  = buf.AsSpan(pos, ((trkNamePos + trkNameLen) - pos) + 0x10).ToArray();
                string trkNameStr = Encoding.ASCII.GetString(buf, trkNamePos, trkNameLen).Trim('\0');
                int    len        = BitConverter.ToInt32(buf, pos + 0x34);
                int    dat        = BitConverter.ToInt32(buf, pos + 0x4C) + dataPos;
                br.BaseStream.Position = dat;
                string outTrkPath = Path.Combine(outDir, trkNameStr) + ".wav";
                var    trkFs      = File.Create(Path.Combine(outDir, Path.GetRandomFileName()));
                string trkFsName  = trkFs.Name;
                trkFs.Write(trkHdrBuf);
                trkFs.SetLength(0x100);
                trkFs.Position = trkFs.Length;
                trkFs.Write(br.ReadBytes(len), 0, len);
                trkFs.Close();
                var pStartInfo = new ProcessStartInfo(testExePath, string.Join(' ', "-o", condPathQuote(outTrkPath), condPathQuote(trkFsName)))
                {
                    RedirectStandardOutput = true
                };
                var test = Process.Start(pStartInfo);
                test.WaitForExit();
                File.Delete(trkFsName);
                pos = trkUuidPos + 0x10;
            }
            File.Delete(txthPath);
            Console.WriteLine("Internal name          " + nameStr);
            Console.Write("Platform               ");
            IStructuralEquatable se = platUuid;

            if (se.Equals(psUuid, StructuralComparisons.StructuralEqualityComparer))
            {
                Console.WriteLine("PlayStation 2");
            }
            else if (se.Equals(xbUuid, StructuralComparisons.StructuralEqualityComparer))
            {
                Console.WriteLine("Xbox");
            }
            else
            {
                Console.WriteLine("Unknown\nCould not determine target platform of AWD.");
                return(2);
            }

            return(0);
        }
예제 #25
0
파일: RSUser.cs 프로젝트: uxsoft/RestSys
        public bool CheckPassword(string attemptedPassword)
        {
            IStructuralEquatable hash = CryptoModule.Hash(Encoding.UTF8.GetBytes(attemptedPassword), PasswordSalt);

            return(hash.Equals(PasswordHash, StructuralComparisons.StructuralEqualityComparer));
        }
예제 #26
0
        // Structural Equality and Hashing Helpers

        public static int StructuralHashMethod(CodeContext /*!*/ context, IStructuralEquatable x)
        {
            return(x.GetHashCode(context.LanguageContext.EqualityComparerNonGeneric));
        }
예제 #27
0
        static bool IsClrType(byte[] a1)
        {
            IStructuralEquatable structuralEquatable = a1;

            return(structuralEquatable.Equals(MsPublicKeyToken, StructuralComparisons.StructuralEqualityComparer));
        }
예제 #28
0
        public static bool CheckEquals(byte[] byte1, byte[] byte2) // common
        {
            IStructuralEquatable temp = byte1;

            return(temp.Equals(byte2, StructuralComparisons.StructuralEqualityComparer));
        }
        private void CheckArraysForEquality(int[][] firstArray, int[][] secondArray)
        {
            IStructuralEquatable structEq = firstArray;

            Assert.True(structEq.Equals(secondArray, StructuralComparisons.StructuralEqualityComparer));
        }
예제 #30
0
        public ViewHexDiff(byte[] data1, byte[] data2)
        {
            InitializeComponent();

            ByteArrayToIndexedHexStringConverter converter = new ByteArrayToIndexedHexStringConverter();


            string original = (string)converter.Convert(data1, typeof(string), "8", CultureInfo.CurrentCulture);
            string modified = (string)converter.Convert(data2, typeof(string), "8", CultureInfo.CurrentCulture);

            Run currentRun  = new Run();
            Run currentRun2 = new Run();

            textBoxHex1.Text = original;
            textBoxHex2.Text = modified;

            /*
             * bool isDifferent = false;
             * for (int i = 0; i < Math.Min(original.Length, modified.Length); i++)
             * {
             *   if (original[i] != modified[i])
             *   {
             *       if (!isDifferent)
             *       {
             *           //end the old run and start a new one
             *           textBoxHex1.Inlines.Add(currentRun);
             *           textBoxHex2.Inlines.Add(currentRun2);
             *           currentRun = new Run();
             *           currentRun2 = new Run();
             *           currentRun.Background = Brushes.Red;
             *           currentRun2.Background = Brushes.Red;
             *       }
             *       isDifferent = true;
             *   }
             *   else
             *   {
             *       if (isDifferent)
             *       {
             *           //end the old run and start a new one
             *           textBoxHex1.Inlines.Add(currentRun);
             *           textBoxHex2.Inlines.Add(currentRun2);
             *           currentRun = new Run();
             *           currentRun2 = new Run();
             *           currentRun.Background = Brushes.Transparent;
             *           currentRun2.Background = Brushes.Transparent;
             *       }
             *       isDifferent = false;
             *   }
             *
             *   currentRun.Text += original[i];
             *   currentRun2.Text += modified[i];
             *
             * }
             * textBoxHex1.Inlines.Add(currentRun);
             * textBoxHex2.Inlines.Add(currentRun2);
             */



            IStructuralEquatable eqa1 = data1;
            bool theSame = eqa1.Equals(data2, StructuralComparisons.StructuralEqualityComparer);

            if (theSame)
            {
                txtMessage.Text = "These files are identical!";
            }
            else
            {
                txtMessage.Text = "There are differences!";
            }
        }