System.Collections.Generic.IEnumerable.LastOrDefault()

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

836 Examples 7

19 Source : FFmpeg.cs
with GNU General Public License v3.0
from audiamus

private void ffMpegAsyncHandlerSilence (object sendingProcess, DataReceivedEventArgs outLine) {
      onCancel ();

      if (outLine.Data is null)
        return;

#if TRACE && EXTRA
      Trace.WriteLine (outLine.Data);
#endif
      Log (4, this, () => ID + outLine.Data.SubsreplacedUser ());

      // continue to the very end
      //if (_success)
      //  return;

      var t = AudioMeta.Time;

      Match match;
      if (!_matchedDuration) {

        match = _rgxDuration.Match (outLine.Data);
        if (match.Success) {
          TimeSpan duration = tryParseTimestamp (match);
          t.Duration = duration;

          _matchedDuration = true;
        }

      } else {

        match = _rgxSilenceStart.Match (outLine.Data);
        if (match.Success) {
          var ivl = Silences.LastOrDefault ();
          if (ivl != null && ivl.End == TimeSpan.Zero)
            Silences.RemoveAt (Silences.Count - 1);
          var start = tryParseSeconds (match);
          Silences.Add (new TimeInterval (start, TimeSpan.Zero));
          return;

        } else {

          match = _rgxSilenceEnd.Match (outLine.Data);
          if (match.Success) {
            var ivl = Silences.LastOrDefault ();
            if (ivl == null)
              return;
            if (ivl.End != TimeSpan.Zero) {
              Silences.RemoveAt (Silences.Count - 1);
              return;
            }
            var end = tryParseSeconds (match);
            var duration = tryParseSeconds (match, 2);
            ivl.End = end;
            if (Math.Abs ((ivl.Duration - duration).TotalSeconds) > 0.01)
              Silences.RemoveAt (Silences.Count - 1);
            return;

          } else {

            match = _rgxTimestamp1.Match (outLine.Data);

            if (!match.Success) {

              match = _rgxMuxFinal.Match (outLine.Data);
              if (match.Success)
                _success = true;

              return;

            }
          }
        }
      }


      if (!match.Success)
        return;

      if (t.Duration == TimeSpan.Zero)
        return;

      TimeSpan ts = tryParseTimestamp (match);
      double progress = ts.TotalSeconds / t.Duration.TotalSeconds;

      Progress?.Invoke (progress);


    }

19 Source : ExpressionExtensions.cs
with MIT License
from AutoMapper

public static bool IsMemberPath(this LambdaExpression exp)
        {
            return exp.Body.GetMembers().LastOrDefault()?.Expression == exp.Parameters.First();
        }

19 Source : Assert.cs
with Apache License 2.0
from AutomateThePlanet

public static void Multiple(params Action[] replacedertions)
        {
            var replacedertionExceptions = new List<Exception>();
            foreach (var replacedertion in replacedertions)
            {
                try
                {
                    replacedertion();
                }
                catch (Exception e)
                {
                    replacedertionExceptions.Add(e);
                }
            }

            if (replacedertionExceptions.Any())
            {
                throw replacedertionExceptions.LastOrDefault();
            }
        }

19 Source : AssemblyFacade.cs
with Apache License 2.0
from AutomateThePlanet

public List<replacedembly> GetreplacedembliesCallChain()
        {
            var trace = new StackTrace();
            var replacedemblies = new List<replacedembly>();
            var frames = trace.GetFrames();

            if (frames == null)
            {
                throw new Exception("Couldn't get the stack trace");
            }

            foreach (var frame in frames)
            {
                var method = frame.GetMethod();
                var declaringType = method.DeclaringType;

                if (declaringType == null)
                {
                    continue;
                }

                var declaringTypereplacedembly = declaringType.replacedembly;
                var lastreplacedembly = replacedemblies.LastOrDefault();

                if (declaringTypereplacedembly != lastreplacedembly)
                {
                    replacedemblies.Add(declaringTypereplacedembly);
                }
            }

            foreach (var currentreplacedembly in replacedemblies)
            {
                Debug.WriteLine(currentreplacedembly.ManifestModule.Name);
            }

            return replacedemblies;
        }

19 Source : Option.cs
with MIT License
from AVPolyakov

public static Option<T> LastOrNone<T>(this IEnumerable<T> it)
        {
            var lastOrDefault = it.Select(_ => new {_}).LastOrDefault();
            return lastOrDefault == null ? new Option<T>() : lastOrDefault._;
        }

19 Source : CertificateUtility.cs
with Apache License 2.0
from awslabs

public static X509Certificate2 GetCertificate(StoreLocation storeLocation, string username, string templateNameRegex = null)
        {
            if (string.IsNullOrWhiteSpace(username)) return null;

            string extractionRegex = null, nameMatchRegex = null;
            if (storeLocation == StoreLocation.LocalMachine)
            {
                extractionRegex = "DNS Name=([a-zA-Z0-9@\\.\\-_]+)";
                nameMatchRegex = $"^{username}(.+)*";
            }
            else
            {
                extractionRegex = "Principal Name=([a-zA-Z0-9@\\.\\-_]+)";
                nameMatchRegex = $"^{username}(@.+)*";
            }

            using (var store = new X509Store(StoreName.My, storeLocation))
            {
                store.Open(OpenFlags.OpenExistingOnly);
                var candidateCertificates = store.Certificates.Find(X509FindType.FindBySubjectName, username, false)
                    .Find(X509FindType.FindByExtension, DnsNameOid, false)
                    .Find(X509FindType.FindByExtension, EnhancedKeyUsageOid, true);

                if (candidateCertificates.Count > 0)
                {
                    foreach (var cert in candidateCertificates)
                    {
                        if (cert.Subject == cert.Issuer)
                        {
                            continue;
                        }

                        if (cert.Extensions[EnhancedKeyUsageOid] is X509EnhancedKeyUsageExtension eku && eku.EnhancedKeyUsages[ClientAuthenticationOid] == null)
                        {
                            continue;
                        }

                        var dnsNameExtension = cert.Extensions[DnsNameOid];
                        if (dnsNameExtension == null)
                        {
                            continue;
                        }

                        if (!string.IsNullOrWhiteSpace(templateNameRegex))
                        {
                            var templateNameExtension = cert.Extensions[TemplateNameOid];
                            if (templateNameExtension == null)
                            {
                                continue;
                            }

                            var templateName = templateNameExtension.Format(false).Split('(').FirstOrDefault()?.Split('=').LastOrDefault()?.Trim();
                            if (string.IsNullOrWhiteSpace(templateName))
                            {
                                continue;
                            }

                            if (!Regex.IsMatch(templateName, templateNameRegex, RegexOptions.IgnoreCase))
                            {
                                continue;
                            }
                        }

                        var nameToMatch = dnsNameExtension.Format(false);

                        var nameMatches = Regex.Match(nameToMatch, extractionRegex);
                        if (nameMatches != null || nameMatches.Groups.Count == 2 || Regex.IsMatch(nameMatches.Groups[1].Value, nameMatchRegex))
                        {
                            return cert;
                        }
                    }
                }

                return null;
            }
        }

19 Source : WaveFinder.cs
with MIT License
from AyrA

private static void Scanner(object o)
        {
            var S = (Stream)o;
            Cont = true;
            Files = new List<WaveFileInfo>();
            var buffer = new byte[100 * 1000 * 1000];
            var SEQ = Encoding.Default.GetBytes("WAVEfmt ");
#if DEBUG
            //For debug only.
            //Right now the audio files seem to be towards the end of the file.
            //To speed up debugging, we skip the first half of the file.
            S.Seek(S.Length / 2, SeekOrigin.Begin);
#endif
            while (Cont)
            {
                if (S.Position > 0)
                {
                    S.Seek(-SEQ.Length, SeekOrigin.Current);
                }
                var StartPos = S.Position;
                int count = S.Read(buffer, 0, buffer.Length);
                Cont = count == buffer.Length;
                for (var i = 0; i < count - SEQ.Length; i++)
                {
                    //Don't bother doing anything if the first character is no match
                    if (SEQ[0] == buffer[i])
                    {
                        for (var j = 0; j < SEQ.Length; j++)
                        {
                            if (SEQ[j] != buffer[i + j])
                            {
                                break;
                            }
                            else if (j == SEQ.Length - 1)
                            {
                                Log.Write("WaveFinder: Found audio at {0}", S.Position - count + i);
                                var LastPos = S.Position;
                                //Found wave chunk, go to start of it
                                S.Seek(StartPos + i - 8, SeekOrigin.Begin);
                                var Info = new WaveFileInfo()
                                {
                                    FilePosition = StartPos + i - 8,
                                    Header = new WAVHeader(S)
                                };
                                //This is always 1 for some reason in Satisfactory
                                Log.Write("WaveFinder: Audio channel count: {0}", Info.Header.ChannelCount);
                                //Info.Header.ChannelCount = 2;

                                S.Seek(Info.Header.DataOffset, SeekOrigin.Begin);
                                if (IsOgg(S))
                                {
                                    Info.Type = WaveFileType.OGG;
                                }
                                else if (Info.Header.SampleRate == 44100 && Info.Header.BitsPerSample == 16)
                                {
                                    Info.Type = WaveFileType.PCM;
                                }
                                else
                                {
                                    Info.Type = WaveFileType.Invalid;
                                }
                                //Remove overlapping section
                                //This means the Wave file was inside another wave file
                                if (Overlaps(Info, Files.LastOrDefault()))
                                {
                                    Log.Write("WaveFinder: Removed overlapping WAV segment at NEW={0}; OLD={1}", Info.FilePosition, Files.Last().FilePosition);
                                    Files.RemoveAt(Files.Count - 1);
                                }
                                Files.Add(Info);
                                //Restore stream position
                                S.Seek(LastPos, SeekOrigin.Begin);
                            }
                        }
                    }
                }
            }
            T = null;
        }

19 Source : ControlFlowGraph.cs
with Apache License 2.0
from azizamari

public static bool AllPathsReturn(BoundBlockStatement body)
        {
            var graph = Create(body);

            foreach (var branch in graph.End.Incoming)
            {
                var lastStatement = branch.From.Statements.LastOrDefault();
                if (lastStatement == null || lastStatement.Kind != BoundNodeKind.ReturnStatement)
                    return false;
            }

            return true;
        }

19 Source : SyntaxNode.cs
with Apache License 2.0
from azizamari

private static void TreePrint(TextWriter writer, SyntaxNode node, string indent = "", bool isLast = true)
        {
            var isToConsole = writer == Console.Out;
            var marker = isLast ? "└──" : "├──";

            if (isToConsole)
                Console.ForegroundColor = ConsoleColor.DarkGray;

            writer.Write(indent);
            writer.Write(marker);

            if (isToConsole)
                Console.ForegroundColor = node is SyntaxToken ? ConsoleColor.Blue : ConsoleColor.Cyan;

            writer.Write(node.Kind);

            if (node is SyntaxToken t && t.Value != null)
            {
                writer.Write(" ");
                writer.Write(t.Value);
            }

            if (isToConsole)
                Console.ResetColor();

            writer.WriteLine();

            indent += isLast ? "   " : "│  ";

            var lastChild = node.GetChildren().LastOrDefault();

            foreach (var child in node.GetChildren())
                TreePrint(writer, child, indent, child == lastChild);
        }

19 Source : TestEntityClasses.cs
with MIT License
from Azure

public DateTime Post(string content)
            {
                // create a monotonically increasing timestamp
                var lastPost = this.ChatEntries.LastOrDefault().Key;
                var timestamp = new DateTime(Math.Max(DateTime.UtcNow.Ticks, lastPost.Ticks + 1));

                this.ChatEntries.Add(timestamp, content);

                return timestamp;
            }

19 Source : VariantEncoderEx.cs
with MIT License
from Azure

public static DiagnosticInfo Decode(this IVariantEncoder codec,
            ServiceResultModel result, DiagnosticsModel config, out StatusCode code) {
            if (result == null) {
                code = StatusCodes.Good;
                return null;
            }
            code = new StatusCode(result.StatusCode ?? StatusCodes.Good);
            var results = codec.Decode(result, config);
            return results?.LastOrDefault()?.DiagnosticsInfo;
        }

19 Source : ObjectTable.Lua.cs
with MIT License
from b-editor

public bool copybuffer(string dst, string src)
        {
            Action<Image<BGRA32>>? GetAction(string dst)
            {
                if (dst == "tmp")
                {
                    return img =>
                    {
                        using var texture = Texture.FromImage(img);
                        _sharedGraphics.SetSize(img.Size);
                        _sharedGraphics.DrawTexture(texture);
                    };
                }
                else if (dst == "obj")
                {
                    return img =>
                    {
                        // "obj" <= "obj" の場合のため
                        var cloned = img.Clone();
                        _img.Dispose();
                        _img = cloned;
                    };
                }
                else if (dst.Contains("cache:"))
                {
                    var name = dst.Split(":").LastOrDefault();
                    if (string.IsNullOrWhiteSpace(name))
                        return null;

                    if (_buffers.TryGetValue(name, out var old))
                    {
                        old.Dispose();
                        _buffers.Remove(name);
                    }

                    return img =>
                    {
                        _buffers.Add(name, img.Clone());
                    };
                }
                else
                {
                    return null;
                }
            }

            var action = GetAction(dst);
            if (action == null)
                return false;

            if (src == "frm")
            {
                var ctx = _imageobj.Parent.Parent.GraphicsContext!;
                using var buffer = new Image<BGRA32>(ctx.Width, ctx.Height);

                ctx.ReadImage(buffer);

                action.Invoke(buffer);
                return true;
            }
            else if (src == "obj")
            {
                action.Invoke(_img);
                return true;
            }
            else if (src.Contains("cache:"))
            {
                var name = src.Split(":").LastOrDefault();
                if (string.IsNullOrWhiteSpace(name))
                    return false;

                if (_buffers.TryGetValue(name, out var buffer))
                {
                    action.Invoke(buffer);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else if (src.Contains("image:"))
            {
                var file = src.Split(":").LastOrDefault();
                if (string.IsNullOrWhiteSpace(file))
                    return false;

                file = Path.GetFullPath(file, BasePath);
                if (!File.Exists(file))
                    return false;

                using var buffer = Image<BGRA32>.FromFile(file);
                action.Invoke(buffer);
                return true;
            }

            return false;
        }

19 Source : GenericLexer.cs
with MIT License
from b3b00

public LexerResult<IN> Tokenize(ReadOnlyMemory<char> memorySource)
        {
            LexerPosition position = new LexerPosition();
            
            var tokens = new List<Token<IN>>();

            var r = LexerFsm.Run(memorySource, new LexerPosition());
            
            if (!r.IsSuccess && !r.IsEOS)
            {
                var result = r.Result;
                var error = new LexicalError(result.Position.Line, result.Position.Column, result.CharValue, I18n);
                return new LexerResult<IN>(error);
            }
            if (r.IsSuccess && r.Result.IsComment)
            {
                position = r.NewPosition;
                position = ConsumeComment(r.Result, memorySource, position);
            }
            else if (r.IsSuccess && !r.Result.IsComment)
            {
                position = r.NewPosition;
            }

            while (r.IsSuccess)
            {
                ComputePositionWhenIgnoringEOL(r, tokens);
                var transcoded = Transcode(r);
                
                if (CallBacks.TryGetValue(transcoded.TokenID, out var callback))
                {
                    transcoded = callback(transcoded);
                }
                
                if (transcoded.IsLineEnding)
                {
                    ComputePositionWhenIgnoringEOL(r, tokens);
                }

                if (r.IsUnIndent && r.UnIndentCount > 1)
                {
                    for (int i = 1; i < r.UnIndentCount; i++)
                    {
                        tokens.Add(transcoded);
                    }   
                }
                tokens.Add(transcoded);
                r = LexerFsm.Run(memorySource,position);
                if (!r.IsSuccess && !r.IsEOS)
                {
                    if (r.IsIndentationError)
                    {
                        var result = r.Result;
                        var error = new IndentationError(result.Position.Line, result.Position.Column,I18n);
                        return new LexerResult<IN>(error);
                    }
                    else
                    {
                        var result = r.Result;
                        var error = new LexicalError(result.Position.Line, result.Position.Column, result.CharValue,I18n);
                        return new LexerResult<IN>(error);
                    }
                }

                if (r.IsSuccess && r.Result.IsComment)
                {
                    position = r.NewPosition;
                    position = ConsumeComment(r.Result, memorySource, position);
                }
                else if (r.IsSuccess && !r.Result.IsComment)
                {
                    position = r.NewPosition;
                }
            }

            var eos = new Token<IN>();
            var prev = tokens.LastOrDefault();
            if (prev == null)
            {
                eos.Position = new LexerPosition(1, 0, 0);
            }
            else
            {
                eos.Position = new LexerPosition(prev.Position.Index + 1, prev.Position.Line,
                    prev.Position.Column + prev.Value.Length);
            }
            tokens.Add(eos);
            return new LexerResult<IN>(tokens);
        }

19 Source : DarkMaze.cs
with MIT License
from baaron4

private void HPCheck(CombatData combatData, FightData fightData)
        {
            AbstractSingleActor eye1 = Targets.FirstOrDefault(x => x.ID == (int)ArcDPSEnums.TargetID.EyeOfFate);
            AbstractSingleActor eye2 = Targets.FirstOrDefault(x => x.ID == (int)ArcDPSEnums.TargetID.EyeOfJudgement);
            if (eye2 == null || eye1 == null)
            {
                throw new MissingKeyActorsException("Eyes not found");
            }
            IReadOnlyList<HealthUpdateEvent> eye1HPs = combatData.GetHealthUpdateEvents(eye1.Agenreplacedem);
            IReadOnlyList<HealthUpdateEvent> eye2HPs = combatData.GetHealthUpdateEvents(eye2.Agenreplacedem);
            if (eye1HPs.Count == 0 || eye2HPs.Count == 0)
            {
                return;
            }
            double lastEye1Hp = eye1HPs.LastOrDefault().HPPercent;
            double lastEye2Hp = eye2HPs.LastOrDefault().HPPercent;
            double margin1 = Math.Min(0.80, lastEye1Hp);
            double margin2 = Math.Min(0.80, lastEye2Hp);
            if (lastEye1Hp <= margin1 && lastEye2Hp <= margin2)
            {
                int lastIEye1;
                for (lastIEye1 = eye1HPs.Count - 1; lastIEye1 >= 0; lastIEye1--)
                {
                    if (eye1HPs[lastIEye1].HPPercent > margin1)
                    {
                        lastIEye1++;
                        break;
                    }
                }
                int lastIEye2;
                for (lastIEye2 = eye2HPs.Count - 1; lastIEye2 >= 0; lastIEye2--)
                {
                    if (eye2HPs[lastIEye2].HPPercent > margin2)
                    {
                        lastIEye2++;
                        break;
                    }
                }
                fightData.SetSuccess(true, Math.Max(eye1HPs[lastIEye1].Time, eye2HPs[lastIEye2].Time));
            }
        }

19 Source : Adina.cs
with MIT License
from baaron4

internal override List<PhaseData> GetPhases(ParsedEvtcLog log, bool requirePhases)
        {
            List<PhaseData> phases = GetInitialPhase(log);
            AbstractSingleActor mainTarget = Targets.FirstOrDefault(x => x.ID == (int)ArcDPSEnums.TargetID.Adina);
            if (mainTarget == null)
            {
                throw new MissingKeyActorsException("Adina not found");
            }
            phases[0].AddTarget(mainTarget);
            if (!requirePhases)
            {
                return phases;
            }
            // Split phases
            List<AbstractBuffEvent> invuls = GetFilteredList(log.CombatData, 762, mainTarget, true);
            long start = 0;
            var splitPhases = new List<PhaseData>();
            var splitPhaseEnds = new List<long>();
            for (int i = 0; i < invuls.Count; i++)
            {
                PhaseData splitPhase;
                AbstractBuffEvent be = invuls[i];
                if (be is BuffApplyEvent)
                {
                    start = be.Time;
                    if (i == invuls.Count - 1)
                    {
                        splitPhase = new PhaseData(start, log.FightData.FightEnd, "Split " + (i / 2 + 1));
                        splitPhaseEnds.Add(log.FightData.FightEnd);
                        AddTargetsToPhaseAndFit(splitPhase, new List<int> { (int)ArcDPSEnums.TrashID.HandOfErosion, (int)ArcDPSEnums.TrashID.HandOfEruption }, log);
                        splitPhases.Add(splitPhase);
                    }
                }
                else
                {
                    long end = be.Time;
                    splitPhase = new PhaseData(start, end, "Split " + (i / 2 + 1));
                    splitPhaseEnds.Add(end);
                    AddTargetsToPhaseAndFit(splitPhase, new List<int> { (int)ArcDPSEnums.TrashID.HandOfErosion, (int)ArcDPSEnums.TrashID.HandOfEruption }, log);
                    splitPhases.Add(splitPhase);
                }
            }
            // Main phases
            var mainPhases = new List<PhaseData>();
            var pillarApplies = log.CombatData.GetBuffData(56204).OfType<BuffApplyEvent>().Where(x => x.To == mainTarget.Agenreplacedem).ToList();
            Dictionary<long, List<BuffApplyEvent>> pillarAppliesGroupByTime = ParserHelper.GroupByTime(pillarApplies);
            var mainPhaseEnds = new List<long>();
            foreach (KeyValuePair<long, List<BuffApplyEvent>> pair in pillarAppliesGroupByTime)
            {
                if (pair.Value.Count == 6)
                {
                    mainPhaseEnds.Add(pair.Key);
                }
            }
            AbstractCastEvent boulderBarrage = mainTarget.GetCastEvents(log, 0, log.FightData.FightEnd).FirstOrDefault(x => x.SkillId == 56648 && x.Time < 6000);
            start = boulderBarrage == null ? 0 : boulderBarrage.EndTime;
            if (mainPhaseEnds.Any())
            {
                int phaseIndex = 1;
                foreach (long quantumQake in mainPhaseEnds)
                {
                    var curPhaseStart = splitPhaseEnds.LastOrDefault(x => x < quantumQake);
                    if (curPhaseStart == 0)
                    {
                        curPhaseStart = start;
                    }
                    long nextPhaseStart = splitPhaseEnds.FirstOrDefault(x => x > quantumQake);
                    if (nextPhaseStart != 0)
                    {
                        start = nextPhaseStart;
                        phaseIndex = splitPhaseEnds.IndexOf(start) + 1;
                    }
                    mainPhases.Add(new PhaseData(curPhaseStart, quantumQake, "Phase " + phaseIndex));
                }
                if (start != mainPhases.Last().Start)
                {
                    mainPhases.Add(new PhaseData(start, log.FightData.FightEnd, "Phase " + (phaseIndex + 1)));
                }
            } 
            else if (start > 0 && !invuls.Any())
            {
                // no split
                mainPhases.Add(new PhaseData(start, log.FightData.FightEnd, "Phase 1"));
            }

            foreach (PhaseData phase in mainPhases)
            {
                phase.AddTarget(mainTarget);
            }
            phases.AddRange(mainPhases);
            phases.AddRange(splitPhases);
            phases.Sort((x, y) => x.Start.CompareTo(y.Start));
            //
            try
            {
                var splitPhasesMap = new List<string>()
                {
                        "https://i.imgur.com/gJ55jKy.png",
                        "https://i.imgur.com/c2Oz5bj.png",
                        "https://i.imgur.com/P4SGbrc.png",
                };
                var mainPhasesMap = new List<string>()
                {
                        "https://i.imgur.com/IQn2RJV.png",
                        "https://i.imgur.com/3pO7eCB.png",
                        "https://i.imgur.com/ZFw590w.png",
                        "https://i.imgur.com/2P7UE8q.png"
                };
                var crMaps = new List<string>();
                int mainPhaseIndex = 0;
                int splitPhaseIndex = 0;
                for (int i = 1; i < phases.Count; i++)
                {
                    PhaseData phaseData = phases[i];
                    if (mainPhases.Contains(phaseData))
                    {
                        if (mainPhasesMap.Contains(crMaps.LastOrDefault()))
                        {
                            splitPhaseIndex++;
                        }
                        crMaps.Add(mainPhasesMap[mainPhaseIndex++]);
                    }
                    else
                    {
                        if (splitPhasesMap.Contains(crMaps.LastOrDefault()))
                        {
                            mainPhaseIndex++;
                        }
                        crMaps.Add(splitPhasesMap[splitPhaseIndex++]);
                    }
                }
                GetCombatReplayMap(log).MatchMapsToPhases(crMaps, phases, log.FightData.FightEnd);
            } 
            catch(Exception)
            {
                log.UpdateProgressWithCancellationCheck("Failed to replacedociate Adina Combat Replay maps");
            }
            
            //
            return phases;
        }

19 Source : WaypointPathVisualization.cs
with GNU Affero General Public License v3.0
from Barsonax

public void SetPath(Vector2[] waypointPath, Transformer transformer)
		{
			Path = waypointPath;
			Start = waypointPath.FirstOrDefault();
			End = waypointPath.LastOrDefault();
			Transformer = transformer;
		}

19 Source : FakeRecipeRepository.cs
with MIT License
from bartschotten

public Recipe GetLatestAdded()
        {
            return Recipes.LastOrDefault();
        }

19 Source : MainWindowViewModel.cs
with MIT License
from bcssov

protected async Task OverlayLoopAsync()
        {
            void setOverlayProperties(OverlayProgressEvent e)
            {
                if (e.IsVisible != OverlayVisible)
                {
                    OverlayVisible = e.IsVisible;
                }
                if (e.Message != OverlayMessage)
                {
                    OverlayMessage = e.Message;
                }
                if (e.MessageProgress != OverlayMessageProgress)
                {
                    OverlayMessageProgress = e.MessageProgress;
                    HasProgress = !string.IsNullOrWhiteSpace(e.MessageProgress);
                }
            }
            while (true)
            {
                await Task.Delay(2);
                lock (queueLock)
                {
                    var now = DateTime.Now;
                    if (overlayStack.Any(p => now >= p.DateAdded) && currentMessageId.HasValue)
                    {
                        var overlays = overlayStack.Where(p => now >= p.DateAdded && p.Event.Id == currentMessageId.GetValueOrDefault()).OrderBy(p => p.DateAdded).ToList();
                        if (overlays.Count > 0)
                        {
                            OverlayQueue overlay = null;
                            if (overlays.Any(p => p.Event.IsVisible != OverlayVisible))
                            {
                                if (overlays.Any(p => p.Event.IsVisible == false))
                                {
                                    overlayStack.RemoveAll(p => p.Event.Id <= currentMessageId.GetValueOrDefault());
                                    if (overlayStack.Count > 0)
                                    {
                                        currentMessageId = overlayStack.OrderByDescending(p => p.Event.Id).FirstOrDefault().Event.Id;
                                    }
                                    else
                                    {
                                        currentMessageId = null;
                                    }
                                    if (currentMessageId.HasValue)
                                    {
                                        lastMessageId = currentMessageId.GetValueOrDefault();
                                    }
                                    else
                                    {
                                        lastMessageId++;
                                    }
                                    overlay = overlays.FirstOrDefault(p => p.Event.IsVisible == false);
                                }
                                else
                                {
                                    overlay = overlays.FirstOrDefault(p => p.Event.IsVisible != OverlayVisible);
                                    if (overlay != null)
                                    {
                                        overlayStack.Remove(overlay);
                                    }
                                }
                            }
                            else
                            {
                                foreach (var item in overlays)
                                {
                                    overlayStack.Remove(item);
                                }
                                overlay = overlays.LastOrDefault();
                            }
                            if (overlay != null)
                            {
                                setOverlayProperties(overlay.Event);
                            }
                        }
                    }
                }
            }
        }

19 Source : ModService.cs
with MIT License
from bcssov

protected virtual IEnumerable<IModInstallationResult> GetAllModDescriptors(string path, ModSource modSource)
        {
            var files = Directory.Exists(path) ? Directory.EnumerateFiles(path, $"*{Shared.Constants.ZipExtension}").Union(Directory.EnumerateFiles(path, $"*{Shared.Constants.BinExtension}")) : Array.Empty<string>();
            var directories = Directory.Exists(path) ? Directory.EnumerateDirectories(path) : Array.Empty<string>();
            var mods = new List<IModInstallationResult>();

            static void setDescriptorPath(IMod mod, string desiredPath, string localPath)
            {
                if (desiredPath.Equals(localPath, StringComparison.OrdinalIgnoreCase))
                {
                    mod.DescriptorFile = desiredPath;
                }
                else
                {
                    if (mod.RemoteId.GetValueOrDefault() > 0)
                    {
                        mod.DescriptorFile = desiredPath;
                    }
                    else
                    {
                        mod.Source = ModSource.Local;
                        mod.DescriptorFile = localPath;
                    }
                }
            }

            void parseModFiles(string path, ModSource source, bool isDirectory)
            {
                var result = GetModelInstance<IModInstallationResult>();
                try
                {
                    var fileInfo = Reader.GetFileInfo(path, Shared.Constants.DescriptorFile);
                    if (fileInfo == null)
                    {
                        fileInfo = Reader.GetFileInfo(path, $"*{Shared.Constants.ModExtension}");
                        if (fileInfo == null)
                        {
                            return;
                        }
                    }
                    var mod = Mapper.Map<IMod>(ModParser.Parse(fileInfo.Content));
                    mod.FileName = path.Replace("\\", "/");
                    mod.FullPath = path.StandardizeDirectorySeparator();
                    mod.IsLocked = fileInfo.IsReadOnly;
                    mod.Source = source;
                    var cleanedPath = path;
                    if (!isDirectory)
                    {
                        cleanedPath = Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path));
                    }

                    var localPath = $"{Shared.Constants.ModDirectory}/{cleanedPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).LastOrDefault()}{Shared.Constants.ModExtension}";
                    switch (mod.Source)
                    {
                        case ModSource.Local:
                            setDescriptorPath(mod, localPath, localPath);
                            break;

                        case ModSource.Steam:
                            if (mod.RemoteId.GetValueOrDefault() == 0)
                            {
                                if (!isDirectory)
                                {
                                    var modParentDirectory = Path.GetDirectoryName(path);
                                    mod.RemoteId = GetSteamModId(modParentDirectory, isDirectory);
                                }
                                else
                                {
                                    mod.RemoteId = GetSteamModId(path, isDirectory);
                                }
                            }
                            setDescriptorPath(mod, $"{Shared.Constants.ModDirectory}/{Constants.Steam_mod_id}{mod.RemoteId}{Shared.Constants.ModExtension}", localPath);
                            break;

                        case ModSource.Paradox:
                            if (!isDirectory)
                            {
                                var modParentDirectory = Path.GetDirectoryName(path);
                                mod.RemoteId = GetPdxModId(modParentDirectory, isDirectory);
                            }
                            else
                            {
                                mod.RemoteId = GetPdxModId(path, isDirectory);
                            }
                            setDescriptorPath(mod, $"{Shared.Constants.ModDirectory}/{Constants.Paradox_mod_id}{mod.RemoteId}{Shared.Constants.ModExtension}", localPath);
                            break;

                        default:
                            break;
                    }
                    result.Mod = mod;
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                    result.Invalid = true;
                }
                result.Path = path;
                result.IsFile = File.Exists(path);
                if (result.IsFile)
                {
                    result.ParentDirectory = Path.GetDirectoryName(path);
                }
                else
                {
                    result.ParentDirectory = path;
                }
                mods.Add(result);
            }
            if (files.Any())
            {
                foreach (var file in files)
                {
                    parseModFiles(file, modSource, false);
                }
            }
            if (directories.Any())
            {
                foreach (var directory in directories)
                {
                    var modSourceOverride = directory.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).
                            LastOrDefault().Contains(Constants.Paradox_mod_id, StringComparison.OrdinalIgnoreCase) ? ModSource.Paradox : modSource;

                    parseModFiles(directory, modSourceOverride, true);

                    var zipFiles = Directory.EnumerateFiles(directory, $"*{Shared.Constants.ZipExtension}").Union(Directory.EnumerateFiles(directory, $"*{Shared.Constants.BinExtension}"));
                    if (zipFiles.Any())
                    {
                        foreach (var zip in zipFiles)
                        {
                            parseModFiles(zip, modSourceOverride, false);
                        }
                    }

                    var subdirectories = Directory.GetDirectories(directory);
                    if (subdirectories.Any())
                    {
                        foreach (var subdirectory in subdirectories)
                        {
                            var subDirectoryModSourceOverride = subdirectory.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).
                                LastOrDefault().Contains(Constants.Paradox_mod_id, StringComparison.OrdinalIgnoreCase) ? ModSource.Paradox : modSource;
                            parseModFiles(subdirectory, subDirectoryModSourceOverride, true);
                        }
                    }
                }
            }
            return mods;
        }

19 Source : scrollParallax.cs
with Apache License 2.0
from Bigotter

void checkLayers (List<Transform> list, float limit, float origin)
	{

		var first = list.FirstOrDefault();
		if (first != null)
		{
			if (first.position.x < origin - limit)
			{
				var last = list.LastOrDefault();
				first.position = new Vector3(last.position.x + limit, first.position.y, first.position.z);

				list.Remove(first);
				list.Add(first);
			}
		}
	}

19 Source : scrollParallax.cs
with Apache License 2.0
from Bigotter

void Start()
	{
		for (int i = 0; i < transform.childCount; i++)
		{
			Transform child = transform.GetChild(i);
			if (child.GetComponent<Transform>() != null)
			{
				backgroundPart.Add(child);

				List<Transform> sprites = new List<Transform> ();
				for (int loopSprites = 0; loopSprites < child.childCount; loopSprites++) {
					var loopLayer = child.GetChild (loopSprites);
					sprites.Add(loopLayer);
				} 
				sprites = sprites.OrderBy (t => t.position.x).ToList ();
				backgroundsContinue.Add (sprites);
				var size = sprites.LastOrDefault ().position.x - sprites.FirstOrDefault ().position.x;
				limits.Add (size);
				float origin = sprites.FirstOrDefault ().position.x;
				origins.Add (origin);
				Debug.Log ("size " + size + " "+origin);
			}
		}
		backgroundPart = backgroundPart.OrderByDescending (t => t.position.x).ToList ();
	}

19 Source : Command.cs
with MIT License
from bilal-fazlani

private void AddOperand(Operand operand)
        {
            operand.Parent = this;
            var lastOperand = Operands.LastOrDefault();
            if (lastOperand is { } && lastOperand.Arity.AllowsMany())
            {
                var message =
                    $"The last operand '{lastOperand.Name}' accepts multiple values. No more operands can be added.";
                throw new InvalidConfigurationException(message);
            }
            _operands.Add(operand);
            RegisterArgumentByAliases(operand);
        }

19 Source : AsyncQueryableExecuter.cs
with MIT License
from bing-framework

public Task<T> LastOrDefaultAsync<T>(IQueryable<T> queryable, CancellationToken cancellationToken = default)
        {
            var provider = FindProvider(queryable);
            return provider != null
                ? provider.LastOrDefaultAsync(queryable, cancellationToken)
                : Task.FromResult(queryable.LastOrDefault());
        }

19 Source : JoinClause.cs
with MIT License
from bing-framework

public void On(ICondition condition) => _params.LastOrDefault()?.On(condition);

19 Source : JoinClause.cs
with MIT License
from bing-framework

public void On(string column, object value, Operator @operator = Operator.Equal) =>
            _params.LastOrDefault()?.On(column, value, @operator);

19 Source : JoinClause.cs
with MIT License
from bing-framework

public void On<TLeft, TRight>(Expression<Func<TLeft, TRight, bool>> expression) where TLeft : clreplaced where TRight : clreplaced
        {
            if (expression == null)
                throw new ArgumentNullException(nameof(expression));
            var expressions = Lambdas.GetGroupPredicates(expression);
            var items = expressions.Select(GetOnItems).ToList();
            _params.LastOrDefault()?.On(items, _dialect);
        }

19 Source : JoinClause.cs
with MIT License
from bing-framework

public void AppendOn(string sql) => _params.LastOrDefault()?.AppendOn(sql, _dialect);

19 Source : KeyCombinationExtensions.cs
with MIT License
from Blacklock

public static void OnSequence(this IKeyboardEvents source, IEnumerable<KeyValuePair<Sequence, Action>> map)
        {
            var actBySeq = map.ToArray();
            var endsWith = new Func<Queue<Combination>, Sequence, bool>((chords, sequence) =>
            {
                var skipCount = chords.Count - sequence.Length;
                return skipCount >= 0 && chords.Skip(skipCount).SequenceEqual(sequence);
            });

            var max = actBySeq.Select(p => p.Key).Max(c => c.Length);
            var min = actBySeq.Select(p => p.Key).Min(c => c.Length);
            var buffer = new Queue<Combination>(max);

            var wrapMap = actBySeq.SelectMany(p => p.Key).Select(c => new KeyValuePair<Combination, Action>(c, () =>
            {
                buffer.Enqueue(c);
                if (buffer.Count > max) buffer.Dequeue();
                if (buffer.Count < min) return;
                //Invoke action corresponding to the longest matching sequence
                actBySeq
                    .Where(pair => endsWith(buffer, pair.Key))
                    .OrderBy(pair => pair.Key.Length)
                    .Select(pair => pair.Value)
                    .LastOrDefault()
                    ?.Invoke();
            }));

            OnCombination(source, wrapMap, buffer.Clear);
        }

19 Source : ItemGroupBase.cs
with MIT License
from BlazorComponent

public async virtual Task Toggle(StringNumber key)
        {
            if (_values.Contains(key))
            {
                _values.Remove(key);
            }
            else
            {
                if (!Multiple)
                {
                    _values.Clear();
                }

                _values.Add(key);
            }

            if (Mandatory && _values.Count == 0)
            {
                _values.Add(key);
            }

            if (ValuesChanged.HasDelegate)
            {
                await ValuesChanged.InvokeAsync(_values);
            }

            if (ValueChanged.HasDelegate)
            {
                await ValueChanged.InvokeAsync(_values.LastOrDefault());
            }

            StateHasChanged();
        }

19 Source : TokenSet.cs
with MIT License
from bleroy

public void Insert(string word)
            {
                int commonPrefix = 0;

                if (StringComparer.Ordinal.Compare(word, _previousWord) < 0)
                    throw new InvalidOperationException("Out of order word insertion.");

                for (int i = 0; i < word.Length && i < _previousWord.Length; i ++)
                {
                    if (word[i] != _previousWord[i]) break;
                    commonPrefix++;
                }

                Minimize(commonPrefix);

                TokenSet node = _uncheckedNodes.LastOrDefault().child ?? Root;

                for (int i = commonPrefix; i < word.Length; i++)
                {
                    var nextNode = new TokenSet(_idProvider);
                    char ch = word[i];

                    node.Edges.Add(ch, nextNode);

                    _uncheckedNodes.Add((node, ch, nextNode));

                    node = nextNode;
                }

                node.IsFinal = true;
                _previousWord = word;
            }

19 Source : MerkleTreeHelper.cs
with GNU Affero General Public License v3.0
from blockbasenetwork

public static byte[] CalculateMerkleRootHash(List<byte[]> leaves)
        {
            if (!leaves.Any())
                return new byte[32];
            if (leaves.Count == 1)
                return leaves.First();
            if ((leaves.Count % 2) > 0)
                leaves.Add(leaves.LastOrDefault());

            var branches = new List<byte[]>();
            
            for (int i = 0; i < leaves.Count; i+=2)
            {
                var concatenatedHash = (leaves[i].Concat(leaves[i+1])).ToArray();
                branches.Add(HashHelper.Sha256Data(concatenatedHash));
            }

            return CalculateMerkleRootHash(branches);
        }

19 Source : ExtensionMethods.cs
with GNU General Public License v3.0
from blqw

public static IServiceProvider Autowired(this IServiceProvider serviceProvider, object instance)
        {
            if (serviceProvider == null || instance == null)
            {
                return serviceProvider;
            }
            var flags = BindingFlags.Public | BindingFlags.NonPublic;
            var type = instance as Type ?? instance.GetType();
            if (instance is Type)
            {
                instance = null;
                flags |= BindingFlags.Static;
            }
            else
            {
                flags |= BindingFlags.Instance;
            }


            foreach (var field in type.GetFields(flags))
            {
                var attr = field.GetCustomAttributes().OfType<IServiceProviderFactory<IServiceProvider>>().LastOrDefault();
                var value = attr?.CreateServiceProvider(serviceProvider).GetServiceOrCreateInstance(field.FieldType);
                if (value != null)
                {
                    field.SetValue(instance, value);
                }
            }

            foreach (var property in type.GetProperties(flags))
            {
                var attr = property.GetCustomAttributes().OfType<IServiceProviderFactory<IServiceProvider>>().FirstOrDefault();
                var value = attr?.CreateServiceProvider(serviceProvider).GetServiceOrCreateInstance(property.PropertyType);
                if (value != null)
                {
                    property.Set(instance, value);
                }
            }

            return serviceProvider;
        }

19 Source : YoutubeDLExtensions.cs
with BSD 3-Clause "New" or "Revised" License
from Bluegrams

public static FormatData SelectSingleFormat(this VideoData videoData, string formatSpecifier)
        {
            if (new[] { "best", "worst" , null }.Contains(formatSpecifier))
            {
                var audioVideoFormats = videoData.GetAudioVideoFormats().ToList();
                if (audioVideoFormats.Count > 0)
                {
                    int index = formatSpecifier == "worst" ? 0 : (audioVideoFormats.Count - 1);
                    return audioVideoFormats[index];
                }
                // select best video-only or audio-only format
                else
                {
                    int index = formatSpecifier == "worst" ? 0 : (videoData.Formats.Length - 1);
                    return videoData.Formats[index];
                }
            }
            else if (formatSpecifier == "bestaudio")
            {
                var audioFormats = videoData.GetAudioOnlyFormats().ToList();
                if (audioFormats.Count > 0)
                    return audioFormats[audioFormats.Count - 1];
                else return null;
            }
            else if (formatSpecifier == "worstaudio")
            {
                var audioFormats = videoData.GetAudioOnlyFormats().ToList();
                if (audioFormats.Count > 0)
                    return audioFormats[0];
                else return null;
            }
            else if (formatSpecifier == "bestvideo")
            {
                var audioFormats = videoData.GetVideoOnlyFormats().ToList();
                if (audioFormats.Count > 0)
                    return audioFormats[audioFormats.Count - 1];
                else return null;
            }
            else if (formatSpecifier == "worstvideo")
            {
                var audioFormats = videoData.GetVideoOnlyFormats().ToList();
                if (audioFormats.Count > 0)
                    return audioFormats[0];
                else return null;
            }
            else
            {
                string[] extensions = new[] { "mp4", "flv", "webm", "3gp", "m4a", "mp3", "ogg", "aac", "wav" };
                if (extensions.Contains(formatSpecifier))
                {
                    var matches = videoData.Formats.Where(f => f.Extension == formatSpecifier);
                    return matches.LastOrDefault();
                }
                else
                {
                    var matches = videoData.Formats.Where(f => f.FormatId == formatSpecifier);
                    return matches.LastOrDefault();
                }
            }
        }

19 Source : MovieStatisticsService.cs
with GNU General Public License v3.0
from bonarr

private MovieStatistics MapMovieStatistics(List<SeasonStatistics> seasonStatistics)
        {
            var movieStatistics = new MovieStatistics
                                   {
                                       SeasonStatistics = seasonStatistics,
                                       MovieId = seasonStatistics.First().MovieId,
                                       EpisodeFileCount = seasonStatistics.Sum(s => s.EpisodeFileCount),
                                       EpisodeCount = seasonStatistics.Sum(s => s.EpisodeCount),
                                       TotalEpisodeCount = seasonStatistics.Sum(s => s.TotalEpisodeCount),
                                       SizeOnDisk = seasonStatistics.Sum(s => s.SizeOnDisk)
                                   };

            var nextAiring = seasonStatistics.Where(s => s.NextAiring != null)
                                             .OrderBy(s => s.NextAiring)
                                             .FirstOrDefault();

            var previousAiring = seasonStatistics.Where(s => s.PreviousAiring != null)
                                                 .OrderBy(s => s.PreviousAiring)
                                                 .LastOrDefault();

            movieStatistics.NextAiringString = nextAiring != null ? nextAiring.NextAiringString : null;
            movieStatistics.PreviousAiringString = previousAiring != null ? previousAiring.PreviousAiringString : null;

            return movieStatistics;
        }

19 Source : QualityParser.cs
with GNU General Public License v3.0
from bonarr

public static QualityModel ParseQuality(string name)
        {
            Logger.Debug("Trying to parse quality for {0}", name);

            name = name.Trim();
            var normalizedName = name.Replace('_', ' ').Trim().ToLower();
            var result = ParseQualityModifiers(name, normalizedName);
            var subMatch = HardcodedSubsRegex.Matches(normalizedName).OfType<Match>().LastOrDefault();

            if (subMatch != null && subMatch.Success)
            {
                if (subMatch.Groups["hcsub"].Success)
                {
                    result.HardcodedSubs = subMatch.Groups["hcsub"].Value;
                }
                else if (subMatch.Groups["hc"].Success)
                {
                    result.HardcodedSubs = "Generic Hardcoded Subs";
                }
            }

            var sourceMatch = SourceRegex.Matches(normalizedName).OfType<Match>().LastOrDefault();
            var resolution = ParseResolution(normalizedName);
            var codecRegex = CodecRegex.Match(normalizedName);

            if (RemuxRegex.IsMatch(normalizedName))
            {
                if (resolution == Resolution.R2160p)
                {
                    result.Quality = Quality.Remux2160p;
                    return result;
                }

                if (resolution == Resolution.R1080p)
                {
                    result.Quality = Quality.Remux1080p;
                    return result;
                }
            }

            if (sourceMatch != null && sourceMatch.Success)
            {
                if (sourceMatch.Groups["bluray"].Success)
                {
                    if (codecRegex.Groups["xvid"].Success || codecRegex.Groups["divx"].Success)
                    {
                        result.Quality = Quality.DVD;
                        return result;
                    }

                    if (resolution == Resolution.R2160p)
                    {
                        result.Quality = Quality.Bluray2160p;
                        return result;
                    }

                    if (resolution == Resolution.R1080p)
                    {
                        result.Quality = Quality.Bluray1080p;
                        return result;
                    }

                    if (resolution == Resolution.R576p)
                    {
                        result.Quality = Quality.Bluray576p;
                        return result;
                    }

                    if (resolution == Resolution.R480P)
                    {
                        result.Quality = Quality.Bluray480p;
                        return result;
                    }

                    result.Quality = Quality.Bluray720p;
                    return result;
                }

                if (sourceMatch.Groups["webdl"].Success)
                {
                    if (resolution == Resolution.R2160p)
                    {
                        result.Quality = Quality.WEBDL2160p;
                        return result;
                    }

                    if (resolution == Resolution.R1080p)
                    {
                        result.Quality = Quality.WEBDL1080p;
                        return result;
                    }

                    if (resolution == Resolution.R720p)
                    {
                        result.Quality = Quality.WEBDL720p;
                        return result;
                    }

                    if (name.Contains("[WEBDL]"))
                    {
                        result.Quality = Quality.WEBDL720p;
                        return result;
                    }

                    result.Quality = Quality.WEBDL480p;
                    return result;
                }

                if (sourceMatch.Groups["hdtv"].Success)
                {
                    if (resolution == Resolution.R2160p)
                    {
                        result.Quality = Quality.HDTV2160p;
                        return result;
                    }

                    if (resolution == Resolution.R1080p)
                    {
                        result.Quality = Quality.HDTV1080p;
                        return result;
                    }

                    if (resolution == Resolution.R720p)
                    {
                        result.Quality = Quality.HDTV720p;
                        return result;
                    }

                    if (name.Contains("[HDTV]"))
                    {
                        result.Quality = Quality.HDTV720p;
                        return result;
                    }

                    result.Quality = Quality.SDTV;
                    return result;
                }

                if (sourceMatch.Groups["bdrip"].Success ||
                    sourceMatch.Groups["brrip"].Success)
                {
                    if (codecRegex.Groups["xvid"].Success || codecRegex.Groups["divx"].Success)
                    {
                        result.Quality = Quality.DVD;
                        return result;
                    }
                    
                    switch (resolution)
                    {
                        case Resolution.R720p:
                            result.Quality = Quality.Bluray720p;
                            return result;
                        case Resolution.R1080p:
                            result.Quality = Quality.Bluray1080p;
                            return result;
						case Resolution.R576p:
							result.Quality = Quality.Bluray576p;
							return result;
						case Resolution.R480P:
							result.Quality = Quality.Bluray480p;
							return result;
                        default:
                            result.Quality = Quality.Bluray480p;
                            return result;
                    }
                }

                if (sourceMatch.Groups["wp"].Success)
                {
                    result.Quality = Quality.WORKPRINT;
                    return result;
                }

                if (sourceMatch.Groups["dvd"].Success)
                {
                    result.Quality = Quality.DVD;
                    return result;
                }

                if (sourceMatch.Groups["dvdr"].Success)
                {
                    result.Quality = Quality.DVDR;
                    return result;
                }

                if (sourceMatch.Groups["scr"].Success)
                {
                    result.Quality = Quality.DVDSCR;
                    return result;
                }

                if (sourceMatch.Groups["regional"].Success)
                {
                    result.Quality = Quality.REGIONAL;
                    return result;
                }

                if (sourceMatch.Groups["cam"].Success)
                {
                    result.Quality = Quality.CAM;
                    return result;
                }

                if (sourceMatch.Groups["ts"].Success)
                {
                    result.Quality = Quality.TELESYNC;
                    return result;
                }

                if (sourceMatch.Groups["tc"].Success)
                {
                    result.Quality = Quality.TELECINE;
                    return result;
                }

                if (sourceMatch.Groups["pdtv"].Success ||
                    sourceMatch.Groups["sdtv"].Success ||
                    sourceMatch.Groups["dsr"].Success ||
                    sourceMatch.Groups["tvrip"].Success)
                {
                    if (HighDefPdtvRegex.IsMatch(normalizedName))
                    {
                        result.Quality = Quality.HDTV720p;
                        return result;
                    }

                    result.Quality = Quality.SDTV;
                    return result;
                }
            }

           


            //Anime Bluray matching
            if (AnimeBlurayRegex.Match(normalizedName).Success)
            {
                if (resolution == Resolution.R480P || resolution == Resolution.R576p || normalizedName.Contains("480p"))
                {
                    result.Quality = Quality.DVD;
                    return result;
                }

                if (resolution == Resolution.R1080p || normalizedName.Contains("1080p"))
                {
                    result.Quality = Quality.Bluray1080p;
                    return result;
                }

                result.Quality = Quality.Bluray720p;
                return result;
            }

            if (resolution == Resolution.R2160p)
            {
                result.Quality = Quality.HDTV2160p;
                return result;
            }

            if (resolution == Resolution.R1080p)
            {
                result.Quality = Quality.HDTV1080p;
                return result;
            }

            if (resolution == Resolution.R720p)
            {
                result.Quality = Quality.HDTV720p;
                return result;
            }

            if (resolution == Resolution.R480P)
            {
                result.Quality = Quality.SDTV;
                return result;
            }

            if (codecRegex.Groups["x264"].Success)
            {
                result.Quality = Quality.SDTV;
                return result;
            }

            if (normalizedName.Contains("848x480"))
            {
                if (normalizedName.Contains("dvd"))
                {
                    result.Quality = Quality.DVD;
                }

                result.Quality = Quality.SDTV;
            }

            if (normalizedName.Contains("1280x720"))
            {
                if (normalizedName.Contains("bluray"))
                {
                    result.Quality = Quality.Bluray720p;
                }

                result.Quality = Quality.HDTV720p;
            }

            if (normalizedName.Contains("1920x1080"))
            {
                if (normalizedName.Contains("bluray"))
                {
                    result.Quality = Quality.Bluray1080p;
                }

                result.Quality = Quality.HDTV1080p;
            }

            if (normalizedName.Contains("bluray720p"))
            {
                result.Quality = Quality.Bluray720p;
            }

            if (normalizedName.Contains("bluray1080p"))
            {
                result.Quality = Quality.Bluray1080p;
            }

            var otherSourceMatch = OtherSourceMatch(normalizedName);

            if (otherSourceMatch != Quality.Unknown)
            {
                result.Quality = otherSourceMatch;
            }

            //Based on extension
            if (result.Quality == Quality.Unknown && !name.ContainsInvalidPathChars())
            {
                try
                {
                    result.Quality = MediaFileExtensions.GetQualityForExtension(Path.GetExtension(name));
                    result.QualitySource = QualitySource.Extension;
                }
                catch (ArgumentException)
                {
                    //Swallow exception for cases where string contains illegal
                    //path characters.
                }
            }

            return result;
        }

19 Source : SeriesStatisticsService.cs
with GNU General Public License v3.0
from bonarr

private SeriesStatistics MapSeriesStatistics(List<SeasonStatistics> seasonStatistics)
        {
            var seriesStatistics = new SeriesStatistics
                                   {
                                       SeasonStatistics = seasonStatistics,
                                       SeriesId = seasonStatistics.First().SeriesId,
                                       EpisodeFileCount = seasonStatistics.Sum(s => s.EpisodeFileCount),
                                       EpisodeCount = seasonStatistics.Sum(s => s.EpisodeCount),
                                       TotalEpisodeCount = seasonStatistics.Sum(s => s.TotalEpisodeCount),
                                       SizeOnDisk = seasonStatistics.Sum(s => s.SizeOnDisk)
                                   };

            var nextAiring = seasonStatistics.Where(s => s.NextAiring != null)
                                             .OrderBy(s => s.NextAiring)
                                             .FirstOrDefault();

            var previousAiring = seasonStatistics.Where(s => s.PreviousAiring != null)
                                                 .OrderBy(s => s.PreviousAiring)
                                                 .LastOrDefault();

            seriesStatistics.NextAiringString = nextAiring != null ? nextAiring.NextAiringString : null;
            seriesStatistics.PreviousAiringString = previousAiring != null ? previousAiring.PreviousAiringString : null;

            return seriesStatistics;
        }

19 Source : InspectBuilder.cs
with MIT License
from bonsai-rx

static InspectBuilder GetInspectBuilder(Expression source)
        {
            while (source is MulticastBranchExpression multicastExpression)
            {
                source = multicastExpression.Source;
            }

            while (source is BlockExpression block)
            {
                source = block.Expressions.LastOrDefault();
            }

            while (source is MethodCallExpression methodCall)
            {
                if (methodCall.Object == null)
                {
                    // If merging dangling branches in a workflow, recurse on the main output source
                    if (methodCall.Method.DeclaringType == typeof(ExpressionBuilder) &&
                        methodCall.Method.Name == nameof(ExpressionBuilder.MergeOutput))
                    {
                        source = methodCall.Arguments[0];
                    }
                    // If disposing declared build context subjects, recurse on the output source
                    else if (methodCall.Method.DeclaringType == typeof(BuildContext) &&
                             methodCall.Method.Name == nameof(BuildContext.Finally))
                    {
                        source = methodCall.Arguments[0];
                    }
                    else break;
                }
                else if (methodCall.Object.Type == typeof(InspectBuilder))
                {
                    return (InspectBuilder)((ConstantExpression)methodCall.Object).Value;
                }
                else if (methodCall.Object.Type.BaseType == typeof(MulticastBranchBuilder))
                {
                    // If closing multicast scope, recurse on the scope body
                    source = ((LambdaExpression)methodCall.Arguments[1]).Body;
                }
                else break;
            }

            return null;
        }

19 Source : MainForm.cs
with MIT License
from bp2008

private void ResetGraphTimestamps()
		{
			IList<PingGraphControl> all = pingGraphs.Values;
			foreach (PingGraphControl g in all)
				g.ShowTimestamps = false;

			PingGraphControl last = all.LastOrDefault();
			if (last != null)
				last.ShowTimestamps = true;
		}

19 Source : Animator.cs
with GNU General Public License v3.0
from BRH-Media

private void Elapsed(ulong millSinceBeginning = 0)
        {
            while (true)
            {
                lock (_tempPaths)
                {
                    if (_tempPaths != null && ActivePath == null && _tempPaths.Count > 0)
                        while (ActivePath == null)
                        {
                            if (_tempReverseRepeat)
                            {
                                ActivePath = _tempPaths.LastOrDefault();
                                _tempPaths.RemoveAt(_tempPaths.Count - 1);
                            }
                            else
                            {
                                ActivePath = _tempPaths.FirstOrDefault();
                                _tempPaths.RemoveAt(0);
                            }

                            _timer.ResetClock();
                            millSinceBeginning = 0;
                        }

                    var ended = ActivePath == null;
                    if (ActivePath != null)
                    {
                        if (!_tempReverseRepeat && millSinceBeginning < ActivePath.Delay)
                        {
                            CurrentStatus = AnimatorStatus.OnHold;
                            return;
                        }

                        if (millSinceBeginning - (!_tempReverseRepeat ? ActivePath.Delay : 0) <= ActivePath.Duration)
                        {
                            if (CurrentStatus != AnimatorStatus.Playing)
                                CurrentStatus = AnimatorStatus.Playing;

                            var value = ActivePath.Function(
                                _tempReverseRepeat ? ActivePath.Duration - millSinceBeginning : millSinceBeginning - ActivePath.Delay, ActivePath.Start,
                                ActivePath.Change, ActivePath.Duration);
                            FrameCallback.Invoke(value);
                            return;
                        }

                        if (CurrentStatus == AnimatorStatus.Playing)
                        {
                            if (_tempPaths.Count == 0)
                            {
                                // For the last path, we make sure that control is in end point
                                FrameCallback.Invoke(_tempReverseRepeat ? ActivePath.Start : ActivePath.End);
                                ended = true;
                            }
                            else
                            {
                                if (_tempReverseRepeat && ActivePath.Delay > 0 || !_tempReverseRepeat && _tempPaths.FirstOrDefault()?.Delay > 0)
                                    // Or if the next path or this one in revese order has a delay
                                    FrameCallback.Invoke(_tempReverseRepeat ? ActivePath.Start : ActivePath.End);
                            }
                        }

                        if (_tempReverseRepeat && millSinceBeginning - ActivePath.Duration < ActivePath.Delay)
                        {
                            CurrentStatus = AnimatorStatus.OnHold;
                            return;
                        }

                        ActivePath = null;
                    }

                    if (!ended)
                        return;
                }

                if (Repeat)
                {
                    lock (_tempPaths)
                    {
                        _tempPaths.AddRange(_paths);
                        _tempReverseRepeat = ReverseRepeat && !_tempReverseRepeat;
                    }

                    millSinceBeginning = 0;
                    continue;
                }

                Stop();
                EndCallback?.Invoke();
                break;
            }
        }

19 Source : SearchPageRenderer.cs
with MIT License
from brminnick

Toolbar? GetToolbar()
        {
            if (Xamarin.Essentials.Platform.CurrentActivity.Window?.DecorView.RootView is ViewGroup viewGroup)
            {
                var toolbars = GetToolbars(viewGroup);

                //Return top-most Toolbar
                return toolbars.LastOrDefault();
            }

            return null;
        }

19 Source : CasterHelpers.cs
with MIT License
from cabarius

public static int GetCachedSpellsKnown(UnitDescriptor unit, Spellbook spellbook, int level) {
            var key = $"{unit.CharacterName}.{spellbook.Blueprint.Name}";
            if (!UnitSpellsKnown.TryGetValue(key, out var spellsKnownList)) {
                //Mod.Trace($"Can't find cached spells known data for character {unit.CharacterName} with key: {key}");
                return level > 1 ? GetCachedSpellsKnown(unit, spellbook, level - 1) : 0;
            }

            return spellsKnownList.Count > level ? spellsKnownList[level] : spellsKnownList.LastOrDefault();
        }

19 Source : StrobeLightingPass.cs
with GNU General Public License v2.0
from Caeden117

public override IEnumerable<MapEvent> StrobePreplacedForLane(IEnumerable<MapEvent> original, int type,
        EventsContainer.PropMode propMode, JSONNode propID)
    {
        var generatedObjects = new List<MapEvent>();

        var startTime = original.First().Time;
        var endTime = original.Last().Time;

        var alternatingTypes = new List<int>(values);
        var typeIndex = 0;
        if (alternateColors)
        {
            for (var i = 0; i < values.Count(); i++)
                alternatingTypes.Add(InvertColors(alternatingTypes[i]));
        }

        var distanceInBeats = endTime - startTime;
        var originalDistance = distanceInBeats;
        MapEvent lastPreplaceded = null;

        while (distanceInBeats >= 0)
        {
            if (typeIndex >= alternatingTypes.Count) typeIndex = 0;

            var any = original.Where(x => x.Time <= endTime - distanceInBeats).LastOrDefault();
            if (any != lastPreplaceded && dynamic && MapEvent.IsBlueEventFromValue(any.Value) !=
                MapEvent.IsBlueEventFromValue(alternatingTypes[typeIndex]))
            {
                lastPreplaceded = any;
                for (var i = 0; i < alternatingTypes.Count; i++)
                    alternatingTypes[i] = InvertColors(alternatingTypes[i]);
            }

            var value = alternatingTypes[typeIndex];
            var progress = (originalDistance - distanceInBeats) / originalDistance;
            var newTime = (easingFunc(progress) * originalDistance) + startTime;
            var data = new MapEvent(newTime, type, value);
            if (propMode != EventsContainer.PropMode.Off)
            {
                if (value != MapEvent.LightValueBlueON && value != MapEvent.LightValueRedON &&
                    value != MapEvent.LightValueOff)
                {
                    data.Value = value < 5
                        ? MapEvent.LightValueBlueON
                        : MapEvent.LightValueRedON;
                }

                data.CustomData = new JSONObject();
                data.CustomData.Add("_lightID", propID);
            }

            generatedObjects.Add(data);
            typeIndex++;

            if (distanceInBeats > 0 && (distanceInBeats -= 1 / precision) < -0.001f)
                distanceInBeats = 0;
            else if (distanceInBeats <= 0) break;
        }

        return generatedObjects;
    }

19 Source : StrobeStepGradientPass.cs
with GNU General Public License v2.0
from Caeden117

public override IEnumerable<MapEvent> StrobePreplacedForLane(IEnumerable<MapEvent> original, int type,
        EventsContainer.PropMode propMode, JSONNode propID)
    {
        var generatedObjects = new List<MapEvent>();

        var startTime = original.First().Time;
        var endTime = original.Last().Time;

        // Aggregate all colors points into a dictionary
        var colorPoints = new Dictionary<float, Color>();

        foreach (var e in original)
        {
            // Might as well be fancy and add support for Chroma 2.0 gradients
            if (e.LightGradient != null)
            {
                colorPoints.Add(e.Time, e.LightGradient.StartColor);
                colorPoints.Add(e.Time + e.LightGradient.Duration, e.LightGradient.EndColor);
            }
            else if (e.IsChromaEvent) // This already checks customData, so if this is true then customData exists.
            {
                colorPoints.Add(e.Time, e.CustomData["_color"]);
            }
        }

        var distanceInBeats = endTime - startTime;
        var originalDistance = distanceInBeats;

        if (colorPoints.Count < 2) return Enumerable.Empty<MapEvent>();

        var lastPoint = colorPoints.ElementAt(0);
        var nextPoint = colorPoints.ElementAt(1);

        while (distanceInBeats >= -0.01f)
        {
            var anyLast = colorPoints.Where(x => x.Key <= endTime - distanceInBeats).LastOrDefault();
            if (anyLast.Key != lastPoint.Key)
            {
                var nextPoints = colorPoints.Where(x => x.Key > endTime - distanceInBeats);

                // Don't progress if this is the last gradient
                if (nextPoints.Any())
                {
                    lastPoint = anyLast;
                    nextPoint = nextPoints.First();
                }
            }

            var progress = (originalDistance - distanceInBeats) / originalDistance;
            var newTime = (progress * originalDistance) + startTime;

            var lerp = easing(Mathf.InverseLerp(lastPoint.Key, nextPoint.Key, newTime));
            var color = Color.Lerp(lastPoint.Value, nextPoint.Value, lerp);

            var data = new MapEvent(newTime, type, value, new JSONObject());
            data.CustomData.Add("_color", color);
            if (propMode != EventsContainer.PropMode.Off)
            {
                if (value != MapEvent.LightValueBlueON && value != MapEvent.LightValueRedON &&
                    value != MapEvent.LightValueOff)
                {
                    data.Value = value < 5
                        ? MapEvent.LightValueBlueON
                        : MapEvent.LightValueRedON;
                }

                data.CustomData.Add("_lightID", propID);
            }

            generatedObjects.Add(data);

            distanceInBeats -= 1 / precision;

            if (alternateColors) value = InvertColors(value);
        }

        return generatedObjects;
    }

19 Source : StrobeLaserSpeedInterpolationPass.cs
with GNU General Public License v2.0
from Caeden117

public override IEnumerable<MapEvent> StrobePreplacedForLane(IEnumerable<MapEvent> original, int type,
        EventsContainer.PropMode propMode, JSONNode propID)
    {
        var generatedObjects = new List<MapEvent>();

        var startTime = original.First().Time;
        var endTime = original.Last().Time;

        var distanceInBeats = endTime - startTime;
        var originalDistance = distanceInBeats;
        var lastPreplaceded = original.First();
        var nextEvent = original.ElementAt(1);

        var lastSpeed = GetLaserSpeedFromEvent(lastPreplaceded);
        var nextSpeed = GetLaserSpeedFromEvent(nextEvent);

        while (distanceInBeats >= 0)
        {
            var any = original.Where(x => x.Time <= endTime - distanceInBeats).LastOrDefault();
            if (lastPreplaceded != any)
            {
                lastPreplaceded = any;
                nextEvent = original.Where(x => x.Time > lastPreplaceded.Time).FirstOrDefault();
                lastSpeed = GetLaserSpeedFromEvent(lastPreplaceded);
                if (nextEvent == null) nextEvent = lastPreplaceded;
                nextSpeed = GetLaserSpeedFromEvent(nextEvent);
            }

            var newTime = originalDistance - distanceInBeats + startTime;
            var progress = Mathf.InverseLerp(lastPreplaceded.Time, nextEvent.Time, newTime);

            var decimalPreciseSpeed =
                Math.Round(Mathf.Lerp(lastSpeed, nextSpeed, easingFunc(progress)), decimalPrecision);
            // This does not support negative numbers, however I do not believe there is a reason to support them in the first place
            var roundedPreciseSpeed = (int)Math.Max(1, Math.Round(decimalPreciseSpeed, MidpointRounding.AwayFromZero));

            var data = new MapEvent(newTime, type, 1) { CustomData = new JSONObject(), Value = roundedPreciseSpeed };

            // Bit cheeky but hopefully a bit more readable
            if (Math.Abs(decimalPreciseSpeed - roundedPreciseSpeed) > 0.01f)
                data.CustomData["_preciseSpeed"] = decimalPreciseSpeed;

            if (overrideDirection)
            {
                switch (type)
                {
                    case MapEvent.EventTypeLeftLasersSpeed:
                        data.CustomData["_direction"] = Convert.ToInt32(leftRotatesClockwise);
                        break;
                    case MapEvent.EventTypeRightLasersSpeed:
                        data.CustomData["_direction"] = Convert.ToInt32(rightRotatesClockwise);
                        break;
                }
            }

            if (lockLaserRotation) data.CustomData["_lockPosition"] = true;

            generatedObjects.Add(data);
            distanceInBeats -= 1 / interval;
        }

        return generatedObjects;
    }

19 Source : IEnumerableCursorPagingCustomExtensions.cs
with MIT License
from cajuncoding

public static ICursorPageSlice<T> SliceAsCursorPage<T>(this IEnumerable<T> items, string? after, int? first, string? before, int? last)
        where T : clreplaced
        {
            //Do nothing if there are no results...
            if (!items.Any())
                return new CursorPageSlice<T>(Enumerable.Empty<ICursorResult<T>>(), 0, false, false);

            var afterIndex = after != null
                ? IndexEdge<string>.DeserializeCursor(after)
                : 0;

            var beforeIndex = before != null
                ? IndexEdge<string>.DeserializeCursor(before)
                : 0;

            //FIRST log the index of all items in the list BEFORE slicing, as these indexes are 
            //  the Cursor Indexes for paging up/down the entire list, & ICursorResult is the Decorator 
            //  around the Enreplacedy Models.

            //NOTE: We MUST materialize this after applying index values to prevent ongoing increments...
            int index = 0;
            IEnumerable<ICursorResult<T>> slice = items
                .Select(c => new CursorResult<T>(c, ++index))
                .ToList();

            int totalCount = slice.Count();

            //If After specified, remove all before After (or skip past After)
            if (afterIndex > 0 && slice.Last().CursorIndex > afterIndex)
            {
                slice = slice.Skip(afterIndex);
            }

            //If Before is specified, remove all after Before (Skip Until Before is reached)
            if (beforeIndex > 0 && slice.Last().CursorIndex > beforeIndex)
            {
                slice = slice.SkipWhile(c => c.CursorIndex < beforeIndex);
            }

            //If First is specified, then take the first/top rows from the current Slice!
            if (first.HasValue && first > 0 && slice.Count() > first)
            {
                slice = slice.Take(first.Value);
            }

            //If First is specified, then take the first/top rows from the current Slice!
            if (last.HasValue && last > 0 && slice.Count() > last)
            {
                slice = slice.TakeLast(last.Value);
            }

            //Wrap all results into a PagedCursor Slice result wit Total Count...
            //NOTE: to ensure our pagination is complete, we materialize the Results!
            var results = slice.ToList();
            var firstCursor = results.FirstOrDefault();
            var lastCursor = results.LastOrDefault();

            var cursorPageSlice = new CursorPageSlice<T>(
                results, 
                totalCount, 
                hasPreviousPage: firstCursor?.CursorIndex > 1,
                hasNextPage: lastCursor?.CursorIndex < totalCount
            );
            return cursorPageSlice;
        }

19 Source : PreProcessedCursorPagingHandler.cs
with MIT License
from cajuncoding

protected override ValueTask<Connection> SliceAsync(IResolverContext context, object source, CursorPagingArguments arguments)
        {
            //If Appropriate we handle the values here to ensure that no post-processing is done other than
            //  correctly mapping the results into a GraphQL Connection as Edges with Cursors...
            if (source is IPreProcessedCursorSlice<TEnreplacedy> pagedResults)
            {
                bool includeTotalCountEnabled = this.PagingOptions.IncludeTotalCount ?? PagingDefaults.IncludeTotalCount;
                var graphQLParamsContext = new GraphQLParamsContext(context);

                //Optimized to only require TotalCount value if the query actually requested it!
                if (includeTotalCountEnabled && graphQLParamsContext.IsTotalCountRequested && pagedResults.TotalCount == null)
                    throw new InvalidOperationException($"Total Count is requested in the query, but was not provided with the results [{this.GetType().GetTypeName()}] from the resolvers pre-processing logic; TotalCount is null.");

                int? totalCount = pagedResults.TotalCount;

                //Ensure we are null safe and return a valid empty list by default.
                IReadOnlyList<IndexEdge<TEnreplacedy>> selectedEdges = 
                    pagedResults?.ToEdgeResults().ToList() ?? new List<IndexEdge<TEnreplacedy>>(); ;

                IndexEdge<TEnreplacedy>? firstEdge = selectedEdges.FirstOrDefault();
                IndexEdge<TEnreplacedy>? lastEdge = selectedEdges.LastOrDefault();

                var connectionPageInfo = new ConnectionPageInfo(
                    hasNextPage: pagedResults?.HasNextPage ?? false,
                    hasPreviousPage: pagedResults?.HasPreviousPage ?? false,
                    startCursor: firstEdge?.Cursor,
                    endCursor: lastEdge?.Cursor,
                    totalCount: totalCount ?? 0
                );

                var graphQLConnection = new Connection<TEnreplacedy>(
                    selectedEdges,
                    connectionPageInfo,
                    ct => new ValueTask<int>(connectionPageInfo.TotalCount ?? 0)
                );

                return new ValueTask<Connection>(graphQLConnection);
            }

            throw new GraphQLException($"[{nameof(PreProcessedCursorPagingHandler<TEnreplacedy>)}] cannot handle the specified data source of type [{source.GetType().Name}].");
        }

19 Source : Statistics.cs
with Apache License 2.0
from Capnode

public static Dictionary<string, string> Generate(IEnumerable<ChartPoint> pointsEquity,
            SortedDictionary<DateTime, decimal> profitLoss,
            IEnumerable<ChartPoint> pointsPerformance,
            Dictionary<DateTime, decimal> unsortedBenchmark,
            decimal startingCash,
            decimal totalFees,
            decimal totalTrades,
            double tradingDaysPerYear = 252
            )
        {
            //Initialise the response:
            double riskFreeRate = 0;
            decimal totalClosedTrades = 0;
            decimal totalWins = 0;
            decimal totalLosses = 0;
            decimal averageWin = 0;
            decimal averageLoss = 0;
            decimal averageWinRatio = 0;
            decimal winRate = 0;
            decimal lossRate = 0;
            decimal totalNetProfit = 0;
            double fractionOfYears = 1;
            decimal profitLossValue = 0, runningCash = startingCash;
            decimal algoCompoundingPerformance = 0;
            decimal finalBenchmarkCash = 0;
            decimal benchCompoundingPerformance = 0;
            var years = new List<int>();
            var annualTrades = new SortedDictionary<int, int>();
            var annualWins = new SortedDictionary<int, int>();
            var annualLosses = new SortedDictionary<int, int>();
            var annualLossTotal = new SortedDictionary<int, decimal>();
            var annualWinTotal = new SortedDictionary<int, decimal>();
            var annualNetProfit = new SortedDictionary<int, decimal>();
            var statistics = new Dictionary<string, string>();
            var dtPrevious = new DateTime();
            var listPerformance = new List<double>();
            var listBenchmark = new List<double>();
            var equity = new SortedDictionary<DateTime, decimal>();
            var performance = new SortedDictionary<DateTime, decimal>();
            SortedDictionary<DateTime, decimal>  benchmark = null;
            try
            {
                //Get array versions of the performance:
                performance = ChartPointToDictionary(pointsPerformance);
                equity = ChartPointToDictionary(pointsEquity);
                performance.Values.ToList().ForEach(i => listPerformance.Add((double)(i / 100)));
                benchmark = new SortedDictionary<DateTime, decimal>(unsortedBenchmark);

                // to find the delta in benchmark for first day, we need to know the price at the opening
                // moment of the day, but since we cannot find this, we cannot find the first benchmark's delta,
                // so we pad it with Zero. If running a short backtest this will skew results, longer backtests
                // will not be affected much
                listBenchmark.Add(0);

                //Get benchmark performance array for same period:
                benchmark.Keys.ToList().ForEach(dt =>
                {
                    if (dt >= equity.Keys.FirstOrDefault().AddDays(-1) && dt < equity.Keys.LastOrDefault())
                    {
                        decimal previous;
                        if (benchmark.TryGetValue(dtPrevious, out previous) && previous != 0)
                        {
                            var deltaBenchmark = (benchmark[dt] - previous)/previous;
                            listBenchmark.Add((double)(deltaBenchmark));
                        }
                        else
                        {
                            listBenchmark.Add(0);
                        }
                        dtPrevious = dt;
                    }
                });

                // TODO : if these lists are required to be the same length then we should create structure to pair the values, this way, by contract it will be enforced.

                //THIS SHOULD NEVER HAPPEN --> But if it does, log it and fail silently.
                while (listPerformance.Count < listBenchmark.Count)
                {
                    listPerformance.Add(0);
                    Log.Error("Statistics.Generate(): Padded Performance");
                }
                while (listPerformance.Count > listBenchmark.Count)
                {
                    listBenchmark.Add(0);
                    Log.Error("Statistics.Generate(): Padded Benchmark");
                }
            }
            catch (Exception err)
            {
                Log.Error(err, "Dic-Array Convert:");
            }

            try
            {
                //Number of years in this dataset:
                fractionOfYears = (equity.Keys.LastOrDefault() - equity.Keys.FirstOrDefault()).TotalDays / 365;
            }
            catch (Exception err)
            {
                Log.Error(err, "Fraction of Years:");
            }

            try
            {
                if (benchmark != null)
                {
                    algoCompoundingPerformance = CompoundingAnnualPerformance(startingCash, equity.Values.LastOrDefault(), (decimal) fractionOfYears);
                    finalBenchmarkCash = ((benchmark.Values.Last() - benchmark.Values.First())/benchmark.Values.First())*startingCash;
                    benchCompoundingPerformance = CompoundingAnnualPerformance(startingCash, finalBenchmarkCash, (decimal) fractionOfYears);
                }
            }
            catch (Exception err)
            {
                Log.Error(err, "Compounding:");
            }

            try
            {
                //Run over each equity day:
                foreach (var closedTrade in profitLoss.Keys)
                {
                    profitLossValue = profitLoss[closedTrade];

                    //Check if this date is in the "years" array:
                    var year = closedTrade.Year;
                    if (!years.Contains(year))
                    {
                        //Initialise a new year holder:
                        years.Add(year);
                        annualTrades.Add(year, 0);
                        annualWins.Add(year, 0);
                        annualWinTotal.Add(year, 0);
                        annualLosses.Add(year, 0);
                        annualLossTotal.Add(year, 0);
                    }

                    //Add another trade:
                    annualTrades[year]++;

                    //Profit loss tracking:
                    if (profitLossValue > 0)
                    {
                        annualWins[year]++;
                        annualWinTotal[year] += profitLossValue / runningCash;
                    }
                    else
                    {
                        annualLosses[year]++;
                        annualLossTotal[year] += profitLossValue / runningCash;
                    }

                    //Increment the cash:
                    runningCash += profitLossValue;
                }

                //Get the annual percentage of profit and loss:
                foreach (var year in years)
                {
                    annualNetProfit[year] = (annualWinTotal[year] + annualLossTotal[year]);
                }

                //Sum the totals:
                try
                {
                    if (profitLoss.Keys.Count > 0)
                    {
                        totalClosedTrades = annualTrades.Values.Sum();
                        totalWins = annualWins.Values.Sum();
                        totalLosses = annualLosses.Values.Sum();
                        totalNetProfit = (equity.Values.LastOrDefault() / startingCash) - 1;

                        //-> Handle Div/0 Errors
                        if (totalWins == 0)
                        {
                            averageWin = 0;
                        }
                        else
                        {
                            averageWin = annualWinTotal.Values.Sum() / totalWins;
                        }
                        if (totalLosses == 0)
                        {
                            averageLoss = 0;
                            averageWinRatio = 0;
                        }
                        else
                        {
                            averageLoss = annualLossTotal.Values.Sum() / totalLosses;
                            averageWinRatio = Math.Abs(averageWin / averageLoss);
                        }
                        if (totalTrades == 0)
                        {
                            winRate = 0;
                            lossRate = 0;
                        }
                        else
                        {
                            winRate = Math.Round(totalWins / totalClosedTrades, 5);
                            lossRate = Math.Round(totalLosses / totalClosedTrades, 5);
                        }
                    }

                }
                catch (Exception err)
                {
                    Log.Error(err, "Second Half:");
                }

                var profitLossRatio = ProfitLossRatio(averageWin, averageLoss);
                var profitLossRatioHuman = profitLossRatio.ToString(CultureInfo.InvariantCulture);
                if (profitLossRatio == -1) profitLossRatioHuman = "0";

                //Add the over all results first, break down by year later:
                statistics = new Dictionary<string, string> {
                    { "Total Trades", Math.Round(totalTrades, 0).ToStringInvariant() },
                    { "Average Win", Math.Round(averageWin * 100, 2).ToStringInvariant() + "%"  },
                    { "Average Loss", Math.Round(averageLoss * 100, 2).ToStringInvariant() + "%" },
                    { "Compounding Annual Return", Math.Round(algoCompoundingPerformance * 100, 3).ToStringInvariant() + "%" },
                    { "Drawdown", (DrawdownPercent(equity, 3) * 100).ToStringInvariant() + "%" },
                    { "Expectancy", Math.Round((winRate * averageWinRatio) - (lossRate), 3).ToStringInvariant() },
                    { "Net Profit", Math.Round(totalNetProfit * 100, 3).ToStringInvariant() + "%"},
                    { "Sharpe Ratio", Math.Round(SharpeRatio(listPerformance, riskFreeRate), 3).ToStringInvariant() },
                    { "Loss Rate", Math.Round(lossRate * 100).ToStringInvariant() + "%" },
                    { "Win Rate", Math.Round(winRate * 100).ToStringInvariant() + "%" },
                    { "Profit-Loss Ratio", profitLossRatioHuman },
                    { "Alpha", Math.Round(Alpha(listPerformance, listBenchmark, riskFreeRate), 3).ToStringInvariant() },
                    { "Beta", Math.Round(Beta(listPerformance, listBenchmark), 3).ToStringInvariant() },
                    { "Annual Standard Deviation", Math.Round(AnnualStandardDeviation(listPerformance, tradingDaysPerYear), 3).ToStringInvariant() },
                    { "Annual Variance", Math.Round(AnnualVariance(listPerformance, tradingDaysPerYear), 3).ToStringInvariant() },
                    { "Information Ratio", Math.Round(InformationRatio(listPerformance, listBenchmark), 3).ToStringInvariant() },
                    { "Tracking Error", Math.Round(TrackingError(listPerformance, listBenchmark), 3).ToStringInvariant() },
                    { "Treynor Ratio", Math.Round(TreynorRatio(listPerformance, listBenchmark, riskFreeRate), 3).ToStringInvariant() },
                    { "Total Fees", "$" + totalFees.ToStringInvariant("0.00") }
                };
            }
            catch (Exception err)
            {
                Log.Error(err);
            }
            return statistics;
        }

19 Source : StatisticsBuilder.cs
with Apache License 2.0
from Capnode

public static StatisticsResults Generate(
            List<Trade> trades,
            SortedDictionary<DateTime, decimal> profitLoss,
            List<ChartPoint> pointsEquity,
            List<ChartPoint> pointsPerformance,
            List<ChartPoint> pointsBenchmark,
            decimal startingCapital,
            decimal totalFees,
            int totalTransactions,
            CapacityEstimate estimatedStrategyCapacity)
        {
            var equity = ChartPointToDictionary(pointsEquity);

            var firstDate = equity.Keys.FirstOrDefault().Date;
            var lastDate = equity.Keys.LastOrDefault().Date;

            var totalPerformance = GetAlgorithmPerformance(firstDate, lastDate, trades, profitLoss, equity, pointsPerformance, pointsBenchmark, startingCapital);
            var rollingPerformances = GetRollingPerformances(firstDate, lastDate, trades, profitLoss, equity, pointsPerformance, pointsBenchmark, startingCapital);
            var summary = GetSummary(totalPerformance, estimatedStrategyCapacity, totalFees, totalTransactions);

            return new StatisticsResults(totalPerformance, rollingPerformances, summary);
        }

19 Source : DefaultOrderBook.cs
with Apache License 2.0
from Capnode

public void RemoveBidRow(decimal price)
        {
            lock (_locker)
            {
                Bids.Remove(price);

                if (price == _bestBidPrice)
                {
                    var priceLevel = Bids.LastOrDefault();
                    _bestBidPrice = priceLevel.Key;
                    _bestBidSize = priceLevel.Value;

                    BestBidAskUpdated?.Invoke(this, new BestBidAskUpdatedEventArgs(_symbol, _bestBidPrice, _bestBidSize, _bestAskPrice, _bestAskSize));
                }
            }
        }

19 Source : FuturesChain.cs
with Apache License 2.0
from Capnode

public T GetAux<T>(Symbol symbol)
        {
            List<BaseData> list;
            Dictionary<Symbol, List<BaseData>> dictionary;
            if (!_auxiliaryData.TryGetValue(typeof(T), out dictionary) || !dictionary.TryGetValue(symbol, out list))
            {
                return default(T);
            }
            return list.OfType<T>().LastOrDefault();
        }

See More Examples