System.Collections.Generic.IEnumerable.SequenceEqual(System.Collections.Generic.IEnumerable)

Here are the examples of the csharp api System.Collections.Generic.IEnumerable.SequenceEqual(System.Collections.Generic.IEnumerable) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

4750 Examples 7

19 Source : SceneUtilities.cs
with Apache License 2.0
from Anapher

public static bool ParticipantsOfRoomChanged(string roomId, SynchronizedRooms rooms,
            SynchronizedRooms? previousRooms)
        {
            if (previousRooms == null)
                return true;

            var roomsParticipants = GetParticipantsOfRoom(rooms, roomId);
            var previousRoomsParticipants = GetParticipantsOfRoom(previousRooms, roomId);

            return !roomsParticipants.SequenceEqual(previousRoomsParticipants);
        }

19 Source : HotReloadPluginModel.Generated.cs
with MIT License
from AndreiMisiukevich

public bool Equals(SavedDoreplacedent other)
    {
      if (ReferenceEquals(null, other)) return false;
      if (ReferenceEquals(this, other)) return true;
      return FilePath == other.FilePath && Content.SequenceEqual(other.Content);
    }

19 Source : StatisticalTestHelper.cs
with MIT License
from AndreyAkinshin

public static TostResult<T> CalculateTost<T>(IOneSidedTest<T> test, double[] baseline, double[] candidate, Threshold threshold)
            where T : OneSidedTestResult
        {
            if (baseline.SequenceEqual(candidate)) // WelchTest would throw StackoverflowException ;)
                return new TostResult<T>(threshold, EquivalenceTestConclusion.Base, null, null);

            var fasterTestResult = test.IsGreater(baseline, candidate, threshold);
            var slowerTestResult = test.IsGreater(candidate, baseline, threshold);

            EquivalenceTestConclusion conclusion;
            if (fasterTestResult == null || slowerTestResult == null)
                conclusion = EquivalenceTestConclusion.Unknown;
            else if (fasterTestResult.NullHypothesisIsRejected)
                conclusion = EquivalenceTestConclusion.Faster;
            else if (slowerTestResult.NullHypothesisIsRejected)
                conclusion = EquivalenceTestConclusion.Slower;
            else
                conclusion = EquivalenceTestConclusion.Same;

            return new TostResult<T>(threshold, conclusion, slowerTestResult, fasterTestResult);
        }

19 Source : Thread_Info.cs
with MIT License
from Andy53

internal ErcResult<List<Tuple<byte[], byte[]>>> BuildSehChain()
        {
            ErcResult<List<Tuple<byte[], byte[]>>> sehList = new ErcResult<List<Tuple<byte[], byte[]>>>(ThreadCore);
            sehList.ReturnValue = new List<Tuple<byte[], byte[]>>();

            if (Teb.Equals(default(TEB)))
            {
                sehList.Error = new Exception("Error: TEB structure for this thread has not yet been populated. Call PopulateTEB first");
                return sehList;
            }

            if(Teb.CurrentSehFrame == IntPtr.Zero)
            {
                sehList.Error = new Exception("Error: No SEH chain has been generated yet. An SEH chain will not be generated until a crash occurs.");
                return sehList;
            }

            byte[] sehEntry;
            byte[] sehFinal;

            int arraySize = 0;
            if(X64 == MachineType.x64)
            {
                arraySize = 8;
                sehEntry = new byte[arraySize];
                sehFinal = new byte[arraySize];
                sehEntry = BitConverter.GetBytes((long)Teb.CurrentSehFrame);
            }
            else
            {
                arraySize = 4;
                sehEntry = new byte[arraySize];
                sehFinal = new byte[arraySize];
                sehEntry = BitConverter.GetBytes((int)Teb.CurrentSehFrame);
            }
            
            for (int i = 0; i < sehFinal.Length; i++)
            {
                sehFinal[i] = 0xFF;
            }

            byte[] prevSEH = new byte[] { 0xFF };
            string pattern_standard = File.ReadAllText(ThreadCore.PatternStandardPath);
            string pattern_extended = File.ReadAllText(ThreadCore.PatternExtendedPath);
            while (!sehEntry.SequenceEqual(sehFinal))
            {
                byte[] reversedSehEntry = new byte[arraySize];
                byte[] nSeh = new byte[arraySize];
                byte[] sehHolder = new byte[arraySize * 2];
                
                int ret = 0;

                if(X64 == MachineType.x64)
                {
                    ret = ErcCore.ReadProcessMemory(ThreadProcess.ProcessHandle, (IntPtr)BitConverter.ToInt64(sehEntry, 0), sehHolder, arraySize * 2, out int retInt);
                    Array.Copy(sehHolder, 0, sehEntry, 0, arraySize);
                    Array.Copy(sehHolder, arraySize, nSeh, 0, arraySize);
                }
                else
                {
                    ret = ErcCore.ReadProcessMemory(ThreadProcess.ProcessHandle, (IntPtr)BitConverter.ToInt32(sehEntry, 0), sehHolder, arraySize * 2, out int retInt);
                    Array.Copy(sehHolder, 0, sehEntry, 0, arraySize);
                    Array.Copy(sehHolder, arraySize, nSeh, 0, arraySize);
                }

                if (ret != 0 && ret != 1)
                {
                    ERCException e = new ERCException("System error: An error occured when executing ReadProcessMemory\n Process Handle = 0x"
                    + ThreadProcess.ProcessHandle.ToString("X") + " TEB Current Seh = 0x" + Teb.CurrentSehFrame.ToString("X") +
                    " Return value = " + ret + Environment.NewLine + "Win32Exception: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    sehList.Error = e;
                    sehList.LogEvent();
                    return sehList;
                }

                Array.Reverse(nSeh);

                for(int i = 0; i < sehEntry.Length; i++)
                {
                    reversedSehEntry[i] = sehEntry[i];
                }

                Array.Reverse(reversedSehEntry, 0, reversedSehEntry.Length);
                if (prevSEH.SequenceEqual(reversedSehEntry))
                {
                    sehEntry = new byte[sehFinal.Length];
                    Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
                }
                else if (!sehEntry.SequenceEqual(sehFinal) && !sehList.ReturnValue.Any(e => e.Item1.SequenceEqual(reversedSehEntry)))
                {
                    Tuple<byte[], byte[]> tuple = new Tuple<byte[], byte[]>(reversedSehEntry, nSeh);
                    sehList.ReturnValue.Add(tuple);
                }

                if (pattern_standard.Contains(Encoding.Unicode.GetString(reversedSehEntry)) ||
                    pattern_extended.Contains(Encoding.Unicode.GetString(reversedSehEntry)))
                {
                    sehEntry = new byte[sehFinal.Length];
                    Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
                }

                if (pattern_standard.Contains(Encoding.ASCII.GetString(reversedSehEntry)) ||
                    pattern_extended.Contains(Encoding.ASCII.GetString(reversedSehEntry)))
                {
                    sehEntry = new byte[sehFinal.Length];
                    Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
                }

                if (pattern_standard.Contains(Encoding.UTF32.GetString(reversedSehEntry)) ||
                    pattern_extended.Contains(Encoding.UTF32.GetString(reversedSehEntry)))
                {
                    sehEntry = new byte[sehFinal.Length];
                    Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
                }

                if (pattern_standard.Contains(Encoding.UTF7.GetString(reversedSehEntry)) ||
                    pattern_extended.Contains(Encoding.UTF7.GetString(reversedSehEntry)))
                {
                    sehEntry = new byte[sehFinal.Length];
                    Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
                }

                if (pattern_standard.Contains(Encoding.UTF8.GetString(reversedSehEntry)) ||
                    pattern_extended.Contains(Encoding.UTF8.GetString(reversedSehEntry)))
                {
                    sehEntry = new byte[sehFinal.Length];
                    Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
                }

                prevSEH = new byte[reversedSehEntry.Length];
                Array.Copy(reversedSehEntry, 0, prevSEH, 0, reversedSehEntry.Length);
            }

            SehChain = new List<Tuple<byte[], byte[]>>(sehList.ReturnValue);
            return sehList;
        }

19 Source : Module_Info.cs
with MIT License
from Andy53

private List<int> SearchBytePattern(byte[] pattern, byte[] bytes)
        {
            List<int> positions = new List<int>();
            int patternLength = pattern.Length;
            int totalLength = bytes.Length;
            byte firstMatchByte = pattern[0];
            for (int i = 0; i < totalLength; i++)
            {
                if (firstMatchByte == bytes[i] && totalLength - i >= patternLength)
                {
                    byte[] match = new byte[patternLength];
                    Array.Copy(bytes, i, match, 0, patternLength);
                    if (match.SequenceEqual<byte>(pattern))
                    {
                        positions.Add(i);
                        i += patternLength - 1;
                    }
                }
            }
            return positions;
        }

19 Source : Service.cs
with MIT License
from andyalm

protected bool Equals(Service other)
        {
            return string.Equals(Id, other.Id) && string.Equals(Name, other.Name) && Nodes.SequenceEqual(other.Nodes);
        }

19 Source : Service.cs
with MIT License
from andyalm

protected bool Equals(ServiceNode other)
        {
            return string.Equals(Name, other.Name) 
                && string.Equals(Address, other.Address) 
                && Port == other.Port 
                && (Tags?.SequenceEqual(other.Tags) ?? other.Tags == null);
        }

19 Source : Models.cs
with MIT License
from ansel86castro

public bool Equals([AllowNull] ModelA other)
        {
            if (other == null)
                return false;

            return IntValue == other.IntValue &&
                GuidValue == other.GuidValue &&
                StringValue == other.StringValue &&
                DoubleValue == other.DoubleValue &&
                FloatValue == other.FloatValue &&
                ByteValue == other.ByteValue &&
                SmallDouble == other.SmallDouble &&
                SmallDecimal == other.SmallDecimal &&
                SmallFloat == other.SmallFloat &&
                SmallDouble2 == other.SmallDouble2 &&
                BufferValue.SequenceEqual(other.BufferValue) &&
                ArrayIntValue.SequenceEqual(other.ArrayIntValue) &&
                ArrayStringValue.SequenceEqual(other.ArrayStringValue) &&
                ModelBValue.Equals(other.ModelBValue) &&
                ModelBListValue.SequenceEqual(other.ModelBListValue) &&
                ModelBCollection.SequenceEqual(other.ModelBCollection) &&
                MapValue.SequenceEqual(other.MapValue) &&
                ListStringValue.SequenceEqual(other.ListStringValue) &&
                EmptyList.SequenceEqual(other.EmptyList);


        }

19 Source : FuzzyLogicCore.cs
with MIT License
from antonio-leonardo

private bool ProcessFilter(string filter, TEnreplacedy invalidData, string propertyName)
        {
            if (typeof(TEnreplacedy).GetProperty(propertyName).PropertyType == typeof(Double) && filter.Contains(","))
            {
                filter = filter.Replace(",", ".");
            }
            bool ratingResult = false;
            const char FIRST_BRACKET = '(',
                       LAST_BRACKET = ')';
            string newFilter = filter;

            ConcurrentBag<int> charsIdWithStartParentesesParallel = new ConcurrentBag<int>();
            ConcurrentBag<int> charsIdWithEndParentesesParallel = new ConcurrentBag<int>();
            char[] filterChars = filter.ToCharArray();
            Parallel.For(0, filterChars.Length, i =>
            {
                if (filterChars[i] == FIRST_BRACKET)
                {
                    charsIdWithStartParentesesParallel.Add(i);
                }
                else if (filterChars[i] == LAST_BRACKET)
                {
                    charsIdWithEndParentesesParallel.Add(i);
                }
            });

            List<int> charsIdWithStartParenteses = charsIdWithStartParentesesParallel.ToList();
            List<int> charsIdWithEndParenteses = charsIdWithEndParentesesParallel.ToList();

            bool isMatch = false;
            while (!isMatch)
            {
                try
                {
                    this.SubsreplaceduteChars(ref newFilter);
                    ratingResult = DynamicLinq.DynamicExpression.ParseLambda<TEnreplacedy, bool>(newFilter).Compile().Invoke(invalidData);
                    isMatch = true;
                }
                catch
                {
                    if (charsIdWithStartParenteses.Count > charsIdWithEndParenteses.Count)
                    {
                        filter = filter.Remove(filter.IndexOf(FIRST_BRACKET), 1);
                        newFilter = filter;
                        charsIdWithStartParenteses.Remove(charsIdWithStartParenteses.FirstOrDefault());
                    }
                    else if (charsIdWithStartParenteses.Count < charsIdWithEndParenteses.Count)
                    {
                        filter = filter.Remove(filter.LastIndexOf(LAST_BRACKET) - 1, 1);
                        newFilter = filter;
                        charsIdWithEndParenteses.Remove(charsIdWithEndParenteses.LastOrDefault());
                    }
                    else
                    {
                        if (charsIdWithStartParenteses.SequenceEqual(Enumerable.Range(1, charsIdWithStartParenteses.Count)))
                        {
                            filter = filter.Remove(filter.LastIndexOf(LAST_BRACKET) - 1, 1);
                            newFilter = filter;
                            charsIdWithEndParenteses.Remove(charsIdWithEndParenteses.LastOrDefault());
                        }
                        else if (charsIdWithEndParenteses.SequenceEqual(Enumerable.Range(1, charsIdWithEndParenteses.Count)))
                        {
                            filter = filter.Remove(filter.IndexOf(FIRST_BRACKET), 1);
                            newFilter = filter;
                            charsIdWithStartParenteses.Remove(charsIdWithStartParenteses.FirstOrDefault());
                        }
                    }
                }
            }
            return ratingResult;
        }

19 Source : Program.cs
with GNU General Public License v3.0
from anydream

protected virtual bool IsHashChanged(string path)
		{
			byte[] savedHash = ReadSavedHash(path);
			if (savedHash == null)
				return true;

			byte[] calcHash = Helper.GetFileHash(path);
			if (calcHash == null)
				return true;

			if (!savedHash.SequenceEqual(calcHash))
				return true;

			return false;
		}

19 Source : Program.cs
with GNU General Public License v3.0
from anydream

private static void TestBinding(
			Il2cppContext context, TypeDef typeDef,
			string imageDir, string imageName, string subDir)
		{
			MethodDef metDef = IsTestBinding(typeDef);
			if (metDef == null)
				return;

			string testName = string.Format("[{0}]{1}", imageName, typeDef.FullName);
			var oldColor = Console.ForegroundColor;
			Console.Write("{0} {1}: ", subDir, testName);

			context.AddEntry(metDef);

			var sw = new Stopwatch();
			sw.Start();
			string exceptionMsg = null;
			try
			{
				context.Resolve();
			}
			catch (TypeLoadException ex)
			{
				exceptionMsg = ex.Message;
			}
			sw.Stop();
			long elapsedMS = sw.ElapsedMilliseconds;
			Console.Write("{0}ms, ", elapsedMS);

			StringBuilder sb = new StringBuilder();
			if (exceptionMsg != null)
				sb.Append(exceptionMsg);
			else
			{
				HierarchyDump dumper = new HierarchyDump(context);

				/*sb.Append("* MethodTables:\n");
				dumper.DumpMethodTables(sb);*/
				sb.Append("* Types:\n");
				dumper.DumpTypes(sb);
			}

			var dumpData = Encoding.UTF8.GetBytes(sb.ToString());

			string validatedName = ValidatePath(testName);
			File.WriteAllBytes(
				Path.Combine(imageDir, validatedName + ".dump"),
				dumpData);

			byte[] cmpData = null;
			try
			{
				cmpData = File.ReadAllBytes(Path.Combine(imageDir, validatedName + ".txt"));
				cmpData = ReplaceNewLines(cmpData);
			}
			catch
			{
			}

			if (cmpData != null && dumpData.SequenceEqual(cmpData))
			{
				Console.ForegroundColor = ConsoleColor.Green;
				Console.WriteLine("Preplaced");
				Console.ForegroundColor = oldColor;

				++PreplacededTests;
			}
			else
			{
				Console.ForegroundColor = ConsoleColor.Red;
				Console.WriteLine("FAIL");
				Console.ForegroundColor = oldColor;
			}

			++TotalTests;

			context.Reset();
		}

19 Source : ModbusServerTests.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn

[Theory]
        [InlineData(false, new short[] { 99, 101, 102 }, new short[] { 100, 101, 103 }, new bool[] { true, false, true })]
        [InlineData(true, new short[] { 99, 101, 102 }, new short[] { 100, 101, 103 }, new bool[] { true, false, true })]
        public async Task CanDetectRegistersChanged(bool useReadWriteMethod, short[] initialValues, short[] newValues, bool[] expected)
        {
            // Arrange
            var actual = new bool[3];
            var address = 99;
            var endpoint = EndpointSource.GetNext();

            using var server = new ModbusTcpServer()
            {
                EnableRaisingEvents = true
            };

            for (int i = 0; i < initialValues.Length; i++)
            {
                server.GetHoldingRegisters()[i + address] = initialValues[i];
            }

            server.RegistersChanged += (sender, e) =>
            {
                replacedert.True(e.Registers.Length == 2);

                for (int i = 0; i < initialValues.Length; i++)
                {
                    actual[i] = e.Registers.Contains(address + i);
                }
            };

            server.Start(endpoint);

            // Act
            var client = new ModbusTcpClient();

            await Task.Run(() =>
            {
                client.Connect(endpoint);

                if (useReadWriteMethod)
                    client.ReadWriteMultipleRegisters<short, short>(0, 0, 1, address, newValues);

                else
                    client.WriteMultipleRegisters(0, address, newValues);
            });

            // replacedert
            replacedert.True(expected.SequenceEqual(actual));
        }

19 Source : ModbusTcpServerTests.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn

[Fact]
        public async void ServerWorksWithExternalTcpClient()
        {
            // Arrange
            var endpoint = EndpointSource.GetNext();
            var listener = new TcpListener(endpoint);
            using var server = new ModbusTcpServer();
            var client = new ModbusTcpClient();

            var expected = new double[] { 0.1, 0.2, 0.3, 0.4, 0.5 };
            double[] actual = null;

            // Act
            listener.Start();

            var clientTask = Task.Run(() =>
            {
                client.Connect(endpoint);

                actual = client
                    .ReadWriteMultipleRegisters<double, double>(0, 0, 5, 0, expected)
                    .ToArray();

                client.Disconnect();
            });

            var serverTask = Task.Run(() =>
            {
                var tcpClient = listener.AcceptTcpClient();
                server.Start(tcpClient);
            });

            await clientTask;

            // replacedert
            replacedert.True(actual.SequenceEqual(expected));
        }

19 Source : HyperslabUtils.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn

private static void CopyMemory(IEnumerator<Step> sourceWalker, IEnumerator<Step> targetWalker, CopyInfo copyInfo)
        {
            /* initialize source walker */
            var sourceBuffer = default(Memory<byte>);
            var lastSourceChunk = default(ulong[]);

            /* initialize target walker */
            var targetBuffer = default(Memory<byte>);
            var lastTargetChunk = default(ulong[]);
            var currentTarget = default(Memory<byte>);

            /* walk until end */
            while (sourceWalker.MoveNext())
            {
                /* load next source buffer */
                var sourceStep = sourceWalker.Current;

                if (sourceBuffer.Length == 0 /* if buffer not replacedigned yet */ ||
                    !sourceStep.Chunk.SequenceEqual(lastSourceChunk) /* or the chunk has changed */)
                {
                    sourceBuffer = copyInfo.GetSourceBuffer(sourceStep.Chunk);
                    lastSourceChunk = sourceStep.Chunk;
                }

                var currentSource = sourceBuffer.Slice(
                    (int)sourceStep.Offset * copyInfo.TypeSize,
                    (int)sourceStep.Length * copyInfo.TypeSize);

                while (currentSource.Length > 0)
                {
                    /* load next target buffer */
                    if (currentTarget.Length == 0)
                    {
                        var success = targetWalker.MoveNext();
                        var targetStep = targetWalker.Current;

                        if (!success || targetStep.Length == 0)
                            throw new UriFormatException("The target walker stopped early.");

                        if (targetBuffer.Length == 0 /* if buffer not replacedigned yet */ ||
                            !targetStep.Chunk.SequenceEqual(lastTargetChunk) /* or the chunk has changed */)
                        {
                            targetBuffer = copyInfo.GetTargetBuffer(targetStep.Chunk);
                            lastTargetChunk = targetStep.Chunk;
                        }

                        currentTarget = targetBuffer.Slice(
                            (int)targetStep.Offset * copyInfo.TypeSize,
                            (int)targetStep.Length * copyInfo.TypeSize);
                    }

                    /* copy */
                    var length = Math.Min(currentSource.Length, currentTarget.Length);

                    currentSource
                        .Slice(0, length)
                        .CopyTo(currentTarget);

                    currentSource = currentSource.Slice(length);
                    currentTarget = currentTarget.Slice(length);
                }
            }
        }

19 Source : HyperslabUtils.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn

private static void CopyStream(IEnumerator<Step> sourceWalker, IEnumerator<Step> targetWalker, CopyInfo copyInfo)
        {
            /* initialize source walker */
            var sourceStream = default(Stream);
            var lastSourceChunk = default(ulong[]);

            /* initialize target walker */
            var targetBuffer = default(Memory<byte>);
            var lastTargetChunk = default(ulong[]);
            var currentTarget = default(Memory<byte>);

            /* walk until end */
            while (sourceWalker.MoveNext())
            {
                /* load next source stream */
                var sourceStep = sourceWalker.Current;

                if (sourceStream is null /* if stream not replacedigned yet */ ||
                    !sourceStep.Chunk.SequenceEqual(lastSourceChunk) /* or the chunk has changed */)
                {
                    sourceStream = copyInfo.GetSourceStream(sourceStep.Chunk);
                    lastSourceChunk = sourceStep.Chunk;
                }

                sourceStream?.Seek((int)sourceStep.Offset * copyInfo.TypeSize, SeekOrigin.Begin);        // corresponds to 
                var currentLength = (int)sourceStep.Length * copyInfo.TypeSize;                          // sourceBuffer.Slice()

                while (currentLength > 0)
                {
                    /* load next target buffer */
                    if (currentTarget.Length == 0)
                    {
                        var success = targetWalker.MoveNext();
                        var targetStep = targetWalker.Current;

                        if (!success || targetStep.Length == 0)
                            throw new UriFormatException("The target walker stopped early.");

                        if (targetBuffer.Length == 0 /* if buffer not replacedigned yet */ ||
                            !targetStep.Chunk.SequenceEqual(lastTargetChunk) /* or the chunk has changed */)
                        {
                            targetBuffer = copyInfo.GetTargetBuffer(targetStep.Chunk);
                            lastTargetChunk = targetStep.Chunk;
                        }

                        currentTarget = targetBuffer.Slice(
                            (int)targetStep.Offset * copyInfo.TypeSize,
                            (int)targetStep.Length * copyInfo.TypeSize);
                    }

                    /* copy */
                    var length = Math.Min(currentLength, currentTarget.Length);
                    sourceStream?.Read(currentTarget.Slice(0, length).Span);                             // corresponds to span.CopyTo

                    sourceStream?.Seek((int)sourceStep.Offset * copyInfo.TypeSize, SeekOrigin.Begin);    // corresponds to 
                    currentLength -= (int)sourceStep.Length * copyInfo.TypeSize;                         // sourceBuffer.Slice()

                    currentTarget = currentTarget.Slice(length);
                }
            }
        }

19 Source : FilterTests.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn

[Theory]
        [InlineData(1, new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x9 })]
        [InlineData(2, new byte[] { 0x01, 0x00, 0x03, 0x02, 0x05, 0x04, 0x07, 0x06, 0x09, 0x8 })]
        [InlineData(4, new byte[] { 0x03, 0x02, 0x01, 0x00, 0x07, 0x06, 0x05, 0x04, 0x08, 0x9 })]
        [InlineData(8, new byte[] { 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00, 0x08, 0x9 })]
        public void CanConvertEndiannessGeneric(int bytesOfType, byte[] input)
        {
            // Arrange
            var expected = Enumerable.Range(0x0, 0x9)
                .Select(value => (byte)value)
                .ToArray();

            // Act
            var actual = new byte[expected.Length];
            EndiannessConverterGeneric.Convert(bytesOfType, input, actual);

            // replacedert
            replacedert.True(actual.SequenceEqual(expected));
        }

19 Source : FieldElementViewModel.cs
with MIT License
from Aptacode

public void UpdateValidationMessage()
        {
            var newValidationResults = Validate();
            if (ValidationResults.SequenceEqual(newValidationResults))
            {
                return;
            }

            ValidationResults.Clear();
            ValidationResults.AddRange(newValidationResults);
            TriggerEvent(new ValidationChangedEvent(DateTime.Now, Name, ValidationMessages));
        }

19 Source : SaslScramSha1.cs
with MIT License
from araditc

private byte[] VerifyServerSignature(byte[] challenge) {
			string s = Encoding.UTF8.GetString(challenge);
			// The server must respond with a "v=signature" message.
			if (!s.StartsWith("v=")) {
				// Cancel authentication process.
				return Encoding.UTF8.GetBytes("*");
			}
			byte[] serverSignature = Convert.FromBase64String(s.Substring(2));
			// Verify server's signature.
			byte[] serverKey = HMAC(SaltedPreplacedword, "Server Key"),
				calculatedSignature = HMAC(serverKey, AuthMessage);
			// If both signatures are equal, server has been authenticated. Otherwise
			// cancel the authentication process.
			return serverSignature.SequenceEqual(calculatedSignature) ?
				new byte[0] : Encoding.UTF8.GetBytes("*");
		}

19 Source : BindingResponse.cs
with MIT License
from araditc

public static BindingResponse Deserialize(byte[] buffer) {
			buffer.ThrowIfNull("buffer");
			if (buffer.Length < headerSize)
				throw new SerializationException("The buffer does not contain a " +
					"valid STUN message header.");
			using (var ms = new MemoryStream(buffer)) {
				using (var r = new BinaryReader(ms)) {
					if (r.ReadInt16() != stunMessageType)
						throw new SerializationException("Unexpected STUN message type.");
					int length = r.ReadInt16(bigEndian: true);
					if (!r.ReadBytes(4).SequenceEqual(magicCookie))
						throw new SerializationException("Invalid 'Magic Cookie' value.");
					byte[] id = r.ReadBytes(12);
					// Read the attributes.
					try {
						while (length > 0) {
							short type = r.ReadInt16(), size = r.ReadInt16(bigEndian: true);
							if (type == mappedAddress || type == xorMappedAddress) {
								r.ReadByte();
								byte family = r.ReadByte();
								if (family != IPv4 && family != IPv6)
									throw new SerializationException("Invalid address-family.");
								short port = r.ReadInt16();
								byte[] address = r.ReadBytes(family == IPv4 ? 4 : 16);
								if (type == xorMappedAddress) {
									address = Xor(address, family == IPv4 ? magicCookie :
										new ByteBuilder().Append(magicCookie).Append(id).ToArray());
								}
								return new BindingResponse(id, new IPAddress(address));
							}
							// If it's any other attribute, skip it.
							r.ReadBytes(size);
							length = length - 4 - size;
						}
					} catch(Exception e) {
						throw new SerializationException("The format of the STUN binding " +
							"response is invalid.", e); 
					}
					throw new SerializationException("+The binding response does not contain " +
						" a MAPPED-ADDRESS attribute.");
				}
			}
		}

19 Source : EthornellDisassembler.cs
with MIT License
from arcusmaximus

private static bool StreamStartsWith(Stream stream, byte[] magic)
        {
            if (stream.Length < magic.Length)
                return false;

            byte[] data = new byte[magic.Length];
            stream.Read(data, 0, data.Length);
            stream.Position = 0;
            return data.SequenceEqual(magic);
        }

19 Source : TjsScript.cs
with MIT License
from arcusmaximus

public void Load(ScriptLocation location)
        {
            using (Stream stream = File.OpenRead(location.ToFilePath()))
            using (BinaryReader reader = new BinaryReader(stream, Encoding.Unicode))
            {
                byte[] magic = reader.ReadBytes(8);
                if (!magic.SequenceEqual(Magic))
                    throw new InvalidDataException("Invalid magic");

                int fileSize = reader.ReadInt32();
                if (fileSize != stream.Length)
                    throw new InvalidDataException("Invalid file size");

                byte[] dataTag = reader.ReadBytes(4);
                if (!dataTag.SequenceEqual(DataTag))
                    throw new InvalidDataException("Invalid DATA tag");

                int dataSectionSize = reader.ReadInt32();
                ReadConstantArrays(reader);
                if (dataSectionSize != stream.Position - (Magic.Length + 4))
                    throw new InvalidDataException("Invalid DATA size");

                _fileRemainder = reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position));
            }
        }

19 Source : CatSystemScript.cs
with MIT License
from arcusmaximus

private static byte[] Decompress(byte[] inputData)
        {
            MemoryStream inputStream = new MemoryStream(inputData);
            BinaryReader reader = new BinaryReader(inputStream);
            byte[] magic = reader.ReadBytes(8);
            if (!magic.SequenceEqual(Magic))
                throw new InvalidDataException("Invalid magic");

            int compressedLength = reader.ReadInt32();
            int uncompressedLength = reader.ReadInt32();
            if (compressedLength == 0)
            {
                if (uncompressedLength != inputStream.Length - 0x10)
                    throw new InvalidDataException("Invalid size");

                return reader.ReadBytes(uncompressedLength);
            }
            else
            {
                if (compressedLength != inputStream.Length - 0x10)
                    throw new InvalidDataException("Invalid compressed size");

                ushort zlibHeader = reader.ReadUInt16();
                byte[] uncompressedData = new byte[uncompressedLength];
                using (DeflateStream decompressionStream = new DeflateStream(inputStream, CompressionMode.Decompress))
                {
                    decompressionStream.Read(uncompressedData, 0, uncompressedData.Length);
                }
                return uncompressedData;
            }
        }

19 Source : Form1.cs
with MIT License
from Arefu

private void opemToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var OFD = new OpenFileDialog())
            {
                OFD.replacedle = "Select Your Save File...";
                OFD.Multiselect = false;
                OFD.Filter = "Save file (*.dat) | *.dat";

                if (OFD.ShowDialog() != DialogResult.OK)
                    return;


                //Start Parsing Save File Populating Items.
                //Check If Save File.
                using (var Reader = new BinaryReader(File.Open(OFD.FileName, FileMode.Open, FileAccess.Read)))
                {
                    var SaveHeader = Reader.ReadBytes(10);
                    var KnownHeader = new byte[] {0xF9, 0x29, 0xCE, 0x54, 0x02, 0x4D, 0x71, 0x04, 0x4D, 0x71};

                    if (!KnownHeader.SequenceEqual(SaveHeader))
                    {
                        MessageBox.Show(
                            "This Is Either A Corrupted Save, Or Not A Save File. Refer To Wiki For Information",
                            "Invalid Save!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    Reader.Close();
                    tabControl1.Enabled = true;
                    SaveFile = OFD.FileName;
                }
            }
        }

19 Source : LOTD_Archive.cs
with MIT License
from Arefu

private static void ValidateData(File_Data file)
        {
            var padding = Enumerable.Repeat((byte) 0xFF, 100).ToArray();
            var buffer = file.ZibFile != null ? file.ZibFile.LoadBuffer() : file.File.LoadBuffer();

            var paddedBuffer = new byte[buffer.Length + padding.Length];
            Buffer.BlockCopy(padding, 0, paddedBuffer, 0, padding.Length);
            Buffer.BlockCopy(buffer, 0, paddedBuffer, padding.Length, buffer.Length);

            using (var ms = new MemoryStream())
            using (var bw = new BinaryWriter(ms))
            {
                bw.Write(padding);

                file.Save(bw);
                var buffer2 = ms.ToArray();
                if (file.FileType == File_Types.Dfymoo)
                {
                    Debug.replacedert(Encoding.ASCII.GetString(paddedBuffer).TrimEnd('\r', '\n') ==
                                 Encoding.ASCII.GetString(buffer2).TrimEnd('\r', '\n'));
                }
                else
                {
                    for (var i = 0; i < paddedBuffer.Length; i++) Debug.replacedert(paddedBuffer[i] == buffer2[i]);
                    Debug.replacedert(paddedBuffer.SequenceEqual(buffer2));
                }
            }
        }

19 Source : ExpressionExtensions.cs
with MIT License
from areller

public static bool AllEqual(this IList<ExpressionNode> arguments, IList<ExpressionNode> otherArguments)
        {
            if (arguments is null && otherArguments is null) return true;
            return arguments?.SequenceEqual(otherArguments ?? ZeroArguments) ?? false;
        }

19 Source : Prune_node.cs
with GNU Affero General Public License v3.0
from arklumpus

public static bool OnParameterChange(object tree, Dictionary<string, object> previousParameterValues, Dictionary<string, object> currentParameterValues, out Dictionary<string, ControlStatus> controlStatus, out Dictionary<string, object> parametersToChange)
        {
            controlStatus = new Dictionary<string, ControlStatus>();
            parametersToChange = new Dictionary<string, object>() { { "Apply", false } };

            controlStatus["Leave one-child parent"] = (double)currentParameterValues["Position:"] == 0 ? ControlStatus.Enabled : ControlStatus.Hidden;

            if ((string)currentParameterValues["Attribute type:"] == "String")
            {
                controlStatus.Add("Comparison type:", ControlStatus.Enabled);
                controlStatus.Add("Comparison type: ", ControlStatus.Hidden);
                controlStatus.Add("Regex", ControlStatus.Enabled);
            }
            else if ((string)currentParameterValues["Attribute type:"] == "Number")
            {
                controlStatus.Add("Comparison type:", ControlStatus.Hidden);
                controlStatus.Add("Comparison type: ", ControlStatus.Enabled);
                controlStatus.Add("Regex", ControlStatus.Hidden);
            }

            if ((bool)currentParameterValues["Keep pruned node names"])
            {
                controlStatus.Add("Attribute name:", ControlStatus.Enabled);
            }
            else
            {
                controlStatus.Add("Attribute name:", ControlStatus.Hidden);
            }

            if ((string)previousParameterValues["Attribute:"] != (string)currentParameterValues["Attribute:"])
            {
                string attributeName = (string)currentParameterValues["Attribute:"];

                string attrType = ((TreeNode)tree).GetAttributeType(attributeName);

                if ((string)previousParameterValues["Attribute type:"] == (string)currentParameterValues["Attribute type:"])
                {
                    if (!string.IsNullOrEmpty(attrType))
                    {
                        parametersToChange.Add("Attribute type:", attrType);

                        if (attrType == "String")
                        {
                            controlStatus["Comparison type:"] = ControlStatus.Enabled;
                            controlStatus["Comparison type: "] = ControlStatus.Hidden;
                            controlStatus["Regex"] = ControlStatus.Enabled;
                        }
                        else if (attrType == "Number")
                        {
                            controlStatus["Comparison type:"] = ControlStatus.Hidden;
                            controlStatus["Comparison type: "] = ControlStatus.Enabled;
                            controlStatus["Regex"] = ControlStatus.Hidden;
                        }
                    }
                }
            }

            if ((int)currentParameterValues["Mode:"] == 0)
            {
                controlStatus["Attribute match"] = ControlStatus.Hidden;
                controlStatus["Attribute:"] = ControlStatus.Hidden;
                controlStatus["Attribute type:"] = ControlStatus.Hidden;
                controlStatus["Value:"] = ControlStatus.Hidden;
                controlStatus["Comparison type: "] = ControlStatus.Hidden;
                controlStatus["Comparison type:"] = ControlStatus.Hidden;
                controlStatus["Regex"] = ControlStatus.Hidden;
                controlStatus["Node:"] = ControlStatus.Enabled;
            }
            else if ((int)currentParameterValues["Mode:"] == 1)
            {
                controlStatus["Attribute match"] = ControlStatus.Enabled;
                controlStatus["Attribute:"] = ControlStatus.Enabled;
                controlStatus["Attribute type:"] = ControlStatus.Enabled;
                controlStatus["Value:"] = ControlStatus.Enabled;
                controlStatus["Node:"] = ControlStatus.Hidden;
            }

            return (bool)currentParameterValues["Apply"] || !((string[])previousParameterValues["Node:"]).SequenceEqual((string[])currentParameterValues["Node:"]);
        }

19 Source : Reroot_selection_action.cs
with GNU Affero General Public License v3.0
from arklumpus

public static void PerformAction(int actionIndex, TreeNode selection, MainWindow window, InstanceStateData stateData)
        {
            FurtherTransformationModule module = Modules.GetModule(Modules.FurtherTransformationModules, "c6f96861-11c0-4853-9738-6a90cc81d660");
            int index = stateData.FurtherTransformationModules().IndexOf(module);

            string[] nodeNames = selection.GetNodeNames().ToArray();

            if (nodeNames.Length == 0 || !selection.IsLastCommonAncestor(nodeNames))
            {
                if (InstanceStateData.IsUIAvailable)
                {
                    MessageBox box = new MessageBox("Attention!", "The requested node cannot be uniquely identified! Please, make sure that it either has a Name or enough of its children have Names.");
                    box.ShowDialog2(window);
                    return;
                }
                else if (InstanceStateData.IsInteractive)
                {
                    Console.WriteLine();
                    Console.WriteLine("Attention! The requested node cannot be uniquely identified! Please, make sure that it either has a Name or enough of its children have Names.");
                    Console.WriteLine();
                    return;
                }
                else
                {
                    return;
                }
            }

            if (InstanceStateData.IsUIAvailable && index >= 0)
            {
                TreeNode tree = index == 0 ? window.FirstTransformedTree : window.AllTransformedTrees[index - 1];

                List<TreeNode> originalNodes = new List<TreeNode>();

                foreach (TreeNode node in selection.GetChildrenRecursiveLazy())
                {
                    if (!string.IsNullOrEmpty(node.Name))
                    {
                        TreeNode correspNode = tree.GetNodeFromId(node.Id);

                        if (correspNode != null)
                        {
                            originalNodes.Add(correspNode);
                        }
                    }
                }

                string[] origNodeNames = (from el in originalNodes where !string.IsNullOrEmpty(el.Name) orderby el.Name select el.Name).ToArray();

                TreeNode lca = tree.GetLastCommonAncestor(origNodeNames);

                List<string> newNodeNames = lca.GetNodeNames();
                newNodeNames.Sort();

                if (newNodeNames.SequenceEqual(origNodeNames))
                {
                    nodeNames = origNodeNames;
                }
                else
                {
                    originalNodes.Clear();
                    List<TreeNode> selectionNodes = selection.GetChildrenRecursive();

                    foreach (TreeNode node in window.TransformedTree.GetChildrenRecursiveLazy())
                    {
                        if (!selectionNodes.Contains(node))
                        {
                            if (!string.IsNullOrEmpty(node.Name))
                            {
                                TreeNode correspNode = tree.GetNodeFromId(node.Id);

                                if (correspNode != null)
                                {
                                    originalNodes.Add(correspNode);
                                }
                            }
                        }
                    }

                    origNodeNames = (from el in originalNodes where !string.IsNullOrEmpty(el.Name) orderby el.Name select el.Name).ToArray();

                    lca = tree.GetLastCommonAncestor(origNodeNames);

                    newNodeNames = lca.GetNodeNames();
                    newNodeNames.Sort();

                    if (newNodeNames.SequenceEqual(origNodeNames))
                    {
                        nodeNames = origNodeNames;
                    }
                }
            }

            if (index < 0)
            {
                Action<Dictionary<string, object>> changeParameter = stateData.AddFurtherTransformationModule(module);
                changeParameter(new Dictionary<string, object>() { { "Outgroup:",  nodeNames }, { "Rooting mode:", 1 } });
                if (InstanceStateData.IsUIAvailable)
                {
                    _ = Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(async () =>
                    {
                        await window.UpdateFurtherTransformations(index);
                        window.SetSelection(window.TransformedTree.GetLastCommonAncestor(selection.GetNodeNames()));
                    });
                }
            }
            else
            {
                stateData.FurtherTransformationModulesParameterUpdater(index)(new Dictionary<string, object>() { { "Outgroup:", nodeNames }, { "Rooting mode:", 1 } });

                if (InstanceStateData.IsUIAvailable)
                {
                    _ = Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(async () =>
                    {
                        await window.UpdateFurtherTransformations(index);
                        window.SetSelection(window.TransformedTree.GetLastCommonAncestor(selection.GetNodeNames()));
                    });
                }
            }
        }

19 Source : Set_up_stochastic_mapping.cs
with GNU Affero General Public License v3.0
from arklumpus

public static void Transform(ref TreeNode tree, Dictionary<string, object> parameterValues, Action<double> progressAction)
        {
            TreeCollection trees = (TreeCollection)parameterValues["Trees"];
            InstanceStateData stateData = (InstanceStateData)parameterValues["StateData"];

            bool isClockLike = (bool)parameterValues["Treat trees as clock-like"];

            double resolution = (double)parameterValues["Resolution:"];
            int resolutionType = (int)parameterValues["Resolution unit:"];

            double actualResolution = resolution;

            switch (resolutionType)
            {
                case 0:
                    break;
                case 1:
                    actualResolution = resolution * tree.LongestDownstreamLength();
                    break;
                case 2:
                    break;
            }

            Dictionary<string, TreeNode> nodeCorresps = new Dictionary<string, TreeNode>();

            foreach (TreeNode node in tree.GetChildrenRecursiveLazy())
            {
                nodeCorresps[node.GetLeafNames().OrderBy(a => a).Aggregate((a, b) => a + "," + b)] = node;
            }

            Dictionary<string, List<(double left, double right, SimmapBranchState[] states)>> branchStates = new Dictionary<string, List<(double, double, SimmapBranchState[])>>(nodeCorresps.Count);

            foreach (KeyValuePair<string, TreeNode> kvp in nodeCorresps)
            {
                branchStates.Add(kvp.Value.Id, new List<(double start, double end, SimmapBranchState[] states)>());
            }

            HashSet<string>[] states = null;

            int sampleIndex = 0;

            foreach (TreeNode sample in trees)
            {
                foreach (TreeNode node in sample.GetChildrenRecursiveLazy())
                {
                    SimmapBranchState[] nodeStates = null;

                    if (node.Attributes.TryGetValue("States", out object statesObj) && statesObj is string statesString)
                    {
                        try
                        {
                            nodeStates = System.Text.Json.JsonSerializer.Deserialize<SimmapBranchState[]>(statesString);
                        }
                        catch { }
                    }

                    if (nodeStates != null)
                    {
                        string leafString = node.GetLeafNames().OrderBy(a => a).Aggregate((a, b) => a + "," + b);

                        if (nodeCorresps.TryGetValue(leafString, out TreeNode corresp))
                        {
                            if (states == null)
                            {
                                states = new HashSet<string>[nodeStates[0].States.Length];
                                for (int i = 0; i < states.Length; i++)
                                {
                                    states[i] = new HashSet<string>();
                                }
                            }

                            for (int i = 0; i < nodeStates.Length; i++)
                            {
                                for (int j = 0; j < nodeStates[i].States.Length; j++)
                                {
                                    states[j].Add(nodeStates[i].States[j]);
                                }
                            }

                            double left;
                            double right;

                            if (!isClockLike)
                            {
                                right = node.UpstreamLength();
                                left = right - node.Length;
                            }
                            else
                            {
                                right = node.LongestDownstreamLength();
                                left = right + node.Length;
                            }

                            branchStates[corresp.Id].Add((left, right, nodeStates));
                        }
                    }
                }

                sampleIndex++;
                progressAction((double)sampleIndex / trees.Count * 0.5);
            }

            List<List<string>> allPossibleStates = GetAllPossibleStates(states);

            Dictionary<string, (double samplePosPerc, double[] stateProbs)[]> preparedStates = new Dictionary<string, (double, double[])[]>();

            Dictionary<string, double[]> conditionedPosteriors = new Dictionary<string, double[]>();
            Dictionary<string, double[]> meanPosteriors = new Dictionary<string, double[]>();

            int nodeIndex = 0;

            List<(string, List<int>)> NaNSamples = new List<(string, List<int>)>();
            List<string> missingConditionedPosteriors = new List<string>();

            foreach (TreeNode node in tree.GetChildrenRecursiveLazy())
            {
                if (!double.IsNaN(node.Length) && node.Length > 0)
                {
                    double left;
                    double right;

                    if (!isClockLike)
                    {
                        right = node.UpstreamLength();
                        left = right - node.Length;
                    }
                    else
                    {
                        right = node.LongestDownstreamLength();
                        left = right + node.Length;
                    }

                    if (resolutionType == 2)
                    {
                        actualResolution = resolution * node.Length;
                    }

                    List<(double left, double right, SimmapBranchState[] states)> observedStates = branchStates[node.Id];

                    double[] meanPosterior = new double[allPossibleStates.Count];

                    for (int i = 0; i < observedStates.Count; i++)
                    {
                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            if (allPossibleStates[j].SequenceEqual(observedStates[i].states[0].States))
                            {
                                meanPosterior[j]++;
                                break;
                            }
                        }
                    }

                    if (observedStates.Count > 0)
                    {
                        for (int i = 0; i < meanPosterior.Length; i++)
                        {
                            meanPosterior[i] /= observedStates.Count;
                        }
                    }

                    {
                        string state = "{";

                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + meanPosterior[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                            if (j < allPossibleStates.Count - 1)
                            {
                                state += ",";
                            }
                        }

                        state += "}";

                        meanPosteriors[node.Id] = meanPosterior;
                        node.Attributes["MeanPosteriors"] = state;
                    }


                    List<(double samplePosPerc, double[] stateProbs)> preparedBranchStates = new List<(double samplePosPerc, double[] stateProbs)>();
                    List<int> NaNs = new List<int>();

                    for (int i = 0; i < Math.Ceiling(Math.Abs(right - left) / actualResolution) + 1; i++)
                    {
                        double samplingTime;
                        if (!isClockLike)
                        {
                            samplingTime = Math.Min(left + actualResolution * i, right);
                        }
                        else
                        {
                            samplingTime = Math.Max(left - actualResolution * i, right);
                        }

                        double perc = (samplingTime - left) / (right - left);



                        int[] counts = new int[allPossibleStates.Count];

                        for (int j = 0; j < observedStates.Count; j++)
                        {
                            string[] sample = SampleBranch(samplingTime, observedStates[j].left, observedStates[j].right, observedStates[j].states);

                            if (sample != null)
                            {
                                for (int k = 0; k < allPossibleStates.Count; k++)
                                {
                                    if (sample.SequenceEqual(allPossibleStates[k]))
                                    {
                                        counts[k]++;
                                        break;
                                    }
                                }
                            }
                        }

                        double total = counts.Sum();

                        double[] probs = new double[counts.Length];

                        if (total > 0)
                        {
                            for (int j = 0; j < probs.Length; j++)
                            {
                                probs[j] = counts[j] / total;
                            }
                        }
                        else
                        {
                            NaNs.Add(i);
                        }

                        preparedBranchStates.Add((perc, probs));

                        if (samplingTime == right)
                        {
                            if (total > 0)
                            {
                                string state = "{";

                                for (int j = 0; j < allPossibleStates.Count; j++)
                                {
                                    state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + probs[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                                    if (j < allPossibleStates.Count - 1)
                                    {
                                        state += ",";
                                    }
                                }

                                state += "}";

                                node.Attributes["ConditionedPosteriors"] = state;
                                conditionedPosteriors[node.Id] = probs;
                            }
                            else
                            {
                                missingConditionedPosteriors.Add(node.Id);
                            }

                            break;
                        }
                    }

                    if (NaNs.Count > 0)
                    {
                        NaNs.Sort();
                        NaNSamples.Add((node.Id, NaNs));
                    }

                    preparedStates[node.Id] = preparedBranchStates.ToArray();
                }
                else if (node.Parent == null && node.Children.Count > 0)
                {
                    List<(double left, double right, SimmapBranchState[] states)> observedStates = branchStates[node.Children[0].Id];

                    double[] meanPosterior = new double[allPossibleStates.Count];

                    for (int i = 0; i < observedStates.Count; i++)
                    {
                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            if (allPossibleStates[j].SequenceEqual(observedStates[i].states[observedStates[i].states.Length - 1].States))
                            {
                                meanPosterior[j]++;
                                break;
                            }
                        }
                    }

                    if (observedStates.Count > 0)
                    {
                        for (int i = 0; i < meanPosterior.Length; i++)
                        {
                            meanPosterior[i] /= observedStates.Count;
                        }
                    }

                    {
                        string state = "{";

                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + meanPosterior[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                            if (j < allPossibleStates.Count - 1)
                            {
                                state += ",";
                            }
                        }

                        state += "}";

                        node.Attributes["MeanPosteriors"] = state;
                        node.Attributes["ConditionedPosteriors"] = state;

                        conditionedPosteriors[node.Id] = meanPosterior;
                    }
                }

                nodeIndex++;
                progressAction(0.5 + (double)nodeIndex / nodeCorresps.Count * 0.5);
            }

            for (int i = 0; i < NaNSamples.Count; i++)
            {
                (double samplePosPerc, double[] stateProbs)[] samples = preparedStates[NaNSamples[i].Item1];
                TreeNode node = tree.GetNodeFromId(NaNSamples[i].Item1);

                if (NaNSamples[i].Item2.Count == samples.Length)
                {
                    if (missingConditionedPosteriors.Contains(node.Id))
                    {
                        conditionedPosteriors[node.Id] = meanPosteriors[node.Id];
                    }

                    for (int j = 0; j < samples.Length; j++)
                    {
                        samples[j] = (samples[j].samplePosPerc, conditionedPosteriors[node.Id]);
                    }
                }
                else
                {
                    List<int> missingSamplesStart = new List<int>();
                    List<int> missingSamplesEnd = new List<int>();

                    for (int j = 0; j < NaNSamples[i].Item2.Count; j++)
                    {
                        if (NaNSamples[i].Item2[j] == j)
                        {
                            missingSamplesStart.Add(NaNSamples[i].Item2[j]);
                        }

                        if (NaNSamples[i].Item2[NaNSamples[i].Item2.Count - 1 - j] == samples.Length - 1 - j)
                        {
                            missingSamplesEnd.Add(NaNSamples[i].Item2[NaNSamples[i].Item2.Count - 1 - j]);
                        }
                    }

                    if (missingSamplesStart.Count > 0)
                    {
                        double[] left = null;
                        double[] right = null;

                        // Parent
                        if (!missingConditionedPosteriors.Contains(node.Parent.Id))
                        {
                            left = conditionedPosteriors[node.Parent.Id];
                        }
                        else
                        {
                            (double samplePosPerc, double[] stateProbs)[] parentSamples = preparedStates[node.Parent.Id];

                            for (int j = parentSamples.Length - 1; j >= 0; j--)
                            {
                                if (parentSamples[j].stateProbs.Sum() > 0)
                                {
                                    left = parentSamples[j].stateProbs;
                                    break;
                                }
                            }
                        }

                        // First sample
                        for (int j = 0; j < samples.Length; j++)
                        {
                            if (samples[j].stateProbs.Sum() > 0)
                            {
                                right = samples[j].stateProbs;
                                break;
                            }
                        }

                        if (left != null && right != null)
                        {
                            for (int j = 0; j < missingSamplesStart.Count; j++)
                            {
                                double[] average = new double[left.Length];

                                for (int k = 0; k < left.Length; k++)
                                {
                                    average[k] = left[k] * (1 - (double)(j + 1) / (missingSamplesStart.Count + 1)) + right[k] * (double)(j + 1) / (missingSamplesStart.Count + 1);
                                }

                                samples[missingSamplesStart[j]] = (samples[missingSamplesStart[j]].samplePosPerc, average);
                            }
                        }
                        else if (right != null)
                        {
                            for (int j = 0; j < missingSamplesStart.Count; j++)
                            {
                                samples[missingSamplesStart[j]] = (samples[missingSamplesStart[j]].samplePosPerc, right);
                            }
                        }
                        else if (left != null)
                        {
                            for (int j = 0; j < missingSamplesStart.Count; j++)
                            {
                                samples[missingSamplesStart[j]] = (samples[missingSamplesStart[j]].samplePosPerc, left);
                            }
                        }
                    }


                    if (missingSamplesEnd.Count > 0)
                    {
                        double[] left = null;
                        List<double[]> right = new List<double[]>();

                        // Children
                        for (int k = 0; k < node.Children.Count; k++)
                        {
                            if (!missingConditionedPosteriors.Contains(node.Children[k].Id))
                            {
                                right.Add(conditionedPosteriors[node.Children[k].Id]);
                            }
                            else
                            {
                                (double samplePosPerc, double[] stateProbs)[] childSamples = preparedStates[node.Children[k].Id];

                                for (int j = 0; j < childSamples.Length; j++)
                                {
                                    if (childSamples[j].stateProbs.Sum() > 0)
                                    {
                                        right.Add(childSamples[j].stateProbs);
                                        break;
                                    }
                                }
                            }
                        }

                        // Last sample
                        for (int j = samples.Length - 1; j >= 0; j--)
                        {
                            if (samples[j].stateProbs.Sum() > 0)
                            {
                                left = samples[j].stateProbs;
                                break;
                            }
                        }

                        if (left != null && right.Count > 0)
                        {
                            double[] rightAverage = new double[right[0].Length];

                            for (int j = 0; j < right.Count; j++)
                            {
                                for (int k = 0; k < rightAverage.Length; k++)
                                {
                                    rightAverage[k] += right[j][k];
                                }
                            }

                            for (int k = 0; k < rightAverage.Length; k++)
                            {
                                rightAverage[k] /= right.Count;
                            }

                            for (int j = 0; j < missingSamplesEnd.Count; j++)
                            {
                                double[] average = new double[left.Length];

                                for (int k = 0; k < left.Length; k++)
                                {
                                    average[k] = rightAverage[k] * (1 - (double)(j + 1) / (missingSamplesEnd.Count + 1)) + left[k] * (double)(j + 1) / (missingSamplesEnd.Count + 1);
                                }

                                samples[missingSamplesEnd[j]] = (samples[missingSamplesEnd[j]].samplePosPerc, average);
                            }
                        }
                        else if (right.Count > 0)
                        {
                            double[] rightAverage = new double[right[0].Length];

                            for (int j = 0; j < right.Count; j++)
                            {
                                for (int k = 0; k < rightAverage.Length; k++)
                                {
                                    rightAverage[k] += right[j][k];
                                }
                            }

                            for (int k = 0; k < rightAverage.Length; k++)
                            {
                                rightAverage[k] /= right.Count;
                            }

                            for (int j = 0; j < missingSamplesEnd.Count; j++)
                            {
                                samples[missingSamplesEnd[j]] = (samples[missingSamplesEnd[j]].samplePosPerc, rightAverage);
                            }
                        }
                        else if (left != null)
                        {
                            for (int j = 0; j < missingSamplesEnd.Count; j++)
                            {
                                samples[missingSamplesEnd[j]] = (samples[missingSamplesEnd[j]].samplePosPerc, left);
                            }
                        }
                    }
                }
            }

            for (int i = 0; i < missingConditionedPosteriors.Count; i++)
            {
                double[] probs = preparedStates[missingConditionedPosteriors[i]].Last().stateProbs;

                string state = "{";

                for (int j = 0; j < allPossibleStates.Count; j++)
                {
                    state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + probs[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                    if (j < allPossibleStates.Count - 1)
                    {
                        state += ",";
                    }
                }

                state += "}";

                tree.GetNodeFromId(missingConditionedPosteriors[i]).Attributes["ConditionedPosteriors"] = state;
                conditionedPosteriors[missingConditionedPosteriors[i]] = probs;
            }

            stateData.Tags["32858c9d-0247-497f-aeee-03f7bfe24158"] = preparedStates;
            stateData.Tags["32858c9d-0247-497f-aeee-03f7bfe24158/states"] = (from el in states select el.ToArray()).ToArray();
            tree.Attributes["32858c9d-0247-497f-aeee-03f7bfe24158"] = "Stochastic map";
        }

19 Source : Set_up_stochastic_mapping_attachment.cs
with GNU Affero General Public License v3.0
from arklumpus

public static void Transform(ref TreeNode tree, Dictionary<string, object> parameterValues, Action<double> progressAction)
        {
            Attachment attachment = (Attachment)parameterValues["Attachment:"];

            if (attachment == null)
            {
                return;
            }

            attachment.Stream.Seek(attachment.StreamStart, SeekOrigin.Begin);

            TreeCollection trees = new TreeCollection(OpenFile(attachment.Stream, progressAction));

            InstanceStateData stateData = (InstanceStateData)parameterValues["StateData"];

            bool isClockLike = (bool)parameterValues["Treat trees as clock-like"];

            double resolution = (double)parameterValues["Resolution:"];
            int resolutionType = (int)parameterValues["Resolution unit:"];

            double actualResolution = resolution;

            switch (resolutionType)
            {
                case 0:
                    break;
                case 1:
                    actualResolution = resolution * tree.LongestDownstreamLength();
                    break;
                case 2:
                    break;
            }

            Dictionary<string, TreeNode> nodeCorresps = new Dictionary<string, TreeNode>();

            foreach (TreeNode node in tree.GetChildrenRecursiveLazy())
            {
                nodeCorresps[node.GetLeafNames().OrderBy(a => a).Aggregate((a, b) => a + "," + b)] = node;
            }

            Dictionary<string, List<(double left, double right, SimmapBranchState[] states)>> branchStates = new Dictionary<string, List<(double, double, SimmapBranchState[])>>(nodeCorresps.Count);

            foreach (KeyValuePair<string, TreeNode> kvp in nodeCorresps)
            {
                branchStates.Add(kvp.Value.Id, new List<(double start, double end, SimmapBranchState[] states)>());
            }

            HashSet<string>[] states = null;

            int sampleIndex = 0;

            foreach (TreeNode sample in trees)
            {
                foreach (TreeNode node in sample.GetChildrenRecursiveLazy())
                {
                    SimmapBranchState[] nodeStates = null;

                    if (node.Attributes.TryGetValue("States", out object statesObj) && statesObj is string statesString)
                    {
                        try
                        {
                            nodeStates = System.Text.Json.JsonSerializer.Deserialize<SimmapBranchState[]>(statesString);
                        }
                        catch { }
                    }

                    if (nodeStates != null)
                    {
                        string leafString = node.GetLeafNames().OrderBy(a => a).Aggregate((a, b) => a + "," + b);

                        if (nodeCorresps.TryGetValue(leafString, out TreeNode corresp))
                        {
                            if (states == null)
                            {
                                states = new HashSet<string>[nodeStates[0].States.Length];
                                for (int i = 0; i < states.Length; i++)
                                {
                                    states[i] = new HashSet<string>();
                                }
                            }

                            for (int i = 0; i < nodeStates.Length; i++)
                            {
                                for (int j = 0; j < nodeStates[i].States.Length; j++)
                                {
                                    states[j].Add(nodeStates[i].States[j]);
                                }
                            }

                            double left;
                            double right;

                            if (!isClockLike)
                            {
                                right = node.UpstreamLength();
                                left = right - node.Length;
                            }
                            else
                            {
                                right = node.LongestDownstreamLength();
                                left = right + node.Length;
                            }

                            branchStates[corresp.Id].Add((left, right, nodeStates));
                        }
                    }
                }

                sampleIndex++;

                progressAction(0.5 + (double)sampleIndex / trees.Count * 0.25);
            }

            List<List<string>> allPossibleStates = GetAllPossibleStates(states);

            Dictionary<string, (double samplePosPerc, double[] stateProbs)[]> preparedStates = new Dictionary<string, (double, double[])[]>();

            Dictionary<string, double[]> conditionedPosteriors = new Dictionary<string, double[]>();
            Dictionary<string, double[]> meanPosteriors = new Dictionary<string, double[]>();

            int nodeIndex = 0;

            List<(string, List<int>)> NaNSamples = new List<(string, List<int>)>();
            List<string> missingConditionedPosteriors = new List<string>();

            foreach (TreeNode node in tree.GetChildrenRecursiveLazy())
            {
                if (!double.IsNaN(node.Length) && node.Length > 0)
                {
                    double left;
                    double right;

                    if (!isClockLike)
                    {
                        right = node.UpstreamLength();
                        left = right - node.Length;
                    }
                    else
                    {
                        right = node.LongestDownstreamLength();
                        left = right + node.Length;
                    }

                    if (resolutionType == 2)
                    {
                        actualResolution = resolution * node.Length;
                    }

                    List<(double left, double right, SimmapBranchState[] states)> observedStates = branchStates[node.Id];

                    double[] meanPosterior = new double[allPossibleStates.Count];

                    for (int i = 0; i < observedStates.Count; i++)
                    {
                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            if (allPossibleStates[j].SequenceEqual(observedStates[i].states[0].States))
                            {
                                meanPosterior[j]++;
                                break;
                            }
                        }
                    }

                    if (observedStates.Count > 0)
                    {
                        for (int i = 0; i < meanPosterior.Length; i++)
                        {
                            meanPosterior[i] /= observedStates.Count;
                        }
                    }

                    {
                        string state = "{";

                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + meanPosterior[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                            if (j < allPossibleStates.Count - 1)
                            {
                                state += ",";
                            }
                        }

                        state += "}";

                        meanPosteriors[node.Id] = meanPosterior;
                        node.Attributes["MeanPosteriors"] = state;
                    }


                    List<(double samplePosPerc, double[] stateProbs)> preparedBranchStates = new List<(double samplePosPerc, double[] stateProbs)>();
                    List<int> NaNs = new List<int>();

                    for (int i = 0; i < Math.Ceiling(Math.Abs(right - left) / actualResolution) + 1; i++)
                    {
                        double samplingTime;
                        if (!isClockLike)
                        {
                            samplingTime = Math.Min(left + actualResolution * i, right);
                        }
                        else
                        {
                            samplingTime = Math.Max(left - actualResolution * i, right);
                        }

                        double perc = (samplingTime - left) / (right - left);



                        int[] counts = new int[allPossibleStates.Count];

                        for (int j = 0; j < observedStates.Count; j++)
                        {
                            string[] sample = SampleBranch(samplingTime, observedStates[j].left, observedStates[j].right, observedStates[j].states);

                            if (sample != null)
                            {
                                for (int k = 0; k < allPossibleStates.Count; k++)
                                {
                                    if (sample.SequenceEqual(allPossibleStates[k]))
                                    {
                                        counts[k]++;
                                        break;
                                    }
                                }
                            }
                        }

                        double total = counts.Sum();

                        double[] probs = new double[counts.Length];


                        if (total > 0)
                        {
                            for (int j = 0; j < probs.Length; j++)
                            {
                                probs[j] = counts[j] / total;
                            }
                        }
                        else
                        {
                            NaNs.Add(i);
                        }

                        preparedBranchStates.Add((perc, probs));

                        if (samplingTime == right)
                        {
                            if (total > 0)
                            {
                                string state = "{";

                                for (int j = 0; j < allPossibleStates.Count; j++)
                                {
                                    state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + probs[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                                    if (j < allPossibleStates.Count - 1)
                                    {
                                        state += ",";
                                    }
                                }

                                state += "}";

                                node.Attributes["ConditionedPosteriors"] = state;
                                conditionedPosteriors[node.Id] = probs;
                            }
                            else
                            {
                                missingConditionedPosteriors.Add(node.Id);
                            }

                            break;
                        }
                    }

                    if (NaNs.Count > 0)
                    {
                        NaNs.Sort();
                        NaNSamples.Add((node.Id, NaNs));
                    }

                    preparedStates[node.Id] = preparedBranchStates.ToArray();
                }
                else if (node.Parent == null && node.Children.Count > 0)
                {
                    List<(double left, double right, SimmapBranchState[] states)> observedStates = branchStates[node.Children[0].Id];

                    double[] meanPosterior = new double[allPossibleStates.Count];

                    for (int i = 0; i < observedStates.Count; i++)
                    {
                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            if (allPossibleStates[j].SequenceEqual(observedStates[i].states[observedStates[i].states.Length - 1].States))
                            {
                                meanPosterior[j]++;
                                break;
                            }
                        }
                    }

                    if (observedStates.Count > 0)
                    {
                        for (int i = 0; i < meanPosterior.Length; i++)
                        {
                            meanPosterior[i] /= observedStates.Count;
                        }
                    }

                    {
                        string state = "{";

                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + meanPosterior[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                            if (j < allPossibleStates.Count - 1)
                            {
                                state += ",";
                            }
                        }

                        state += "}";

                        node.Attributes["MeanPosteriors"] = state;
                        node.Attributes["ConditionedPosteriors"] = state;

                        conditionedPosteriors[node.Id] = meanPosterior;
                    }
                }

                nodeIndex++;
                progressAction(0.75 + (double)nodeIndex / nodeCorresps.Count * 0.25);
            }

            for (int i = 0; i < NaNSamples.Count; i++)
            {
                (double samplePosPerc, double[] stateProbs)[] samples = preparedStates[NaNSamples[i].Item1];
                TreeNode node = tree.GetNodeFromId(NaNSamples[i].Item1);

                if (NaNSamples[i].Item2.Count == samples.Length)
                {
                    if (missingConditionedPosteriors.Contains(node.Id))
                    {
                        conditionedPosteriors[node.Id] = meanPosteriors[node.Id];
                    }

                    for (int j = 0; j < samples.Length; j++)
                    {
                        samples[j] = (samples[j].samplePosPerc, conditionedPosteriors[node.Id]);
                    }
                }
                else
                {
                    List<int> missingSamplesStart = new List<int>();
                    List<int> missingSamplesEnd = new List<int>();

                    for (int j = 0; j < NaNSamples[i].Item2.Count; j++)
                    {
                        if (NaNSamples[i].Item2[j] == j)
                        {
                            missingSamplesStart.Add(NaNSamples[i].Item2[j]);
                        }

                        if (NaNSamples[i].Item2[NaNSamples[i].Item2.Count - 1 - j] == samples.Length - 1 - j)
                        {
                            missingSamplesEnd.Add(NaNSamples[i].Item2[NaNSamples[i].Item2.Count - 1 - j]);
                        }
                    }

                    if (missingSamplesStart.Count > 0)
                    {
                        double[] left = null;
                        double[] right = null;

                        // Parent
                        if (!missingConditionedPosteriors.Contains(node.Parent.Id))
                        {
                            left = conditionedPosteriors[node.Parent.Id];
                        }
                        else
                        {
                            (double samplePosPerc, double[] stateProbs)[] parentSamples = preparedStates[node.Parent.Id];

                            for (int j = parentSamples.Length - 1; j >= 0; j--)
                            {
                                if (parentSamples[j].stateProbs.Sum() > 0)
                                {
                                    left = parentSamples[j].stateProbs;
                                    break;
                                }
                            }
                        }

                        // First sample
                        for (int j = 0; j < samples.Length; j++)
                        {
                            if (samples[j].stateProbs.Sum() > 0)
                            {
                                right = samples[j].stateProbs;
                                break;
                            }
                        }

                        if (left != null && right != null)
                        {
                            for (int j = 0; j < missingSamplesStart.Count; j++)
                            {
                                double[] average = new double[left.Length];

                                for (int k = 0; k < left.Length; k++)
                                {
                                    average[k] = left[k] * (1 - (double)(j + 1) / (missingSamplesStart.Count + 1)) + right[k] * (double)(j + 1) / (missingSamplesStart.Count + 1);
                                }

                                samples[missingSamplesStart[j]] = (samples[missingSamplesStart[j]].samplePosPerc, average);
                            }
                        }
                        else if (right != null)
                        {
                            for (int j = 0; j < missingSamplesStart.Count; j++)
                            {
                                samples[missingSamplesStart[j]] = (samples[missingSamplesStart[j]].samplePosPerc, right);
                            }
                        }
                        else if (left != null)
                        {
                            for (int j = 0; j < missingSamplesStart.Count; j++)
                            {
                                samples[missingSamplesStart[j]] = (samples[missingSamplesStart[j]].samplePosPerc, left);
                            }
                        }
                    }


                    if (missingSamplesEnd.Count > 0)
                    {
                        double[] left = null;
                        List<double[]> right = new List<double[]>();

                        // Children
                        for (int k = 0; k < node.Children.Count; k++)
                        {
                            if (!missingConditionedPosteriors.Contains(node.Children[k].Id))
                            {
                                right.Add(conditionedPosteriors[node.Children[k].Id]);
                            }
                            else
                            {
                                (double samplePosPerc, double[] stateProbs)[] childSamples = preparedStates[node.Children[k].Id];

                                for (int j = 0; j < childSamples.Length; j++)
                                {
                                    if (childSamples[j].stateProbs.Sum() > 0)
                                    {
                                        right.Add(childSamples[j].stateProbs);
                                        break;
                                    }
                                }
                            }
                        }

                        // Last sample
                        for (int j = samples.Length - 1; j >= 0; j--)
                        {
                            if (samples[j].stateProbs.Sum() > 0)
                            {
                                left = samples[j].stateProbs;
                                break;
                            }
                        }

                        if (left != null && right.Count > 0)
                        {
                            double[] rightAverage = new double[right[0].Length];

                            for (int j = 0; j < right.Count; j++)
                            {
                                for (int k = 0; k < rightAverage.Length; k++)
                                {
                                    rightAverage[k] += right[j][k];
                                }
                            }

                            for (int k = 0; k < rightAverage.Length; k++)
                            {
                                rightAverage[k] /= right.Count;
                            }

                            for (int j = 0; j < missingSamplesEnd.Count; j++)
                            {
                                double[] average = new double[left.Length];

                                for (int k = 0; k < left.Length; k++)
                                {
                                    average[k] = rightAverage[k] * (1 - (double)(j + 1) / (missingSamplesEnd.Count + 1)) + left[k] * (double)(j + 1) / (missingSamplesEnd.Count + 1);
                                }

                                samples[missingSamplesEnd[j]] = (samples[missingSamplesEnd[j]].samplePosPerc, average);
                            }
                        }
                        else if (right.Count > 0)
                        {
                            double[] rightAverage = new double[right[0].Length];

                            for (int j = 0; j < right.Count; j++)
                            {
                                for (int k = 0; k < rightAverage.Length; k++)
                                {
                                    rightAverage[k] += right[j][k];
                                }
                            }

                            for (int k = 0; k < rightAverage.Length; k++)
                            {
                                rightAverage[k] /= right.Count;
                            }

                            for (int j = 0; j < missingSamplesEnd.Count; j++)
                            {
                                samples[missingSamplesEnd[j]] = (samples[missingSamplesEnd[j]].samplePosPerc, rightAverage);
                            }
                        }
                        else if (left != null)
                        {
                            for (int j = 0; j < missingSamplesEnd.Count; j++)
                            {
                                samples[missingSamplesEnd[j]] = (samples[missingSamplesEnd[j]].samplePosPerc, left);
                            }
                        }
                    }
                }
            }

            for (int i = 0; i < missingConditionedPosteriors.Count; i++)
            {
                double[] probs = preparedStates[missingConditionedPosteriors[i]].Last().stateProbs;

                string state = "{";

                for (int j = 0; j < allPossibleStates.Count; j++)
                {
                    state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + probs[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                    if (j < allPossibleStates.Count - 1)
                    {
                        state += ",";
                    }
                }

                state += "}";

                tree.GetNodeFromId(missingConditionedPosteriors[i]).Attributes["ConditionedPosteriors"] = state;
                conditionedPosteriors[missingConditionedPosteriors[i]] = probs;
            }

            stateData.Tags["32858c9d-0247-497f-aeee-03f7bfe24158"] = preparedStates;
            stateData.Tags["32858c9d-0247-497f-aeee-03f7bfe24158/states"] = (from el in states select el.ToArray()).ToArray();
            tree.Attributes["32858c9d-0247-497f-aeee-03f7bfe24158"] = "Stochastic map";
        }

19 Source : Cartoon_node.cs
with GNU Affero General Public License v3.0
from arklumpus

public static bool OnParameterChange(object tree, Dictionary<string, object> previousParameterValues, Dictionary<string, object> currentParameterValues, out Dictionary<string, ControlStatus> controlStatus, out Dictionary<string, object> parametersToChange)
        {
            controlStatus = new Dictionary<string, ControlStatus>();
            parametersToChange = new Dictionary<string, object>() { };

            return !((string[])previousParameterValues["Node:"]).SequenceEqual((string[])currentParameterValues["Node:"]) || !((VectSharp.Colour)currentParameterValues["Fill colour:"]).Equals(((VectSharp.Colour)previousParameterValues["Fill colour:"])) || ((bool)currentParameterValues["Equalise lengths"] != (bool)previousParameterValues["Equalise lengths"]);
        }

19 Source : Switch_children.cs
with GNU Affero General Public License v3.0
from arklumpus

public static bool OnParameterChange(object tree, Dictionary<string, object> previousParameterValues, Dictionary<string, object> currentParameterValues, out Dictionary<string, ControlStatus> controlStatus, out Dictionary<string, object> parametersToChange)
        {
            controlStatus = new Dictionary<string, ControlStatus>();
            parametersToChange = new Dictionary<string, object>();

            return (bool)currentParameterValues["Recursive"] != (bool)previousParameterValues["Recursive"] || !((string[])currentParameterValues["Node:"]).SequenceEqual((string[])previousParameterValues["Node:"]);
        }

19 Source : ValueObject.cs
with MIT License
from armanab

public override bool Equals(object obj)
        {
            if (obj == null || obj.GetType() != GetType())
            {
                return false;
            }

            var other = (ValueObject)obj;
            return GetEqualityComponents().SequenceEqual(other.GetEqualityComponents());
        }

19 Source : GitRepoInspector.cs
with MIT License
from AshleighAdams

private async Task Deepen()
		{
			var probe = await ProbeDepth();

			if (probe.ShallowCommits.Count == 0)
				throw new AutoDeepenException("Failed to deepen the repository. No shallow commits accessible from head. Maybe accessing orphaned commit?");

			Log?.Normal($"Deepen(): Attempting to deepen the repository.");
			try
			{
				if (DeepenFromCommitSupported)
				{
					foreach (var (commit, depth) in probe.ShallowCommits)
					{
						var additionalDepth = Math.Max(32, depth); // effectively doubling

						Log?.Normal($"Deepen(): Deepen {additionalDepth} commits from {commit}.");
						_ = await Git("fetch", Remote, commit.Id, $"--depth={additionalDepth}");
					}
				}
				else
				{
					var maxDepth = probe.ShallowCommits.Max(x => x.depth);
					var newTotalDepth = Math.Max(32, maxDepth * 2);

					Log?.Normal($"Deepen(): Deepen {newTotalDepth} commits from HEAD.");
					_ = await Git("fetch", Remote, $"--depth={newTotalDepth}");
				}
			}
			catch (CommandException ex)
				when (
					DeepenFromCommitSupported &&
					ex.StandardError.Contains("error: Server does not allow request for unadvertised object"))
			{
				Log?.Normal($"Deepen(): From commit not supported, falling back to old method.");
				DeepenFromCommitSupported = false;
				await Deepen();
			}
			catch (CommandException ex)
			{
				throw new AutoDeepenException(ex);
			}

			var reprobe = await ProbeDepth();
			if (reprobe.ShallowCommits.SequenceEqual(probe.ShallowCommits))
				throw new AutoDeepenException("Failed to deepen the repository. Shallow commits did not change.");
		}

19 Source : ModuleInfo.cs
with GNU Affero General Public License v3.0
from asmejkal

private static CommandInfo.CommandHandlerDelegate BuildCommandHandler(Type type, MethodInfo method)
        {
            var moduleParameter = Expression.Parameter(typeof(object));
            var convertedModuleParameter = Expression.Convert(moduleParameter, type);
            var commandParameter = Expression.Parameter(typeof(ICommand));
            var loggerParameter = Expression.Parameter(typeof(ILogger));
            var ctParameter = Expression.Parameter(typeof(CancellationToken));

            var parameters = method.GetParameters().Select(x => x.ParameterType).ToList();
            MethodCallExpression call;
            if (parameters.SequenceEqual(new[] { typeof(ICommand), typeof(ILogger), typeof(CancellationToken) }))
                call = Expression.Call(convertedModuleParameter, method, commandParameter, loggerParameter, ctParameter);
            if (parameters.SequenceEqual(new[] { typeof(ICommand), typeof(ILogger) }))
                call = Expression.Call(convertedModuleParameter, method, commandParameter, loggerParameter);
            else if (parameters.SequenceEqual(new[] { typeof(ICommand), typeof(CancellationToken) }))
                call = Expression.Call(convertedModuleParameter, method, commandParameter, ctParameter);
            else if (parameters.SequenceEqual(new[] { typeof(ICommand) }))
                call = Expression.Call(convertedModuleParameter, method, commandParameter);
            else
                throw new ArgumentException($"Invalid method signature of command {method.Name} on type {type}.");

            var lambda = Expression.Lambda<CommandInfo.CommandHandlerDelegate>(call, moduleParameter, commandParameter, loggerParameter, ctParameter);

            return lambda.Compile();
        }

19 Source : ModHandler.cs
with MIT License
from AstroTechies

public void VerifyIntegrity()
        {
            MismatchedSteamworksDLL = false;

            try
            {
                string potentialDllDir = Path.Combine(GamePath, "Engine", "Binaries", "ThirdParty", "Steamworks");
                if (Directory.Exists(potentialDllDir))
                {
                    string[] dllPaths = Directory.GetFiles(potentialDllDir, "steam_api*.dll", SearchOption.AllDirectories);
                    if (dllPaths.Length > 0 && File.Exists(dllPaths[0]))
                    {
                        var data = File.ReadAllBytes(dllPaths[0]);
                        var hash = SHA1.Create().ComputeHash(data);
                        if (!hash.SequenceEqual(steamsworksDLLHash)) MismatchedSteamworksDLL = true;
                    }
                }
            }
            catch
            {
                MismatchedSteamworksDLL = false;
            }
        }

19 Source : AssetUnitTests.cs
with MIT License
from atenfyr

private void TestJsonOnFile(string file, UE4Version version)
        {
            Debug.WriteLine(file);
            var tester = new Ureplacedet(Path.Combine("TestJson", file), version);
            replacedert.IsTrue(tester.VerifyBinaryEquality());
            replacedert.IsTrue(CheckAllExportsParsedCorrectly(tester));

            string jsonSerializedreplacedet = tester.SerializeJson();
            File.WriteAllText(Path.Combine("TestJson", "raw.json"), jsonSerializedreplacedet);

            var tester2 = Ureplacedet.DeserializeJson(File.ReadAllText(Path.Combine("TestJson", "raw.json")));
            tester2.Write(Path.Combine("TestJson", "MODIFIED.ureplacedet"));

            // For the replacedets we're testing binary equality is maintained and can be used as a metric of success, but binary equality is not guaranteed for most replacedets
            replacedert.IsTrue(File.ReadAllBytes(Path.Combine("TestJson", file)).SequenceEqual(File.ReadAllBytes(Path.Combine("TestJson", "MODIFIED.ureplacedet"))));
        }

19 Source : AssetUnitTests.cs
with MIT License
from atenfyr

[TestMethod]
        [Deploymenreplacedem(@"Testreplacedets/TestManyreplacedets/Bloodstained/PB_DT_RandomizerRoomCheck.ureplacedet", "TestDataTables")]
        public void TestDataTables()
        {
            var tester = new Ureplacedet(Path.Combine("TestDatatables", "PB_DT_RandomizerRoomCheck.ureplacedet"), UE4Version.VER_UE4_18);
            replacedert.IsTrue(tester.VerifyBinaryEquality());
            replacedert.IsTrue(CheckAllExportsParsedCorrectly(tester));
            replacedert.IsTrue(tester.Exports.Count == 1);

            var ourDataTableExport = tester.Exports[0] as DataTableExport;
            var ourTable = ourDataTableExport?.Table;
            replacedert.IsNotNull(ourTable);

            // Check out the first entry to make sure it's parsing alright, and flip all the flags for later testing
            StructPropertyData firstEntry = ourTable.Data[0];

            bool didFindTestName = false;
            for (int i = 0; i < firstEntry.Value.Count; i++)
            {
                var propData = firstEntry.Value[i];
                Debug.WriteLine(i + ": " + propData.Name + ", " + propData.PropertyType);
                if (propData.Name == new FName("AcceleratorANDDoubleJump")) didFindTestName = true;
                if (propData is BoolPropertyData boolProp) boolProp.Value = !boolProp.Value;
            }
            replacedert.IsTrue(didFindTestName);

            // Save the modified table
            tester.Write(Path.Combine("TestDatatables", "MODIFIED.ureplacedet"));

            // Load the modified table back in and make sure we're good
            var tester2 = new Ureplacedet(Path.Combine("TestDatatables", "MODIFIED.ureplacedet"), UE4Version.VER_UE4_18);
            replacedert.IsTrue(tester2.VerifyBinaryEquality());
            replacedert.IsTrue(CheckAllExportsParsedCorrectly(tester2));
            replacedert.IsTrue(tester2.Exports.Count == 1);

            // Flip the flags back to what they originally were
            firstEntry = (tester2.Exports[0] as DataTableExport)?.Table?.Data?[0];
            replacedert.IsNotNull(firstEntry);
            for (int i = 0; i < firstEntry.Value.Count; i++)
            {
                if (firstEntry.Value[i] is BoolPropertyData boolProp) boolProp.Value = !boolProp.Value;
            }

            // Save and check that it's binary equal to what we originally had
            tester2.Write(tester2.FilePath);
            replacedert.IsTrue(File.ReadAllBytes(Path.Combine("TestDatatables", "PB_DT_RandomizerRoomCheck.ureplacedet")).SequenceEqual(File.ReadAllBytes(Path.Combine("TestDatatables", "MODIFIED.ureplacedet"))));
        }

19 Source : CommandContext.cs
with MIT License
from AtomicBlom

public bool Equals(CommandContext<TSource> other)
		{
			if (ReferenceEquals(null, other)) return false;
			if (ReferenceEquals(this, other)) return true;
			return _arguments.SequenceEqual(other._arguments) 
			       && Equals(RootNode, other.RootNode) 
			       && Nodes.SequenceEqual(other.Nodes) 
			       && Equals(Command, other.Command) 
			       && EqualityComparer<TSource>.Default.Equals(Source, other.Source) 
			       && Equals(Child, other.Child);
		}

19 Source : ScriptSwitchSettings.cs
with GNU General Public License v3.0
from AutoDarkMode

public override bool Equals(object obj)
        {
            if (obj is ScriptSwitchSettings other)
            {
                return Scripts.SequenceEqual(other.Scripts);
            }
            return base.Equals(obj);
        }

19 Source : ScriptSwitchSettings.cs
with GNU General Public License v3.0
from AutoDarkMode

public override bool Equals(object obj)
        {
            if (obj is Script other)
            {
                if (other.Name != Name) return false;
                if (other.Command != Command) return false;
                if (!other.ArgsDark.SequenceEqual(ArgsDark)) return false;
                if (!other.ArgsLight.SequenceEqual(ArgsLight)) return false;
                if (other.WorkingDirectory != WorkingDirectory) return false;
                if (!other.AllowedSources.SequenceEqual(AllowedSources)) return false;
                return true;
            }
            return base.Equals(obj);
        }

19 Source : Workplane.Test.cs
with MIT License
from Autodesk

[Test]
        public void WhenWritingWorkplaneToMatrix_ThenCheckOutput()
        {
            var matrixFile =
                new File(AppDomain.CurrentDomain.BaseDirectory + @"\..\..\TestFiles\WokplaneTestFiles\x_30_ty10.matrix");
            var output = File.CreateTemporaryFile("matrix");

            var workplane = new Workplane(matrixFile);
            workplane.WriteToMatrix(output);

            bool filesAreTheSame = System.IO.File.ReadLines(output.Path).SequenceEqual(System.IO.File.ReadLines(matrixFile.Path));

            replacedert.True(filesAreTheSame, "Failed to read matrix file.");
            output.Delete();
        }

19 Source : BadInput.cs
with Apache License 2.0
from Autodesk-Forge

public bool Equals(BadInput other)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            if (other == null)
                return false;

            return 
                (
                    this.Jsonapi == other.Jsonapi ||
                    this.Jsonapi != null &&
                    this.Jsonapi.Equals(other.Jsonapi)
                ) && 
                (
                    this.Errors == other.Errors ||
                    this.Errors != null &&
                    this.Errors.SequenceEqual(other.Errors)
                );
        }

19 Source : Conflict.cs
with Apache License 2.0
from Autodesk-Forge

public bool Equals(Conflict other)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            if (other == null)
                return false;

            return 
                (
                    this.Jsonapi == other.Jsonapi ||
                    this.Jsonapi != null &&
                    this.Jsonapi.Equals(other.Jsonapi)
                ) && 
                (
                    this.Errors == other.Errors ||
                    this.Errors != null &&
                    this.Errors.SequenceEqual(other.Errors)
                );
        }

19 Source : BucketObjects.cs
with Apache License 2.0
from Autodesk-Forge

public bool Equals(BucketObjects other)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            if (other == null)
                return false;

            return 
                (
                    this.Items == other.Items ||
                    this.Items != null &&
                    this.Items.SequenceEqual(other.Items)
                ) && 
                (
                    this.Next == other.Next ||
                    this.Next != null &&
                    this.Next.Equals(other.Next)
                );
        }

19 Source : Folder.cs
with Apache License 2.0
from Autodesk-Forge

public bool Equals(Folder other)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            if (other == null)
                return false;

            return 
                (
                    this.Jsonapi == other.Jsonapi ||
                    this.Jsonapi != null &&
                    this.Jsonapi.Equals(other.Jsonapi)
                ) && 
                (
                    this.Data == other.Data ||
                    this.Data != null &&
                    this.Data.Equals(other.Data)
                ) && 
                (
                    this.Included == other.Included ||
                    this.Included != null &&
                    this.Included.SequenceEqual(other.Included)
                ) && 
                (
                    this.Links == other.Links ||
                    this.Links != null &&
                    this.Links.Equals(other.Links)
                ) && 
                (
                    this.Id == other.Id ||
                    this.Id != null &&
                    this.Id.Equals(other.Id)
                ) && 
                (
                    this.Type == other.Type ||
                    this.Type != null &&
                    this.Type.Equals(other.Type)
                ) && 
                (
                    this.Attributes == other.Attributes ||
                    this.Attributes != null &&
                    this.Attributes.Equals(other.Attributes)
                ) && 
                (
                    this.Meta == other.Meta ||
                    this.Meta != null &&
                    this.Meta.Equals(other.Meta)
                ) && 
                (
                    this.Relationships == other.Relationships ||
                    this.Relationships != null &&
                    this.Relationships.Equals(other.Relationships)
                );
        }

19 Source : Buckets.cs
with Apache License 2.0
from Autodesk-Forge

public bool Equals(Buckets other)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            if (other == null)
                return false;

            return 
                (
                    this.Items == other.Items ||
                    this.Items != null &&
                    this.Items.SequenceEqual(other.Items)
                ) && 
                (
                    this.Next == other.Next ||
                    this.Next != null &&
                    this.Next.Equals(other.Next)
                );
        }

19 Source : FormatsFormats.cs
with Apache License 2.0
from Autodesk-Forge

public bool Equals(FormatsFormats other)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            if (other == null)
                return false;

            return 
                (
                    this.Svf == other.Svf ||
                    this.Svf != null &&
                    this.Svf.SequenceEqual(other.Svf)
                ) && 
                (
                    this.Thumbnail == other.Thumbnail ||
                    this.Thumbnail != null &&
                    this.Thumbnail.SequenceEqual(other.Thumbnail)
                ) && 
                (
                    this.Stl == other.Stl ||
                    this.Stl != null &&
                    this.Stl.SequenceEqual(other.Stl)
                ) && 
                (
                    this.Step == other.Step ||
                    this.Step != null &&
                    this.Step.SequenceEqual(other.Step)
                ) && 
                (
                    this.Iges == other.Iges ||
                    this.Iges != null &&
                    this.Iges.SequenceEqual(other.Iges)
                ) && 
                (
                    this.Obj == other.Obj ||
                    this.Obj != null &&
                    this.Obj.SequenceEqual(other.Obj)
                );
        }

19 Source : Hubs.cs
with Apache License 2.0
from Autodesk-Forge

public bool Equals(Hubs other)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            if (other == null)
                return false;

            return 
                (
                    this.Jsonapi == other.Jsonapi ||
                    this.Jsonapi != null &&
                    this.Jsonapi.Equals(other.Jsonapi)
                ) && 
                (
                    this.Data == other.Data ||
                    this.Data != null &&
                    this.Data.SequenceEqual(other.Data)
                );
        }

19 Source : ItemCreated.cs
with Apache License 2.0
from Autodesk-Forge

public bool Equals(ItemCreated other)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            if (other == null)
                return false;

            return 
                (
                    this.Jsonapi == other.Jsonapi ||
                    this.Jsonapi != null &&
                    this.Jsonapi.Equals(other.Jsonapi)
                ) && 
                (
                    this.Data == other.Data ||
                    this.Data != null &&
                    this.Data.Equals(other.Data)
                ) && 
                (
                    this.Included == other.Included ||
                    this.Included != null &&
                    this.Included.SequenceEqual(other.Included)
                ) && 
                (
                    this.Links == other.Links ||
                    this.Links != null &&
                    this.Links.Equals(other.Links)
                );
        }

19 Source : JobObjOutputPayloadAdvanced.cs
with Apache License 2.0
from Autodesk-Forge

public bool Equals(JobObjOutputPayloadAdvanced other)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            if (other == null)
                return false;

            return 
                (
                    this.ExportFileStructure == other.ExportFileStructure ||
                    this.ExportFileStructure != null &&
                    this.ExportFileStructure.Equals(other.ExportFileStructure)
                ) && 
                (
                    this.ModelGuid == other.ModelGuid ||
                    this.ModelGuid != null &&
                    this.ModelGuid.Equals(other.ModelGuid)
                ) && 
                (
                    this.ObjectIds == other.ObjectIds ||
                    this.ObjectIds != null &&
                    this.ObjectIds.SequenceEqual(other.ObjectIds)
                ) &&
                (
                    this.Unit == other.Unit ||
                    this.Unit != null &&
                    this.Unit.Equals(other.Unit)
                );
        }

See More Examples