private static void TrackProgress(ProgressListener progressListener, BaseResponseInterpretor interpretor) { while (interpretor.Progress < 100) { progressListener.SetProgress(interpretor.Progress); } }
private void InitializeUI() { switch (_operator) { case FileOperator.Export: this.Text = "Export Configuration"; this.labelTitle.Text = "Following files will be copied to folder " + _path + ". Please click \"OK\" button to continue."; break; case FileOperator.Import: this.Text = "Import Configuration"; this.labelTitle.Text = "Following files will be copied from folder " + _path + ". Please click \"OK\" button to continue."; break; } this.listBoxFiles.Items.Clear(); foreach (string f in _files) { this.listBoxFiles.Items.Add(f); } _interfaceManager = new GCInterfaceManager(Program.ConfigDB, Program.ConfigMgt.Config.InterfaceFolder); _listener = new ProgressListener(this.labelHide, this.progressBarMain); _listener.AttachProgress(_interfaceManager); }
public void CallNotifyProgress_Twice() { //setup ProgressListener mock = Substitute.For <ProgressListener>(); sut = new AlbumDictionaryCreatorImpl(mock); string path1 = "path1"; string path2 = "path2"; string[] files = new string[2]; files[0] = path1; files[1] = path2; MusicTagStub.pathAlbumDictionary[path1] = "album1"; MusicTagStub.pathDiscDictionary[path1] = 1; MusicTagStub.pathDiscCountDictionary[path1] = 1; MusicTagStub.pathTrackDictionary[path1] = 1; MusicTagStub.pathTrackCountDictionary[path1] = 2; MusicTagStub.pathTitleDictionary[path1] = "title1"; MusicTagStub.pathAlbumDictionary[path2] = "album1"; MusicTagStub.pathDiscDictionary[path2] = 1; MusicTagStub.pathDiscCountDictionary[path2] = 1; MusicTagStub.pathTrackDictionary[path2] = 2; MusicTagStub.pathTrackCountDictionary[path2] = 2; MusicTagStub.pathTitleDictionary[path2] = "title2"; //exercise Dictionary <string, Album> dict = sut.create(files); //verify mock.Received().notifyProgress(2, 1); mock.Received().notifyProgress(2, 2); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldReportProgressInTheSpecifiedIntervals() public virtual void ShouldReportProgressInTheSpecifiedIntervals() { // given Indicator indicator = IndicatorMock(); ProgressListener progressListener = Factory.mock(indicator, 10).singlePart(TestName.MethodName, 16); // when progressListener.Started(); for (int i = 0; i < 16; i++) { progressListener.Add(1); } progressListener.Done(); // then InOrder order = inOrder(indicator); order.verify(indicator).startProcess(16); for (int i = 0; i < 10; i++) { order.verify(indicator).progress(i, i + 1); } order.verify(indicator).completeProcess(); order.verifyNoMoreInteractions(); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldAllowStartingAPartBeforeCompletionOfMultiPartBuilder() public virtual void ShouldAllowStartingAPartBeforeCompletionOfMultiPartBuilder() { // given Indicator indicator = mock(typeof(Indicator)); ProgressMonitorFactory.MultiPartBuilder builder = Factory.mock(indicator, 10).multipleParts(TestName.MethodName); ProgressListener part1 = builder.ProgressForPart("part1", 1); ProgressListener part2 = builder.ProgressForPart("part2", 1); // when part1.Add(1); builder.Build(); part2.Add(1); part1.Done(); part2.Done(); // then InOrder order = inOrder(indicator); order.verify(indicator).startPart("part1", 1); order.verify(indicator).startProcess(2); order.verify(indicator).startPart("part2", 1); order.verify(indicator).completePart("part1"); order.verify(indicator).completePart("part2"); order.verify(indicator).completeProcess(); }
public ProgressMonitor(ProgressListener p) { if (p != null) { this._progressListeners.Add(p); } }
private void InitializeControl() { _interfaceMgt = new GCInterfaceManager(Program.ConfigDB, Program.ConfigMgt.Config.InterfaceFolder); _progressListener = new ProgressListener(this.labelProcess, this.progressBarProcess); _progressListener.AttachProgress(_interfaceMgt); panelProcess.Visible = false; }
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected: //ORIGINAL LINE: public void checkCounts(org.neo4j.kernel.impl.api.CountsAccessor counts, final org.neo4j.consistency.report.ConsistencyReporter reporter, org.neo4j.helpers.progress.ProgressMonitorFactory progressFactory) public virtual void CheckCounts(CountsAccessor counts, ConsistencyReporter reporter, ProgressMonitorFactory progressFactory) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int nodes = nodeCounts.size(); int nodes = _nodeCounts.size(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int relationships = relationshipCounts.size(); int relationships = _relationshipCounts.size(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int total = nodes + relationships; int total = nodes + relationships; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger nodeEntries = new java.util.concurrent.atomic.AtomicInteger(0); AtomicInteger nodeEntries = new AtomicInteger(0); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger relationshipEntries = new java.util.concurrent.atomic.AtomicInteger(0); AtomicInteger relationshipEntries = new AtomicInteger(0); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.neo4j.helpers.progress.ProgressListener listener = progressFactory.singlePart("Checking node and relationship counts", total); ProgressListener listener = progressFactory.SinglePart("Checking node and relationship counts", total); listener.Started(); Counts.accept(new CountsVisitor_AdapterAnonymousInnerClass(this, reporter, nodeEntries, relationshipEntries, listener)); reporter.ForCounts(new CountsEntry(nodeKey(WILDCARD), nodeEntries.get()), CHECK_NODE_KEY_COUNT); reporter.ForCounts(new CountsEntry(relationshipKey(WILDCARD, WILDCARD, WILDCARD), relationshipEntries.get()), CHECK_RELATIONSHIP_KEY_COUNT); listener.Done(); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldCopeWithCollisionsBasedOnDifferentInputIds() public virtual void ShouldCopeWithCollisionsBasedOnDifferentInputIds() { // GIVEN Monitor monitor = mock(typeof(Monitor)); Encoder encoder = mock(typeof(Encoder)); when(encoder.Encode(any())).thenReturn(12345L); IdMapper mapper = mapper(encoder, Radix.String, monitor); System.Func <long, object> ids = Values("10", "9"); for (int i = 0; i < 2; i++) { mapper.Put(ids(i), i, GLOBAL); } // WHEN ProgressListener progress = mock(typeof(ProgressListener)); Collector collector = mock(typeof(Collector)); mapper.Prepare(ids, collector, progress); // THEN verifyNoMoreInteractions(collector); verify(monitor).numberOfCollisions(2); assertEquals(0L, mapper.Get("10", GLOBAL)); assertEquals(1L, mapper.Get("9", GLOBAL)); // 7 times since SPLIT+SORT+DETECT+RESOLVE+SPLIT+SORT,DEDUPLICATE verify(progress, times(7)).started(anyString()); verify(progress, times(7)).done(); }
private async Task AddToManagedTasks(Task taskToAdd) { Tasks.Add(taskToAdd); ProgressListener?.SetCount(GetCompletedTasksCount(), GetTotalTasksCount()); try { await taskToAdd; } finally { // After the task is done update the progress listener again: ProgressListener?.SetCount(GetCompletedTasksCount(), GetTotalTasksCount()); } }
internal void Add(ProgressListener progress, long totalCount) { lock (this) { _states[progress] = ProgressListener_MultiPartProgressListener.State.Init; this._totalCount += totalCount; } }
internal DetectWorker(EncodingIdMapper outerInstance, long fromInclusive, long toExclusive, bool last, ProgressListener progress) { this._outerInstance = outerInstance; this.FromInclusive = fromInclusive; this.ToExclusive = toExclusive; this.Last = last; this.Progress = progress; }
public CountsVisitor_AdapterAnonymousInnerClass(CountsBuilderDecorator outerInstance, ConsistencyReporter reporter, AtomicInteger nodeEntries, AtomicInteger relationshipEntries, ProgressListener listener) { this.outerInstance = outerInstance; this._reporter = reporter; this._nodeEntries = nodeEntries; this._relationshipEntries = relationshipEntries; this._listener = listener; }
public SignalServiceAttachmentStream(Stream inputStream, String contentType, long length, May <byte[]> preview, ProgressListener listener) : base(contentType) { this.inputStream = inputStream; this.length = length; this.listener = listener; this.preview = preview; }
internal StoreProcessorTask(string name, Statistics statistics, int threads, RecordStore <R> store, StoreAccess storeAccess, string builderPrefix, ProgressMonitorFactory.MultiPartBuilder builder, CacheAccess cacheAccess, StoreProcessor processor, QueueDistribution distribution) : base(name, statistics, threads) { this._store = store; this._storeAccess = storeAccess; this._cacheAccess = cacheAccess; this._processor = processor; this._distribution = distribution; this._progressListener = builder.ProgressForPart(name + IndexedPartName(store.StorageFile.Name, builderPrefix), store.HighId); }
internal RecordScanner(string name, Statistics statistics, int threads, BoundedIterable <RECORD> store, ProgressMonitorFactory.MultiPartBuilder builder, RecordProcessor <RECORD> processor, params IterableStore[] warmUpStores) : base(name, statistics, threads) { this.Store = store; this.Processor = processor; long maxCount = store.MaxCount(); this.Progress = maxCount == -1 ? builder.ProgressForUnknownPart(name) : builder.ProgressForPart(name, maxCount); this._warmUpStores = warmUpStores; }
public virtual ProgressListener ProgressForUnknownPart(string part) { AssertNotBuilt(); AssertUniquePart(part); ProgressListener progress = ProgressListener_Fields.None; Aggregator.add(progress, 0); return(progress); }
public SignalServiceAttachmentStream(Stream inputStream, String contentType, long length, string fileName, bool voiceNote, May <byte[]> preview, ProgressListener listener) : base(contentType) { this.inputStream = inputStream; this.length = length; FileName = fileName; this.listener = listener; VoiceNote = voiceNote; this.preview = preview; }
protected void ProgressItemUpdated(ProgressItem progressItem, Exception e) { ProgressEvent progressEvent = new ProgressEvent(); progressEvent.ProgressID = progressItem.progressId; progressEvent.CurrentSteps = progressItem.stepCount; progressEvent.ProgressID = progressItem.maxCount; progressEvent.Exception = e; ProgressListener.HandleProgress(progressEvent); }
public ParallelSort(Radix radix, LongArray dataCache, long highestSetIndex, Tracker tracker, int threads, ProgressListener progress, Comparator comparator) { this._progress = progress; this._comparator = comparator; this._radixIndexCount = radix.RadixIndexCounts; this._radixCalculator = radix.Calculator(); this._dataCache = dataCache; this._highestSetIndex = highestSetIndex; this._tracker = tracker; this._threads = threads; }
public FormCopyInterface(GCInterfaceManager interfaceMgt, GCInterface fromInterface) { InitializeComponent(); ToInterface = null; _interfaceMgt = interfaceMgt; _fromInterface = fromInterface; this.Text = string.Format(this.Text, _fromInterface.InterfaceName); _progressListener = new ProgressListener(this.labelProcess, this.progressBarProcess); _progressListener.AttachProgress(_interfaceMgt); }
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected: //ORIGINAL LINE: public <R extends org.neo4j.kernel.impl.store.record.AbstractBaseRecord> void applyFilteredParallel(final org.neo4j.kernel.impl.store.RecordStore<R> store, final org.neo4j.helpers.progress.ProgressListener progressListener, int numberOfThreads, long recordsPerCpu, final org.neo4j.consistency.checking.full.QueueDistribution_QueueDistributor<R> distributor) public virtual void ApplyFilteredParallel <R>(RecordStore <R> store, ProgressListener progressListener, int numberOfThreads, long recordsPerCpu, QueueDistribution_QueueDistributor <R> distributor) where R : Org.Neo4j.Kernel.impl.store.record.AbstractBaseRecord { CacheAccess.prepareForProcessingOfSingleStore(recordsPerCpu); RecordProcessor <R> processor = new RecordProcessor_AdapterAnonymousInnerClass(this, store); ResourceIterable <R> scan = scan(store, _stage.Forward); using (ResourceIterator <R> records = scan.GetEnumerator()) { distributeRecords(numberOfThreads, this.GetType().Name, _qSize, cloned(records), progressListener, processor, distributor); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private void detectDuplicateInputIds(Radix radix, org.neo4j.unsafe.impl.batchimport.input.Collector collector, org.neo4j.helpers.progress.ProgressListener progress) throws InterruptedException private void DetectDuplicateInputIds(Radix radix, Collector collector, ProgressListener progress) { // We do this collision sort using ParallelSort which has the data cache and the tracker cache, // the tracker cache gets sorted, data cache stays intact. In the collision data case we actually // have one more layer in here so we have tracker cache pointing to collisionNodeIdCache // pointing to dataCache. This can be done using the ParallelSort.Comparator abstraction. // // The Comparator below takes into account dataIndex for each eId its comparing so that an extra // comparison based on dataIndex is done if it's comparing two equal eIds. We do this so that // stretches of multiple equal eIds are sorted by dataIndex (i.e. node id) order, // to be able to write an efficient duplication scanning below and to have deterministic duplication reporting. Comparator duplicateComparator = new ComparatorAnonymousInnerClass(this); (new ParallelSort(radix, As5ByteLongArray(_collisionNodeIdCache), _numberOfCollisions - 1, _collisionTrackerCache, _processorsForParallelWork, progress, duplicateComparator)).run(); // Here we have a populated C // We want to detect duplicate input ids within it long previousEid = 0; int previousGroupId = -1; SameInputIdDetector detector = new SameInputIdDetector(); progress.Started("DEDUPLICATE"); for (int i = 0; i < _numberOfCollisions; i++) { long collisionIndex = _collisionTrackerCache.get(i); long nodeId = _collisionNodeIdCache.get5ByteLong(collisionIndex, 0); long offset = _collisionNodeIdCache.get6ByteLong(collisionIndex, 5); long eid = _dataCache.get(nodeId); int groupId = GroupOf(nodeId); // collisions of same eId AND groupId are always together bool same = eid == previousEid && previousGroupId == groupId; if (!same) { detector.Clear(); } // Potential duplicate object inputId = _collisionValues.get(offset); long nonDuplicateNodeId = detector.Add(nodeId, inputId); if (nonDuplicateNodeId != -1) { // Duplicate collector.CollectDuplicateNode(inputId, nodeId, _groups.get(groupId).name()); _trackerCache.markAsDuplicate(nodeId); UnmarkAsCollision(nonDuplicateNodeId); } previousEid = eid; previousGroupId = groupId; progress.Add(1); } progress.Done(); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldAggregateProgressFromMultipleProcesses() public virtual void ShouldAggregateProgressFromMultipleProcesses() { // given Indicator indicator = IndicatorMock(); ProgressMonitorFactory.MultiPartBuilder builder = Factory.mock(indicator, 10).multipleParts(TestName.MethodName); ProgressListener first = builder.ProgressForPart("first", 5); ProgressListener other = builder.ProgressForPart("other", 5); builder.Build(); InOrder order = inOrder(indicator); order.verify(indicator).startProcess(10); order.verifyNoMoreInteractions(); // when first.Started(); for (int i = 0; i < 5; i++) { first.Add(1); } first.Done(); // then order.verify(indicator).startPart("first", 5); for (int i = 0; i < 5; i++) { order.verify(indicator).progress(i, i + 1); } order.verify(indicator).completePart("first"); order.verifyNoMoreInteractions(); // when other.Started(); for (int i = 0; i < 5; i++) { other.Add(1); } other.Done(); // then order.verify(indicator).startPart("other", 5); for (int i = 5; i < 10; i++) { order.verify(indicator).progress(i, i + 1); } order.verify(indicator).completePart("other"); order.verify(indicator).completeProcess(); order.verifyNoMoreInteractions(); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldPrintADotEveryHalfPercentAndFullPercentageEveryTenPercentWithTextualIndicator() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldPrintADotEveryHalfPercentAndFullPercentageEveryTenPercentWithTextualIndicator() { // given MemoryStream stream = new MemoryStream(); ProgressListener progressListener = ProgressMonitorFactory.Textual(stream).singlePart(TestName.MethodName, 1000); // when for (int i = 0; i < 1000; i++) { progressListener.Add(1); } // then assertEquals(TestName.MethodName + lineSeparator() + _expectedTextualOutput, stream.ToString(Charset.defaultCharset().name())); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldPrintADotEveryHalfPercentAndFullPercentageEveryTenPercentEvenWhenStepResolutionIsLower() public virtual void ShouldPrintADotEveryHalfPercentAndFullPercentageEveryTenPercentEvenWhenStepResolutionIsLower() { // given StringWriter writer = new StringWriter(); ProgressListener progressListener = ProgressMonitorFactory.Textual(writer).singlePart(TestName.MethodName, 50); // when for (int i = 0; i < 50; i++) { progressListener.Add(1); } // then assertEquals(TestName.MethodName + lineSeparator() + _expectedTextualOutput, writer.ToString()); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldReportyProgressForSortAndDetect() public virtual void ShouldReportyProgressForSortAndDetect() { // GIVEN IdMapper idMapper = Mapper(new StringEncoder(), Radix.String, NO_MONITOR); ProgressListener progress = mock(typeof(ProgressListener)); idMapper.Prepare(null, mock(typeof(Collector)), progress); // WHEN long id = idMapper.Get("123", GLOBAL); // THEN assertEquals(ID_NOT_FOUND, id); verify(progress, times(3)).started(anyString()); verify(progress, times(3)).done(); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private long applyTransactions(java.io.File fromPath, org.neo4j.kernel.internal.GraphDatabaseAPI toDb, org.neo4j.kernel.configuration.Config toConfig, long fromTxExclusive, long toTxInclusive, java.io.PrintStream out) throws Exception private long ApplyTransactions( File fromPath, GraphDatabaseAPI toDb, Config toConfig, long fromTxExclusive, long toTxInclusive, PrintStream @out ) { DependencyResolver resolver = toDb.DependencyResolver; TransactionRepresentationCommitProcess commitProcess = new TransactionRepresentationCommitProcess( resolver.ResolveDependency( typeof( TransactionAppender ) ), resolver.ResolveDependency( typeof( StorageEngine ) ) ); LifeSupport life = new LifeSupport(); try { using ( DefaultFileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction(), JobScheduler jobScheduler = createInitialisedScheduler(), PageCache pageCache = StandalonePageCacheFactory.createPageCache(fileSystem, jobScheduler) ) { LogicalTransactionStore source = life.Add( new ReadOnlyTransactionStore( pageCache, fileSystem, DatabaseLayout.of( fromPath ), Config.defaults(), new Monitors() ) ); life.Start(); long lastAppliedTx = fromTxExclusive; // Some progress if there are more than a couple of transactions to apply ProgressListener progress = toTxInclusive - fromTxExclusive >= 100 ? textual( @out ).singlePart( "Application progress", toTxInclusive - fromTxExclusive ) : Org.Neo4j.Helpers.progress.ProgressListener_Fields.None; using ( IOCursor<CommittedTransactionRepresentation> cursor = source.GetTransactions( fromTxExclusive + 1 ) ) { while ( cursor.next() ) { CommittedTransactionRepresentation transaction = cursor.get(); TransactionRepresentation transactionRepresentation = transaction.TransactionRepresentation; try { commitProcess.Commit( new TransactionToApply( transactionRepresentation ), NULL, EXTERNAL ); progress.Add( 1 ); } //JAVA TO C# CONVERTER WARNING: 'final' catch parameters are not available in C#: //ORIGINAL LINE: catch (final Throwable e) catch ( Exception e ) { Console.Error.WriteLine( "ERROR applying transaction " + transaction.CommitEntry.TxId ); throw e; } lastAppliedTx = transaction.CommitEntry.TxId; if ( lastAppliedTx == toTxInclusive ) { break; } } } return lastAppliedTx; } } finally { life.Shutdown(); } }
/// <summary> /// There are two types of collisions: /// - actual: collisions coming from equal input value. These might however not impose /// keeping original input value since the colliding values might be for separate id groups, /// just as long as there's at most one per id space. /// - accidental: collisions coming from different input values that happens to coerce into /// the same encoded value internally. /// /// For any encoded value there might be a mix of actual and accidental collisions. As long as there's /// only one such value (accidental or actual) per id space the original input id doesn't need to be kept. /// For scenarios where there are multiple per for any given id space: /// - actual: there are two equal input values in the same id space /// ==> fail, not allowed /// - accidental: there are two different input values coerced into the same encoded value /// in the same id space /// ==> original input values needs to be kept /// </summary> /// <returns> rough number of collisions. The number can be slightly more than it actually is due to benign /// races between detector workers. This is not a problem though, this value serves as a pessimistic value /// for allocating arrays to hold collision data to later sort and use to discover duplicates. </returns> private long DetectAndMarkCollisions(ProgressListener progress) { progress.Started("DETECT"); long totalCount = _highestSetIndex + 1; Workers <DetectWorker> workers = new Workers <DetectWorker>("DETECT"); int processors = _processorsForParallelWork; long stride = totalCount / _processorsForParallelWork; if (stride < 10) { // Multi-threading would be overhead processors = 1; stride = totalCount; } long fromInclusive = 0; long toExclusive = 0; for (int i = 0; i < processors; i++) { bool last = i == processors - 1; fromInclusive = toExclusive; toExclusive = last ? totalCount : toExclusive + stride; workers.Start(new DetectWorker(this, fromInclusive, toExclusive, last, progress)); } workers.AwaitAndThrowOnErrorStrict(); long numberOfCollisions = 0; foreach (DetectWorker detectWorker in workers) { numberOfCollisions += detectWorker.NumberOfCollisions; } progress.Done(); if (numberOfCollisions > int.MaxValue) { throw new InputException("Too many collisions: " + numberOfCollisions); } int intNumberOfCollisions = toIntExact(numberOfCollisions); _monitor.numberOfCollisions(intNumberOfCollisions); return(intNumberOfCollisions); }
//JAVA TO C# CONVERTER TODO TASK: There is no .NET equivalent to the Java 'super' constraint: //ORIGINAL LINE: <R extends org.neo4j.kernel.impl.store.record.AbstractBaseRecord> void apply(RecordStore<R> store, org.neo4j.helpers.progress.ProgressListener progressListener, System.Predicate<? super R>... filters) throws FAILURE //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: internal virtual void Apply <R>(RecordStore <R> store, ProgressListener progressListener, params System.Predicate <object>[] filters) where R : Org.Neo4j.Kernel.impl.store.record.AbstractBaseRecord { ResourceIterable <R> iterable = Scanner.Scan(store, true, filters); using (ResourceIterator <R> scan = iterable.GetEnumerator()) { while (scan.MoveNext()) { R record = scan.Current; if (ShouldStop) { break; } store.Accept(this, record); progressListener.Set(record.Id); } progressListener.Done(); } }
/// <summary> /// Runs simulation. /// </summary> /// <param name="runListener">Simulation listener.</param> /// <param name="runInSameThread">If <c>true</c>, simulation is run in same thread like caller, /// ie. method blocks until simulation don't finish. If <c>false</c>, simulation is /// run in separate thread and method returns immediately.</param> /// <remarks> /// Simulation is run the way that trigger invokes <see cref="ILinkableComponent.GetValues">ILinkableComponent.GetValues</see> /// method of the model it's connected to /// at the time specified by <see cref="TriggerInvokeTime">TriggerInvokeTime</see> property. /// If you need to use more than one listener you can use <see cref="ProxyListener">ProxyListener</see> /// class or <see cref="ProxyMultiThreadListener">ProxyMultiThreadListener</see> if <c>runInSameThread</c> is <c>false</c>. /// </remarks> public void Run(Logger logger, bool runInSameThread) { LoggerListener loggerListener = new LoggerListener(logger); ProgressListener progressListener = new ProgressListener(); progressListener.ModelProgressChangedHandler += new ModelProgressChangedDelegate(delegate(ILinkableComponent linkableComponent, ITimeStamp simTime) { string guid = cmGuidMapping[linkableComponent]; string progress = CalendarConverter.ModifiedJulian2Gregorian(simTime.ModifiedJulianDay).ToString(); CompositionModelProgressChangedHandler(this, guid, progress); }); ArrayList listeners = new ArrayList(); listeners.Add(loggerListener); listeners.Add(progressListener); ProxyListener proxyListener = new ProxyListener(); proxyListener.Initialize(listeners); startTime = DateTime.Now; if (_running) throw (new Exception("Simulation is already running.")); _running = true; _runListener = proxyListener; try { TimeStamp runToTime = new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(_triggerInvokeTime)); // Create informative message if (_runListener != null) { StringBuilder description = new StringBuilder(); description.Append("Starting simulation at "); description.Append(DateTime.Now.ToString()); description.Append(","); description.Append(" composition consists from following models:\n"); foreach (Model model in _models) { description.Append(model.ModelID); description.Append(", "); } // todo: add more info? Event theEvent = new Event(EventType.Informative); theEvent.Description = description.ToString(); _runListener.OnEvent(theEvent); } _runPrepareForComputationStarted = true; // prepare for computation if (_runListener != null) { Event theEvent = new Event(EventType.Informative); theEvent.Description = "Preparing for computation...."; _runListener.OnEvent(theEvent); } // subscribing event listener to all models if (_runListener != null) { Event theEvent = new Event(EventType.Informative); theEvent.Description = "Subscribing proxy event listener...."; _runListener.OnEvent(theEvent); for (int i = 0; i < _runListener.GetAcceptedEventTypeCount(); i++) foreach (Model uimodel in _models) { theEvent = new Event(EventType.Informative); theEvent.Description = "Calling Subscribe() method with EventType." + ((EventType)i).ToString() + " of model " + uimodel.ModelID; _runListener.OnEvent(theEvent); for (int j = 0; j < uimodel.LinkableComponent.GetPublishedEventTypeCount(); j++) if (uimodel.LinkableComponent.GetPublishedEventType(j) == _runListener.GetAcceptedEventType(i)) { uimodel.LinkableComponent.Subscribe(_runListener, _runListener.GetAcceptedEventType(i)); break; } } } if (!runInSameThread) { // creating run thread if (_runListener != null) { Event theEvent = new Event(EventType.Informative); theEvent.Description = "Creating run thread...."; _runListener.OnEvent(theEvent); } _runThread = new Thread(RunThreadFunction) { Priority = ThreadPriority.Normal }; // starting thread... if (_runListener != null) { Event theEvent = new Event(EventType.GlobalProgress); theEvent.Description = "Starting run thread...."; _runListener.OnEvent(theEvent); } _runThread.Start(); } else { // run simulation in same thread (for example when running from console) if (_runListener != null) { Event theEvent = new Event(EventType.Informative); theEvent.Description = "Running simulation in same thread...."; _runListener.OnEvent(theEvent); } RunThreadFunction(); } } catch (System.Exception e) { if (_runListener != null) { Event theEvent = new Event(EventType.Informative); theEvent.Description = "Exception occured while initiating simulation run: " + e.ToString(); _runListener.OnEvent(theEvent); _runListener.OnEvent(SimulationFailedEvent); // todo: add info about time to this event endTime = DateTime.Now; var ev = new Event { Description = "Elapsed time: " + (endTime - startTime), Type = EventType.GlobalProgress }; _runListener.OnEvent(ev); } } finally { } }
/** * Sets the optional progress listener for receiving updates for object * upload status. */ public void setProgressListener(ProgressListener progressListener) { this.progressListener = progressListener; }
//UPGRADE_NOTE: Synchronized keyword was removed from method 'convert'. Lock expression was added. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1027"' public virtual void convert(System.IO.Stream sourceStream, System.String destName, ProgressListener progressListener, Decoder.Params decoderParams) { lock (this) { if (progressListener == null) progressListener = PrintWriterProgressListener.newStdOut(PrintWriterProgressListener.NO_DETAIL); try { if (!(sourceStream is System.IO.BufferedStream)) sourceStream = new System.IO.BufferedStream(sourceStream); int frameCount = - 1; //UPGRADE_ISSUE: Method 'java.io.InputStream.markSupported' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioInputStreammarkSupported"' if (sourceStream.markSupported()) { //UPGRADE_ISSUE: Method 'java.io.InputStream.mark' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioInputStreammark_int"' sourceStream.mark(- 1); frameCount = countFrames(sourceStream); //UPGRADE_ISSUE: Method 'java.io.InputStream.reset' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioInputStreamreset"' sourceStream.reset(); } progressListener.converterUpdate(javazoom.jl.converter.Converter.ProgressListener_Fields.UPDATE_FRAME_COUNT, frameCount, 0); Obuffer output = null; Decoder decoder = new Decoder(decoderParams); Bitstream stream = new Bitstream(sourceStream); if (frameCount == - 1) frameCount = System.Int32.MaxValue; int frame = 0; long startTime = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; try { for (; frame < frameCount; frame++) { try { Header header = stream.readFrame(); if (header == null) break; progressListener.readFrame(frame, header); if (output == null) { // REVIEW: Incorrect functionality. // the decoder should provide decoded // frequency and channels output as it may differ from // the source (e.g. when downmixing stereo to mono.) int channels = (header.mode() == Header.SINGLE_CHANNEL)?1:2; int freq = header.frequency(); output = new WaveFileObuffer(channels, freq, destName); decoder.OutputBuffer = output; } Obuffer decoderOutput = decoder.decodeFrame(header, stream); // REVIEW: the way the output buffer is set // on the decoder is a bit dodgy. Even though // this exception should never happen, we test to be sure. if (decoderOutput != output) throw new System.ApplicationException("Output buffers are different."); progressListener.decodedFrame(frame, header, output); stream.closeFrame(); } catch (System.Exception ex) { bool stop = !progressListener.converterException(ex); if (stop) { throw new JavaLayerException(ex.Message, ex); } } } } finally { if (output != null) output.close(); } int time = (int) ((System.DateTime.Now.Ticks - 621355968000000000) / 10000 - startTime); progressListener.converterUpdate(javazoom.jl.converter.Converter.ProgressListener_Fields.UPDATE_CONVERT_COMPLETE, time, frame); } catch (System.IO.IOException ex) { throw new JavaLayerException(ex.Message, ex); } } }
//UPGRADE_NOTE: Synchronized keyword was removed from method 'convert'. Lock expression was added. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1027"' public virtual void convert(System.String sourceName, System.String destName, ProgressListener progressListener) { lock (this) { convert(sourceName, destName, progressListener, null); } }
public virtual void convert(System.String sourceName, System.String destName, ProgressListener progressListener, Decoder.Params decoderParams) { if (destName.Length == 0) destName = null; try { System.IO.Stream in_Renamed = openInput(sourceName); convert(in_Renamed, destName, progressListener, decoderParams); in_Renamed.Close(); } catch (System.IO.IOException ioe) { throw new JavaLayerException(ioe.Message, ioe); } }