public void TestAddRange()
 {
     var list = new List<string> { "aaa", "bbb", "ccc" };
     var set = new ObservableList<string>(list);
     Assert.AreEqual(set.Count, list.Count);
     bool propertyChangedInvoked = false;
     bool collectionChangedInvoked = false;
     set.PropertyChanged += (sender, e) =>
     {
         Assert.AreEqual(e.PropertyName, nameof(ObservableList<string>.Count));
         propertyChangedInvoked = true;
     };
     set.CollectionChanged += (sender, e) =>
     {
         Assert.AreEqual(e.Action, NotifyCollectionChangedAction.Add);
         Assert.AreEqual(e.NewStartingIndex, 3);
         Assert.NotNull(e.NewItems);
         Assert.AreEqual(e.NewItems.Count, 2);
         Assert.AreEqual(e.NewItems[0], "ddd");
         Assert.AreEqual(e.NewItems[1], "eee");
         collectionChangedInvoked = true;
     };
     set.AddRange(new[] { "ddd", "eee" });
     Assert.AreEqual(set.Count, 5);
     Assert.AreEqual(set[0], "aaa");
     Assert.AreEqual(set[1], "bbb");
     Assert.AreEqual(set[2], "ccc");
     Assert.AreEqual(set[3], "ddd");
     Assert.AreEqual(set[4], "eee");
     Assert.True(propertyChangedInvoked);
     Assert.True(collectionChangedInvoked);
 }
Exemple #2
0
        public Morpher(ITraceManager traceManager, Language lang)
        {
            _lang           = lang;
            _traceManager   = traceManager;
            _allomorphTries = new Dictionary <Stratum, RootAllomorphTrie>();
            var morphemes = new ObservableList <Morpheme>();

            foreach (Stratum stratum in _lang.Strata)
            {
                var allomorphs = new HashSet <RootAllomorph>(stratum.Entries.SelectMany(entry => entry.Allomorphs));
                var trie       = new RootAllomorphTrie(ann => ann.Type() == HCFeatureSystem.Segment);
                foreach (RootAllomorph allomorph in allomorphs)
                {
                    trie.Add(allomorph);
                }
                _allomorphTries[stratum] = trie;

                morphemes.AddRange(stratum.Entries);
                morphemes.AddRange(stratum.MorphologicalRules.OfType <AffixProcessRule>());
                morphemes.AddRange(stratum.AffixTemplates.SelectMany(t => t.Slots).SelectMany(s => s.Rules).Distinct());
            }
            _analysisRule    = lang.CompileAnalysisRule(this);
            _synthesisRule   = lang.CompileSynthesisRule(this);
            MaxStemCount     = 2;
            LexEntrySelector = entry => true;
            RuleSelector     = rule => true;

            _morphemes = new ReadOnlyObservableCollection <Morpheme>(morphemes);
        }
Exemple #3
0
        public ItemsListSample()
        {
            var obsList = new ObservableList <IComponent>();

            var vs = VisibilitySensor((v) =>
            {
                obsList.Remove(v);
                obsList.AddRange(GetSomeItems(20));
                v.Reset();
                obsList.Add(v);
            });

            obsList.AddRange(GetSomeItems(10));
            obsList.Add(vs);
            _content = SectionStack().WidthStretch()
                       .Title(SampleHeader(nameof(ItemsListSample)))
                       .Section(
                Stack()
                .Children(
                    SampleTitle("Overview"),
                    TextBlock("List provides a base component for rendering small sets of items. " +
                              "It is agnostic of the tile component used, and selection " +
                              "management. These concerns can be layered separately.")
                    .PaddingBottom(16.px()),
                    TextBlock("Performance is adequate for smaller lists, for large number of items use VirtualizedList.")
                    .PaddingBottom(16.px())))
                       .Section(
                Stack()
                .Children(
                    SampleTitle("Usage"),
                    TextBlock("Basic List")
                    .Medium()
                    .PaddingBottom(16.px()),
                    ItemsList(GetSomeItems(10)).PaddingBottom(16.px()).Height(500.px()).PaddingBottom(32.px()),
                    TextBlock("Basic List with columns")
                    .Medium()
                    .PaddingBottom(16.px()),
                    ItemsList(GetSomeItems(100), 25.percent(), 25.percent(), 25.percent(), 25.percent()).Height(500.px()).PaddingBottom(32.px()),
                    TextBlock("Basic List with VisibilitySensor")
                    .Medium()
                    .PaddingBottom(16.px()),
                    ItemsList(obsList, 25.percent(), 25.percent(), 25.percent(), 25.percent()).Height(500.px()).PaddingBottom(32.px()),
                    TextBlock("Basic List with Empty List Message ")
                    .Medium()
                    .PaddingBottom(16.px()),
                    ItemsList(new IComponent[0], 25.percent(), 25.percent(), 25.percent(), 25.percent())
                    .WithEmptyMessage(() => BackgroundArea(Card(TextBlock("Empty list").Padding(16.px()))).WidthStretch().HeightStretch().MinHeight(100.px()))
                    .Height(500.px())));
        }
        public void AddRange_FiresCollectionChanged()
        {
            var list = new ObservableList<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            int eventFireCount = 0;

            list.CollectionChanged += (sender, args) =>
            {
                eventFireCount++;

                Assert.AreEqual(NotifyCollectionChangedAction.Add, args.Action);

                switch (eventFireCount)
                {
                    case 1:
                        Assert.AreEqual(9, args.NewStartingIndex);
                        Assert.IsTrue(new[] { 10 }.SequenceEqual(args.NewItems.Cast<int>()));
                        break;

                    case 2:
                        Assert.AreEqual(10, args.NewStartingIndex);
                        Assert.IsTrue(new[] { 11 }.SequenceEqual(args.NewItems.Cast<int>()));
                        break;
                }
            };

            list.AddRange(new[] { 10, 11 });
        }
        public void AddRange_FiresCollectionChanged()
        {
            var list = new ObservableList <int> {
                1, 2, 3, 4, 5, 6, 7, 8, 9
            };
            int eventFireCount = 0;

            list.CollectionChanged += (sender, args) =>
            {
                eventFireCount++;

                Assert.AreEqual(NotifyCollectionChangedAction.Add, args.Action);

                switch (eventFireCount)
                {
                case 1:
                    Assert.AreEqual(9, args.NewStartingIndex);
                    Assert.IsTrue(new[] { 10 }.SequenceEqual(args.NewItems.Cast <int>()));
                    break;

                case 2:
                    Assert.AreEqual(10, args.NewStartingIndex);
                    Assert.IsTrue(new[] { 11 }.SequenceEqual(args.NewItems.Cast <int>()));
                    break;
                }
            };

            list.AddRange(new[] { 10, 11 });
        }
Exemple #6
0
 public MainWindow()
 {
     InitializeComponent();
     LogRecords  = new ObservableList <LogRecord>();
     DataContext = this;
     new Thread(() =>
     {
         LogRecord record = new LogRecord();
         record.Message   = "Hello, world.";
         record.Timestamp = DateTime.Now;
         List <LogRecord> logRecordList = new List <LogRecord>();
         for (int i = 0; i < 1000000; i++)
         {
             logRecordList.Add(record);
         }
         Stopwatch timer = new Stopwatch();
         timer.Start();
         Dispatcher.Invoke(() =>
         {
             LogRecords.AddRange(logRecordList);
         });
         timer.Stop();
         Console.WriteLine("The operation took {0} milliseconds.", timer.ElapsedMilliseconds);
     }).Start();
 }
        public void AddRangeNotifiesAsResetInsteadOfIndividualItemsWhenItemCountAboveThresholdTest(int lowerLimit, int upperLimit)
        {
            // given
            var rangeToAdd = Enumerable.Range(lowerLimit, upperLimit - lowerLimit + 1).ToList();
            var testScheduler = new TestScheduler();
            var testObserverCollectionChanges = testScheduler.CreateObserver<IObservableCollectionChange<int>>();
            var testObserverResets = testScheduler.CreateObserver<Unit>();

            using (var observableList = new ObservableList<int>())
            {
                // when
                observableList.ThresholdAmountWhenChangesAreNotifiedAsReset = 0;

                observableList.CollectionChanges.Subscribe(testObserverCollectionChanges);
                observableList.Resets.Subscribe(testObserverResets);

                testScheduler.Schedule(TimeSpan.FromTicks(100), () => { observableList.AddRange(rangeToAdd); });
                testScheduler.Start();

                // then
                var shouldBeReset = rangeToAdd.Count >= observableList.ThresholdAmountWhenChangesAreNotifiedAsReset;
                testObserverCollectionChanges.Messages.Count.Should().Be(shouldBeReset ? 1 : rangeToAdd.Count);
                testObserverCollectionChanges.Messages.Should()
                    .Match(recordedMessages =>
                        recordedMessages.All(message => message.Value.Value.ChangeType == (shouldBeReset ? ObservableCollectionChangeType.Reset : ObservableCollectionChangeType.ItemAdded)));

                testObserverResets.Messages.Count.Should().Be(shouldBeReset ? 1 : 0);
            }
        }
Exemple #8
0
        public void AddRangeNotifiesAsResetInsteadOfIndividualItemsWhenItemCountAboveThresholdTest(int lowerLimit, int upperLimit)
        {
            // given
            var rangeToAdd    = Enumerable.Range(lowerLimit, upperLimit - lowerLimit + 1).ToList();
            var testScheduler = new TestScheduler();
            var testObserverCollectionChanges = testScheduler.CreateObserver <IObservableCollectionChange <int> >();
            var testObserverResets            = testScheduler.CreateObserver <Unit>();

            using (var observableList = new ObservableList <int>())
            {
                // when
                observableList.ThresholdAmountWhenChangesAreNotifiedAsReset = 0;

                observableList.CollectionChanges.Subscribe(testObserverCollectionChanges);
                observableList.Resets.Subscribe(testObserverResets);

                testScheduler.Schedule(TimeSpan.FromTicks(100), () => { observableList.AddRange(rangeToAdd); });
                testScheduler.Start();

                // then
                var shouldBeReset = rangeToAdd.Count >= observableList.ThresholdAmountWhenChangesAreNotifiedAsReset;
                testObserverCollectionChanges.Messages.Count.Should().Be(shouldBeReset ? 1 : rangeToAdd.Count);
                testObserverCollectionChanges.Messages.Should()
                .Match(recordedMessages =>
                       recordedMessages.All(message => message.Value.Value.ChangeType == (shouldBeReset ? ObservableCollectionChangeType.Reset : ObservableCollectionChangeType.ItemAdded)));

                testObserverResets.Messages.Count.Should().Be(shouldBeReset ? 1 : 0);
            }
        }
Exemple #9
0
        public void UnitTest4(ObservableList <int> list)
        {
            // ARRANGE
            EnvironmentSettings.AlwaysSuppressCurrentSynchronizationContext = true;

            list.AddRange(new[] { 6, 5, 2 });
            Assert.True(list.Contains(6));
            Assert.True(list.Contains(5));
            Assert.True(list.Contains(2));
            list.Undo();
            Assert.False(list.Contains(6));
            Assert.False(list.Contains(5));
            Assert.False(list.Contains(2));
            Assert.Equal(
                5,
                list.Count);

            // ACT
            list.Redo();

            // ASSERT
            Assert.True(list.Contains(6));
            Assert.True(list.Contains(5));
            Assert.True(list.Contains(2));
            Assert.Equal(
                8,
                list.Count);
        }
        public void SetInstructions(ImmutableList <string> instructions)
        {
            _instructions.Clear();
            _instructions.AddRange(instructions);

            _playhead.Value = 0;
            Save();
        }
Exemple #11
0
        public void HandleMessage(Message message)
        {
            var messageHash  = message.Hash;
            T   value        = (T)message.Body.Value;
            var predecessors = message.Predecessors;

            if (!_predecessors.Contains(messageHash))
            {
                _candidates.Add(new Candidate <T>(messageHash, value));
            }

            var newPredecessors = predecessors.Except(_predecessors);

            _candidates.RemoveAll(c => newPredecessors.Contains(c.MessageHash));

            _predecessors.AddRange(newPredecessors);
        }
        public void AddRange_ItemCountOverThresHold_FiresCollectionChanged()
        {
            var list = new ObservableList<int> { 1, 2, 3, 4, 5 };

            list.CollectionChanged += (sender, args) => Assert.AreEqual(NotifyCollectionChangedAction.Reset, args.Action);

            list.AddRange(new[] { 6, 7, 8, 9, 10 });
        }
 protected void UpdateTemplateList()
 {
     templates.Clear();
     if (SelectedGroup != null)
     {
         templates.AddRange(SelectedGroup.GetTemplatesRecursively());
     }
 }
 private void OnStudyLoaded(object sender, StudyLoadedEventArgs e)
 {
     _availableContexts.AddRange(e.Study.Series
                                 .SelectMany(s => s.Sops)
                                 .Where(s => s.SopClassUid == SopClass.KeyObjectSelectionDocumentStorageUid)
                                 .Select(s => new KeyImageInformation(_studyTree, s))
                                 .OrderByDescending(s => s.ContentDateTime)
                                 .ThenBy(s => s.SeriesNumber));
 }
        private void _listTestButton_Click(object sender, EventArgs e)
        {
            var list = new ObservableList <string>();

            list.ObservationWindow.ItemAdded += (dict, value, key) =>
                                                _outputWriter.WriteLine("Single event: Added {0} at {1} ", value, key);

            list.ObservationWindow.ItemRemoved += (dict, value, key) =>
                                                  _outputWriter.WriteLine("Single event: Removed {0} at {1} ", value, key);

            list.ObservationWindow.Changed += (dict, events) => {
                _outputWriter.WriteLine("Global Handler");
                foreach (var @event in events)
                {
                    _outputWriter.WriteLine("\t: {0} {1} at {2} ", @event.EventType, @event.Item, @event.Location);
                }
            };

            list.Add("string 1");
            list.Add("string 2");
            list.RemoveAt(1);
            list.Remove("string 1");
            list.AddRange(new [] { "bulk 1", "bulk 2" });
            list.AddRange(new[] { "bulk 3", "bulk 4" });
            list.RemoveRange(2, 2);
            list.RemoveAt(1);
            list.RemoveAt(0);
            list.AddRange(new[] { "bulk 5", "bulk 6" });
            list.Clear();

            list.Add("padding 1");
            list.Add("padding 2");
            list.AddRange(new [] { "padding 6", "padding 7" });
            list.Insert(2, "single insert 3");
            list.InsertRange(3, new [] { "bulk insert 4", "bulk insert 5" });

            _outputWriter.WriteLine("Should be 1,2,3,4,5,6,7: {0}", list.ToDelimittedString(", "));

            list.RemoveRange(1, 5);

            _outputWriter.WriteLine("Should be 1, 7: {0}", list.ToDelimittedString(", "));

            list.Clear();
        }
Exemple #16
0
        public void SelectedMain()
        {
            var list = AllSecondaryGroups[MainGroup.SelectedItem.Name];

            xOffset.Value = (int)((MainGroup.SelectedIndex + 0.5f - MainGroup.Count / 2f) * 100);

            SecondaryGroup.Clear();
            SecondaryGroup.AddRange(list);
            _controller.SelectedTool = null;
        }
Exemple #17
0
 public Asn1Tree(Asn1Reader asn)
 {
     if (asn == null)
     {
         throw new ArgumentNullException("asn");
     }
     RawData = new ObservableList <Byte>(true);
     RawData.AddRange(asn.RawData);
     m_initialize(asn);
 }
Exemple #18
0
        public void Initialize(MetaData metaData)
        {
            var newModels = metaData.Select(info => new ItemPreviewModel(_store, _relay, info));

            _models.AddRange(newModels);
            foreach (var model in _models)
            {
                _modelsByHash[model.FileHash] = model;
            }
        }
        public void AddRange_ItemCountOverThresHold_FiresCollectionChanged()
        {
            var list = new ObservableList <int> {
                1, 2, 3, 4, 5
            };

            list.CollectionChanged += (sender, args) => Assert.AreEqual(NotifyCollectionChangedAction.Reset, args.Action);

            list.AddRange(new[] { 6, 7, 8, 9, 10 });
        }
Exemple #20
0
        private ObservableList <RouterOutput> getAllOutputs()
        {
            ObservableList <RouterOutput> outputs = new ObservableList <RouterOutput>();

            foreach (Router router in routers)
            {
                outputs.AddRange(router.Outputs);
            }
            return(outputs);
        }
Exemple #21
0
        public TimelineSample()
        {
            var obsList = new ObservableList <IComponent>();

            var vs = VisibilitySensor((v) =>
            {
                obsList.Remove(v);
                obsList.AddRange(GetSomeItems(20));
                v.Reset();
                obsList.Add(v);
            });

            obsList.AddRange(GetSomeItems(10));
            obsList.Add(vs);
            _content = SectionStack().WidthStretch()
                       .Title(SampleHeader(nameof(TimelineSample)))
                       .Section(
                Stack()
                .Children(
                    SampleTitle("Overview"),
                    TextBlock("Timeline provides a base component for rendering vertical timelines. " +
                              "It is agnostic of the tile component used, and selection " +
                              "management. These concerns can be layered separately.")
                    .PaddingBottom(16.px())))
                       .Section(
                Stack()
                .Children(
                    SampleTitle("Usage"),
                    TextBlock("Timeline").Medium().PaddingBottom(16.px()),
                    Timeline().Children(GetSomeItems(10)).PaddingBottom(16.px()).Height(500.px()).PaddingBottom(32.px()),

                    TextBlock("Timeline with Max Width").Medium().PaddingBottom(16.px()),
                    Timeline().TimelineWidth(600.px()).Children(GetSomeItems(10)).PaddingBottom(16.px()).Height(500.px()).PaddingBottom(32.px()),

                    TextBlock("Timeline Same Side").Medium().PaddingBottom(16.px()),
                    Timeline().SameSide().Children(GetSomeItems(10)).PaddingBottom(16.px()).Height(500.px()).PaddingBottom(32.px()),

                    TextBlock("Timeline Same Side with Max Width").Medium().PaddingBottom(16.px()),
                    Timeline().TimelineWidth(600.px()).SameSide().Children(GetSomeItems(10)).PaddingBottom(16.px()).Height(500.px()).PaddingBottom(32.px())

                    ));
        }
Exemple #22
0
        public void TemplatePagesRangeAdded()
        {
            var page = CreateMultiPage();

            page.ItemTemplate = new DataTemplate(() =>
            {
                var p     = new ContentPage();
                p.Content = new Label();
                p.Content.SetBinding(Label.TextProperty, new Binding("."));
                return(p);
            });

            var items = new ObservableList <string> {
                "Foo", "Bar"
            };

            page.ItemsSource = items;

            Action <IList <Element>, int, string> assertPage = (ps, index, s) =>
            {
                Page p = (Page)ps[index];
                Assert.That(p, Is.InstanceOf <ContentPage>());
                Assert.That(GetIndex((T)p), Is.EqualTo(index));

                var cp = (ContentPage)p;
                Assert.That(cp.Content, Is.InstanceOf <Label>());
                Assert.That(((Label)cp.Content).Text, Is.EqualTo(s));
            };

            int addedCount = 0;

            page.PagesChanged += (sender, e) =>
            {
                if (e.Action != NotifyCollectionChangedAction.Add)
                {
                    return;
                }

                addedCount++;
                Assert.That(e.NewItems.Count, Is.EqualTo(2));
            };

            items.AddRange(new[] { "Baz", "Bam" });

            Assert.That(addedCount, Is.EqualTo(1));

            var pages = page.Children.ToArray();

            Assert.That(pages.Length, Is.EqualTo(4));
            assertPage(pages, 0, "Foo");
            assertPage(pages, 1, "Bar");
            assertPage(pages, 2, "Baz");
            assertPage(pages, 3, "Bam");
        }
            public void AddRangeWithIEnumerableCollection()
            {
                var list = new ObservableList <int>();

                Assert.AreEqual(0, list.Count);

                list.AddRange(new List <int> {
                    1, 2, 3
                }.Where(t => t > 0));

                Assert.AreEqual(3, list.Count);
            }
            public void AddRangeWithObservableList()
            {
                var list = new ObservableList <int>();

                Assert.AreEqual(0, list.Count);

                list.AddRange(new ObservableList <int> {
                    1, 2, 3
                });

                Assert.AreEqual(3, list.Count);
            }
        public MainWindowViewModel()
        {
            WinList            = new ObservableList <Type>();
            ProgramStart_Click = new RelayCommand(SelectedWindowStart);
            Hyperlink_Click    = new RelayCommand(LanguageChange);
            LanguageChange();

            var assems = Assembly.GetExecutingAssembly().DefinedTypes;
            var result = from a in assems where a.BaseType.Name == "Window" && a.Name != "MainWindow" orderby a.Name select a;

            WinList.AddRange(result);
        }
Exemple #26
0
        public void HandleAllMessages(IEnumerable <Message> messages)
        {
            var predecessors = messages
                               .SelectMany(m => m.Predecessors)
                               .ToLookup(h => h);
            var candidates = messages
                             .Where(m => !predecessors.Contains(m.Hash))
                             .Select(m => new Candidate <T>(m.Hash, (T)m.Body.Value));

            _candidates.RemoveAll(c => predecessors.Contains(c.MessageHash));
            _predecessors.AddRange(predecessors.Select(p => p.Key));
            _candidates.AddRange(candidates);
        }
 public TaxonListViewModel()
 {
     RegroupListCommand      = new Command <TaxonListGroup>(arg => RegroupList(arg));
     SelectedTaxonListSource = new ObservableList <Taxon>();
     HiddenTaxonList         = new ObservableList <Taxon>();
     SelectedTaxonList       = new ObservableList <TaxonListGroup>();
     EnableSearchbar         = true;
     SelectedTaxonListSource.AddRange(((App)App.Current).Taxa.Where(t => t.TaxonomyStateName == "sp.").ToList());
     PlaceholderText = $"Suchen in {SelectedTaxonListSource.Count} Arten";
     OnPropertyChanged(nameof(PlaceholderText));
     OnPropertyChanged(nameof(EnableSearchbar));
     OnPropertyChanged(nameof(SearchText));
 }
        public void HandleAllMessages(IEnumerable <Message> messages)
        {
            var cardsDeleted = messages
                               .Where(m => m.Type == "CardDeleted")
                               .Select(m => Guid.Parse(m.Body.CardId))
                               .ToLookup(g => g);
            var cardsCreated = messages
                               .Where(m => m.Type == "CardCreated")
                               .Select(m => Guid.Parse(m.Body.CardId))
                               .Where(g => !cardsDeleted.Contains(g))
                               .Select(g => new Card(g));

            _cards.AddRange(cardsCreated);
        }
		public KeyImageClipboard(StudyTree studyTree)
		{
			_studyTree = studyTree;

			_currentContext = new KeyImageInformation();
			_availableContexts = new ObservableList<KeyImageInformation> {_currentContext};
			_availableContexts.AddRange(_studyTree.Studies
			                            	.SelectMany(s => s.Series)
			                            	.SelectMany(s => s.Sops)
			                            	.Where(s => s.SopClassUid == SopClass.KeyObjectSelectionDocumentStorageUid)
			                            	.Select(s => new KeyImageInformation(studyTree, s))
			                            	.OrderByDescending(s => s.ContentDateTime)
			                            	.ThenBy(s => s.SeriesNumber));
		}
Exemple #30
0
 void UpdateViewOptions()
 {
     viewOptions.Clear();
     viewOptions.AddRange("Prediction", "Reference");
     if (Graph?.Data?.Characteristics != null)
     {
         foreach (var characteristic in Graph.Data.Characteristics)
         {
             viewOptions.Add("Characteristic_" + characteristic);
         }
     }
     viewOptions.Add("Observation");
     NotifyPropertyChanged("ViewOptions");
 }
        public KeyImageClipboard(StudyTree studyTree)
        {
            _studyTree = studyTree;

            _currentContext    = new KeyImageInformation();
            _availableContexts = new ObservableList <KeyImageInformation> {
                _currentContext
            };
            _availableContexts.AddRange(_studyTree.Studies
                                        .SelectMany(s => s.Series)
                                        .SelectMany(s => s.Sops)
                                        .Where(s => s.SopClassUid == SopClass.KeyObjectSelectionDocumentStorageUid)
                                        .Select(s => new KeyImageInformation(studyTree, s))
                                        .OrderByDescending(s => s.ContentDateTime)
                                        .ThenBy(s => s.SeriesNumber));
        }
Exemple #32
0
        public StoryboardParametersModel(IEnumerable <ImageFileInfo> imagesInfo)
        {
            _imagesInfo = imagesInfo;
            _sampleIDDefinitionModel = new SampleIDDefinitionModel();

            _allSampleIDs = new Computed <IEnumerable <SampleID> >(() =>
                                                                   ComputeAllSampleIDs(_sampleIDDefinitionModel));
            _selectedSampleIDs = new ObservableList <SampleID>(_allSampleIDs.Value);
            // when the list of all sample IDs changes, change the _selectedSampleIDs, so that by default all the items
            // in the CheckedComboBox get selected in UI. This is a user requirement specification for our case.
            _allSampleIDs.Subscribe(s =>
            {
                _selectedSampleIDs.Clear();
                _selectedSampleIDs.AddRange(_allSampleIDs.Value);
            });
        }
        /// <summary>
        /// Sets dune locations and calculations for the failure mechanism.
        /// </summary>
        /// <param name="duneLocations">The dune locations to add to the failure mechanism.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="duneLocations"/> is <c>null</c>.</exception>
        public void SetDuneLocations(IEnumerable <DuneLocation> duneLocations)
        {
            if (duneLocations == null)
            {
                throw new ArgumentNullException(nameof(duneLocations));
            }

            duneLocationCollection.Clear();
            duneLocationCollection.AddRange(duneLocations);

            DuneLocationCalculationsForUserDefinedTargetProbabilities.ForEach(dlc =>
            {
                dlc.DuneLocationCalculations.Clear();
                dlc.DuneLocationCalculations.AddRange(duneLocations.Select(dl => new DuneLocationCalculation(dl)));
            });
        }
Exemple #34
0
        /// <summary>
        /// Constructor with necessary parameter
        /// </summary>
        /// <param name="baseProjectPath">The root project path</param>
        public MappingMonitor(string baseProjectPath)
        {
            if (string.IsNullOrWhiteSpace(baseProjectPath))
            {
                throw new ArgumentException(
                          string.Format(Languages.Global.Str1ArgumentIsInvalid, nameof(baseProjectPath)),
                          nameof(baseProjectPath));
            }

            if (Directory.Exists(baseProjectPath) == false)
            {
                try {
                    Directory.CreateDirectory(baseProjectPath);
                    Directory.Delete(baseProjectPath);
                }
                catch {
                    throw new ArgumentException(
                              string.Format(Languages.Global.Str1ArgumentIsInvalid, nameof(baseProjectPath)),
                              nameof(baseProjectPath));
                }
            }

            BaseProjectPath = baseProjectPath;
            if (BaseProjectPath.EndsWith($"{Path.DirectorySeparatorChar}") == false)
            {
                BaseProjectPath = BaseProjectPath + Path.DirectorySeparatorChar;
            }
            GlossaryPath = Path.Combine(BaseProjectPath, GlossaryFolderName);

            mFileList = new ObservableList <string>(Directory.GetFiles(BaseProjectPath, "*.*", SearchOption.AllDirectories));
            mFileList.AddRange(Directory.GetDirectories(BaseProjectPath, "*", SearchOption.AllDirectories));

            // finally, prepare FileSystemWatcher instance
            mWatcher              = new FileSystemWatcher();
            mWatcher.Path         = BaseProjectPath;
            mWatcher.NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName |
                                    NotifyFilters.LastWrite | NotifyFilters.Size;
            mWatcher.Filter = "*.*";
            mWatcher.IncludeSubdirectories = true;
            mWatcher.Changed            += OnFileChanged;
            mWatcher.Created            += OnFileChanged;
            mWatcher.Deleted            += OnFileChanged;
            mWatcher.Renamed            += OnFileRenamed;
            mWatcher.EnableRaisingEvents = false;
        }
Exemple #35
0
        private IEnumerator CollectionTestA1()
        {
            var listA = new List <object>(collectionTestCount);
            var listB = new List <object>(collectionTestCount);

            for (int i = 0; i < collectionTestCount; i++)
            {
                listA.Add(i);
                listB.Add(2 * i);
            }

            var collection = new ObservableList <object>(collectionTestCount);

            collection.CollectionChanged += (sender, arg) => { };

            var test = RunMemoryTestAsync("CollectionTestA1", () =>
            {
                // add
                for (int i = 0; i < collectionTestCount; i++)
                {
                    collection.Add(listA[i]);
                }

                // indexer
                for (int i = 0; i < collectionTestCount; i++)
                {
                    collection[i] = listB[i];
                }

                // remove
                for (int i = 0; i < collectionTestCount; i++)
                {
                    collection.RemoveAt(0);
                }

                // range
                for (int i = 0; i < collectionTestCount; i++)
                {
                    collection.AddRange(listA);
                    collection.Clear();
                }
            });

            yield return(StartCoroutine(test));
        }
        public void AddRangeIncreasesCountTest(int lowerLimit, int upperLimit)
        {
            // given
            var rangeToAdd = Enumerable.Range(lowerLimit, upperLimit - lowerLimit + 1).ToList();
            var testScheduler = new TestScheduler();
            var testObserver = testScheduler.CreateObserver<int>();

            using (var observableList = new ObservableList<int>())
            {
                // when
                observableList.ThresholdAmountWhenChangesAreNotifiedAsReset = rangeToAdd.Count + 1;
                observableList.CountChanges.Subscribe(testObserver);

                testScheduler.Schedule(TimeSpan.FromTicks(100), () => { observableList.AddRange(rangeToAdd); });
                testScheduler.Start();

                // then
                observableList.Count.Should().Be(rangeToAdd.Count);
            }
        }
        public void AddRangeNotifiesCountAfterResetWhenItemCountAboveThresholdTest(int lowerLimit, int upperLimit)
        {
            // given
            var rangeToAdd = Enumerable.Range(lowerLimit, upperLimit - lowerLimit + 1).ToList();
            var testScheduler = new TestScheduler();
            var testObserver = testScheduler.CreateObserver<int>();

            using (var observableList = new ObservableList<int>())
            {
                // when
                observableList.ThresholdAmountWhenChangesAreNotifiedAsReset = 0;
                observableList.CountChanges.Subscribe(testObserver);

                testScheduler.Schedule(TimeSpan.FromTicks(100), () => { observableList.AddRange(rangeToAdd); });
                testScheduler.Start();

                // then
                testObserver.Messages.Count.Should().Be(1);
                testObserver.Messages.Last().Should().NotBeNull();
                testObserver.Messages.Last().Value.Value.Should().Be(observableList.Count);
            }
        }
Exemple #38
0
        /// <summary>
        /// The convert.
        /// </summary>
        /// <param name="value">
        /// The value.
        /// </param>
        /// <param name="targetType">
        /// The target type.
        /// </param>
        /// <param name="parameter">
        /// The parameter.
        /// </param>
        /// <param name="culture">
        /// The culture.
        /// </param>
        /// <returns>
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// </exception>
        /// <exception cref="NotImplementedException">
        /// </exception>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (targetType == null)
            {
                throw new ArgumentNullException("targetType");
            }

            var bytes = (byte[])value;
            if (targetType.IsAssignableFrom(typeof(IEnumerable)))
            {
                var observable = new ObservableList<SixteenBytes>();
                if (bytes != null && bytes.Length > 0)
                {
                    Task.Factory.StartNew(
                        () =>
                            {
                                const int ChunkSize = 16;
                                var chunk = new List<SixteenBytes>(ChunkSize);
                                int n;
                                var len = bytes.Length;
                                for (n = 0; n < len; n += SixteenBytes.Size)
                                {
                                    chunk.Add(new SixteenBytes { Value = bytes, Index = n });
                                    if (chunk.Count == chunk.Capacity)
                                    {
                                        observable.AddRange(chunk);
                                        chunk = new List<SixteenBytes>(ChunkSize);
                                    }
                                }

                                if (n < len)
                                {
                                    chunk.Add(new SixteenBytes { Value = bytes, Index = n });
                                }

                                if (chunk.Count > 0)
                                {
                                    observable.AddRange(chunk);
                                }
                            });
                }

                return observable;
            }

            throw new NotImplementedException();
        }