auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void sendMessage(ConsumerRecord<?, ?> record, Instant readTime) throws Exception { int sendAttempts = 0; while (true) { sendAttempts++; int numBytes = record.serializedKeySize() + record.serializedValueSize(); _consumerMetrics.updateBytesProcessedRate(numBytes); DatastreamProducerRecord datastreamProducerRecord = translate(record, readTime); try { sendDatastreamProducerRecord(datastreamProducerRecord); return; } catch (Exception e) { _logger.error("Error sending Message. task: ; error: {};", _taskName, e.toString()); _logger.error("Stack Trace: {}", Arrays.toString(e.getStackTrace())); if (_shouldDie || sendAttempts >= _maxRetryCount) { if (sendAttempts >= _maxRetryCount && _pausePartitionOnRetryExhaustion) { _autoPausedSourcePartitions.add(new TopicPartition(record.topic(), record.partition())); _autoPausedPartitionsCount++; _taskUpdates.add(DatastreamConstants.UpdateType.PAUSE_RESUME_PARTITIONS); return; } else { _logger.info("Send messages failed with exception: {}", e); throw e; } } _logger.warn("Sleeping for seconds before retrying. Retry of {}", _retrySleepDuration.getSeconds(), sendAttempts, _maxRetryCount); Thread.sleep(_retrySleepDuration.toMillis()); } } }

Target:
protected void sendMessage(ConsumerRecord<?, ?> record, Instant readTime) throws Exception { int sendAttempts = 0; while (true) { sendAttempts++; int numBytes = record.serializedKeySize() + record.serializedValueSize(); _consumerMetrics.updateBytesProcessedRate(numBytes); DatastreamProducerRecord datastreamProducerRecord = translate(record, readTime); try { sendDatastreamProducerRecord(datastreamProducerRecord); return; } catch (Exception e) { _logger.error("Error sending Message. task: ; error: {};", _taskName, e.toString()); _logger.error("Stack Trace: {}", Arrays.toString(e.getStackTrace())); if (_shouldDie || sendAttempts >= _maxRetryCount) { _logger.error("Send messages failed with exception: {}", e); throw e; } _logger.warn("Sleeping for seconds before retrying. Retry of {}", _retrySleepDuration.getSeconds(), sendAttempts, _maxRetryCount); Thread.sleep(_retrySleepDuration.toMillis()); } } }
Source:
CompletableFuture<Object> poll(String location, Duration delay, Duration duration) { CompletableFuture<Object> resultFuture = new CompletableFuture<>(); long deadline = System.currentTimeMillis() + duration.toMillis(); CompletableRequest req = new CompletableRequest(Request.GET, location); Future pollFuture = executor.submit(() -> { do { req.call().thenAccept(res -> { if (req.isRedirected()) { resultFuture.complete(res.getResult()); } }).exceptionally(ex -> { resultFuture.completeExceptionally(ex.getCause()); return null; }); try { Thread.sleep(delay.toMillis()); } catch (InterruptedException e) { return; } } while (deadline > System.currentTimeMillis()); }); resultFuture.whenComplete((result, thrown) -> { pollFuture.cancel(true); }); return resultFuture; }

Target:
protected CompletableFuture<Object> poll(String location, Duration delay, Duration duration) { CompletableFuture<Object> resultFuture = new CompletableFuture<>(); long deadline = System.nanoTime() + duration.toNanos(); CompletableRequest req = new CompletableRequest(Request.GET, location); Future pollFuture = executor.submit(() -> { do { req.call().thenAccept(res -> { if (req.isRedirected()) { resultFuture.complete(res.getResult()); } }).exceptionally(ex -> { resultFuture.completeExceptionally(ex.getCause()); return null; }); try { Thread.sleep(delay.toMillis()); } catch (InterruptedException e) { return; } } while (deadline > System.nanoTime()); }); resultFuture.whenComplete((result, thrown) -> { pollFuture.cancel(true); }); return resultFuture; }
Source:
protected void postLoad(DAnalysis dAnalysis, Version loadedVersion) { if (loadedVersion.compareTo(MIGRATION_VERSION) < 0) { Iterator<EObject> it = EcoreUtil.getAllContents(getGMFDiagrams(dAnalysis)); while (it.hasNext()) { EObject next = it.next(); if (next instanceof View && ViewType.NOTE.equals(((View) next).getType()) && ((View) next).getElement() instanceof DRepresentationDescriptor) { SiriusNoteViewFactory.markAsLinkNote((View) next); } } } }

Target:
protected void postLoad(DAnalysis dAnalysis, Version loadedVersion) { if (loadedVersion.compareTo(MIGRATION_VERSION) < 0) { StringBuilder builder = new StringBuilder(); boolean isModified = false; for (DView view : dAnalysis.getOwnedViews()) { for (DRepresentation representation : new DViewQuery(view).getLoadedRepresentations()) { if (representation instanceof DDiagram) { DDiagramGraphicalQuery query = new DDiagramGraphicalQuery((DDiagram) representation); Option<Diagram> option = query.getAssociatedGMFDiagram(); if (option.some() && migrateDiagram(option.get())) { builder.append(MessageFormat.format(Messages.LinkNoteMigrationParticipant_entry, representation.getName())).append(System.lineSeparator()); isModified = true; } } } } if (isModified) { builder.insert(0, System.lineSeparator()); builder.insert(0, Messages.LinkNoteMigrationParticipant_title); DiagramPlugin.getDefault().logInfo(builder.toString()); } } }
Source:
public boolean isExpired(final String token) { boolean isUnknownToken; isUnknownToken = isUnknown(token); if (!isUnknownToken) { isUnknownToken = (getTokenExpiration(token) <= System.currentTimeMillis()); } return isUnknownToken; }

Target:
public boolean isExpired(final String token) { boolean isExpired; isExpired = isUnknown(token); if (!isExpired) { isExpired = (getTokenExpiration(token) <= System.currentTimeMillis()); } return isExpired; }
Source:
private void removeDeviceInternal(String deviceId) { synchronized (mConfigLock) { Iterator<Device> it = mConfig.devices.iterator(); while (it.hasNext()) { Device d = it.next(); if (d.deviceID.equals(deviceId)) { it.remove(); } } } }

Target:
private void removeDeviceInternal(String deviceId) { synchronized (mConfigLock) { Iterator<Device> it = mConfig.devices.iterator(); while (it.hasNext()) { Device d = it.next(); if (d.deviceID.equals(deviceId)) { it.remove(); break; } } } }
Source:
public IObservableValue<?> getObservableValue() { return (IObservableValue<?>) source; }

Target:
public IObservableValue<T> getObservableValue() { return (IObservableValue<T>) source; }
Source:
private SymbolStatsEstimate getExpressionStats(Expression expression) { return Symbol.optionalFrom(expression) .map(symbol -> requireNonNull(input.getSymbolStatistics(symbol), () -> format("No statistics for symbol %s", symbol))) .orElseGet(() -> scalarStatsCalculator.calculate(expression, input, session)); }

Target:
private SymbolStatsEstimate getExpressionStats(Expression expression) { if (expression instanceof SymbolReference) { Symbol symbol = Symbol.from(expression); return requireNonNull(input.getSymbolStatistics(symbol), () -> format("No statistics for symbol %s", symbol)); } return scalarStatsCalculator.calculate(expression, input, session); }
Source:
public Vector2i toInt() { return new SpongeVector2i((int) Math.round(x), (int) Math.round(y)); }

Target:
public Vector2i toInt() { return new SpongeVector2i((int) x, (int) y); }
Source:
public void startup(IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor, 1); Preferences preferences = ResourcesPlugin.getPlugin().getPluginPreferences(); preferences.addPropertyChangeListener(this); refreshJob = new RefreshJob(); monitors = new MonitorManager(workspace, this); boolean autoRefresh = preferences.getBoolean(ResourcesPlugin.PREF_AUTO_REFRESH); if (autoRefresh) manageAutoRefresh(autoRefresh, subMonitor.split(1)); subMonitor.setWorkRemaining(0); }

Target:
public void startup(IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor, 1); Preferences preferences = ResourcesPlugin.getPlugin().getPluginPreferences(); preferences.addPropertyChangeListener(this); refreshJob = new RefreshJob(); monitors = new MonitorManager(workspace, this); boolean autoRefresh = preferences.getBoolean(ResourcesPlugin.PREF_AUTO_REFRESH); if (autoRefresh) manageAutoRefresh(autoRefresh, subMonitor.split(1)); }
Source:
public void testExitOnError() throws Exception { XMLParser.Config config = new XMLParser.Config("body", "UTF-8", "title:/book/title,author:/book/author," + "year:/book/year", "title:string,author:int,year:int", "Exit on error"); try { Transform<StructuredRecord, StructuredRecord> transform = new XMLParser(config); transform.initialize(new MockTransformContext()); StructuredRecord inputRecord = StructuredRecord.builder(INPUT) .set("offset", 1) .set("body", "<book category=\"COOKING\"><title lang=\"en\">Everyday Italian</title>" + "<author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book>").build(); MockEmitter<StructuredRecord> emitter = new MockEmitter<>(); transform.transform(inputRecord, emitter); } catch (IllegalStateException e) { LOG.error("Test passes. Exiting on exception.", e); } }

Target:
public void testExitOnError() throws Exception { XMLParser.Config config = new XMLParser.Config("body", "UTF-8", "title:/book/title,author:/book/author," + "year:/book/year", "title:string,author:int,year:int", "Exit on error"); try { Transform<StructuredRecord, StructuredRecord> transform = new XMLParser(config); transform.initialize(new MockTransformContext()); StructuredRecord inputRecord = StructuredRecord.builder(INPUT) .set("offset", 1) .set("body", "<book category=\"COOKING\"><title lang=\"en\">Everyday Italian</title>" + "<author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book>").build(); MockEmitter<StructuredRecord> emitter = new MockEmitter<>(); transform.transform(inputRecord, emitter); Assert.fail(); } catch (IllegalStateException e) { LOG.error("Test passes. Exiting on exception.", e); } }
Source:
private boolean isUserMetric(MetricResult metricResult) { MetricName metricName = metricResult.getKey().metricName(); String urn = ((MonitoringInfoMetricName) metricName).getUrn(); return (metricName instanceof MonitoringInfoMetricName) && (urn.contains(MonitoringInfoConstants.Urns.USER_SUM_INT64) || urn.contains(MonitoringInfoConstants.Urns.USER_SUM_DOUBLE)|| urn.contains(MonitoringInfoConstants.Urns.USER_DISTRIBUTION_DOUBLE) || urn.contains(MonitoringInfoConstants.Urns.USER_DISTRIBUTION_INT64)); }

Target:
private boolean isUserMetric(MetricResult metricResult) { MetricName metricName = metricResult.getKey().metricName(); if (metricName instanceof MonitoringInfoMetricName) { String urn = ((MonitoringInfoMetricName) metricName).getUrn(); return urn.contains(MonitoringInfoConstants.Urns.USER_SUM_INT64) || urn.contains(MonitoringInfoConstants.Urns.USER_SUM_DOUBLE) || urn.contains(MonitoringInfoConstants.Urns.USER_DISTRIBUTION_DOUBLE) || urn.contains(MonitoringInfoConstants.Urns.USER_DISTRIBUTION_INT64); } return false; }
Source:
public Collection<String> getTokenIdentifiers() { return CACHE.asMap().keySet(); }

Target:
public Collection<String> getTokenIdentifiers() { return Collections.unmodifiableCollection(CACHE.asMap().keySet()); }
Source:
public CacheResource parse(ConfigResource parent, IdString id) throws AuthException, ResourceNotFoundException { final CurrentUser user = self.get(); if (user instanceof AnonymousUser) { throw new AuthException("Authentication required"); } else if(!(user.isIdentifiedUser())) { throw new ResourceNotFoundException(); } if (!user.getCapabilities().canViewCaches()) { throw new AuthException("not allowed to view caches"); } String cacheName = id.get(); String pluginName = "gerrit"; int i = cacheName.lastIndexOf('-'); if (i != -1) { pluginName = cacheName.substring(0, i); cacheName = cacheName.length() > i + 1 ? cacheName.substring(i + 1) : ""; } Provider<Cache<?, ?>> cacheProvider = cacheMap.byPlugin(pluginName).get(cacheName); if (cacheProvider == null) { throw new ResourceNotFoundException(id); } return new CacheResource(pluginName, cacheName, cacheProvider); }

Target:
public CacheResource parse(ConfigResource parent, IdString id) throws AuthException, ResourceNotFoundException { CurrentUser user = self.get(); if (user instanceof AnonymousUser) { throw new AuthException("Authentication required"); } else if (!user.isIdentifiedUser()) { throw new ResourceNotFoundException(); } else if (!user.getCapabilities().canViewCaches()) { throw new AuthException("not allowed to view caches"); } String cacheName = id.get(); String pluginName = "gerrit"; int i = cacheName.lastIndexOf('-'); if (i != -1) { pluginName = cacheName.substring(0, i); cacheName = cacheName.length() > i + 1 ? cacheName.substring(i + 1) : ""; } Provider<Cache<?, ?>> cacheProvider = cacheMap.byPlugin(pluginName).get(cacheName); if (cacheProvider == null) { throw new ResourceNotFoundException(id); } return new CacheResource(pluginName, cacheName, cacheProvider); }
Source:
public <T> T service(String name) { if (!enterBusy()) return null; try { ctx.security().authorize(name, SecurityPermission.SERVICE_INVOKE, null); Collection<ServiceContextImpl> ctxs = Optional.ofNullable(lookupDeployedServiceId(name)) .map(locServices::get).orElse(null); if (F.isEmpty(ctxs)) return null; for (ServiceContextImpl ctx : ctxs) { Service svc = ctx.service(); if (svc != null) return (T)svc; } return null; } finally { leaveBusy(); } }

Target:
@Override public <T> T service(String name) { ctx.security().authorize(name, SecurityPermission.SERVICE_INVOKE, null); Collection<ServiceContextImpl> ctxs; synchronized (locSvcs) { ctxs = locSvcs.get(name); } if (ctxs == null) return null; synchronized (ctxs) { if (ctxs.isEmpty()) return null; for (ServiceContextImpl ctx : ctxs) { Service svc = ctx.service(); if (svc != null) return (T)svc; } return null; } }
Source:
void notifyException(Exception exception) { this.exception = exception; interruptTestThread(); }

Target:
void notifyException(Exception exception) { this.exception = Objects.requireNonNull(exception); if (! Thread.currentThread().equals(testThread) && testThreadInterrupted.compareAndSet(false, true)) { testThread.interrupt(); } }
Source:
public void initPlugin(final BRLConditionColumn brlConditionColumn) { plugin.setOriginalColumnConfig52(brlConditionColumn); final NewGuidedDecisionTableColumnWizard wizard = new NewGuidedDecisionTableColumnWizard(mock(WizardView.class), mock(SummaryPage.class), mock(TranslationService.class), mock(DecisionTablePopoverUtils.class)); doReturn(EXTENDED_ENTRY).when(model).getTableFormat(); doReturn(model).when(presenter).getModel(); doReturn(mock(EventBus.class)).when(presenter).getEventBus(); wizard.init(presenter); plugin.init(wizard); }

Target:
private void initPlugin(final BRLConditionColumn brlConditionColumn) { plugin.setOriginalColumnConfig52(brlConditionColumn); final NewGuidedDecisionTableColumnWizard wizard = new NewGuidedDecisionTableColumnWizard(mock(WizardView.class), mock(SummaryPage.class), mock(TranslationService.class), mock(DecisionTablePopoverUtils.class)); doReturn(EXTENDED_ENTRY).when(model).getTableFormat(); doReturn(model).when(presenter).getModel(); doReturn(mock(EventBus.class)).when(presenter).getEventBus(); wizard.init(presenter); plugin.init(wizard); }
Source:
public Change perform(IProgressMonitor pm) throws CoreException { try { pm.beginTask(getName(), 1); final INamedElementEditor editor = ModelUtils .findEditor(element); boolean isDirtyInEditor = false; if (editor != null && editor.isDirty()) { isDirtyInEditor = true; } IQ7NamedElement elementWc = element.getWorkingCopy(pm); try { elementWc.setTags(elementTags); if (!isDirtyInEditor) { if (editor != null) { final IProgressMonitor monitor = pm; Display.getDefault().syncExec(new Runnable() { public void run() { editor.doSave(monitor); } }); } else { WriteAccessChecker writeAccessChecker = new WriteAccessChecker(); if (writeAccessChecker.makeResourceWritable(elementWc)) { elementWc.commitWorkingCopy(true, pm); } } } } catch (Exception e) { Q7UIPlugin.log(e); } finally { elementWc.discardWorkingCopy(); } Tag restoredTag = tag; TagsRegistry registry = Q7UIPlugin.getDefault().getTags(); synchronized (registry) { for (Tag currentTag : registry.getTags()) { if (currentTag.getPath().equals(tag.getPath())) { restoredTag = currentTag; break; } } } return new DeleteTagReferenceChange(element, restoredTag); } finally { pm.done(); } }

Target:
public Change perform(IProgressMonitor pm) throws CoreException { try { pm.beginTask(getName(), 1); final INamedElementEditor editor = ModelUtils .findEditor(element); boolean isDirtyInEditor = false; if (editor != null && editor.isDirty()) { isDirtyInEditor = true; } IQ7NamedElement elementWc = element.getWorkingCopy(pm); try { elementWc.setTags(elementTags); if (!isDirtyInEditor) { if (editor != null) { final IProgressMonitor monitor = pm; Display.getDefault().syncExec(new Runnable() { public void run() { editor.doSave(monitor); } }); } else { elementWc.commitWorkingCopy(true, pm); } } } catch (Exception e) { Q7UIPlugin.log(e); } finally { elementWc.discardWorkingCopy(); } Tag restoredTag = tag; TagsRegistry registry = Q7UIPlugin.getDefault().getTags(); synchronized (registry) { for (Tag currentTag : registry.getTags()) { if (currentTag.getPath().equals(tag.getPath())) { restoredTag = currentTag; break; } } } return new DeleteTagReferenceChange(element, restoredTag); } finally { pm.done(); } }
Source:
protected VariablesDropSupport(TreeViewer viewer, TestSuiteModel model) { super(viewer); fTreeViewer = viewer; fModel = model; }

Target:
protected VariablesDropSupport(TreeViewer viewer, TestSuiteModel model) { super(viewer); fModel = model; }
Source:
public void close() { for (Map.Entry<TopicPartition, TopicPartitionWriter> ent : topicPartitionWriters.entrySet()) { try { TopicPartitionWriter writer = ent.getValue(); if (writer != null) { writer.close(); } } catch (ConnectException e) { log.warn( "Unable to close writer for topic partition {}: {}", ent.getKey(), e.getMessage(), e ); } } topicPartitionWriters.clear(); assignment.clear(); }

Target:
public void close() { for (TopicPartitionWriter writer : topicPartitionWriters.values()) { try { if (writer != null) { writer.close(); } } catch (ConnectException e) { log.warn("Unable to close writer for topic partition {}: ", writer.topicPartition(), e); } } topicPartitionWriters.clear(); assignment.clear(); }
Source:
private static String normaliseTypeName(String dataType) { if (dataType.indexOf("(")<=0) dataType = dataType.toUpperCase().trim(); else dataType = dataType.toUpperCase().trim().substring(0,dataType.indexOf("(")); return dataType; }

Target:
private static String normaliseTypeName(String dataType) { if (dataType.indexOf("(") <= 0) { dataType = dataType.toUpperCase().trim(); } else { dataType = dataType.toUpperCase().trim().substring(0,dataType.indexOf("(")); } return dataType; }
Source:
protected void execute() { try { final InfoResponse response = createProtocol().info(); if (response == null) { logger.error("Failed to connect to neohub [host '{}' port '{}']", new Object[] { hostname, port }); return; } for (NeoHubBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { final String device = provider.getNeoStatDevice(itemName); final NeoStatProperty property = provider.getNeoStatProperty(itemName); final State result = mapResponseToState(response, device, property); if (eventPublisher != null) { eventPublisher.postUpdate(itemName, result); } } } } catch (final RuntimeException e) { logger.warn("Failed to fetch info from neo hub.", e); } }

Target:
protected void execute() { try { final InfoResponse response = createProtocol().info(); if (response == null) { return; } for (NeoHubBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { final String device = provider.getNeoStatDevice(itemName); final NeoStatProperty property = provider.getNeoStatProperty(itemName); final State result = mapResponseToState(response, device, property); if (eventPublisher != null) { eventPublisher.postUpdate(itemName, result); } } } } catch (final RuntimeException e) { logger.warn("Failed to fetch info from neo hub.", e); } }
Source:
void updateInfo() { DirectionsGenerator gen = new DirectionsGenerator(itinerary.legs, getActivity().getApplicationContext()); List<Direction> directions = gen.getDirections(); Direction direction_data[] = directions.toArray(new Direction[directions.size()]); DirectionExpandableListAdapter adapter = new DirectionExpandableListAdapter( getActivity(), R.layout.list_direction_item, R.layout.list_subdirection_item, direction_data); mDirectionsListView.setAdapter(adapter); mDirectionsListView.setGroupIndicator(null); Context context = Application.get().getApplicationContext(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); NotificationChannel channel = manager.getNotificationChannel(Application.CHANNEL_REALTIME_ID); if(channel.getImportance() != NotificationManager.IMPORTANCE_NONE){ RealtimeService.start(getActivity(), getArguments()); } } else{ if (Application.getPrefs() .getBoolean(getString(R.string.preference_key_trip_plan_notifications), true)) { RealtimeService.start(getActivity(), getArguments()); } } }

Target:
void updateInfo() { DirectionsGenerator gen = new DirectionsGenerator(itinerary.legs, getActivity().getApplicationContext()); List<Direction> directions = gen.getDirections(); Direction direction_data[] = directions.toArray(new Direction[directions.size()]); DirectionExpandableListAdapter adapter = new DirectionExpandableListAdapter( getActivity(), R.layout.list_direction_item, R.layout.list_subdirection_item, direction_data); mDirectionsListView.setAdapter(adapter); mDirectionsListView.setGroupIndicator(null); Context context = Application.get().getApplicationContext(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); NotificationChannel channel = manager.getNotificationChannel(Application.CHANNEL_TRIP_PLAN_UPDATES_ID); if(channel.getImportance() != NotificationManager.IMPORTANCE_NONE){ RealtimeService.start(getActivity(), getArguments()); } } else { if (Application.getPrefs() .getBoolean(getString(R.string.preference_key_trip_plan_notifications), true)) { RealtimeService.start(getActivity(), getArguments()); } } }
Source:
public void eventFilterApplied(TmfFilterAppliedSignal signal) { if (signal.getSource() == this) { return; } Runnable runnable = () -> { ITmfFilter eventFilter = signal.getFilter().getEventFilter(); if (eventFilter == null) { fTable.setData(Key.SEARCH_OBJ, null); fTable.refresh(); } else { fTable.setData(Key.SEARCH_OBJ, eventFilter); fTable.refresh(); searchNext(); } }; Display display = PlatformUI.getWorkbench().getDisplay(); if (display == Display.getCurrent()) { runnable.run(); } else { Display.getDefault().asyncExec(runnable); } }

Target:
public void eventFilterApplied(TmfFilterAppliedSignal signal) { if (signal.getSource() == this) { return; } Runnable runnable = () -> { if (fTable.isDisposed()) { return; } ITmfFilter eventFilter = signal.getFilter().getEventFilter(); if (eventFilter == null) { fTable.setData(Key.SEARCH_OBJ, null); fTable.refresh(); } else { fTable.setData(Key.SEARCH_OBJ, eventFilter); fTable.refresh(); searchNext(); } }; Display display = PlatformUI.getWorkbench().getDisplay(); if (display == Display.getCurrent()) { runnable.run(); } else { Display.getDefault().asyncExec(runnable); } }
Source:
private static CodeableConcept buildCode(Allergy allergy) { if (allergy.getAllergen() != null) { return FHIRUtils.createCodeableConcept(allergy.getAllergen()); } return null; }

Target:
private static CodeableConcept buildCode(Allergy allergy) { return (allergy.getAllergen() != null) ? FHIRUtils.createCodeableConcept(allergy.getAllergen()) : null; }
Source:
public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { supportRequestWindowFeature(Window.FEATURE_NO_TITLE); } catch (final AndroidRuntimeException ex) { Log.e("Error requesting indeterminate progress", ex); } this.setTheme(ActivityMixin.getDialogTheme()); final Bundle extras = getIntent().getExtras(); if (extras != null) { geocode = extras.getString(Intents.EXTRA_GEOCODE); } if (StringUtils.isBlank(geocode)) { showToast(res.getString(R.string.err_detail_cache_find)); finish(); return; } showDialog(); }

Target:
public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { supportRequestWindowFeature(Window.FEATURE_NO_TITLE); } catch (final AndroidRuntimeException ex) { Log.e("Error requesting no title feature", ex); } this.setTheme(ActivityMixin.getDialogTheme()); final Bundle extras = getIntent().getExtras(); if (extras != null) { geocode = extras.getString(Intents.EXTRA_GEOCODE); } if (StringUtils.isBlank(geocode)) { showToast(res.getString(R.string.err_detail_cache_find)); finish(); return; } showDialog(); }
Source:
public void samMetricsProvider() { final File[] files = new File[]{ simpleSamWithBaseErrors1, simpleSamWithBaseErrors2, simpleSingleStrandConsensusSamWithBaseErrors, simpleDuplexConsensusSamWithBaseErrors, chrMReadsWithClips}; OUTPUT_DATA_PATH = IOUtil.createTempDir("CollectSamErrorMetricsTest", null); for (final File file : files) { final File vcf = new File(TEST_DIR, "NIST.selected.vcf"); final File outputBaseFileName = new File(OUTPUT_DATA_PATH, file.getName()); outputBaseFileName.deleteOnExit(); final String[] args = { "INPUT=" + file, "OUTPUT=" + outputBaseFileName, "REFERENCE_SEQUENCE=" + CHR_M_REFERENCE.getAbsolutePath(), "ERROR_METRICS=" + "ERROR:TWO_BASE_PADDED_CONTEXT", "ERROR_METRICS=" + "ERROR:CONSENSUS", "ERROR_METRICS=" + "ERROR:NS_IN_READ", "ERROR_METRICS=" + "ERROR:BINNED_CYCLE", "VCF=" + vcf.getAbsolutePath() }; Assert.assertEquals(new CollectSamErrorMetrics().instanceMain(args), 0); errorMetrics.put(file, outputBaseFileName); } }

Target:
public void samMetricsProvider() { final File[] files = new File[]{ simpleSamWithBaseErrors1, simpleSamWithBaseErrors2, simpleSingleStrandConsensusSamWithBaseErrors, simpleDuplexConsensusSamWithBaseErrors, chrMReadsWithClips}; if (OUTPUT_DATA_PATH != null) { throw new PicardException("This should only be called once!"); } OUTPUT_DATA_PATH = IOUtil.createTempDir("CollectSamErrorMetricsTest", null); for (final File file : files) { final File vcf = new File(TEST_DIR, "NIST.selected.vcf"); final File outputBaseFileName = new File(OUTPUT_DATA_PATH, file.getName()); outputBaseFileName.deleteOnExit(); final String[] args = { "INPUT=" + file, "OUTPUT=" + outputBaseFileName, "REFERENCE_SEQUENCE=" + CHR_M_REFERENCE.getAbsolutePath(), "ERROR_METRICS=" + "ERROR:TWO_BASE_PADDED_CONTEXT", "ERROR_METRICS=" + "ERROR:CONSENSUS", "ERROR_METRICS=" + "ERROR:NS_IN_READ", "ERROR_METRICS=" + "ERROR:BINNED_CYCLE", "VCF=" + vcf.getAbsolutePath() }; Assert.assertEquals(new CollectSamErrorMetrics().instanceMain(args), 0); errorMetrics.put(file, outputBaseFileName); } }
Source:
public boolean check() { try { Integer exitCode = hub.getQueryService().getMandatoryContainer(containerId).getExitCode(); if (exitCode == null) { return false; } return exitCode == this.exitCode; } catch (DockerAccessException e) { return false; } }

Target:
public boolean check() { try { Integer exitCodeActual = hub.getQueryService().getMandatoryContainer(containerId).getExitCode(); return exitCodeActual != null && exitCodeActual == exitCodeExpected; } catch (DockerAccessException e) { return false; } }
Source:
public SpongeItemStatistic(String statId, String itemName, ITextComponent statName, Item item) { super(statId, itemName, statName, item); String args = new ItemStack(item).getDisplayName(); translation = new SpongeTranslation(statId.substring(0, statId.length() - 1), args); }

Target:
public SpongeItemStatistic(String statId, String itemName, ITextComponent statName, Item item) { super(statId, itemName, statName, item); }
Source:
protected void onCreate(Bundle arg0) { super.onCreate(arg0); setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); ActionBar bar = getSupportActionBar(); if (bar != null) { bar.setDisplayShowHomeEnabled(true); bar.setDisplayHomeAsUpEnabled(true); bar.setIcon(android.R.color.transparent); } errorNotification = new OverlayErrorNotification(progressWheel); snackbarErrorNotification = new SnackbarErrorNotification(progressWheel); Bundle bundle = arg0; if ( bundle == null ) { if ( getIntent() != null ) bundle = getIntent().getBundleExtra(Router.EXTRA_BUNDLE); } restore(bundle); blockDrawerFromOpening(); }

Target:
protected void onCreate(Bundle arg0) { super.onCreate(arg0); setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); ActionBar bar = getSupportActionBar(); if (bar != null) { bar.setDisplayShowHomeEnabled(true); bar.setDisplayHomeAsUpEnabled(true); bar.setIcon(android.R.color.transparent); } errorNotification = new FullScreenErrorNotification(contentLayout); snackbarErrorNotification = new SnackbarErrorNotification(contentLayout); Bundle bundle = arg0; if ( bundle == null ) { if ( getIntent() != null ) bundle = getIntent().getBundleExtra(Router.EXTRA_BUNDLE); } restore(bundle); blockDrawerFromOpening(); }
Source:
public static TACmiMeasureType fromInt(int type) { if (type >= 0 && type <= 21) { return measureTypes[type]; } else { logger.warn("Received unexpected measure type {}", type); return TACmiMeasureType.UNSUPPORTED; } }

Target:
public static TACmiMeasureType fromInt(int type) { for (TACmiMeasureType mtype : TACmiMeasureType.values()) { if (mtype.getTypeValue() == type) { return mtype; } } logger.warn("Received unexpected measure type {}", type); return TACmiMeasureType.UNSUPPORTED; }
Source:
private synchronized void processTableConfigurationItem(WatchedEvent event) { if (event.getPath() == null || event.getPath().isEmpty()) return; try { Stat versionStat = getZooKeeper().exists(event.getPath(), watcher); if (versionStat == null) { return; } byte[] configToRefresh = getZooKeeper().getData(event.getPath(), true, versionStat); if (configToRefresh == null) { return; } if ((versionStat != null) && (versionStat.getVersion() - lastTableConfigVersion == 1)) { lastTableConfigVersion = versionStat.getVersion(); refreshTableConfig(configToRefresh); if (log.isTraceEnabled()) { log.trace( "Successfully refreshed table single table config: " + new String(configToRefresh)); } } else { if (log.isTraceEnabled()) { log.trace("We have to update all table configs."); } if (versionStat != null) { lastTableConfigVersion = versionStat.getVersion(); updateAllTableConfigurations(); } } } catch (Exception e) { log.error("Error getting data from TABLE_CONFIGS zoonode " + e.getMessage()); } return; }

Target:
private synchronized void processTableConfigurationItem(WatchedEvent event) throws KeeperException, InterruptedException { if (event.getPath() == null || event.getPath().isEmpty()) return; Stat versionStat = new Stat(); byte[] configToRefresh = getZooKeeper().getData(event.getPath(), watcher, versionStat); if (configToRefresh == null) { throw new IllegalStateException("The table-config-version znode should have data in it."); } if ((versionStat != null) && (versionStat.getVersion() - lastTableConfigVersion == 1)) { lastTableConfigVersion = versionStat.getVersion(); refreshTableConfig(configToRefresh); if (log.isTraceEnabled()) { log.trace( "Successfully refreshed table single table config: " + new String(configToRefresh)); } } else { if (log.isTraceEnabled()) { log.trace("We have to update all table configs."); } if (versionStat != null) { lastTableConfigVersion = versionStat.getVersion(); updateAllTableConfigurations(); } } return; }
Source:
public void obtainStyledAttributes_shouldExtractAttributesFromAttributeSet() throws Exception { RoboAttributeSet roboAttributeSet = shadowOf(RuntimeEnvironment.application).createAttributeSet( new Attribute(TEST_PACKAGE + ":attr/itemType", "ungulate", TEST_PACKAGE), new Attribute(TEST_PACKAGE + ":attr/scrollBars", "horizontal|vertical", TEST_PACKAGE), new Attribute(TEST_PACKAGE + ":attr/quitKeyCombo", "^q", TEST_PACKAGE), new Attribute(TEST_PACKAGE + ":attr/aspectRatio", "1.5", TEST_PACKAGE), new Attribute(TEST_PACKAGE + ":attr/aspectRatioEnabled", "true", TEST_PACKAGE) ); TypedArray a = context.obtainStyledAttributes(roboAttributeSet, R.styleable.CustomView); assertThat(a.getInt(R.styleable.CustomView_itemType, -1234)).isEqualTo(1 ); assertThat(a.getInt(R.styleable.CustomView_scrollBars, -1234)).isEqualTo(0x300); assertThat(a.getString(R.styleable.CustomView_quitKeyCombo)).isEqualTo("^q"); assertThat(a.getText(R.styleable.CustomView_quitKeyCombo).toString()).isEqualTo("^q"); assertThat(a.getFloat(R.styleable.CustomView_aspectRatio, 1f)).isEqualTo(1.5f); assertThat(a.getBoolean(R.styleable.CustomView_aspectRatioEnabled, false)).isTrue(); TypedArray typedArray = context.obtainStyledAttributes(roboAttributeSet, new int[]{R.attr.quitKeyCombo, R.attr.itemType}); assertThat(typedArray.getString(0)).isEqualTo("^q"); assertThat(typedArray.getInt(1, -1234)).isEqualTo(1 ); }

Target:
public void obtainStyledAttributes_shouldExtractAttributesFromAttributeSet() throws Exception { RoboAttributeSet roboAttributeSet = ShadowApplication.getInstance().createAttributeSet( new Attribute(TEST_PACKAGE + ":attr/itemType", "ungulate", TEST_PACKAGE), new Attribute(TEST_PACKAGE + ":attr/scrollBars", "horizontal|vertical", TEST_PACKAGE), new Attribute(TEST_PACKAGE + ":attr/quitKeyCombo", "^q", TEST_PACKAGE), new Attribute(TEST_PACKAGE + ":attr/aspectRatio", "1.5", TEST_PACKAGE), new Attribute(TEST_PACKAGE + ":attr/aspectRatioEnabled", "true", TEST_PACKAGE) ); TypedArray a = context.obtainStyledAttributes(roboAttributeSet, R.styleable.CustomView); assertThat(a.getInt(R.styleable.CustomView_itemType, -1234)).isEqualTo(1 ); assertThat(a.getInt(R.styleable.CustomView_scrollBars, -1234)).isEqualTo(0x300); assertThat(a.getString(R.styleable.CustomView_quitKeyCombo)).isEqualTo("^q"); assertThat(a.getText(R.styleable.CustomView_quitKeyCombo).toString()).isEqualTo("^q"); assertThat(a.getFloat(R.styleable.CustomView_aspectRatio, 1f)).isEqualTo(1.5f); assertThat(a.getBoolean(R.styleable.CustomView_aspectRatioEnabled, false)).isTrue(); TypedArray typedArray = context.obtainStyledAttributes(roboAttributeSet, new int[]{R.attr.quitKeyCombo, R.attr.itemType}); assertThat(typedArray.getString(0)).isEqualTo("^q"); assertThat(typedArray.getInt(1, -1234)).isEqualTo(1 ); }
Source:
public static String createFlagIssue(JiraClient jiraClient, String principalId, String displayName, String dataObjectId) { Map<String,String> params = new HashMap<String,String>(); params.put(JIRA_PRINCIPAL_ID_ISSUE_FIELD_NAME, principalId); params.put(JIRA_USER_DISPLAY_NAME_ISSUE_FIELD_NAME, displayName); params.put(JIRA_SYNAPSE_ENTITY_ID_FIELD_NAME, dataObjectId); CreatedIssue createdIssue = createIssue(jiraClient, JIRA_FLAG_ISSUE_TYPE_NAME, FLAG_SUMMARY, params); return (String) createdIssue.getKey(); }

Target:
public static String createFlagIssue(JiraClient jiraClient, String principalId, String displayName, String dataObjectId) { Map<String,String> params = new HashMap<String,String>(); params.put(JIRA_PRINCIPAL_ID_ISSUE_FIELD_NAME, principalId); params.put(JIRA_USER_DISPLAY_NAME_ISSUE_FIELD_NAME, displayName); params.put(JIRA_SYNAPSE_ENTITY_ID_FIELD_NAME, dataObjectId); CreatedIssue createdIssue = createIssue(jiraClient, JIRA_FLAG_ISSUE_TYPE_NAME, FLAG_SUMMARY, params); return createdIssue.getKey(); }
Source:
public void execute() throws MojoExecutionException { if (!outputDirectory.exists()) { outputDirectory.mkdirs(); } List<String> list = new ArrayList<>(); for (File jsonFile : cucumberFiles(cucumberOutput)) { list.add(jsonFile.getAbsolutePath()); } list.addAll(jsonFiles); try { Configuration configuration = new Configuration(outputDirectory, projectName); configuration.setBuildNumber(buildNumber); configuration.setParallelTesting(parallelTesting); if (!MapUtils.isEmpty(classifications)) { for (Map.Entry<String, String> entry : classifications.entrySet()) { configuration.addClassifications(StringUtils.capitalise(entry.getKey()), entry.getValue()); } } ReportBuilder reportBuilder = new ReportBuilder(list, configuration); getLog().info("About to generate Cucumber report."); Reportable report = reportBuilder.generateReports(); if (checkBuildResult && null != report && report.getScenarios() > report.getPassedScenarios()) { float totalScenarios = report.getScenarios(); float passedScenarios = report.getPassedScenarios(); getLog().info("Total Scenarios : " + totalScenarios + " , Passed Scenarios : " + passedScenarios); float percent = ((passedScenarios / totalScenarios) * 100); getLog().info( "Test Pass percent : " + percent + "% , PassPercentThreshold : " + passPercentThreshold + "%"); if (passPercentThreshold > percent) { throw new MojoExecutionException("BUILD FAILED - Check Report For Details"); } } } catch (Exception e) { throw new MojoExecutionException("Error Found:", e); } }

Target:
public void execute() throws MojoExecutionException { if (!outputDirectory.exists()) { outputDirectory.mkdirs(); } List<String> list = new ArrayList<>(); for (File jsonFile : cucumberFiles(cucumberOutput)) { list.add(jsonFile.getAbsolutePath()); } list.addAll(jsonFiles); try { Configuration configuration = new Configuration(outputDirectory, projectName); configuration.setBuildNumber(buildNumber); configuration.setParallelTesting(parallelTesting); if (!MapUtils.isEmpty(classifications)) { for (Map.Entry<String, String> entry : classifications.entrySet()) { configuration.addClassifications(StringUtils.capitalise(entry.getKey()), entry.getValue()); } } ReportBuilder reportBuilder = new ReportBuilder(list, configuration); getLog().info("About to generate Cucumber report."); Reportable report = reportBuilder.generateReports(); if (checkBuildResult && null != report && report.getScenarios() > report.getPassedScenarios()) { float totalScenarios = report.getScenarios(); float passedScenarios = report.getPassedScenarios(); getLog().info("Total Scenarios : " + totalScenarios + " , Passed Scenarios : " + passedScenarios); float percent = (passedScenarios / totalScenarios) * 100; getLog().info( "Test Pass percent : " + percent + "% , PassPercentThreshold : " + passPercentThreshold + "%"); if (passPercentThreshold > percent) { throw new MojoFailureException("BUILD FAILED - Pass Percent of Tests is :" + percent + " which is less than defined Threshold of " + passPercentThreshold); } } } catch (Exception e) { throw new MojoExecutionException("Error Found:", e); } }
Source:
public static final RESTException create(int code, String streamsMessage) { RESTErrorMessage error = null; RESTException rcException; try { error = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(streamsMessage, RESTErrorMessage.class); } catch (IllegalStateException e) { rcException = new RESTException(code, streamsMessage); } rcException = new RESTException(code, error); return rcException; }

Target:
public static final RESTException create(int code, String streamsMessage) { RESTErrorMessage error = null; RESTException rcException; try { error = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(streamsMessage, RESTErrorMessage.class); rcException = new RESTException(code, error); } catch (IllegalStateException e) { rcException = new RESTException(code, streamsMessage); } return rcException; }
Source:
public void addRow( final TupleBatch from, final int fromRow, final MutableTupleBuffer to, final int toRow, final int offset) { Objects.requireNonNull(from, "from"); ReplaceableColumn toCol = to.getColumn(offset, toRow); final int inColumRow = to.getInColumnIndex(toRow); switch (aggOp) { case COUNT: toCol.replaceLong(toCol.getLong(inColumRow) + 1, inColumRow); break; default: throw new IllegalArgumentException(aggOp + " is invalid"); } }

Target:
public void addRow( final TupleBatch from, final int fromRow, final MutableTupleBuffer to, final int toRow, final int offset) { Objects.requireNonNull(from, "from"); ReplaceableColumn toCol = to.getColumn(offset, toRow); final int inColumnRow = to.getInColumnIndex(toRow); switch (aggOp) { case COUNT: toCol.replaceLong(toCol.getLong(inColumnRow) + 1, inColumnRow); break; default: throw new IllegalArgumentException(aggOp + " is invalid"); } }
Source:
public static boolean isNotNullAndNotEmpty(String string) { return ( (string != null) && (! string.trim().isEmpty())); }

Target:
public static boolean isNotNullAndNotEmpty(String string) { return ! (isNullOrEmpty(string)); }
Source:
public void applyToVertex(Vertex vertex) throws IOException { String[] vertexTypes = getEntityTypesOrDefault(vertex); String id = vertex.value("tim_id"); String adminVertexType = getAbstractType(vertexTypes); vertex.edges(Direction.BOTH).forEachRemaining(edge -> { if (edge.keys().contains("tim_id")) { String[] edgeTypes = getEntityTypesOrDefault(edge); for (String edgeType : edgeTypes) { Optional<Collection> collectionOptional = vres.getCollectionForType(edgeType); collectionOptional.ifPresent(collection -> { if (collection.getVre().getOwnType(vertexTypes) == null) { if (Objects.equals("language", adminVertexType) || Objects.equals("location", adminVertexType)) { duplicateDefaultInformationToMissingVariant(vertex, collection, adminVertexType); } else { List<String> types = Lists.newArrayList(edgeTypes); types.remove(edgeType); edge.property(TYPES_PROP, types.toArray(new String[types.size()])); } } }); } } }); processedTypes.clear(); }

Target:
public void applyToVertex(Vertex vertex) throws IOException { String[] vertexTypes = getEntityTypesOrDefault(vertex); String adminVertexType = getAbstractType(vertexTypes); vertex.edges(Direction.BOTH).forEachRemaining(edge -> { if (!Objects.equals(edge.label(), "VERSION_OF")) { String[] edgeTypes = getEntityTypesOrDefault(edge); for (String edgeType : edgeTypes) { Optional<Collection> collectionOptional = vres.getCollectionForType(edgeType); collectionOptional.ifPresent(collection -> { if (collection.getVre().getOwnType(vertexTypes) == null) { if (Objects.equals("language", adminVertexType) || Objects.equals("location", adminVertexType)) { duplicateDefaultInformationToMissingVariant(vertex, collection, adminVertexType); } else { List<String> types = Lists.newArrayList(edgeTypes); types.remove(edgeType); try { edge.property("types", objectMapper.writeValueAsString(types)); } catch (JsonProcessingException e) { throw new RuntimeException("Types could not be set to edge", e); } } } }); } } }); processedTypes.clear(); }
Source:
public static void registerNodeType(Workspace workspace, String typeName, boolean referenceable, boolean orderable, boolean mixin) { try { NodeTypeManager manager = workspace.getNodeTypeManager(); if (manager.hasNodeType(typeName) == false) { logger.info("Registering node type: in workspace {}", typeName, workspace .getName()); String type; if(manager.getClass().toString().contains("jackrabbit")) { type = "[" + typeName + "] > nt:unstructured "; } else { type = "[" + typeName + "] > brix:unstructured "; } if (referenceable) { type += ", mix:referenceable "; } if (orderable) { type += "orderable "; } if (mixin) { type += " mixin"; } CndImporter.registerNodeTypes(new StringReader(type), workspace.getSession()); } else { logger.info("Type: already registered in workspace {}", typeName, workspace .getName()); } } catch (Exception e) { throw new RuntimeException("Could not register type: " + typeName, e); } }

Target:
public static void registerNodeType(Workspace workspace, String typeName, boolean referenceable, boolean orderable, boolean mixin) { try { NodeTypeManager manager = workspace.getNodeTypeManager(); if (manager.hasNodeType(typeName) == false) { logger.info("Registering node type: in workspace {}", typeName, workspace .getName()); String type; if(manager.getClass().getName().contains("jackrabbit")) { type = "[" + typeName + "] > nt:unstructured "; } else { type = "[" + typeName + "] > brix:unstructured "; } if (referenceable) { type += ", mix:referenceable "; } if (orderable) { type += "orderable "; } if (mixin) { type += " mixin"; } CndImporter.registerNodeTypes(new StringReader(type), workspace.getSession()); } else { logger.info("Type: already registered in workspace {}", typeName, workspace .getName()); } } catch (Exception e) { throw new RuntimeException("Could not register type: " + typeName, e); } }
Source:
public Service getServiceInstance(String name) { Stack<Service> stack = null; synchronized (services) { stack = services.get(name); if (stack == null) { stack = new Stack<Service>(); services.put(name, stack); } } synchronized (stack) { if (stack.isEmpty()) { return newServiceInstance(name); } else { Service service = stack.pop(); if (System.currentTimeMillis() - service.getLastUsed() > 10000) { for (int i = 0; i < stack.size(); i++) { metrics.closeService(name); } stack.clear(); return newServiceInstance(name); } return service; } } }

Target:
public Service getServiceInstance(String name) { Stack<Service> stack = null; synchronized (services) { stack = services.get(name); if (stack == null) { stack = new Stack<Service>(); services.put(name, stack); } } synchronized (stack) { if (stack.isEmpty()) { return newServiceInstance(name); } else { Service service = stack.pop(); if (System.currentTimeMillis() - service.getLastUsed() > expiryInterval) { for (int i = 0; i < stack.size(); i++) { metrics.closeService(name); } stack.clear(); return newServiceInstance(name); } return service; } } }
Source:
private <T> List<T> transform(JSONArray jsonList, Class<T> someClass) { List<T> result; try { result = objectMapper.readValue(jsonList.toJSONString(), objectMapper.getTypeFactory().constructCollectionType(List.class, someClass)); } catch (IOException e) { throw new StashException("Error parsing json strings to objects", e); } return result; }

Target:
private <T> List<T> transform(JSONArray jsonList, Class<T> someClass) { try { return objectMapper.readValue(jsonList.toJSONString(), objectMapper.getTypeFactory().constructCollectionType(List.class, someClass)); } catch (IOException e) { throw new StashException("Error parsing json strings to objects", e); } }
Source:
private void loadStatistics() { if (disposable != null) { disposable.dispose(); } disposable = Observable.fromCallable(() -> { List<StatisticsItem> statisticsData = DBReader.getStatistics(); Collections.sort(statisticsData, (item1, item2) -> CompareCompat.compareLong(item1.totalDownloadSize, item2.totalDownloadSize)); return statisticsData; }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(result -> { for (StatisticsItem item : result) { if (item.feed.getId() == feed.getId()) { podcastStatistics = item; break; } } showFeed(); }, error -> Log.e(TAG, Log.getStackTraceString(error))); }

Target:
private void loadStatistics() { if (disposableStatistics != null) { disposableStatistics.dispose(); } disposableStatistics = Observable.fromCallable(() -> { List<StatisticsItem> statisticsData = DBReader.getStatistics(); for (StatisticsItem statisticsItem : statisticsData) { if (statisticsItem.feed.getId() == feed.getId()) { return statisticsItem; } } return null; }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(result -> { txtvPodcastTime.setText(Converter.shortLocalizedDuration( getContext(), result.timePlayed)); txtvPodcastSpace.setText(Formatter.formatShortFileSize( getContext(), result.totalDownloadSize)); txtvPodcastEpisodeCount.setText(String.format(Locale.getDefault(), "%d%s", result.episodesDownloadCount, getString(R.string.episodes_suffix))); }, error -> { Log.d(TAG, Log.getStackTraceString(error)); lblStatistics.setVisibility(View.GONE); txtvPodcastSpace.setVisibility(View.GONE); txtvPodcastTime.setVisibility(View.GONE); txtvPodcastEpisodeCount.setVisibility(View.GONE); btnvOpenStatistics.setVisibility(View.GONE); }); }