System.Action.Invoke(double)

Here are the examples of the csharp api System.Action.Invoke(double) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

101 Examples 7

19 Source : EnterNumberWindow.xaml.cs
with MIT License
from 3RD-Dimension

private void buttonOk_Click(object sender, RoutedEventArgs e)
		{
			Ok = true;

			if (User_Ok != null)
				User_Ok.Invoke(Value);

			Close();
		}

19 Source : SciChartTestRunner.cs
with MIT License
from ABTSoftware

private void RunNext(TimeSpan duration, Action testCallback, Action<double> completedCallback)
        {
            if (_stopWatch.ElapsedMilliseconds > duration.TotalMilliseconds)
            {
                _stopWatch.Stop();

                double fps = _frameCount/_stopWatch.Elapsed.TotalSeconds;
                completedCallback(fps);
                return;
            }

            _frameCount++;
            testCallback();
        }

19 Source : TimerRunner.cs
with MIT License
from ABTSoftware

public virtual void Run()
        {
            timer = new Timer();
            timer.Interval = 10; // 100Hz
            //timer.Interval = 1; // 100Hz

            ElapsedEventHandler tickHandler = null;
            tickHandler = (s, e) =>
                {
                    _testCallback();

                    lock (this)
                    {
                        if (_stopped) return;
                        if (_stopWatch.ElapsedMilliseconds > _duration.TotalMilliseconds)
                        {
                            _stopWatch.Stop();
                            _stopped = true;
                            timer.Elapsed -= tickHandler;
                            timer.Stop();
                            double fps = _frameCount/_stopWatch.Elapsed.TotalSeconds;
                            Application.Current.Dispatcher.BeginInvoke(new Action(() => _completedCallback(fps)));
                        }
                    }
                };

            timer.Elapsed += tickHandler;
            _stopWatch = Stopwatch.StartNew();
            timer.Start();
        }

19 Source : KoiSystem.cs
with GNU General Public License v3.0
from Aekras1a

public void Login(string koiId)
        {
            try
            {
#if DEBUG || __TRACE
                const string PACK_URI = @"http://ki.no-ip.info/koi/{0}/koi.pack";
#else
				const string PACK_URI = @"https://ki-host.appspot.com/KoiVM/koi/{0}/koi.pack";
#endif
                var pack = new Uri(string.Format(PACK_URI, koiId));
                var client = new WebClient();
                var file = Path.Combine(KoiInfo.KoiDirectory, "koi.pack");

                client.DownloadProgressChanged += (sender, e) =>
                {
                    var progressValue = (double) e.BytesReceived / e.TotalBytesToReceive;
                    if(e.TotalBytesToReceive == -1)
                        progressValue = 0;
                    Progress(progressValue);
                };

                client.DownloadFileCompleted += (sender, e) =>
                {
                    if(e.Error != null)
                        if(File.Exists(file))
                            File.Delete(file);
                    Finish(e.Error == null);
                };

                if(File.Exists(file))
                    File.Delete(file);
                client.DownloadFileAsync(pack, file);
            }
            catch
            {
                Finish(false);
            }
        }

19 Source : IOs8AnalogInputCard.cs
with GNU General Public License v3.0
from alvaroyurrita

void SubscribeInreplacedogInChanged()
        {
            IOPorts[0].replacedogInput_Changed += (port, value) => { if (ai1_Changed != null) ai1_Changed(value??0); };
            IOPorts[1].replacedogInput_Changed += (port, value) => { if (ai2_Changed != null) ai2_Changed(value ?? 0); };
            IOPorts[2].replacedogInput_Changed += (port, value) => { if (ai3_Changed != null) ai3_Changed(value ?? 0); };
            IOPorts[3].replacedogInput_Changed += (port, value) => { if (ai4_Changed != null) ai4_Changed(value ?? 0); };
            IOPorts[4].replacedogInput_Changed += (port, value) => { if (ai5_Changed != null) ai5_Changed(value ?? 0); };
            IOPorts[5].replacedogInput_Changed += (port, value) => { if (ai6_Changed != null) ai6_Changed(value ?? 0); };
            IOPorts[6].replacedogInput_Changed += (port, value) => { if (ai7_Changed != null) ai7_Changed(value ?? 0); };
            IOPorts[7].replacedogInput_Changed += (port, value) => { if (ai8_Changed != null) ai8_Changed(value ?? 0); };
        }

19 Source : AnimationWrapper.cs
with MIT License
from AndreiMisiukevich

private void CommitWithoutAnimation(AnimationWrapper animation)
        {
            foreach (AnimationWrapper childAnimation in animation)
            {
                CommitWithoutAnimation(childAnimation);
            }
            animation.Callback?.Invoke(animation.End);
        }

19 Source : MainViewModel.cs
with MIT License
from AntonyCorbett

private async Task GenerateSlideItems(Action<double>? onProgressPercentageChanged = null)
        {
            using (new ObservableCollectionSuppression<SlideItem>(SlideItems))
            {
                var thumbnailCache = GetThumbnailCache();
                SlideItems.Clear();

                if (_currentSlideFileBuilder != null)
                {
                    const int batchSize = 10;
                    var batchHelper =
                        new SlideBuilderBatchHelper(_currentSlideFileBuilder.GetSlides().ToList(), batchSize);

                    var batchCount = batchHelper.GetBatchCount();
                    var batchesComplete = 0;

                    var batch = batchHelper.GetBatch();
                    while (batch != null)
                    {
                        var thumbnails = await GenerateThumbnailsForBatch(batch, thumbnailCache);
                        var slideIndex = 1;

                        foreach (var slide in batch)
                        {
                            if (thumbnails.TryGetValue(slide, out var thumbnailBytes))
                            {
                                var slideItem = GenerateSlideItem(slide, thumbnailBytes, slideIndex++);
                                SlideItems.Add(slideItem);
                            }
                        }

                        ++batchesComplete;

                        onProgressPercentageChanged?.Invoke((batchesComplete * 100F) / batchCount);
                        batch = batchHelper.GetBatch();
                    }
                }

                AddEndMarker();
            }

            OnPropertyChanged(nameof(Hreplacedlides));
            OnPropertyChanged(nameof(HasNoSlides));
        }

19 Source : MainViewModel.cs
with MIT License
from AntonyCorbett

private void SetOpacityProperty(
            string propertyName,
            double currentValue, 
            double newValue, 
            Action<double> setter)
        {
            if (Math.Abs(currentValue - newValue) > OpacityTolerance && 
                IsValidOpacity(newValue))
            {
                setter(newValue);

                _singleExecAction.Execute(() =>
                {
                    DispatcherHelper.CheckBeginInvokeOnUI(() =>
                    {
                        RaisePropertyChanged(propertyName);
                        UpdateImage();
                    });
                });
            }
        }

19 Source : SignalBuilder.cs
with MIT License
from ar1st0crat

public virtual SignalBuilder SetParameter(string parameterName, double parameterValue)
        {
            foreach (var parameterKey in ParameterSetters.Keys)
            {
                var keywords = parameterKey.Split(',').Select(s => s.Trim());

                if (keywords.Any(keyword => string.Compare(keyword, parameterName, StringComparison.OrdinalIgnoreCase) == 0))
                {
                    var setter = ParameterSetters[parameterKey];
                    setter.Invoke(parameterValue);
                    return this;
                }
            }

            return this;
        }

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

public static TreeCollection Load(Avalonia.Controls.Window parentWindow, FileInfo fileInfo, string filetypeModuleId, IEnumerable<TreeNode> treeLoader, List<(string, Dictionary<string, object>)> moduleSuggestions, ref Action<double> openerProgressAction, Action<double> progressAction)
        {
            long largeFileThreshold = 26214400;

            if (TreeViewer.GlobalSettings.Settings.AdditionalSettings.TryGetValue("Large file threshold:", out object largeFileThresholdValue))
            {
                if (largeFileThresholdValue is long threshValue)
                {
                    largeFileThreshold = threshValue;
                }
                else if (largeFileThresholdValue is JsonElement element)
                {
                    largeFileThreshold = element.GetInt64();
                }
            }

            if (fileInfo.Length > largeFileThreshold)
            {
                bool result = false;
                int skip = 0;
                int every = 1;
                int until = -1;

                if (InstanceStateData.IsUIAvailable)
                {
                    EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset);

                    Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(async () =>
                    {
                        ChildWindow settingsWindow = new ChildWindow() { Width = 450, SizeToContent = SizeToContent.Height, FontFamily = Avalonia.Media.FontFamily.Parse("resm:TreeViewer.Fonts.?replacedembly=TreeViewer#Open Sans"), FontSize = 14, replacedle = "Skip trees...", WindowStartupLocation = WindowStartupLocation.CenterOwner };

                        Grid mainGrid = new Grid() { Margin = new Avalonia.Thickness(10) };
                        mainGrid.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
                        mainGrid.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));

                        settingsWindow.Content = mainGrid;

                        StackPanel panel = new StackPanel();
                        mainGrid.Children.Add(panel);


                        Grid alertPanel = new Grid() { Margin = new Avalonia.Thickness(0, 0, 0, 10) };
                        alertPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                        alertPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                        alertPanel.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                        alertPanel.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));

                        Viewbox alert = MainWindow.GetAlertIcon();
                        alert.Width = 32;
                        alert.Height = 32;

                        alertPanel.Children.Add(alert);

                        TextBlock alertreplacedle = new TextBlock() { Text = "Large tree file", FontSize = 16, Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(0, 114, 178)), Margin = new Avalonia.Thickness(10, 0, 0, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                        Grid.SetColumn(alertreplacedle, 1);
                        alertPanel.Children.Add(alertreplacedle);

                        TextBlock alertBlock = new TextBlock() { Text = "The file you are trying to open is very large (" + (fileInfo.Length / 1024 / 1024).ToString() + "MB). The trees are going to be loaded in compressed format, so there should not be any memory issues; however, to speed things up, you may want to skip some of the trees.", TextWrapping = Avalonia.Media.TextWrapping.Wrap, Margin = new Avalonia.Thickness(0, 5, 0, 0), FontSize = 13 };

                        Grid.SetRow(alertBlock, 1);
                        Grid.SetColumnSpan(alertBlock, 2);
                        alertPanel.Children.Add(alertBlock);
                        panel.Children.Add(alertPanel);

                        Grid skipPanel = new Grid() { Margin = new Avalonia.Thickness(0, 0, 0, 10) };
                        skipPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                        skipPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                        skipPanel.Children.Add(new TextBlock() { FontWeight = Avalonia.Media.FontWeight.Bold, Text = "Trees to skip:", Margin = new Avalonia.Thickness(0, 0, 5, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center });
                        NumericUpDown skipNud = new NumericUpDown() { Minimum = 0, FormatString = "0", Value = 0, Padding = new Avalonia.Thickness(5, 0, 5, 0) };
                        Grid.SetColumn(skipNud, 1);
                        skipPanel.Children.Add(skipNud);
                        panel.Children.Add(skipPanel);

                        Grid everyPanel = new Grid() { Margin = new Avalonia.Thickness(0, 0, 0, 10) };
                        everyPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                        everyPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                        everyPanel.Children.Add(new TextBlock() { FontWeight = Avalonia.Media.FontWeight.Bold, Text = "Sample a tree every:", Margin = new Avalonia.Thickness(0, 0, 5, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center });
                        NumericUpDown everyNud = new NumericUpDown() { Minimum = 1, FormatString = "0", Value = 1, Padding = new Avalonia.Thickness(5, 0, 5, 0) };
                        Grid.SetColumn(everyNud, 1);
                        everyPanel.Children.Add(everyNud);
                        panel.Children.Add(everyPanel);

                        Grid untilPanel = new Grid() { Margin = new Avalonia.Thickness(0, 0, 0, 10) };
                        untilPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                        untilPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                        CheckBox untilBox = new CheckBox() { FontWeight = Avalonia.Media.FontWeight.Bold, Content = "Up to tree:", Margin = new Avalonia.Thickness(0, 0, 5, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                        untilPanel.Children.Add(untilBox);
                        NumericUpDown untilNud = new NumericUpDown() { Minimum = 1, FormatString = "0", Value = 1, Padding = new Avalonia.Thickness(5, 0, 5, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                        Grid.SetColumn(untilNud, 1);
                        untilPanel.Children.Add(untilNud);
                        panel.Children.Add(untilPanel);

                        Grid buttonPanel = new Grid();
                        buttonPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                        buttonPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                        buttonPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                        buttonPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                        buttonPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                        Button okButton = new Button() { Width = 100, Content = "OK", HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, FontSize = 13 };
                        okButton.Clreplacedes.Add("PlainButton");
                        Grid.SetColumn(okButton, 1);
                        buttonPanel.Children.Add(okButton);
                        Button cancelButton = new Button() { Width = 100, Content = "Cancel", HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, FontSize = 13 };
                        cancelButton.Clreplacedes.Add("PlainButton");
                        Grid.SetColumn(cancelButton, 3);
                        buttonPanel.Children.Add(cancelButton);
                        Grid.SetRow(buttonPanel, 1);
                        mainGrid.Children.Add(buttonPanel);


                        okButton.Click += (s, e) =>
                        {
                            result = true;
                            settingsWindow.Close();
                        };

                        cancelButton.Click += (s, e) =>
                        {
                            result = false;
                            settingsWindow.Close();
                        };

                        await settingsWindow.ShowDialog2(parentWindow);

                        skip = (int)Math.Round(skipNud.Value);
                        every = (int)Math.Round(everyNud.Value);
                        if (untilBox.IsChecked == true)
                        {
                            until = (int)Math.Round(untilNud.Value);
                        }

                        handle.Set();
                    });

                    handle.WaitOne();
                }
                else
                {
                    result = true;
                }

                if (!result)
                {
                    return null;
                }
                else
                {
                    MemoryStream ms = new MemoryStream();

                    if (until == -1)
                    {
                        if (!(treeLoader is TreeCollection))
                        {
                            openerProgressAction = (val) => { progressAction(val); };

                            BinaryTree.WriteAllTrees(treeLoader.Skip(skip).Where((item, index) => index % every == 0), ms, true);
                        }
                        else if (skip == 0 && every == 1)
                        {
                            openerProgressAction = (_) => { };

                            ((TreeCollection)treeLoader).UnderlyingStream.Seek(0, SeekOrigin.Begin);
                            ((TreeCollection)treeLoader).UnderlyingStream.CopyToWithProgress(ms, progressAction);
                        }
                        else
                        {
                            openerProgressAction = (_) => { };

                            double totalTrees = (((TreeCollection)treeLoader).Count - skip) / every;

                            BinaryTree.WriteAllTrees(treeLoader.Skip(skip).Where((item, index) => index % every == 0), ms, true, (count) =>
                            {
                                double progress = Math.Max(0, Math.Min(1, count / totalTrees));
                                progressAction(progress);
                            });
                        }

                    }
                    else
                    {
                        openerProgressAction = (_) => { };

                        double totalTrees = (until - skip) / every;

                        BinaryTree.WriteAllTrees(treeLoader.Take(until).Skip(skip).Where((item, index) => index % every == 0), ms, true, (count) =>
                        {
                            double progress = Math.Max(0, Math.Min(1, count / totalTrees));
                            progressAction(progress);
                        });
                    }

                    ms.Seek(0, SeekOrigin.Begin);

                    TreeCollection tbr = new TreeCollection(ms);

                    if (tbr[0].Children.Count > 2)
                    {
                        if (moduleSuggestions[1].Item1 == "68e25ec6-5911-4741-8547-317597e1b792" && moduleSuggestions[1].Item2.Count == 0)
                        {
                            moduleSuggestions[1] = ("95b61284-b870-48b9-b51c-3276f7d89df1", new Dictionary<string, object>());
                        }
                    }

                    if (treeLoader is IDisposable disposable)
                    {
                        disposable.Dispose();
                    }

                    return tbr;
                }
            }
            else
            {
                if (!(treeLoader is TreeCollection))
                {
                    openerProgressAction = (val) => { progressAction(val); };

                    MemoryStream ms = new MemoryStream();

                    BinaryTree.WriteAllTrees(treeLoader, ms, true);

                    ms.Seek(0, SeekOrigin.Begin);

                    TreeCollection tbr = new TreeCollection(ms);

                    if (tbr[0].Children.Count > 2)
                    {
                        if (moduleSuggestions[1].Item1 == "68e25ec6-5911-4741-8547-317597e1b792" && moduleSuggestions[1].Item2.Count == 0)
                        {
                            moduleSuggestions[1] = ("95b61284-b870-48b9-b51c-3276f7d89df1", new Dictionary<string, object>());
                        }
                    }

                    if (treeLoader is IDisposable disposable)
                    {
                        disposable.Dispose();
                    }

                    return tbr;
                }
                else
                {
                    openerProgressAction = (_) => { };

                    MemoryStream ms = new MemoryStream();

                    ((TreeCollection)treeLoader).UnderlyingStream.Seek(0, SeekOrigin.Begin);
                    ((TreeCollection)treeLoader).UnderlyingStream.CopyToWithProgress(ms, progressAction);

                    ms.Seek(0, SeekOrigin.Begin);

                    TreeCollection tbr = new TreeCollection(ms);

                    if (tbr[0].Children.Count > 2)
                    {
                        if (moduleSuggestions[1].Item1 == "68e25ec6-5911-4741-8547-317597e1b792" && moduleSuggestions[1].Item2.Count == 0)
                        {
                            moduleSuggestions[1] = ("95b61284-b870-48b9-b51c-3276f7d89df1", new Dictionary<string, object>());
                        }
                    }

                    if (treeLoader is IDisposable disposable)
                    {
                        disposable.Dispose();
                    }

                    return tbr;
                }
            }
        }

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

public static TreeNode Transform(TreeCollection trees, Dictionary<string, object> parameterValues, Action<double> progressAction)
        {
            if (trees.Count == 1)
            {
                return trees[0];
            }
            else
            {
                if ((bool)parameterValues["Consensus tree"])
                {
                    int skip = (int)(double)parameterValues["Skip:"];
                    int every = (int)(double)parameterValues["Every:"];
                    int until = (int)(double)parameterValues["Until:"];

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

                    if (skip == 0 && every == 1 && until == trees.Count)
                    {
                        return trees.GetConsensus(trees[0].Children.Count < 3 && trees[1].Children.Count < 3, clocklike, (double)parameterValues["Threshold:"], (int)parameterValues["Branch lengths:"] == 1, x => progressAction(x / trees.Count));
                    }
                    else
                    {
                        int totalTrees = (until - skip) / every;

                        return trees.Take(until).Skip(skip).Where((item, index) => index % every == 0).GetConsensus(trees[0].Children.Count < 3 && trees[1].Children.Count < 3, clocklike, (double)parameterValues["Threshold:"], (int)parameterValues["Branch lengths:"] == 1, x => progressAction(x / totalTrees));
                    }
                }
                else
                {
                    return trees[(int)(double)parameterValues["Tree #"] - 1];
                }
            }
        }

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

public static TreeCollection Load(Avalonia.Controls.Window parentWindow, FileInfo fileInfo, string filetypeModuleId, IEnumerable<TreeNode> treeLoader, List<(string, Dictionary<string, object>)> moduleSuggestions, ref Action<double> openerProgressAction, Action<double> progressAction)
        {
            long largeFileThreshold = 26214400;

            if (TreeViewer.GlobalSettings.Settings.AdditionalSettings.TryGetValue("Large file threshold:", out object largeFileThresholdValue))
            {
                if (largeFileThresholdValue is long threshValue)
				{
					largeFileThreshold = threshValue;
				}
				else if (largeFileThresholdValue is JsonElement element)
				{
					largeFileThreshold = element.GetInt64();
				}
            }

            if (treeLoader is TreeCollection coll)
            {
                openerProgressAction = (val) => { progressAction(val); };

                if (coll[0].Children.Count > 2)
                {
                    if (moduleSuggestions[1].Item1 == "68e25ec6-5911-4741-8547-317597e1b792" && moduleSuggestions[1].Item2.Count == 0)
                    {
                        moduleSuggestions[1] = ("95b61284-b870-48b9-b51c-3276f7d89df1", new Dictionary<string, object>());
                    }
                }

                return coll;
            }
            else
            {
                if (fileInfo.Length > largeFileThreshold)
                {
                    bool result = false;
                    int skip = 0;
                    int every = 1;
                    int until = -1;

                    if (InstanceStateData.IsUIAvailable)
                    {
                        EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset);

                        Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(async () =>
                        {
                            Window settingsWindow = new Window() { Width = 450, Height = 300, FontFamily = Avalonia.Media.FontFamily.Parse("resm:TreeViewer.Fonts.?replacedembly=TreeViewer#Open Sans"), FontSize = 15, replacedle = "Skip trees...", WindowStartupLocation = WindowStartupLocation.CenterOwner };

                            Grid mainGrid = new Grid() { Margin = new Avalonia.Thickness(10) };
                            mainGrid.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
                            mainGrid.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));

                            settingsWindow.Content = mainGrid;

                            StackPanel panel = new StackPanel();
                            mainGrid.Children.Add(panel);


                            Grid alertPanel = new Grid() { Margin = new Avalonia.Thickness(0, 0, 0, 10) };
                            alertPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                            alertPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                            alertPanel.Children.Add(MainWindow.GetAlertIcon());
                            TextBlock alertBlock = new TextBlock() { Text = "The file you are trying to open is very large (" + (fileInfo.Length / 1024 / 1024).ToString() + "MB). The trees are going to be read from the disk, so there should not be any memory issues; however, the input file needs to be converted to a binary format: to speed things up, you may want to skip some of the trees.", TextWrapping = Avalonia.Media.TextWrapping.Wrap, Margin = new Avalonia.Thickness(5, 0, 0, 0) };

                            Grid.SetColumn(alertBlock, 1);
                            alertPanel.Children.Add(alertBlock);
                            panel.Children.Add(alertPanel);

                            Grid skipPanel = new Grid() { Margin = new Avalonia.Thickness(0, 0, 0, 10) };
                            skipPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                            skipPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                            skipPanel.Children.Add(new TextBlock() { FontWeight = Avalonia.Media.FontWeight.Bold, Text = "Trees to skip:", Margin = new Avalonia.Thickness(0, 0, 5, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center });
                            NumericUpDown skipNud = new NumericUpDown() { Minimum = 0, FormatString = "0", Value = 0, Padding = new Avalonia.Thickness(5, 0, 5, 0) };
                            Grid.SetColumn(skipNud, 1);
                            skipPanel.Children.Add(skipNud);
                            panel.Children.Add(skipPanel);

                            Grid everyPanel = new Grid() { Margin = new Avalonia.Thickness(0, 0, 0, 10) };
                            everyPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                            everyPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                            everyPanel.Children.Add(new TextBlock() { FontWeight = Avalonia.Media.FontWeight.Bold, Text = "Sample a tree every:", Margin = new Avalonia.Thickness(0, 0, 5, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center });
                            NumericUpDown everyNud = new NumericUpDown() { Minimum = 1, FormatString = "0", Value = 1, Padding = new Avalonia.Thickness(5, 0, 5, 0) };
                            Grid.SetColumn(everyNud, 1);
                            everyPanel.Children.Add(everyNud);
                            panel.Children.Add(everyPanel);

                            Grid untilPanel = new Grid() { Margin = new Avalonia.Thickness(0, 0, 0, 10) };
                            untilPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                            untilPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                            CheckBox untilBox = new CheckBox() { FontWeight = Avalonia.Media.FontWeight.Bold, Content = "Up to tree:", Margin = new Avalonia.Thickness(0, 0, 5, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                            untilPanel.Children.Add(untilBox);
                            NumericUpDown untilNud = new NumericUpDown() { Minimum = 1, FormatString = "0", Value = 1, Padding = new Avalonia.Thickness(5, 0, 5, 0) };
                            Grid.SetColumn(untilNud, 1);
                            untilPanel.Children.Add(untilNud);
                            panel.Children.Add(untilPanel);

                            Grid buttonPanel = new Grid();
                            buttonPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                            buttonPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                            buttonPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                            buttonPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                            buttonPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                            Button okButton = new Button() { Width = 100, Content = "OK" };
                            Grid.SetColumn(okButton, 1);
                            buttonPanel.Children.Add(okButton);
                            Button cancelButton = new Button() { Width = 100, Content = "Cancel" };
                            Grid.SetColumn(cancelButton, 3);
                            buttonPanel.Children.Add(cancelButton);
                            Grid.SetRow(buttonPanel, 1);
                            mainGrid.Children.Add(buttonPanel);


                            okButton.Click += (s, e) =>
                            {
                                result = true;
                                settingsWindow.Close();
                            };

                            cancelButton.Click += (s, e) =>
                            {
                                result = false;
                                settingsWindow.Close();
                            };

                            await settingsWindow.ShowDialog2(parentWindow);

                            skip = (int)Math.Round(skipNud.Value);
                            every = (int)Math.Round(everyNud.Value);
                            if (untilBox.IsChecked == true)
                            {
                                until = (int)Math.Round(untilNud.Value);
                            }

                            handle.Set();
                        });

                        handle.WaitOne();
                    }
                    else
                    {
                        result = true;
                    }

                    if (!result)
                    {
                        if (treeLoader is IDisposable disposable)
                        {
                            disposable.Dispose();
                        }

                        return null;
                    }
                    else
                    {
                        string tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

                        using (FileStream fs = new FileStream(tempFile, FileMode.Create, FileAccess.Write))
                        {
                            if (until == -1)
                            {
                                openerProgressAction = (val) => { progressAction(val); };

                                BinaryTree.WriteAllTrees(treeLoader.Skip(skip).Where((item, index) => index % every == 0), fs);
                            }
                            else
                            {
                                openerProgressAction = (_) => { };

                                double totalTrees = (until - skip) / every;

                                BinaryTree.WriteAllTrees(treeLoader.Take(until).Skip(skip).Where((item, index) => index % every == 0), fs, false, (count) =>
                                {
                                    double progress = Math.Max(0, Math.Min(1, count / totalTrees));
                                    progressAction(progress);
                                });
                            }
                        }

                        FileStream readerFs = new FileStream(tempFile, FileMode.Open, FileAccess.Read, FileShare.Read);

                        TreeCollection tbr = new TreeCollection(readerFs) { TemporaryFile = tempFile };

                        if (tbr[0].Children.Count > 2)
                        {
                            if (moduleSuggestions[1].Item1 == "68e25ec6-5911-4741-8547-317597e1b792" && moduleSuggestions[1].Item2.Count == 0)
                            {
                                moduleSuggestions[1] = ("95b61284-b870-48b9-b51c-3276f7d89df1", new Dictionary<string, object>());
                            }
                        }

                        if (treeLoader is IDisposable disposable)
                        {
                            disposable.Dispose();
                        }

                        return tbr;
                    }
                }
                else
                {
                    openerProgressAction = (val) => { progressAction(val); };

                    string tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

                    using (FileStream fs = new FileStream(tempFile, FileMode.Create, FileAccess.Write))
                    {
                        BinaryTree.WriteAllTrees(treeLoader, fs);
                    }

                    FileStream readerFs = new FileStream(tempFile, FileMode.Open, FileAccess.Read, FileShare.Read);
                    TreeCollection tbr = new TreeCollection(readerFs) { TemporaryFile = tempFile };

                    if (tbr[0].Children.Count > 2)
                    {
                        if (moduleSuggestions[1].Item1 == "68e25ec6-5911-4741-8547-317597e1b792" && moduleSuggestions[1].Item2.Count == 0)
                        {
                            moduleSuggestions[1] = ("95b61284-b870-48b9-b51c-3276f7d89df1", new Dictionary<string, object>());
                        }
                    }

                    if (treeLoader is IDisposable disposable)
                    {
                        disposable.Dispose();
                    }

                    return tbr;
                }
            }
        }

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

public static TreeCollection Load(Window parentWindow, FileInfo fileInfo, string loaderModuleId, IEnumerable<TreeNode> treeLoader, List<(string, Dictionary<string, object>)> moduleSuggestions, ref Action<double> openerProgressAction, Action<double> progressAction)
        {
            long largeFileThreshold = 26214400;

            if (TreeViewer.GlobalSettings.Settings.AdditionalSettings.TryGetValue("Large file threshold:", out object largeFileThresholdValue))
            {
                if (largeFileThresholdValue is long threshValue)
                {
                    largeFileThreshold = threshValue;
                }
                else if (largeFileThresholdValue is JsonElement element)
                {
                    largeFileThreshold = element.GetInt64();
                }
            }

            if (fileInfo.Length > largeFileThreshold)
            {
                bool result = false;
                int skip = 0;
                int every = 1;
                int until = -1;

                if (InstanceStateData.IsUIAvailable)
                {
                    EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset);

                    Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(async () =>
                    {
                        ChildWindow settingsWindow = new ChildWindow() { Width = 450, SizeToContent = SizeToContent.Height, FontFamily = Avalonia.Media.FontFamily.Parse("resm:TreeViewer.Fonts.?replacedembly=TreeViewer#Open Sans"), FontSize = 14, replacedle = "Skip trees...", WindowStartupLocation = WindowStartupLocation.CenterOwner };

                        Grid mainGrid = new Grid() { Margin = new Avalonia.Thickness(10) };
                        mainGrid.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));
                        mainGrid.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));

                        settingsWindow.Content = mainGrid;

                        StackPanel panel = new StackPanel();
                        mainGrid.Children.Add(panel);


                        Grid alertPanel = new Grid() { Margin = new Avalonia.Thickness(0, 0, 0, 10) };
                        alertPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                        alertPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                        alertPanel.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
                        alertPanel.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));

                        Viewbox alert = MainWindow.GetAlertIcon();
                        alert.Width = 32;
                        alert.Height = 32;

                        alertPanel.Children.Add(alert);

                        TextBlock alertreplacedle = new TextBlock() { Text = "Large tree file", FontSize = 16, Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(0, 114, 178)), Margin = new Avalonia.Thickness(10, 0, 0, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                        Grid.SetColumn(alertreplacedle, 1);
                        alertPanel.Children.Add(alertreplacedle);

                        TextBlock alertBlock = new TextBlock() { Text = "The file you are trying to open is very large (" + (fileInfo.Length / 1024 / 1024).ToString() + "MB). The trees are going to be loaded into memory, which may cause the program to run out of memory. To reduce memory pressure, you may want to skip some of the trees. You may also click 'Cancel' to close this window and then used the 'Advanced open...' menu option to specify the Disk loader.", TextWrapping = Avalonia.Media.TextWrapping.Wrap, Margin = new Avalonia.Thickness(0, 5, 0, 0), FontSize = 13 };

                        Grid.SetRow(alertBlock, 1);
                        Grid.SetColumnSpan(alertBlock, 2);
                        alertPanel.Children.Add(alertBlock);
                        panel.Children.Add(alertPanel);

                        Grid skipPanel = new Grid() { Margin = new Avalonia.Thickness(0, 0, 0, 10) };
                        skipPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                        skipPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                        skipPanel.Children.Add(new TextBlock() { FontWeight = Avalonia.Media.FontWeight.Bold, Text = "Trees to skip:", Margin = new Avalonia.Thickness(0, 0, 5, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center });
                        NumericUpDown skipNud = new NumericUpDown() { Minimum = 0, FormatString = "0", Value = 0, Padding = new Avalonia.Thickness(5, 0, 5, 0) };
                        Grid.SetColumn(skipNud, 1);
                        skipPanel.Children.Add(skipNud);
                        panel.Children.Add(skipPanel);

                        Grid everyPanel = new Grid() { Margin = new Avalonia.Thickness(0, 0, 0, 10) };
                        everyPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                        everyPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                        everyPanel.Children.Add(new TextBlock() { FontWeight = Avalonia.Media.FontWeight.Bold, Text = "Sample a tree every:", Margin = new Avalonia.Thickness(0, 0, 5, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center });
                        NumericUpDown everyNud = new NumericUpDown() { Minimum = 1, FormatString = "0", Value = 1, Padding = new Avalonia.Thickness(5, 0, 5, 0) };
                        Grid.SetColumn(everyNud, 1);
                        everyPanel.Children.Add(everyNud);
                        panel.Children.Add(everyPanel);

                        Grid untilPanel = new Grid() { Margin = new Avalonia.Thickness(0, 0, 0, 10) };
                        untilPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                        untilPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                        CheckBox untilBox = new CheckBox() { FontWeight = Avalonia.Media.FontWeight.Bold, Content = "Up to tree:", Margin = new Avalonia.Thickness(0, 0, 5, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                        untilPanel.Children.Add(untilBox);
                        NumericUpDown untilNud = new NumericUpDown() { Minimum = 1, FormatString = "0", Value = 1, Padding = new Avalonia.Thickness(5, 0, 5, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                        Grid.SetColumn(untilNud, 1);
                        untilPanel.Children.Add(untilNud);
                        panel.Children.Add(untilPanel);

                        Grid buttonPanel = new Grid();
                        buttonPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                        buttonPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                        buttonPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                        buttonPanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
                        buttonPanel.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                        Button okButton = new Button() { Width = 100, Content = "OK", HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, FontSize = 13 };
                        okButton.Clreplacedes.Add("PlainButton");
                        Grid.SetColumn(okButton, 1);
                        buttonPanel.Children.Add(okButton);
                        Button cancelButton = new Button() { Width = 100, Content = "Cancel", HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, FontSize = 13 };
                        cancelButton.Clreplacedes.Add("PlainButton");
                        Grid.SetColumn(cancelButton, 3);
                        buttonPanel.Children.Add(cancelButton);
                        Grid.SetRow(buttonPanel, 1);
                        mainGrid.Children.Add(buttonPanel);


                        okButton.Click += (s, e) =>
                        {
                            result = true;
                            settingsWindow.Close();
                        };

                        cancelButton.Click += (s, e) =>
                        {
                            result = false;
                            settingsWindow.Close();
                        };

                        await settingsWindow.ShowDialog2(parentWindow);

                        skip = (int)Math.Round(skipNud.Value);
                        every = (int)Math.Round(everyNud.Value);
                        if (untilBox.IsChecked == true)
                        {
                            until = (int)Math.Round(untilNud.Value);
                        }

                        handle.Set();
                    });

                    handle.WaitOne();
                }
                else
                {
                    result = true;
                }


                if (!result)
                {
                    if (treeLoader is IDisposable disposable)
                    {
                        disposable.Dispose();
                    }

                    return null;
                }
                else
                {

                    if (until == -1)
                    {
                        openerProgressAction = (val) => { progressAction(val); };

                        if (skip == 0 && every == 1)
                        {
                            TreeCollection tbr = new TreeCollection(treeLoader as List<TreeNode> ?? treeLoader.ToList());

                            if (tbr[0].Children.Count > 2)
                            {
                                if (moduleSuggestions[1].Item1 == "68e25ec6-5911-4741-8547-317597e1b792" && moduleSuggestions[1].Item2.Count == 0)
                                {
                                    moduleSuggestions[1] = ("95b61284-b870-48b9-b51c-3276f7d89df1", new Dictionary<string, object>());
                                }
                            }

                            if (treeLoader is IDisposable disposable)
                            {
                                disposable.Dispose();
                            }

                            return tbr;
                        }
                        else
                        {
                            TreeCollection tbr = new TreeCollection(treeLoader.Skip(skip).Where((item, index) => index % every == 0).ToList());

                            if (tbr[0].Children.Count > 2)
                            {
                                if (moduleSuggestions[1].Item1 == "68e25ec6-5911-4741-8547-317597e1b792" && moduleSuggestions[1].Item2.Count == 0)
                                {
                                    moduleSuggestions[1] = ("95b61284-b870-48b9-b51c-3276f7d89df1", new Dictionary<string, object>());
                                }
                            }

                            if (treeLoader is IDisposable disposable)
                            {
                                disposable.Dispose();
                            }

                            return tbr;
                        }
                    }
                    else
                    {
                        openerProgressAction = (_) => { };

                        double totalTrees = (until - skip) / every;

                        List<TreeNode> trees = new List<TreeNode>((until - skip) / every + 1);

                        foreach (TreeNode tree in treeLoader.Take(until).Skip(skip).Where((item, index) => index % every == 0))
                        {
                            trees.Add(tree);
                            double progress = Math.Max(0, Math.Min(1, trees.Count / totalTrees));
                            progressAction(progress);
                        }

                        TreeCollection tbr = new TreeCollection(trees);

                        if (tbr[0].Children.Count > 2)
                        {
                            if (moduleSuggestions[1].Item1 == "68e25ec6-5911-4741-8547-317597e1b792" && moduleSuggestions[1].Item2.Count == 0)
                            {
                                moduleSuggestions[1] = ("95b61284-b870-48b9-b51c-3276f7d89df1", new Dictionary<string, object>());
                            }
                        }

                        if (treeLoader is IDisposable disposable)
                        {
                            disposable.Dispose();
                        }

                        return tbr;
                    }
                }
            }
            else
            {
                openerProgressAction = (val) => { progressAction(val); };

                TreeCollection tbr = new TreeCollection(treeLoader as List<TreeNode> ?? treeLoader.ToList());

                if (tbr[0].Children.Count > 2)
                {
                    if (moduleSuggestions[1].Item1 == "68e25ec6-5911-4741-8547-317597e1b792" && moduleSuggestions[1].Item2.Count == 0)
                    {
                        moduleSuggestions[1] = ("95b61284-b870-48b9-b51c-3276f7d89df1", new Dictionary<string, object>());
                    }
                }

                if (treeLoader is IDisposable disposable)
                {
                    disposable.Dispose();
                }

                return tbr;
            }
        }

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

private static async Task<TreeCollection> LoadFile(string fileName, MainWindow window)
        {
            double maxResult = 0;
            int maxIndex = -1;

            for (int i = 0; i < Modules.FileTypeModules.Count; i++)
            {
                try
                {
                    double priority = Modules.FileTypeModules[i].IsSupported(fileName);
                    if (priority > maxResult)
                    {
                        maxResult = priority;
                        maxIndex = i;
                    }
                }
                catch { }
            }

            if (maxIndex >= 0)
            {
                double maxLoadResult = 0;
                int maxLoadIndex = -1;

                IEnumerable<TreeNode> loader;

                try
                {
                    List<(string, Dictionary<string, object>)> moduleSuggestions = new List<(string, Dictionary<string, object>)>()
                    {
                        ("32914d41-b182-461e-b7c6-5f0263cc1ccd", new Dictionary<string, object>()),
                        ("68e25ec6-5911-4741-8547-317597e1b792", new Dictionary<string, object>()),
                    };

                    EventWaitHandle progressWindowHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
                    ProgressWindow progressWin = new ProgressWindow(progressWindowHandle) { ProgressText = "Opening and loading file..." };
                    Action<double> progressAction = (progress) =>
                    {
                        if (progress >= 0)
                        {
                            Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() =>
                            {
                                progressWin.IsIndeterminate = false;
                                progressWin.Progress = progress;
                            });
                        }
                        else
                        {
                            Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() =>
                            {
                                progressWin.IsIndeterminate = true;
                            });
                        }
                    };

                    TreeCollection coll = null;

                    Thread thr = new Thread(async () =>
                    {
                        progressWindowHandle.WaitOne();

                        Action<double> openerProgressAction = (_) => { };

                        bool askForCodePermission(RSAParameters? publicKey)
                        {
                            return false;
                        };

                        loader = Modules.FileTypeModules[maxIndex].OpenFile(fileName, moduleSuggestions, (val) => { openerProgressAction(val); }, askForCodePermission);

                        FileInfo finfo = new FileInfo(fileName);

                        for (int i = 0; i < Modules.LoadFileModules.Count; i++)
                        {
                            try
                            {
                                double priority = Modules.LoadFileModules[i].IsSupported(finfo, Modules.FileTypeModules[maxIndex].Id, loader);
                                if (priority > maxLoadResult)
                                {
                                    maxLoadResult = priority;
                                    maxLoadIndex = i;
                                }
                            }
                            catch { }
                        }

                        if (maxLoadIndex >= 0)
                        {
                            try
                            {
                                coll = Modules.LoadFileModules[maxLoadIndex].Load(window, finfo, Modules.FileTypeModules[maxIndex].Id, loader, moduleSuggestions, ref openerProgressAction, progressAction);
                            }
                            catch (Exception ex)
                            {
                                await Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(async () => { await new MessageBox("Error!", "An error has occurred while loading the file!\n" + ex.Message).ShowDialog2(window); return Task.CompletedTask; });
                            }

                            await Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() => { progressWin.Close(); });
                        }
                        else
                        {
                            await Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(async () => { await new MessageBox("Attention!", "The file cannot be loaded by any of the currently installed modules!").ShowDialog2(window); return Task.CompletedTask; });
                        }
                    });

                    thr.Start();

                    await progressWin.ShowDialog2(window);

                    if (coll != null)
                    {
                        return coll;
                    }
                    else
                    {
                        return null;
                    }
                }
                catch (Exception ex)
                {
                    await new MessageBox("Error!", "An error has occurred while opening the file!\n" + ex.Message).ShowDialog2(window);
                    return null;
                }
            }
            else
            {
                await new MessageBox("Attention!", "The file type is not supported by any of the currently installed modules!").ShowDialog2(window);
                return null;
            }
        }

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

public static IEnumerable<TreeNode> OpenFile(string fileName, List<(string, Dictionary<string, object>)> moduleSuggestions, Action<double> progressAction, Func<RSAParameters?, bool> askForCodePermission)
        {
            bool escaping = false;
            bool escaped;
            bool openQuotes = false;
            bool openApostrophe = false;
            bool eof = false;

            using (StreamReader sr = new StreamReader(fileName))
            {
                double length = sr.BaseStream.Length;

                while (!eof)
                {
                    StringBuilder sb = new StringBuilder();

                    char c = sr.NextToken(ref escaping, out escaped, ref openQuotes, ref openApostrophe, out eof);

                    while (!eof && !(c == ';' && !escaped && !openQuotes && !openApostrophe))
                    {
                        sb.Append((char)c);
                        c = sr.NextToken(ref escaping, out escaping, ref openQuotes, ref openApostrophe, out eof);
                    }

                    if (sb.Length > 0)
                    {
                        yield return NWKA.ParseTree(sb.ToString());
                        double progress = Math.Max(0, Math.Min(1, sr.BaseStream.Position / length));
                        progressAction?.Invoke(progress);
                    }
                }
            }
        }

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

private static TreeCollection LoadFile(string fileName)
        {
            double maxResult = 0;
            int maxIndex = -1;

            for (int i = 0; i < Modules.FileTypeModules.Count; i++)
            {
                try
                {
                    double priority = Modules.FileTypeModules[i].IsSupported(fileName);
                    if (priority > maxResult)
                    {
                        maxResult = priority;
                        maxIndex = i;
                    }
                }
                catch { }
            }

            if (maxIndex >= 0)
            {
                double maxLoadResult = 0;
                int maxLoadIndex = -1;

                IEnumerable<TreeNode> loader;

                try
                {
                    List<(string, Dictionary<string, object>)> moduleSuggestions = new List<(string, Dictionary<string, object>)>()
                    {
                        ("32914d41-b182-461e-b7c6-5f0263cc1ccd", new Dictionary<string, object>()),
                        ("68e25ec6-5911-4741-8547-317597e1b792", new Dictionary<string, object>()),
                    };

                    TreeCollection coll = null;

                    Action<double> openerProgressAction = (_) => { };

                    bool askForCodePermission(RSAParameters? publicKey)
                    {
                        return false;
                    };

                    loader = Modules.FileTypeModules[maxIndex].OpenFile(fileName, moduleSuggestions, (val) => { openerProgressAction(val); }, askForCodePermission);

                    FileInfo finfo = new FileInfo(fileName);

                    for (int i = 0; i < Modules.LoadFileModules.Count; i++)
                    {
                        try
                        {
                            double priority = Modules.LoadFileModules[i].IsSupported(finfo, Modules.FileTypeModules[maxIndex].Id, loader);
                            if (priority > maxLoadResult)
                            {
                                maxLoadResult = priority;
                                maxLoadIndex = i;
                            }
                        }
                        catch { }
                    }

                    if (maxLoadIndex >= 0)
                    {
                        try
                        {
                            coll = Modules.LoadFileModules[maxLoadIndex].Load(null, finfo, Modules.FileTypeModules[maxIndex].Id, loader, moduleSuggestions, ref openerProgressAction, a => { });
                        }
                        catch (Exception ex)
                        {
                            ConsoleWrapper.WriteLine();
                            ConsoleWrapper.WriteLine(new ConsoleTextSpan("An error has occurred while loading the file!\n" + ex.Message, ConsoleColor.Red));
                            ConsoleWrapper.WriteLine();
                        }
                    }
                    else
                    {
                        ConsoleWrapper.WriteLine();
                        ConsoleWrapper.WriteLine(new ConsoleTextSpan("The file cannot be loaded by any of the currently installed modules!", ConsoleColor.Red));
                        ConsoleWrapper.WriteLine();
                    }

                    if (coll != null)
                    {
                        return coll;
                    }
                    else
                    {
                        return null;
                    }
                }
                catch (Exception ex)
                {
                    ConsoleWrapper.WriteLine();
                    ConsoleWrapper.WriteLine(new ConsoleTextSpan("An error has occurred while opening the file!\n" + ex.Message, ConsoleColor.Red));
                    ConsoleWrapper.WriteLine();
                    return null;
                }
            }
            else
            {
                ConsoleWrapper.WriteLine();
                ConsoleWrapper.WriteLine(new ConsoleTextSpan("The file type is not supported by any of the currently installed modules!", ConsoleColor.Red));
                ConsoleWrapper.WriteLine();
                return null;
            }
        }

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

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

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

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

            double actualResolution = resolution;

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

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

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

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

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

            HashSet<string>[] states = null;

            int sampleIndex = 0;

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

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

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

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

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

                            double left;
                            double right;

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

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

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

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

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

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

            int nodeIndex = 0;

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

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

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

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

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

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

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

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

                    {
                        string state = "{";

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

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

                        state += "}";

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


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

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

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



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

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

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

                        double total = counts.Sum();

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

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

                        preparedBranchStates.Add((perc, probs));

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

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

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

                                state += "}";

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

                            break;
                        }
                    }

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

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

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

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

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

                    {
                        string state = "{";

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

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

                        state += "}";

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

                        conditionedPosteriors[node.Id] = meanPosterior;
                    }
                }

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

                string state = "{";

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

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

                state += "}";

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

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

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

public static void Transform(ref TreeNode tree, Dictionary<string, object> parameterValues, Action<double> progressAction)
        {
            bool fromLeft = (int)parameterValues["Age type:"] == 1;
            double threshold = (double)parameterValues["Threshold:"];
            int ciType = (int)parameterValues["Credible interval:"];
            bool computeMean = (bool)parameterValues["Compute mean"];

            TreeCollection treeCollection = (TreeCollection)parameterValues["Trees"];
            InstanceStateData stateData = (InstanceStateData)parameterValues["StateData"];

            List<TreeNode> nodes = tree.GetChildrenRecursive();

            Dictionary<string, List<double>> ageSamples = new Dictionary<string, List<double>>();
            for (int i = 0; i < nodes.Count; i++)
            {
                ageSamples.Add(nodes[i].Id, new List<double>());
            }

            int sampleIndex = 0;

            TreeNode treeClone = tree;

            object progressLock = new object();
            object addLock = new object();

            System.Threading.Tasks.Parallel.ForEach(treeCollection, new ParallelOptions() { MaxDegreeOfParallelism = 6 }, sampledTree =>
              {
                  double treeHeight = -1;

                  if (!fromLeft)
                  {
                      treeHeight = sampledTree.LongestDownstreamLength();
                  }

                  foreach (TreeNode node in sampledTree.GetChildrenRecursiveLazy())
                  {
                      TreeNode LCA = treeClone.GetLastCommonAncestor(node.GetLeafNames());

                      if (Compare(LCA.GetLeafNames(), node.GetLeafNames()))
                      {
                          double age = node.UpstreamLength();

                          if (!fromLeft)
                          {
                              age = treeHeight - age;
                          }

                          lock (addLock)
                          {
                              ageSamples[LCA.Id].Add(age);
                          }
                      }
                  }

                  lock (progressLock)
                  {
                      sampleIndex++;
                      progressAction((double)sampleIndex / treeCollection.Count);
                  }
              });

            if (ciType > 0 || computeMean)
            {
                for (int i = 0; i < nodes.Count; i++)
                {
                    if (ageSamples[nodes[i].Id].Count > 0)
                    {
                        if (computeMean)
                        {
                            nodes[i].Attributes["Mean age"] = ageSamples[nodes[i].Id].Average();
                        }

                        if (ciType == 1)
                        {
                            double[] hdi = BayesStats.HighestDensityInterval(ageSamples[nodes[i].Id], threshold);
                            nodes[i].Attributes[threshold.ToString("0%") + "_HDI"] = "[ " + hdi[0].ToString() + ", " + hdi[1].ToString() + "]";
                        }
                        else if (ciType == 2)
                        {
                            double[] eti = BayesStats.EqualTailedInterval(ageSamples[nodes[i].Id], threshold);
                            nodes[i].Attributes[threshold.ToString("0%") + "_ETI"] = "[ " + eti[0].ToString() + ", " + eti[1].ToString() + "]";
                        }
                    }
                }
            }

            stateData.Tags["a1ccf05a-cf3c-4ca4-83be-af56f501c2a6"] = ageSamples;
            tree.Attributes["a1ccf05a-cf3c-4ca4-83be-af56f501c2a6"] = "Age distributions";
        }

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

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

            if (attachment == null)
            {
                return;
            }

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

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

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

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

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

            double actualResolution = resolution;

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

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

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

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

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

            HashSet<string>[] states = null;

            int sampleIndex = 0;

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

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

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

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

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

                            double left;
                            double right;

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

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

                sampleIndex++;

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

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

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

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

            int nodeIndex = 0;

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

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

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

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

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

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

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

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

                    {
                        string state = "{";

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

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

                        state += "}";

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


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

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

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



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

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

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

                        double total = counts.Sum();

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


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

                        preparedBranchStates.Add((perc, probs));

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

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

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

                                state += "}";

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

                            break;
                        }
                    }

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

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

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

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

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

                    {
                        string state = "{";

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

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

                        state += "}";

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

                        conditionedPosteriors[node.Id] = meanPosterior;
                    }
                }

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

                string state = "{";

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

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

                state += "}";

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

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

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

private static List<TreeNode> OpenFile(Stream fileStream, Action<double> progressAction)
        {
            Action<double> nwkaProgressAction = (prog) => { progressAction(prog * 0.25); };

            List<TreeNode> trees = NWKA.ParseTrees(fileStream, progressAction: nwkaProgressAction, keepOpen: true).ToList();

            HashSet<string>[] characters = null;

            int treeIndex = 0;

            foreach (TreeNode tree in trees)
            {
                foreach (TreeNode node in tree.GetChildrenRecursiveLazy())
                {
                    string attributeToRemove = null;

                    foreach (KeyValuePair<string, object> attribute in node.Attributes)
                    {
                        if (attribute.Key.StartsWith("Unknown") && attribute.Value is string attributeValue && attributeValue.StartsWith("{") && attributeValue.EndsWith("}"))
                        {
                            SimmapBranchState[] states = SimmapBranchState.Parse(attributeValue).ToArray();

                            if (states.Length > 0)
                            {
                                if (characters == null)
                                {
                                    characters = new HashSet<string>[states[0].States.Length];

                                    for (int i = 0; i < characters.Length; i++)
                                    {
                                        characters[i] = new HashSet<string>();
                                    }
                                }

                                node.Attributes.Add("States", System.Text.Json.JsonSerializer.Serialize(states, Modules.DefaultSerializationOptions));
                                node.Length = (from el in states select el.Length).Sum();

                                foreach (SimmapBranchState state in states)
                                {
                                    for (int i = 0; i < state.States.Length; i++)
                                    {
                                        characters[i].Add(state.States[i]);
                                    }
                                }

                                attributeToRemove = attribute.Key;

                                break;
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(attributeToRemove))
                    {
                        node.Attributes.Remove(attributeToRemove);
                    }
                }

                tree.Attributes.Add("Characters", System.Text.Json.JsonSerializer.Serialize(characters, Modules.DefaultSerializationOptions));

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

            return trees;
        }

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

public static IEnumerable<TreeNode> OpenFile(string fileName, List<(string, Dictionary<string, object>)> moduleSuggestions, Action<double> progressAction, Func<RSAParameters?, bool> askForCodePermission)
        {
            bool escaping = false;
            bool escaped;
            bool openQuotes = false;
            bool openApostrophe = false;
            bool eof = false;

            if (GlobalSettings.Settings.DrawTreeWhenOpened)
            {
                moduleSuggestions.Add(("32858c9d-0247-497f-aeee-03f7bfe24158", new Dictionary<string, object>()));

                moduleSuggestions.Add(("7c767b07-71be-48b2-8753-b27f3e973570", new Dictionary<string, object>()));
                moduleSuggestions.Add(("f7a20f2f-94b2-4331-8bbf-4e0087da6fba", new Dictionary<string, object>()));
                moduleSuggestions.Add(("ac496677-2650-4d92-8646-0812918bab03", new Dictionary<string, object>() { { "Position:", new VectSharp.Point(10, 0) } }));

                NumberFormatterOptions widthFO = new NumberFormatterOptions(Modules.DefaultAttributeConvertersToDouble[1]) { AttributeName = "StateWidth", AttributeType = "Number", DefaultValue = 10.0, Parameters = new object[] { Modules.DefaultAttributeConvertersToDouble[1], 0, double.PositiveInfinity, true } };
                NumberFormatterOptions heightFO = new NumberFormatterOptions(Modules.DefaultAttributeConvertersToDouble[1]) { AttributeName = "StateHeight", AttributeType = "Number", DefaultValue = 10.0, Parameters = new object[] { Modules.DefaultAttributeConvertersToDouble[1], 0, double.PositiveInfinity, true } };

                moduleSuggestions.Add(("0512b822-044d-4c13-b3bb-bca494c51daa", new Dictionary<string, object>()
                {
                    { "Show on:",  2 },
                    { "Stroke thickness:", 1.0 },
                    { "Width:", widthFO },
                    { "Height:", heightFO },
                    { "Attribute:", "ConditionedPosteriors" }
                }));
            }

            using (StreamReader sr = new StreamReader(fileName))
            {
                double length = sr.BaseStream.Length;

                while (!eof)
                {
                    StringBuilder sb = new StringBuilder();

                    char c = sr.NextToken(ref escaping, out escaped, ref openQuotes, ref openApostrophe, out eof);

                    while (!eof && !(c == ';' && !escaped && !openQuotes && !openApostrophe))
                    {
                        sb.Append((char)c);
                        c = sr.NextToken(ref escaping, out escaping, ref openQuotes, ref openApostrophe, out eof);
                    }

                    if (sb.Length > 0)
                    {
                        TreeNode tree = NWKA.ParseTree(sb.ToString());

                        HashSet<string>[] characters = null;

                        foreach (TreeNode node in tree.GetChildrenRecursiveLazy())
                        {
                            string attributeToRemove = null;

                            foreach (KeyValuePair<string, object> attribute in node.Attributes)
                            {
                                if (attribute.Key.StartsWith("Unknown") && attribute.Value is string attributeValue && attributeValue.StartsWith("{") && attributeValue.EndsWith("}"))
                                {
                                    SimmapBranchState[] states = SimmapBranchState.Parse(attributeValue).ToArray();

                                    if (states.Length > 0)
                                    {
                                        if (characters == null)
                                        {
                                            characters = new HashSet<string>[states[0].States.Length];

                                            for (int i = 0; i < characters.Length; i++)
                                            {
                                                characters[i] = new HashSet<string>();
                                            }
                                        }

                                        node.Attributes.Add("States", System.Text.Json.JsonSerializer.Serialize(states, Modules.DefaultSerializationOptions));
                                        node.Length = (from el in states select el.Length).Sum();

                                        foreach (SimmapBranchState state in states)
                                        {
                                            for (int i = 0; i < state.States.Length; i++)
                                            {
                                                characters[i].Add(state.States[i]);
                                            }
                                        }

                                        attributeToRemove = attribute.Key;

                                        break;
                                    }
                                }
                            }

                            if (!string.IsNullOrEmpty(attributeToRemove))
                            {
                                node.Attributes.Remove(attributeToRemove);
                            }
                        }

                        tree.Attributes.Add("Characters", System.Text.Json.JsonSerializer.Serialize(characters, Modules.DefaultSerializationOptions));

                        yield return tree;
                        double progress = Math.Max(0, Math.Min(1, sr.BaseStream.Position / length));
                        progressAction?.Invoke(progress);
                    }
                }
            }
        }

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

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

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

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

            double actualResolution = resolution;

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

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

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

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

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

            HashSet<string>[] states = null;

            int sampleIndex = 0;

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

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

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

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

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

                            double left;
                            double right;

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

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

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

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

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

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

            int nodeIndex = 0;

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

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

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

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

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

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

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

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

                    {
                        string state = "{";

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

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

                        state += "}";

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


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

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

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



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

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

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

                        double total = counts.Sum();

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

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

                        preparedBranchStates.Add((perc, probs));

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

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

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

                                state += "}";

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

                            break;
                        }
                    }

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

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

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

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

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

                    {
                        string state = "{";

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

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

                        state += "}";

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

                        conditionedPosteriors[node.Id] = meanPosterior;
                    }
                }

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

                string state = "{";

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

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

                state += "}";

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

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

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

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

            if (attachment == null)
            {
                return;
            }

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

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

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

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

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

            double actualResolution = resolution;

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

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

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

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

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

            HashSet<string>[] states = null;

            int sampleIndex = 0;

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

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

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

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

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

                            double left;
                            double right;

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

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

                sampleIndex++;

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

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

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

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

            int nodeIndex = 0;

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

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

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

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

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

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

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

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

                    {
                        string state = "{";

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

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

                        state += "}";

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


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

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

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



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

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

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

                        double total = counts.Sum();

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


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

                        preparedBranchStates.Add((perc, probs));

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

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

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

                                state += "}";

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

                            break;
                        }
                    }

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

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

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

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

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

                    {
                        string state = "{";

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

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

                        state += "}";

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

                        conditionedPosteriors[node.Id] = meanPosterior;
                    }
                }

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

                string state = "{";

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

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

                state += "}";

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

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

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

private void BuildInterface()
        {
            Grid parentContainer = new Grid();
            parentContainer.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star) { MaxWidth = 700 });

            ScrollViewer mainContainer = new ScrollViewer() { HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled, VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto, AllowAutoHide = false, Padding = new Avalonia.Thickness(0, 0, 17, 0) };
            parentContainer.Children.Add(mainContainer);

            this.PageContent = parentContainer;

            StackPanel contentPanel = new StackPanel();
            mainContainer.Content = contentPanel;


            contentPanel.Children.Add(new TextBlock() { Text = "Tree file", FontSize = 20, Foreground = new SolidColorBrush(Color.FromRgb(0, 114, 178)), Margin = new Avalonia.Thickness(0, 0, 0, 0) });

            Grid treeFilePanel = new Grid() { VerticalAlignment = Avalonia.Layout.VerticalAlignment.Top, Height = 50 };
            treeFilePanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
            treeFilePanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
            treeFilePanel.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
            contentPanel.Children.Add(treeFilePanel);

            StackPanel browseButtonContentPanel = new StackPanel() { Orientation = Avalonia.Layout.Orientation.Horizontal };
            browseButtonContentPanel.Children.Add(new DPIAwareBox(Icons.GetIcon16("TreeViewer.replacedets.OpenDark")) { Width = 16, Height = 16, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Margin = new Avalonia.Thickness(0, 0, 5, 0) });
            browseButtonContentPanel.Children.Add(new TextBlock() { Text = "Browse...", FontSize = 14, Foreground = Brushes.Black });

            Button browseButton = new Button() { Content = browseButtonContentPanel, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
            browseButton.Clreplacedes.Add("SideBarButton");
            Grid.SetColumn(browseButton, 2);
            treeFilePanel.Children.Add(browseButton);

            ContentControl iconContainer = new ContentControl() { Width = 32, Height = 32, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Margin = new Avalonia.Thickness(0, 0, 9, 0), IsVisible = false };

            treeFilePanel.Children.Add(iconContainer);

            StackPanel treeFileName = new StackPanel() { Margin = new Avalonia.Thickness(0, 0, 5, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, IsVisible = false };

            TextBlock treeNameBlock = new TextBlock() { Text = "", FontSize = 16 };
            TextBlock treePathBlock = new TextBlock() { Text = "G:\\OneDrive - University of Bristol", Foreground = new SolidColorBrush(Color.FromRgb(102, 102, 102)), FontSize = 12 };
            treeFileName.Children.Add(treeNameBlock);
            treeFileName.Children.Add(treePathBlock);
            Grid.SetColumn(treeFileName, 1);
            treeFilePanel.Children.Add(treeFileName);


            TextBlock fileTypeModuleHeader = new TextBlock() { Text = "File type module", FontSize = 20, Foreground = new SolidColorBrush(Color.FromRgb(0, 114, 178)), Margin = new Avalonia.Thickness(0, 10, 0, 0), IsVisible = false };
            contentPanel.Children.Add(fileTypeModuleHeader);

            ScrollViewer filetypeModuleScrollViewer = new ScrollViewer() { HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto, VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled, AllowAutoHide = false, Padding = new Avalonia.Thickness(0, 0, 0, 17), IsVisible = false };
            StackPanel filetypeModulesContainer = new StackPanel() { Orientation = Avalonia.Layout.Orientation.Horizontal };
            filetypeModuleScrollViewer.Content = filetypeModulesContainer;
            contentPanel.Children.Add(filetypeModuleScrollViewer);

            CheckBox compileCode = new CheckBox() { VerticalContentAlignment = Avalonia.Layout.VerticalAlignment.Center, Content = "Compile and load source code", Margin = new Avalonia.Thickness(0, 5, 0, 0), IsVisible = false };
            contentPanel.Children.Add(compileCode);

            CheckBox storeKey = new CheckBox() { VerticalContentAlignment = Avalonia.Layout.VerticalAlignment.Center, Content = "Store public key", IsVisible = false };
            contentPanel.Children.Add(storeKey);

            Button continueButton = new Button() { Content = new TextBlock() { Text = "Continue", FontSize = 14, Foreground = Brushes.Black }, IsVisible = false, Margin = new Avalonia.Thickness(0, 5, 0, 0) };
            continueButton.Clreplacedes.Add("SideBarButton");
            contentPanel.Children.Add(continueButton);

            List<double> OpenPriorities = null;

            TextBlock loadFileModuleHeader = new TextBlock() { Text = "Load file module", FontSize = 20, Foreground = new SolidColorBrush(Color.FromRgb(0, 114, 178)), Margin = new Avalonia.Thickness(0, 5, 0, 0), IsVisible = false };
            contentPanel.Children.Add(loadFileModuleHeader);

            ScrollViewer loadFileModuleScrollViewer = new ScrollViewer() { HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto, VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled, AllowAutoHide = false, Padding = new Avalonia.Thickness(0, 0, 0, 17), IsVisible = false };
            StackPanel loadFileModulesContainer = new StackPanel() { Orientation = Avalonia.Layout.Orientation.Horizontal };
            loadFileModuleScrollViewer.Content = loadFileModulesContainer;
            contentPanel.Children.Add(loadFileModuleScrollViewer);

            Button finishButton = new Button() { Content = new TextBlock() { Text = "Finish", FontSize = 14, Foreground = Brushes.Black }, IsVisible = false };
            finishButton.Clreplacedes.Add("SideBarButton");
            contentPanel.Children.Add(finishButton);

            string currentFile = null;

            browseButton.Click += async (s, e) =>
            {
                OpenFileDialog dialog;

                List<FileDialogFilter> filters = new List<FileDialogFilter>();

                List<string> allExtensions = new List<string>();

                for (int i = 0; i < Modules.FileTypeModules.Count; i++)
                {
                    filters.Add(new FileDialogFilter() { Name = Modules.FileTypeModules[i].Extensions[0], Extensions = new List<string>(Modules.FileTypeModules[i].Extensions.Skip(1)) });
                    allExtensions.AddRange(Modules.FileTypeModules[i].Extensions.Skip(1));
                }

                filters.Insert(0, new FileDialogFilter() { Name = "All tree files", Extensions = allExtensions });
                filters.Add(new FileDialogFilter() { Name = "All files", Extensions = new List<string>() { "*" } });

                if (!Modules.IsMac)
                {
                    dialog = new OpenFileDialog()
                    {
                        replacedle = "Open tree file",
                        AllowMultiple = false,
                        Filters = filters
                    };
                }
                else
                {
                    dialog = new OpenFileDialog()
                    {
                        replacedle = "Open tree file",
                        AllowMultiple = false
                    };
                }

                string[] result = await dialog.ShowAsync(this.FindAncestorOfType<Window>());

                if (result != null && result.Length == 1)
                {
                    this.SelectedFileTypeModule = -1;

                    string fileName = System.IO.Path.GetFileName(result[0]);
                    string directoryName = System.IO.Path.GetDirectoryName(result[0]);

                    treeNameBlock.Text = fileName;
                    treePathBlock.Text = directoryName;

                    treeFilePanel.ColumnDefinitions[1].Width = new GridLength(1, GridUnitType.Star);

                    string extension = System.IO.Path.GetExtension(result[0]).ToLowerInvariant().Replace(".", "");

                    if (!FileExtensions.EmbeddedFileTypeIcons.Contains(extension))
                    {
                        extension = "tree";
                    }

                    iconContainer.Content = new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.FileTypeIcons." + extension)) { Width = 32, Height = 32 };

                    treeFileName.IsVisible = true;
                    iconContainer.IsVisible = true;

                    OpenPriorities = new List<double>();

                    for (int i = 0; i < Modules.FileTypeModules.Count; i++)
                    {
                        try
                        {
                            OpenPriorities.Add(Modules.FileTypeModules[i].IsSupported(result[0]));
                        }
                        catch
                        {
                            OpenPriorities.Add(0);
                        }
                    }

                    currentFile = result[0];

                    BuildFileTypeModuleList(filetypeModulesContainer, OpenPriorities);

                    fileTypeModuleHeader.IsVisible = true;
                    filetypeModuleScrollViewer.IsVisible = true;
                    compileCode.IsVisible = true;
                    storeKey.IsVisible = true;
                    compileCode.IreplacedTestVisible = true;
                    storeKey.IreplacedTestVisible = true;
                    loadFileModuleHeader.IsVisible = false;
                    loadFileModuleScrollViewer.IsVisible = false;
                    finishButton.IsVisible = false;
                }
            };

            this.PropertyChanged += (s, e) =>
            {
                if (e.Property == AdvancedOpenPage.SelectedFileTypeModuleProperty)
                {
                    if ((int)e.NewValue >= 0)
                    {
                        continueButton.IsVisible = true;
                    }
                    else
                    {
                        continueButton.IsVisible = false;
                    }
                }
                else if (e.Property == AdvancedOpenPage.SelectedLoadFileModuleProperty)
                {
                    if ((int)e.NewValue >= 0)
                    {
                        finishButton.IsVisible = true;
                    }
                    else
                    {
                        finishButton.IsVisible = false;
                    }
                }
            };

            System.IO.FileInfo OpenedFileInfo = null;
            Action<double> OpenerProgressAction = null;
            List<(string, Dictionary<string, object>)> ModuleSuggestions = null;
            IEnumerable<TreeNode> OpenedFile = null;

            continueButton.Click += async (s, e) =>
            {
                if (OpenPriorities[this.SelectedFileTypeModule] <= 0)
                {
                    MessageBox box = new MessageBox("Confirm action", "The file opener module has reported that it is not able to handle this file. Are you sure you wish to proceed using this module?", MessageBox.MessageBoxButtonTypes.YesNo);
                    await box.ShowDialog2(this.FindAncestorOfType<Window>());
                    if (box.Result != MessageBox.Results.Yes)
                    {
                        return;
                    }
                }

                try
                {
                    bool codePermissionGranted = compileCode.IsChecked == true;

                    bool addKeyPermissionGranted = storeKey.IsChecked == true;

                    bool askForCodePermission(RSAParameters? publicKey)
                    {
                        if (publicKey.HasValue && addKeyPermissionGranted)
                        {
                            CryptoUtils.AddPublicKey(publicKey.Value);
                        }

                        return codePermissionGranted;
                    };

                    ModuleSuggestions = new List<(string, Dictionary<string, object>)>()
                    {
                        ("32914d41-b182-461e-b7c6-5f0263cc1ccd", new Dictionary<string, object>()),
                        ("68e25ec6-5911-4741-8547-317597e1b792", new Dictionary<string, object>()),
                    };

                    OpenerProgressAction = (_) => { };

                    OpenedFile = Modules.FileTypeModules[this.SelectedFileTypeModule].OpenFile(currentFile, ModuleSuggestions, (val) => { OpenerProgressAction(val); }, askForCodePermission);

                    OpenedFileInfo = new System.IO.FileInfo(currentFile);

                    string OpenerModuleId = Modules.FileTypeModules[SelectedFileTypeModule].Id;

                    List<double> LoadPriorities = new List<double>();

                    for (int i = 0; i < Modules.LoadFileModules.Count; i++)
                    {
                        try
                        {
                            LoadPriorities.Add(Modules.LoadFileModules[i].IsSupported(OpenedFileInfo, OpenerModuleId, OpenedFile));
                        }
                        catch
                        {
                            LoadPriorities.Add(0);
                        }
                    }

                    BuildLoadFileModules(loadFileModulesContainer, LoadPriorities);
                }
                catch (Exception ex)
                {
                    await new MessageBox("Error!", "An error has occurred while opening the file!\n" + ex.Message).ShowDialog2(this.FindAncestorOfType<Window>());
                    return;
                }


                continueButton.IsVisible = false;
                for (int i = 0; i < FileTypeModuleButtons.Count; i++)
                {
                    FileTypeModuleButtons[i].IsEnabled = false;
                }
                compileCode.IreplacedTestVisible = false;
                storeKey.IreplacedTestVisible = false;

                loadFileModuleHeader.IsVisible = true;
                loadFileModuleScrollViewer.IsVisible = true;


            };

            finishButton.Click += async (s, e) =>
            {
                try
                {
                    EventWaitHandle progressWindowHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
                    ProgressWindow progressWin = new ProgressWindow(progressWindowHandle) { ProgressText = "Opening and loading file..." };
                    Action<double> progressAction = (progress) =>
                    {
                        if (progress >= 0)
                        {
                            Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() =>
                            {
                                progressWin.IsIndeterminate = false;
                                progressWin.Progress = progress;
                            });
                        }
                        else
                        {
                            Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() =>
                            {
                                progressWin.IsIndeterminate = true;
                            });
                        }
                    };

                    TreeCollection LoadedTrees = null;

                    MainWindow parent = this.FindAncestorOfType<MainWindow>();
                    int sftm = this.SelectedFileTypeModule;
                    int slfm = this.SelectedLoadFileModule;

                    SemapreplacedSlim semapreplaced = new SemapreplacedSlim(0, 1);

                    Thread thr = new Thread(() =>
                    {
                        LoadedTrees = Modules.LoadFileModules[slfm].Load(parent, OpenedFileInfo, Modules.FileTypeModules[sftm].Id, OpenedFile, ModuleSuggestions, ref OpenerProgressAction, progressAction);

                        semapreplaced.Release();
                    });

                    thr.Start();

                    _ = progressWin.ShowDialog2(parent);

                    await semapreplaced.WaitAsync();
                    semapreplaced.Release();
                    semapreplaced.Dispose();

                    if (LoadedTrees != null)
                    {

                        if (parent.Trees == null)
                        {
                            parent.Trees = LoadedTrees;
                            parent.FileOpened(ModuleSuggestions, currentFile, progressWin);

                            if (!string.IsNullOrEmpty(currentFile))
                            {
                                parent.replacedle = "TreeViewer - " + System.IO.Path.GetFileName(currentFile);
                                parent.OriginalFileName = currentFile;
                            }
                        }
                        else
                        {
                            progressWin.Close();
                            MainWindow win2 = new MainWindow(LoadedTrees, ModuleSuggestions, currentFile);
                            win2.Show();
                        }
                    }
                    else
                    {
                        progressWin.Close();
                    }

                    this.Reset();
                }
                catch (Exception ex)
                {
                    await new MessageBox("Error!", "An error has occurred while loading the trees!\n" + ex.Message).ShowDialog2(this.FindAncestorOfType<Window>());
                }
            };

            this.Reset = () =>
            {
                continueButton.IsVisible = false;
                filetypeModuleScrollViewer.IsVisible = false;
                compileCode.IsVisible = false;
                storeKey.IsVisible = false;
                loadFileModuleHeader.IsVisible = false;
                loadFileModuleScrollViewer.IsVisible = false;
                finishButton.IsVisible = false;
                fileTypeModuleHeader.IsVisible = false;
                treeFileName.IsVisible = false;
                iconContainer.IsVisible = false;
                treeFilePanel.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Auto);
                this.SelectedFileTypeModule = -1;
                this.SelectedLoadFileModule = -1;
            };

            this.AttachedToVisualTree += (s, e) =>
            {
                this.FindAncestorOfType<RibbonFilePage>().PropertyChanged += (s, e) =>
                {
                    if (e.Property == RibbonFilePage.IsVisibleProperty)
                    {
                        if ((bool)e.NewValue)
                        {
                            this.Reset?.Invoke();
                        }
                    }
                };
            };
        }

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

internal static void LoadFile(string moduleId)
        {
            if (string.IsNullOrEmpty(moduleId))
            {
                Dictionary<string, double> priorities = GetLoadInfo();
                KeyValuePair<string, double> bestModule = (from el in priorities orderby el.Value descending select el).FirstOrDefault();
                if (bestModule.Value == 0)
                {
                    ConsoleWrapper.WriteLine();
                    ConsoleWrapper.WriteLine(new ConsoleTextSpan("The file is not supported by any of the currently installed modules!", ConsoleColor.Red));
                    ConsoleWrapper.WriteLine();
                    return;
                }
                moduleId = bestModule.Key;
            }

            TreeCollection coll;

            List<(string, Dictionary<string, object>)> moduleSuggestions = Program.ModuleSuggestions;

            Action<double> progressAction = (_) => { };

            coll = Modules.GetModule(Modules.LoadFileModules, moduleId).Load(null, Program.OpenedFileInfo, Program.OpenerModuleId, Program.FileOpener, moduleSuggestions, ref progressAction, (val) => { progressAction(val); });

            Program.Trees = coll;
            Program.LoaderModuleId = moduleId;

            Program.TransformerModuleId = null;
            Program.TransformerParameters = null;
            Program.FurtherTransformations.Clear();
            Program.CoordinatesModuleId = null;
            Program.CoordinatesParameters = null;
            Program.PlotActions.Clear();

            ConsoleWrapper.WriteLine();
            ConsoleWrapper.WriteLine(new ConsoleTextSpan("  Suggested modules:", 2));
            ConsoleWrapper.WriteLine();

            for (int i = 0; i < moduleSuggestions.Count; i++)
            {
                if (moduleSuggestions[i].Item1 != "@Background" && moduleSuggestions[i].Item1 != "@Attachment")
                {
                    ConsoleWrapper.WriteLine(new ConsoleTextSpan[]
                    {
                    new ConsoleTextSpan("    " + Modules.LoadedModulesMetadata[moduleSuggestions[i].Item1].Name, 4, ConsoleColor.Cyan),
                    new ConsoleTextSpan(" (" + moduleSuggestions[i].Item1 + ")", 4),
                    });
                }

            }

            ConsoleWrapper.WriteLine();
            ConsoleWrapper.Write(new ConsoleTextSpan("  Would you like to load the suggested modules? [Y(es)/N(o)] ", 2));


            char key = '?';

            while (key != 'y' && key != 'Y' && key != 'n' && key != 'N')
            {
                key = ConsoleWrapper.ReadKey(true).KeyChar;
            }

            ConsoleWrapper.Write(key);
            ConsoleWrapper.WriteLine();

            bool loadModules = false;

            if (key == 'y' || key == 'Y')
            {
                loadModules = true;
            }
            else if (key == 'n' || key == 'N')
            {
                loadModules = false;
            }



            if (loadModules)
            {
                for (int i = 0; i < moduleSuggestions.Count; i++)
                {
                    if (moduleSuggestions[i].Item1 == "@Attachment")
                    {
                        Attachment att = (Attachment)moduleSuggestions[i].Item2["Attachment"];
                        Program.StateData.Attachments.Add(att.Name, att);
                    }
                }

                for (int i = 0; i < moduleSuggestions.Count; i++)
                {
                    MainWindow.UpdateAttachmentLinks(moduleSuggestions[i].Item2, Program.StateData);
                }

                for (int i = 0; i < moduleSuggestions.Count; i++)
                {
                    if (moduleSuggestions[i].Item1 == "@Background")
                    {
                        Program.StateData.GraphBackgroundColour = (VectSharp.Colour)moduleSuggestions[i].Item2["Colour"];
                    }
                    else if (moduleSuggestions[i].Item1 != "@Attachment")
                    {
                        ModuleCommand.EnableModule(Modules.LoadedModulesMetadata[moduleSuggestions[i].Item1], -1, moduleSuggestions[i].Item2);
                        if (i == 0)
                        {
                            UpdateCommand.UpdateTransformer();
                            UpdateCommand.UpdateFurtherTransformations();
                        }

                        if (Modules.LoadedModulesMetadata[moduleSuggestions[i].Item1].ModuleType == ModuleTypes.FurtherTransformation)
                        {
                            UpdateCommand.UpdateFurtherTransformations(Program.FurtherTransformations.Count - 1);
                        }
                        else if (Modules.LoadedModulesMetadata[moduleSuggestions[i].Item1].ModuleType == ModuleTypes.Coordinate)
                        {
                            UpdateCommand.UpdateCoordinates();
                        }

                    }
                }
            }

        }

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

public static void CopyToWithProgress(this System.IO.Stream source, System.IO.Stream destination, Action<double> progressAction = null, int bufferSize = 81920)
        {
            byte[] buffer = new byte[bufferSize];
            int read;
            double length = source.Length;
            while ((read = source.Read(buffer, 0, buffer.Length)) != 0)
            {
                destination.Write(buffer, 0, read);
                double progress = Math.Max(0, Math.Min(1, source.Position / length));
                progressAction?.Invoke(progress);
            }

        }

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

public static IEnumerable<TreeNode> OpenFile(string fileName, List<(string, Dictionary<string, object>)> moduleSuggestions, Action<double> progressAction, Func<RSAParameters?, bool> askForCodePermission)
        {
            progressAction(0);

            // TODO: read and parse trees from the file.
            //
            // Return individual trees like this:
            //       yield return tree;

            progressAction(1);

            yield break;
        }

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

internal static void OpenFile(string fileName, string moduleId)
        {
            if (string.IsNullOrEmpty(moduleId))
            {
                Dictionary<string, double> priorities = GetOpenInfo(fileName);
                KeyValuePair<string, double> bestModule = (from el in priorities orderby el.Value descending select el).FirstOrDefault();
                if (bestModule.Value == 0)
                {
                    ConsoleWrapper.WriteLine();
                    ConsoleWrapper.WriteLine(new ConsoleTextSpan("The file type is not supported by any of the currently installed modules!", ConsoleColor.Red));
                    ConsoleWrapper.WriteLine();
                    return;
                }
                moduleId = bestModule.Key;
            }

            IEnumerable<TreeNode> opener;

            List<(string, Dictionary<string, object>)> moduleSuggestions = new List<(string, Dictionary<string, object>)>()
            {
                ("32914d41-b182-461e-b7c6-5f0263cc1ccd", new Dictionary<string, object>()),
                ("68e25ec6-5911-4741-8547-317597e1b792", new Dictionary<string, object>()),
            };

            Action<double> openerProgressAction = (_) => { };

            bool? codePermissionGranted = null;

            bool askForCodePermission(RSAParameters? publicKey)
            {
                if (codePermissionGranted.HasValue)
                {
                    return codePermissionGranted.Value;
                }
                else
                {
                    ConsoleWrapper.Write(new ConsoleTextSpan[]
                    {
                        new ConsoleTextSpan("Attention! The selected file contains source code and its signature does not match any known keys. Do you want to load and compile it? You should only do this if you trust the source of the file and/or you have accurately reviewed the code. [Y(es)/N(o)] ", ConsoleColor.Yellow)
                    });

                    char key = '?';

                    while (key != 'y' && key != 'Y' && key != 'n' && key != 'N')
                    {
                        key = ConsoleWrapper.ReadKey(true).KeyChar;
                    }

                    ConsoleWrapper.Write(key);
                    ConsoleWrapper.WriteLine();

                    if (key == 'y' || key == 'Y')
                    {
                        codePermissionGranted = true;

                        if (publicKey.HasValue)
                        {
                            ConsoleWrapper.Write(new ConsoleTextSpan[]
                            {
                                new ConsoleTextSpan("Would you like to add the file's public key to the local storage? This will allow you to open other files produced by the same author without seeing this message. You should only do this if you trust the source of the file. [Y(es)/N(o)] ", ConsoleColor.Yellow)
                            });

                            char key2 = '?';

                            while (key2 != 'y' && key2 != 'Y' && key2 != 'n' && key2 != 'N')
                            {
                                key2 = ConsoleWrapper.ReadKey(true).KeyChar;
                            }

                            ConsoleWrapper.Write(key2);
                            ConsoleWrapper.WriteLine();

                            if (key2 == 'y' || key2 == 'Y')
                            {
                                TreeViewer.CryptoUtils.AddPublicKey(publicKey.Value);
                            }
                        }

                        return true;
                    }
                    else if (key == 'n' || key == 'N')
                    {
                        codePermissionGranted = false;
                        return false;
                    }
                    else
                    {
                        return false;
                    }
                }
            };

            opener = Modules.GetModule(Modules.FileTypeModules, moduleId).OpenFile(fileName, moduleSuggestions, (val) => { openerProgressAction(val); }, askForCodePermission);

            FileInfo finfo = new FileInfo(fileName);

            Program.FileOpener = opener;
            Program.OpenedFileInfo = finfo;
            Program.ModuleSuggestions = moduleSuggestions;
            Program.OpenerModuleId = moduleId;

        }

19 Source : AnchorManager.cs
with MIT License
from ARUnityBook

public void EarlyUpdate()
        {
            _SetNewTrackingState(Frame.TrackingState, SessionManager.Instance.MotionTrackingManager.IsLocalized);

            const string POSE_HISTORY_EVENT_KEY = "EXPERIMENTAL_PoseHistoryChanged";
            double earliestTimestamp = double.MaxValue;
            for (int i = 0; i < SessionManager.Instance.TangoEvents.Count; i++)
            {
                var tangoEvent = SessionManager.Instance.TangoEvents[i];
                if (tangoEvent.key == POSE_HISTORY_EVENT_KEY && double.Parse(tangoEvent.value) < earliestTimestamp)
                {
                    earliestTimestamp = double.Parse(tangoEvent.value);
                }
            }

            // Update the pose of anchors.
            if (earliestTimestamp < double.MaxValue)
            {
                for (int i = 0; i < m_anchors.Count; i++)
                {
                    m_anchors[i].m_updateTracking(earliestTimestamp);
                }

                for (int i = 0;  i < m_nonLocalizedAnchors.Count; i++)
                {
                    m_nonLocalizedAnchors[i].m_updateTracking(earliestTimestamp);
                }
            }
        }

19 Source : SliderUIAttributes.cs
with MIT License
from arup-group

protected override void Layout()
        {
            base.Layout();

            // first change the width to suit; using max to determine component visualisation style
            FixLayout();

            int s = 2; // spacing to edges and internal between boxes

            // create bound for spacer and replacedle
            int h0 = 0; // height of spacer bound
            if (SpacerTxt != "")
            {
                h0 = 10;
                SpacerBounds = new RectangleF(Bounds.X, Bounds.Bottom + s / 2, Bounds.Width, h0);
            }

            int hslider = 15; // height of bound for slider
            int bhslider = 10; // height and width of grab

            // create overall bound for slider
            SliderBound = new RectangleF(Bounds.X + 2 * s, Bounds.Bottom + h0 + 2 * s, Bounds.Width - 2 - 4 * s, hslider);

            // slider grab 
            GrabBound = new RectangleF(SliderBound.X + deltaX + scrollStartX, SliderBound.Y + SliderBound.Height / 2 - bhslider / 2, bhslider, bhslider);

            // round current value for snapping
            CurrentValue = Math.Round(CurrentValue, noDigits);
            double dragPercentage;

            // when component is initiated or value range is changed
            // calculate position of grab
            if (first)
            {
                dragPercentage = (CurrentValue - MinValue) / (MaxValue - MinValue);
                scrollStartX = (float)(dragPercentage * (SliderBound.Width - GrabBound.Width));
                first = false;
            }

            // horizontal position (.X)
            if (deltaX + scrollStartX >= 0) // handle if user drags left of starting point
            {
                // dragging right-wards:
                if (SliderBound.Width - GrabBound.Width >= deltaX + scrollStartX) // handles if user drags below bottom point
                {
                    // update scroll bar position for normal scroll event within bounds
                    dragPercentage = (deltaX + scrollStartX) / (SliderBound.Width - GrabBound.Width);
                    CurrentValue = Math.Round(MinValue + dragPercentage * (MaxValue - MinValue), noDigits);
                    dragPercentage = (CurrentValue - MinValue) / (MaxValue - MinValue);
                }
                else
                {
                    // scroll reached end
                    dragPercentage = 1;
                    scrollStartX = SliderBound.Width - GrabBound.Width;
                    deltaX = 0;
                    CurrentValue = MaxValue;
                }
            }
            else
            {
                // scroll reached start
                dragPercentage = 0;
                scrollStartX = 0;
                deltaX = 0;
                CurrentValue = MinValue;
            }

            // set grab item position with snap
            GrabBound.X = SliderBound.X + (float)(dragPercentage * (SliderBound.Width - GrabBound.Width));

            // return new current value to component
            ReturnSliderValue(CurrentValue);

            // text box for value display

            if (CurrentValue < (MaxValue - MinValue) / 2) // we are in the left half of the range
                SliderValTextBound = new RectangleF(GrabBound.X + GrabBound.Width, SliderBound.Y, SliderBound.X + SliderBound.Width - GrabBound.X + GrabBound.Width, SliderBound.Height);
            else // we are in the right half of the range
                SliderValTextBound = new RectangleF(SliderBound.X, SliderBound.Y, GrabBound.X - SliderBound.X, SliderBound.Height);

            //update component bounds
            Bounds = new RectangleF(Bounds.X, Bounds.Y, Bounds.Width, Bounds.Height + h0 + hslider + 4 * s);

        }

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 : FFmpeg.cs
with GNU General Public License v3.0
from audiamus

private void ffMpegAsyncHandlerTranscode (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 ());

      var t = AudioMeta.Time;

      Match matchErr = _rgxErrorVarious.Match (outLine.Data);
      if (matchErr.Success)
        _error = true;

      Match matchTs = _rgxTimestamp1.Match (outLine.Data);
      if (!matchTs.Success)
        matchTs = _rgxTimestamp2.Match (outLine.Data);
      if (!matchTs.Success) {

        if (!_matchedDuration) {
          Match matchDur = _rgxDuration.Match (outLine.Data);
          if (matchDur.Success) {
            _matchedDuration = true;
            TimeSpan duration = tryParseTimestamp (matchDur);
            if (t.Begin == TimeSpan.Zero)
              t.Duration = duration;
            else
              t.Duration = duration - t.Begin;
            return;
          }
        } else {
          Match matchFinal = _rgxMuxFinal.Match (outLine.Data);
          if (matchFinal.Success) {
            // HACK test only
            //_error = true;
            _success = true;
          } 
        }
      }


      if (!matchTs.Success)
        return;

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

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

#if TRACE && EXTRA
      Trace.WriteLine ($"{this.GetType ().Name}.{nameof (ffMpegAsyncHandlerTranscode)} {ts.TotalSeconds:f0}/{t.Duration.TotalSeconds:f0}");
#endif
      Log (4, this, () => ID + $"{ts.TotalSeconds:f0}/{t.Duration.TotalSeconds:f0}");

      Progress?.Invoke (progress);


    }

19 Source : DetailsRow.razor.cs
with MIT License
from BlazorFluentUI

protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (baseModule == null)
            {
                baseModule = await JSRuntime!.InvokeAsync<IJSObjectReference>("import", BasePath);
            }

            if (firstRender)
            {
                await OnRowDidMount.InvokeAsync(this);
            }

            try
            {
                if (columnMeasureInfo != null && columnMeasureInfo.Index >= 0 && cellMeasurer.Id != null)
                {
                    Action<double>? method = columnMeasureInfo.OnMeasureDone;
                    Rectangle? size = await baseModule.InvokeAsync<Rectangle>("measureElementRect", cancellationTokenSource.Token, cellMeasurer);
                    method?.Invoke(size.Width);
                    columnMeasureInfo = null;
                    Debug.WriteLine($"rerendering {ItemIndex} because of column measurement");
                    await InvokeAsync(StateHasChanged);
                }
            }
            catch (Exception)
            {

            }

            await base.OnAfterRenderAsync(firstRender);
        }

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

void OnValueChanged(double value)
        {
            ValueChanged?.Invoke(value);
        }

19 Source : Trackhead.cs
with MIT License
from chstetco

protected override bool MouseDrag(Event evt, WindowState state)
        {
            if (!m_IsCaptured)
                return false;

            m_OnMouseDrag(state.GetSnappedTimeAtMousePosition(evt.mousePosition));

            return true;
        }

19 Source : ExcelCalcWrapper.cs
with MIT License
from cmdty

private void UpdateProgress(double progress)
        {
            // TODO some sort of synchonisation needed? Look online.
            Progress = progress;
            OnProgressUpdate?.Invoke(progress);
        }

19 Source : JsonReadOptionalUtils.cs
with MIT License
from colgreen

public static void ReadDoubleOptional(
            JsonElement jelem,
            string propertyName,
            Action<double> setter)
        {
            if(jelem.TryGetProperty(propertyName, out JsonElement propElem)) {
                setter(propElem.GetDouble());
            }
        }

19 Source : IntroductionScreenPanelViewModel.cs
with GNU General Public License v3.0
from d2dyno1

private void UpdateTwoHalfProgress(int index, int count, params Action<double>[] progress)
        {
            int progressIndex = 0;
            int progressCount = progress.Count();
            bool progressHalf = false;

            // Fill
            for (int i = 0; i < count; i++)
            {
                if (i <= index)
                {
                    if (!progressHalf)
                    {
                        progress[progressIndex](50.0d);
                        progressHalf = true;
                    }
                    else
                    {
                        progress[progressIndex](100.0d);
                        progressHalf = false;
                        progressIndex++;
                    }
                }
                else
                {
                    if (!progressHalf)
                    {
                        // Unfill
                        progress[progressIndex](0.0d);
                        progressHalf = true;
                    }
                    else
                    {
                        progressHalf = false;
                        progressIndex++;
                    }
                }
            }
        }

19 Source : MusicManagerIOS.cs
with MIT License
from DanielCKennedy

public void Play()
        {
            System.Diagnostics.Debug.WriteLine("Play()");
            if (_player != null)
            {
                _player.Play();

                Task.Run(() =>
                {
                    while (_player.Rate != 0 && _player.Error == null)
                    {
                        var seconds = _player.CurrentTime.Seconds;
                        _getPosition(_player.CurrentTime.Seconds);
                        Thread.Sleep(250);
                    }
                });
            }
            _isPlaying?.Invoke(_player != null && _player.Rate != 0 && _player.Error == null);
            UpdateInfoCenter();
        }

19 Source : AudioService.cs
with MIT License
from DanielCKennedy

public void Play()
        {
            System.Diagnostics.Debug.WriteLine("Play()");
            if (_player != null && !_isPreparing && !_player.IsPlaying)
            {
                _player.Start();
                UpdatePlaybackState(PlaybackStateCompat.StatePlaying);
                StartNotification();
                UpdateMediaMetadataCompat();

                Task.Run(() =>
                {
                    _playing = true;
                    while (_playing && !_isPreparing)
                    {
                        double sPos = _player.CurrentPosition / 1000;
                        _getPosition(_player.CurrentPosition / 1000);
                        Thread.Sleep(250);
                    }
                });
            }
            _isPlaying?.Invoke((bool)_player?.IsPlaying);
            UpdatePlaybackState(PlaybackStateCompat.StatePlaying);
        }

19 Source : AudioService.cs
with MIT License
from DanielCKennedy

public void OnSeekComplete(MediaPlayer mp)
        {
            _getPosition(mp.CurrentPosition / 1000);
        }

19 Source : MetricsAssertValid.cs
with Apache License 2.0
from elastic

internal static void replacedertValid(MetricSetDto metricSet)
		{
			metricSet.Should().NotBeNull();

			foreach (var metricSample in metricSet.Samples)
			{
				//GC metrics are only captured when at least 1 GC happens during the test - so we don't replacedert on those.
				if (metricSample.Key.Contains("clr.gc", StringComparison.CurrentCultureIgnoreCase))
					continue;

				MetricMetadataPerType.Should().ContainKey(metricSample.Key);
				MetricMetadataPerType[metricSample.Key].VerifyAction(metricSample.Value.Value);
			}
		}

19 Source : FileGeneratorHelper.cs
with GNU General Public License v3.0
from fdonnet

public static async Task WriteSqlScriptsFileAsync(TSqlModel model, GeneratorSettings generatorSettings, Action<double> progressHandler = null)
        {
            var fileName = generatorSettings.OutputPath_SqlScripts;
            var tables = model.GetAllTables().ToDictionary(currTable => currTable.Name.Parts[1].ToLower());
            double progress = 0.0;

            var fileStream = File.Open(fileName, FileMode.Create, FileAccess.Write);
            var bufferSize = 5 * 1024 * 1024; // 5 MB
            using (StreamWriter writer = new StreamWriter(fileStream, Encoding.UTF8, bufferSize))
            {
                // Flush stream after every table loop, manually
                writer.AutoFlush = false;

                // Loop only on selected tables, or on every table in model if GenerateForAllTables == true
                IEnumerable<string> tableNames;
                if (generatorSettings.RunGeneratorForAllTables)
                    tableNames = tables.Keys;
                else
                    tableNames = (IEnumerable<string>)generatorSettings.RunGeneratorForSelectedTables ?? new string[0];

                var tablesCount = tableNames.Count();

                foreach (var currTableName in tableNames)
                {
                    string sql = "";
                    var currTable = tables.ContainsKey(currTableName.ToLower()) ? tables[currTableName.ToLower()] : null;

                    if (currTable != null)
                    {
                        sql = new SqlInsertGenerator(generatorSettings, currTable).Generate();
                        if (sql != string.Empty) writer.WriteLine(sql);
                        sql = new SqlTableTypeGenerator(generatorSettings, currTable).Generate();
                        if (sql != string.Empty) writer.WriteLine(sql);
                        sql = new SqlBulkInsertGenerator(generatorSettings, currTable).Generate();
                        if (sql != string.Empty) writer.WriteLine(sql);
                        sql = new SqlBulkUpdateGenerator(generatorSettings, currTable).Generate();
                        if (sql != string.Empty) writer.WriteLine(sql);
                        sql = new SqlUpdateGenerator(generatorSettings, currTable).Generate();
                        if (sql != string.Empty) writer.WriteLine(sql);
                        sql = new SqlDeleteGenerator(generatorSettings, currTable).Generate();
                        if (sql != string.Empty) writer.WriteLine(sql);
                        sql = new SqlSelectAllGenerator(generatorSettings, currTable).Generate();
                        if (sql != string.Empty) writer.WriteLine(sql);
                        sql = new SqlSelectByPKGenerator(generatorSettings, currTable).Generate();
                        if (sql != string.Empty) writer.WriteLine(sql);
                        sql = new SqlSelectByPKListGenerator(generatorSettings, currTable).Generate();
                        if (sql != string.Empty) writer.WriteLine(sql);
                        sql = new SqlSelectByUKGenerator(generatorSettings, currTable).Generate();
                        if (sql != string.Empty) writer.WriteLine(sql);

                        await writer.FlushAsync();
                        progress += 100.0 / tablesCount;
                        progressHandler?.Invoke((int)progress);
                    }
                }
            }

            return;
        }

19 Source : FileGeneratorHelper.cs
with GNU General Public License v3.0
from fdonnet

public static async Task WriteCsEnreplacedyClreplacedesFileAsync(TSqlModel model, GeneratorSettings generatorSettings, Action<double> progressHandler = null)
        {
            var fileName = generatorSettings.OutputPath_CsEnreplacedyClreplacedes;
            var tables = model.GetAllTables().ToDictionary(currTable => currTable.Name.Parts[1].ToLower());
            double progress = 0.0;

            var fileStream = File.Open(fileName, FileMode.Create, FileAccess.Write);
            var bufferSize = 5 * 1024 * 1024; // 5 MB
            using (StreamWriter writer = new StreamWriter(fileStream, Encoding.UTF8, bufferSize))
            {
                // Flush stream after every table loop, manually
                writer.AutoFlush = false;

                // Loop only on selected tables, or on every table in model if GenerateForAllTables == true
                IEnumerable<string> tableNames;
                if (generatorSettings.RunGeneratorForAllTables)
                    tableNames = tables.Keys;
                else
                    tableNames = (IEnumerable<string>)generatorSettings.RunGeneratorForSelectedTables ?? new string[0];

                var tablesCount = tableNames.Count();

                foreach (var currTableName in tableNames)
                {
                    string cs = "";
                    var currTable = tables.ContainsKey(currTableName.ToLower()) ? tables[currTableName.ToLower()] : null;

                    if (currTable != null)
                    {
                        cs = new CsEnreplacedyClreplacedGenerator(generatorSettings, currTable).Generate();
                        if (cs != string.Empty) writer.WriteLine(cs);

                        await writer.FlushAsync();
                        progress += 100.0 / tablesCount;
                        progressHandler?.Invoke((int)progress);
                    }
                }
            }

            return;
        }

19 Source : FileGeneratorHelper.cs
with GNU General Public License v3.0
from fdonnet

public static async Task WriteCsRepositoryClreplacedesFileAsync(TSqlModel model, GeneratorSettings generatorSettings, Action<double> progressHandler = null)
        {
            var fileName = generatorSettings.OutputPath_CsRepositoryClreplacedes;
            var tables = model.GetAllTables().ToDictionary(currTable => currTable.Name.Parts[1].ToLower());
            double progress = 0.0;

            var fileStream = File.Open(fileName, FileMode.Create, FileAccess.Write);
            var bufferSize = 5 * 1024 * 1024; // 5 MB
            using (StreamWriter writer = new StreamWriter(fileStream, Encoding.UTF8, bufferSize))
            {
                // Flush stream after every table
                writer.AutoFlush = false;

                string cs = "";

                // Loop only on selected tables, or on every table in model if GenerateForAllTables == true
                IEnumerable<string> tableNames;
                if (generatorSettings.RunGeneratorForAllTables)
                    tableNames = tables.Keys;
                else
                    tableNames = (IEnumerable<string>)generatorSettings.RunGeneratorForSelectedTables ?? new string[0];

                var tablesCount = tableNames.Count();

                cs = new CsDbContextGenerator(generatorSettings, model).Generate();
                writer.WriteLine(cs);
                await writer.FlushAsync();

                foreach (var currTableName in tableNames)
                {
                    var currTable = tables.ContainsKey(currTableName.ToLower()) ? tables[currTableName.ToLower()] : null;

                    if (currTable != null)
                    {
                        cs = new CsRepositoryClreplacedGenerator(generatorSettings, currTable).Generate();
                        if (cs != string.Empty) writer.WriteLine(cs);

                        await writer.FlushAsync();
                        progress += 100.0 / tablesCount;
                        progressHandler?.Invoke((int)progress);
                    }
                }
            }

            return;
        }

19 Source : Installer.cs
with GNU General Public License v3.0
from fifty-six

private static async Task<(byte[] data, string filename)> DownloadFile(string uri, Action<double> setProgress)
        {
            var dl = new WebClient();

            setProgress(0);

            dl.DownloadProgressChanged += (_, args) =>
            {
                if (args.TotalBytesToReceive < 0)
                {
                    setProgress(-1);

                    return;
                }

                setProgress(100 * args.BytesReceived / (double) args.TotalBytesToReceive);
            };

            byte[] data = await dl.DownloadDataTaskAsync(new Uri(uri));

            string filename = string.Empty;

            if (!string.IsNullOrEmpty(dl.ResponseHeaders?["Content-Disposition"]))
            {
                var disposition = new ContentDisposition(dl.ResponseHeaders["Content-Disposition"] ?? throw new InvalidOperationException());

                filename = disposition.FileName ?? throw new InvalidOperationException();
            }

            if (string.IsNullOrEmpty(filename))
            {
                filename = uri[(uri.LastIndexOf("/") + 1)..];
            }

            return (data, filename);
        }

19 Source : FlightGaugeViewModel.cs
with MIT License
from Foglio1024

private void OnPlayerChangeFlightEnergy(S_PLAYER_CHANGE_FLIGHT_ENERGY m)
        {
            EnergyChanged?.Invoke(m.Energy);
        }

19 Source : ClockRateIndicatorControlReceptor.cs
with GNU General Public License v3.0
from Game4all

public bool OnPressed(KeyBindingPressEvent<GamebosuAction> action)
        {
            switch (action.Action)
            {
                case GamebosuAction.ButtonIncrementClockRate:
                    AdjustAction(0.1);
                    return true;

                case GamebosuAction.ButtonDecrementClockRate:
                    AdjustAction(-0.1);
                    return true;

                default:
                    return false;
            }
        }

19 Source : ProgressBar.cs
with MIT License
from hornyyy

protected override void OnUserChange(double value) => OnSeek?.Invoke(value);

19 Source : SongProgressBar.cs
with MIT License
from hornyyy

protected override void OnUserChange(double value)
        {
            scheduledSeek?.Cancel();
            scheduledSeek = Schedule(() =>
            {
                if (showHandle)
                    OnSeek?.Invoke(value);
            });
        }

See More Examples