auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testBinLogStartStop() throws Exception { AtomicInteger releaseCount = new AtomicInteger(); CountDownLatch ready = new CountDownLatch(2); binLog.put(new BinLog.ReleaseableWriteMarshallable() { public void release() { releaseCount.incrementAndGet(); } protected long version() { return 0; } protected String type() { return "test"; } public void writeMarshallablePayload(WireOut wire) { ready.countDown(); } }); binLog.put(new BinLog.ReleaseableWriteMarshallable() { protected long version() { return 0; } protected String type() { return "test"; } public void writeMarshallablePayload(WireOut wire) { ready.countDown(); } public void release() { releaseCount.incrementAndGet(); } }); ready.await(); Util.spinAssertEquals("Both records should be released", 2, releaseCount::get, 10, TimeUnit.SECONDS); Thread t = new Thread(() -> { try { binLog.stop(); } catch (InterruptedException e) { throw new AssertionError(e); } }); t.start(); t.join(60 * 1000); assertEquals("BinLog stop should not block forever", t.getState(), Thread.State.TERMINATED); Util.spinAssertEquals(2, releaseCount::get, 60); Util.spinAssertEquals(Thread.State.TERMINATED, binLog.binLogThread::getState, 60); }

Target:
public void testBinLogStartStop() throws Exception { AtomicInteger releaseCount = new AtomicInteger(); CountDownLatch ready = new CountDownLatch(2); Supplier<BinLog.ReleaseableWriteMarshallable> recordSupplier = () -> new BinLog.ReleaseableWriteMarshallable() { public void release() { releaseCount.incrementAndGet(); } protected long version() { return 0; } protected String type() { return "test"; } public void writeMarshallablePayload(WireOut wire) { ready.countDown(); } }; binLog.put(recordSupplier.get()); binLog.put(recordSupplier.get()); ready.await(1, TimeUnit.MINUTES); Util.spinAssertEquals("Both records should be released", 2, releaseCount::get, 10, TimeUnit.SECONDS); Thread t = new Thread(() -> { try { binLog.stop(); } catch (InterruptedException e) { throw new AssertionError(e); } }); t.start(); t.join(60 * 1000); assertEquals("BinLog should not take more than 1 minute to stop", t.getState(), Thread.State.TERMINATED); Util.spinAssertEquals(2, releaseCount::get, 60); Util.spinAssertEquals(Thread.State.TERMINATED, binLog.binLogThread::getState, 60); }
Source:
public void testVerificationResourceFields() throws HTTPError { BankAccount bankAccount = createdAssociatedBankAccount(); BankAccountVerification verification = bankAccount.verify(); assertEquals(verification.attempts.toString(), "0"); assertEquals(verification.attempts_remaining.toString(), "3"); assertNotNull(verification.created_at); assertEquals(verification.deposit_status, "succeeded"); assertTrue(verification.href.contains("/verifications/BZ")); assertTrue(verification.id.contains("BZ")); assertEquals(verification.bank_account.href, bankAccount.href); assertNotNull(verification.updated_at); assertEquals(verification.verification_status, "pending"); }

Target:
public void testVerificationResourceFields() throws HTTPError { BankAccount bankAccount = createdAssociatedBankAccount(); BankAccountVerification verification = bankAccount.verify(); assertEquals(verification.attempts.intValue(), 0); assertEquals(verification.attempts_remaining.intValue(), 3); assertNotNull(verification.created_at); assertEquals(verification.deposit_status, "succeeded"); assertTrue(verification.href.contains("/verifications/BZ")); assertTrue(verification.id.contains("BZ")); assertEquals(verification.bank_account.href, bankAccount.href); assertNotNull(verification.updated_at); assertEquals(verification.verification_status, "pending"); }
Source:
public void pauseResume() throws Exception { logger.log(Level.INFO, "Pause/Resume"); try { switch(getControlState()) { case COMM_IDLE: default: if (!this.controller.isStreaming()) { throw new Exception("Cannot pause while '" + getControlState() + "'."); } case COMM_SENDING: this.controller.pauseStreaming(); return; case COMM_SENDING_PAUSED: this.controller.resumeStreaming(); return; } } catch (Exception e) { logger.log(Level.SEVERE, "Exception in pauseResume", e); throw new Exception(Localization.getString("mainWindow.error.pauseResume")); } }

Target:
public void pauseResume() throws Exception { logger.log(Level.INFO, "Pause/Resume"); try { switch(getControlState()) { case COMM_IDLE: default: if (!isSendingFile()) { throw new Exception("Cannot pause while '" + getControlState() + "'."); } case COMM_SENDING: this.controller.pauseStreaming(); return; case COMM_SENDING_PAUSED: this.controller.resumeStreaming(); return; } } catch (Exception e) { logger.log(Level.SEVERE, "Exception in pauseResume", e); throw new Exception(Localization.getString("mainWindow.error.pauseResume")); } }
Source:
public void testVmOvfImportWithoutDbGeneration() throws Exception{ VM vm = createVM(); String xml = manager.ExportVm(vm, new ArrayList<DiskImage>()); assertNotNull(xml); final VM newVm = new VM(); assertTrue(xml.contains("Generation")); String replacedXml = xml.replaceAll("Generation", "test_replaced"); manager.ImportVm(replacedXml, newVm, new ArrayList<DiskImage>(), new ArrayList<VmNetworkInterface>()); assertEquals(vm, newVm); assertEquals(new Long(1), newVm.getDbGeneration()); }

Target:
public void testVmOvfImportWithoutDbGeneration() throws Exception { VM vm = createVM(); String xml = manager.ExportVm(vm, new ArrayList<DiskImage>()); assertNotNull(xml); final VM newVm = new VM(); assertTrue(xml.contains("Generation")); String replacedXml = xml.replaceAll("Generation", "test_replaced"); manager.ImportVm(replacedXml, newVm, new ArrayList<DiskImage>(), new ArrayList<VmNetworkInterface>()); assertEquals("imported vm is different than expected",vm, newVm); assertTrue("imported db generation is different than expected", newVm.getDbGeneration() == 1); }
Source:
private Stream<Output> queryAsStream( List<String> terms, ReadOnlyFulltext indexReader, boolean fuzzy, boolean matchAll ) { PrimitiveLongIterator primitiveLongIterator; if ( fuzzy ) { primitiveLongIterator = indexReader.fuzzyQuery( matchAll, terms.toArray( new String[0] ) ); } else { primitiveLongIterator = indexReader.query( matchAll, terms.toArray( new String[0] ) ); } Iterator<Output> iterator = PrimitiveLongCollections.map( Output::new, primitiveLongIterator ); return StreamSupport.stream( Spliterators.spliteratorUnknownSize( iterator, Spliterator.ORDERED ), false ); }

Target:
private Stream<EntityOutput> queryAsStream( List<String> terms, ReadOnlyFulltext indexReader, boolean fuzzy, boolean matchAll ) { PrimitiveLongIterator primitiveLongIterator; if ( fuzzy ) { primitiveLongIterator = indexReader.fuzzyQuery( terms, matchAll ); } else { primitiveLongIterator = indexReader.query( terms, matchAll ); } Iterator<EntityOutput> iterator = PrimitiveLongCollections.map( EntityOutput::new, primitiveLongIterator ); return StreamSupport.stream( Spliterators.spliteratorUnknownSize( iterator, Spliterator.ORDERED ), false ); }
Source:
public OperationContext(T optionsBuilder) { this(optionsBuilder, null); mOptionsBuilder = optionsBuilder; mCallTracker = () -> { throw new IllegalStateException("Call tracking is not supported."); }; }

Target:
public OperationContext(T optionsBuilder) { this(optionsBuilder, null); mOptionsBuilder = optionsBuilder; mCallTracker = CallTracker.DISABLED_TRACKER; }
Source:
public String toString() { return "CacheQuotaRequirement{" + "cacheQuotaScope=" + cacheQuotaScope + ", quota=" + quota + '}'; }

Target:
public String toString() { return toStringHelper(this) .add("cacheQuotaScope", cacheQuotaScope) .add("quota", quota) .toString(); }
Source:
public void testViewActionsLink(){ ______TS("Link: recent actions link"); try { String expectedPersonInfo = logPage.getPersonInfoOfFirstEntry(); logPage.clickViewActionsButtonOfSecondEntry(); String actualPersonInfo = logPage.getFilterBoxString(); assertEqualsIfQueryStringNotEmpty(expectedPersonInfo, actualPersonInfo); } catch (NoSuchElementException emptylogs) { } }

Target:
public void testViewActionsLink(){ ______TS("Link: recent actions link"); try { String expectedPersonInfo = logPage.getPersonInfoOfFirstEntry(); logPage.clickViewActionsButtonOfFirstEntry(); String actualPersonInfo = logPage.getFilterBoxString(); assertEqualsIfQueryStringNotEmpty(expectedPersonInfo, actualPersonInfo); } catch (NoSuchElementException exceptionFromEmptyLogs) { } catch (IndexOutOfBoundsException exceptionFromInvisibleTmtLogs) { } }
Source:
public void testValidateExecutableWithoutFix() { FormValidation actual = FormValidation.validateExecutable("git"); String failMessage = "There's no such executable git in PATH:"; assertThat(actual.equals(FormValidation.error(failMessage)), is(false)); }

Target:
public void testValidateExecutableWithoutFix() { FormValidation actual = FormValidation.validateExecutable("git"); String failMessage = "There's no such executable git in PATH:"; assertThat(actual, not(is(FormValidation.error(failMessage)))); }
Source:
public MisoRunSample mapRow(ResultSet rs, int rowNum) throws SQLException { MisoRunSample s = new MisoRunSample(); s.setId(rs.getString("dilutionId")); s.setPartitionId(rs.getInt("partitionId")); s.setBarcode(AttributeKey.BARCODE.extractStringValueFrom(rs)); String barcode2 = AttributeKey.BARCODE_TWO.extractStringValueFrom(rs); boolean reverseComplement2 = rs.getString("dataManglingPolicy").equals("RC_I5"); s.setBarcodeTwo(reverseComplement2 ? reverseComplement(barcode2) : barcode2); Attribute att = AttributeKey.TARGETED_RESEQUENCING.extractAttributeFrom(rs); if (att != null) { Set<Attribute> atts = new HashSet<>(); atts.add(att); s.setAttributes(atts); } return s; }

Target:
public MisoRunSample mapRow(ResultSet rs, int rowNum) throws SQLException { MisoRunSample s = new MisoRunSample(); s.setId(rs.getString("dilutionId")); s.setPartitionId(rs.getInt("partitionId")); s.setBarcode(AttributeKey.BARCODE.extractStringValueFrom(rs)); String barcode2 = AttributeKey.BARCODE_TWO.extractStringValueFrom(rs); boolean reverseComplement2 = rs.getString("dataManglingPolicy").equals("I5_RC"); s.setBarcodeTwo(reverseComplement2 ? reverseComplement(barcode2) : barcode2); Attribute att = AttributeKey.TARGETED_RESEQUENCING.extractAttributeFrom(rs); if (att != null) { Set<Attribute> atts = new HashSet<>(); atts.add(att); s.setAttributes(atts); } return s; }
Source:
private static boolean setValue(Object object, String value, Field field) throws IllegalAccessException { if (setIntegralValue(object, value, field)) { return true; } if (setFloatingPointValue(object, value, field)) { return true; } if (setNonNumericValue(object, value, field)) { return true; } return isProbeField(field); }

Target:
private static boolean setValue(Object object, String value, Field field) throws IllegalAccessException { if (setIntegralValue(object, value, field)) { return true; } if (setFloatingPointValue(object, value, field)) { return true; } return setNonNumericValue(object, value, field); }
Source:
public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId, true, Duration.ofSeconds(5)).subscribe(trainingOperationResponse -> trainingOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(extractedForm -> { extractedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); }); extractedForm.getPages().forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println(); }); }) ) ); END: com.azure.ai.formrecognizer.FormRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl#string-string-boolean-Duration }

Target:
public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeTextDetails = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId, includeTextDetails, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); END: com.azure.ai.formrecognizer.FormRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl#string-string-boolean-Duration }
Source:
private <R> R execute(OpenStackRequest<R> request) { try { return request.execute(); } catch (OpenStackResponseException e) { log.error("{} (OpenStack response error code: {})", e.getMessage(), e.getStatus()); throw new EngineException(EngineError.PROVIDER_FAILURE, e); } catch (RuntimeException e) { log.error("{}: {}", e.getMessage(), e.getCause() == null ? null : e.getCause().getMessage()); throw new EngineException(EngineError.PROVIDER_FAILURE, ExceptionUtils.getRootCause(e), true); } }

Target:
private <R> R execute(OpenStackRequest<R> request) { try { return request.execute(); } catch (OpenStackResponseException e) { log.error("{} (OpenStack response error code: {})", e.getMessage(), e.getStatus()); throw new EngineException(EngineError.PROVIDER_FAILURE, ExceptionUtils.getRootCause(e), true); } catch (RuntimeException e) { log.error("{}: {}", e.getMessage(), e.getCause() == null ? null : e.getCause().getMessage()); throw new EngineException(EngineError.PROVIDER_FAILURE, ExceptionUtils.getRootCause(e), true); } }
Source:
private void fireDamageEventDamage(final ArmorStandEntity self, final DamageSource source, final float amount) { try (final CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { DamageEventHandler.generateCauseFor(source, frame); final DamageEntityEvent event = SpongeEventFactory.createDamageEntityEvent(frame.getCurrentCause(), new ArrayList<>(), (Entity) this, amount); if (!SpongeImpl.postEvent(event)) { this.shadow$func_213817_e(source, (float) event.getFinalDamage()); } } }

Target:
private void impl$fireDamageEventDamage(final ArmorStandEntity self, final DamageSource source, final float amount) { try (final CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { DamageEventHandler.generateCauseFor(source, frame); final DamageEntityEvent event = SpongeEventFactory.createDamageEntityEvent(frame.getCurrentCause(), new ArrayList<>(), (Entity) this, amount); if (!SpongeImpl.postEvent(event)) { this.shadow$func_213817_e(source, (float) event.getFinalDamage()); } } }
Source:
public static final String formatFileSize(long size, final String[] unitStrings) { final double log1024 = Math.log10(1024); if (size <= 0) { return "0"; } int digitGroups = (int) (Math.log10(size) / log1024); return String.format(unitStrings[digitGroups], new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups))); }

Target:
public static final String formatFileSize(long size, final String[] unitStrings) { final double log1024 = Math.log10(1024); if (size <= 0) { return "0"; } int digitGroups = (int) (Math.log10(size) / log1024); NumberFormat f = NumberFormat.getInstance(); if (f instanceof DecimalFormat) { ((DecimalFormat) f).applyPattern("#,##0.#"); } return String.format(unitStrings[digitGroups], f.format(size / Math.pow(1024, digitGroups))); }
Source:
public void logoutWhenInvokedThenWritesResponseHeaders() { ServerHttpHeadersWriter headersWriter = Mockito.mock(ServerHttpHeadersWriter.class); HeaderWriterServerLogoutHandler handler = new HeaderWriterServerLogoutHandler(headersWriter); ServerWebExchange serverWebExchange = Mockito.mock(ServerWebExchange.class); WebFilterExchange filterExchange = Mockito.mock(WebFilterExchange.class); Mockito.when(filterExchange.getExchange()).thenReturn(serverWebExchange); Authentication authentication = Mockito.mock(Authentication.class); handler.logout(filterExchange, authentication); Mockito.verify(headersWriter).writeHttpHeaders(serverWebExchange); }

Target:
public void logoutWhenInvokedThenWritesResponseHeaders() { ServerHttpHeadersWriter headersWriter = mock(ServerHttpHeadersWriter.class); HeaderWriterServerLogoutHandler handler = new HeaderWriterServerLogoutHandler(headersWriter); ServerWebExchange serverWebExchange = mock(ServerWebExchange.class); WebFilterExchange filterExchange = mock(WebFilterExchange.class); when(filterExchange.getExchange()).thenReturn(serverWebExchange); Authentication authentication = mock(Authentication.class); handler.logout(filterExchange, authentication); verify(headersWriter).writeHttpHeaders(serverWebExchange); }
Source:
private static String extractSingleCharFromText(@NotNull GoStringLiteral element) { return format("'%c'", element.getText().charAt(1)); }

Target:
private static String extractSingleCharFromText(@NotNull GoStringLiteral element) { return format("'%s'", getValueTextRange(element).substring(element.getText())); }
Source:
public String status(TestExecutionResult result) { switch (result.getStatus()) { case SUCCESSFUL: return successful(); case ABORTED: return aborted(); case FAILED: return failed(); } return result.getStatus().name(); }

Target:
public final String status(TestExecutionResult result) { switch (result.getStatus()) { case SUCCESSFUL: return successful(); case ABORTED: return aborted(); case FAILED: return failed(); } return result.getStatus().name(); }
Source:
public static void main(final String args[]) throws IOException, SignatureException { try (final Ds3Client client = Ds3ClientBuilder.create("ds3Endpoint:8080", new Credentials("accessKey", "secretKey")).withHttps(false).build()) { final GetServiceResponse response = client.getService(new GetServiceRequest()); for (final Ds3Bucket bucket : response.getListAllMyBucketsResult().getBuckets()) { System.out.println(bucket.getName()); } } catch (final UnknownHostException e) { System.out.println("Invalid Endpoint Server Name or IP Address"); } catch (final FailedRequestException e) { if (e.getStatusCode() == 403) { System.out.println("Invalid Access ID or Secret Key"); } else { System.out.println("BlackPearl return an unexpected status code we did not expect"); } } }

Target:
public static void main(final String args[]) throws IOException, SignatureException { try (final Ds3Client client = Ds3ClientBuilder.create("ds3Endpoint:8080", new Credentials("accessKey", "secretKey")).withHttps(false).build()) { final GetServiceResponse response = client.getService(new GetServiceRequest()); for (final Ds3Bucket bucket : response.getListAllMyBucketsResult().getBuckets()) { System.out.println(bucket.getName()); } } catch (final UnknownHostException e) { System.out.println("Invalid Endpoint Server Name or IP Address"); } catch (final FailedRequestException e) { if (e.getStatusCode() == 403) { System.out.println("Invalid Access ID or Secret Key"); } else { System.out.println("BlackPearl return an unexpected status code we did not expect"); } } catch (final IOException e) { System.out.println("Encountered a networking error"); } }
Source:
@Test public void testPlusOperator() { String sql = "select SAL + 10 FROM SALES.EMP"; RelRoot relRoot = tester.convertSqlToRel(sql); RelJsonWriter jsonWriter = new RelJsonWriter(); relRoot.rel.explain(jsonWriter); String relJson = jsonWriter.asString(); System.out.println(relJson); final RelOptSchema[] schemas = {null}; relRoot.rel.accept(new RelShuttleImpl() { @Override public RelNode visit(TableScan scan) { schemas[0] = scan.getTable().getRelOptSchema(); return super.visit(scan); } }); String s = Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> { final RelJsonReader reader = new RelJsonReader( cluster, schemas[0], rootSchema); RelNode node; try { node = reader.read(relJson); } catch (IOException e) { throw TestUtil.rethrow(e); } return RelOptUtil.dumpPlan("", node, SqlExplainFormat.TEXT, SqlExplainLevel.EXPPLAN_ATTRIBUTES); }); assertThat(s, isLinux("LogicalProject(EXPR$0=[+($5, 10)])\n" + " LogicalTableScan(table=[[CATALOG, SALES, EMP]])\n")); }

Target:
@Test public void testPlusOperator() { final FrameworkConfig config = RelBuilderTest.config().build(); final RelBuilder builder = RelBuilder.create(config); final RelNode rel = builder .scan("EMP") .project( builder.call(SqlStdOperatorTable.PLUS, builder.field("SAL"), builder.literal(10))) .build(); RelJsonWriter jsonWriter = new RelJsonWriter(); rel.explain(jsonWriter); String relJson = jsonWriter.asString(); String s = Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> { final RelJsonReader reader = new RelJsonReader( cluster, getSchema(rel), rootSchema); RelNode node; try { node = reader.read(relJson); } catch (IOException e) { throw TestUtil.rethrow(e); } return RelOptUtil.dumpPlan("", node, SqlExplainFormat.TEXT, SqlExplainLevel.EXPPLAN_ATTRIBUTES); }); final String expected = "" + "LogicalProject($f0=[+($5, 10)])\n" + " LogicalTableScan(table=[[scott, EMP]])\n"; assertThat(s, isLinux(expected)); }
Source:
public <T, E extends Exception> T runTaskWithRetry(TransactionTask<T, E> task) throws E { int failureCount = 0; UUID runId = UUID.randomUUID(); while (true) { checkOpen(); try { T result = runTaskThrowOnConflict(task); if (failureCount > 0) { log.info("[{}] Successfully completed transaction after retries.", SafeArg.of("runId", runId), SafeArg.of("failureCount", failureCount)); } return result; } catch (TransactionFailedException e) { if (!e.canTransactionBeRetried()) { log.warn("[{}] Non-retriable exception while processing transaction.", SafeArg.of("runId", runId), SafeArg.of("failureCount", failureCount)); throw e; } failureCount++; if (shouldStopRetrying(failureCount)) { log.warn("[{}] Failing after tries.", SafeArg.of("runId", runId), SafeArg.of("failureCount", failureCount), e); throw Throwables.rewrap(String.format("Failing after %d tries.", failureCount), e); } log.info("[{}] Retrying transaction after failure(s).", SafeArg.of("runId", runId), SafeArg.of("failureCount", failureCount), e); } catch (NotInitializedException e) { log.warn("Asynchronous initialization of resources is not complete. Retrying in 10 seconds.", e); Uninterruptibles.sleepUninterruptibly(AsyncInitializer.sleepInterval, TimeUnit.SECONDS); } catch (RuntimeException e) { log.warn("[{}] RuntimeException while processing transaction. {}", SafeArg.of("runId", runId), e); throw e; } sleepForBackoff(failureCount); } }

Target:
public <T, E extends Exception> T runTaskWithRetry(TransactionTask<T, E> task) throws E { int failureCount = 0; UUID runId = UUID.randomUUID(); while (true) { checkOpen(); try { T result = runTaskThrowOnConflict(task); if (failureCount > 0) { log.info("[{}] Successfully completed transaction after retries.", SafeArg.of("runId", runId), SafeArg.of("failureCount", failureCount)); } return result; } catch (TransactionFailedException e) { if (!e.canTransactionBeRetried()) { log.warn("[{}] Non-retriable exception while processing transaction.", SafeArg.of("runId", runId), SafeArg.of("failureCount", failureCount)); throw e; } failureCount++; if (shouldStopRetrying(failureCount)) { log.warn("[{}] Failing after tries.", SafeArg.of("runId", runId), SafeArg.of("failureCount", failureCount), e); throw Throwables.rewrap(String.format("Failing after %d tries.", failureCount), e); } log.info("[{}] Retrying transaction after failure(s).", SafeArg.of("runId", runId), SafeArg.of("failureCount", failureCount), e); } catch (NotInitializedException e) { log.warn("Asynchronous initialization of resources is not complete. Retrying in 10 seconds.", e); Uninterruptibles.sleepUninterruptibly(AsyncInitializer.millisUntilNextAttempt, TimeUnit.MILLISECONDS); } catch (RuntimeException e) { log.warn("[{}] RuntimeException while processing transaction.", SafeArg.of("runId", runId), e); throw e; } sleepForBackoff(failureCount); } }
Source:
protected Map<Guid, KeyValuePairCompat<String, List<Guid>>> populateVmsMetadataForOvfUpdate(List<Guid> idsToProcess) { Map<Guid, KeyValuePairCompat<String, List<Guid>>> vmsAndTemplateMetadata = new HashMap<Guid, KeyValuePairCompat<String, List<Guid>>>(); List<VM> vms = getVmDao().getVmsByIds(idsToProcess); for (VM vm : vms) { if (VMStatus.ImageLocked != vm.getStatus()) { updateVmDisksFromDb(vm); vm.setSnapshots(getSnapshotDao().getAllWithConfiguration(vm.getId())); if (verifyDisksNotLocked(vm.getDiskList()) && verifySnapshotsNotLocked(vm.getSnapshots())) { loadVmData(vm); Long currentDbGeneration = getVmStaticDao().getDbGeneration(vm.getId()); if (currentDbGeneration != null && vm.getStaticData().getDbGeneration() == currentDbGeneration) { proccessedOvfConfigurationsInfo.add(buildMetadataDictionaryForVm(vm, vmsAndTemplateMetadata)); proccessedIdsInfo.add(vm.getId()); proccessedOvfGenerationsInfo.add(vm.getStaticData().getDbGeneration()); proccessDisksDomains(vm.getDiskList()); } } } } return vmsAndTemplateMetadata; }

Target:
protected Map<Guid, KeyValuePairCompat<String, List<Guid>>> populateVmsMetadataForOvfUpdate(List<Guid> idsToProcess) { Map<Guid, KeyValuePairCompat<String, List<Guid>>> vmsAndTemplateMetadata = new HashMap<Guid, KeyValuePairCompat<String, List<Guid>>>(); List<VM> vms = getVmDao().getVmsByIds(idsToProcess); for (VM vm : vms) { if (VMStatus.ImageLocked != vm.getStatus()) { updateVmDisksFromDb(vm); ArrayList<DiskImage> vmDisks = updateSnapshotsForVM(vm); if (verifyDisksNotLocked(vm.getDiskList()) && verifySnapshotsStatus(vm.getSnapshots())) { loadVmData(vm); Long currentDbGeneration = getVmStaticDao().getDbGeneration(vm.getId()); if (currentDbGeneration != null && vm.getStaticData().getDbGeneration() == currentDbGeneration) { proccessedOvfConfigurationsInfo.add(buildMetadataDictionaryForVm(vm, vmsAndTemplateMetadata, vmDisks)); proccessedIdsInfo.add(vm.getId()); proccessedOvfGenerationsInfo.add(vm.getStaticData().getDbGeneration()); proccessDisksDomains(vm.getDiskList()); } } } } return vmsAndTemplateMetadata; }
Source:
private void initActionContext(ActionContext actionContext) { actionContext.setParameters(HttpParameters.create(request.getParameterMap()).build()); initSession(actionContext); ActionContext.setContext(actionContext); }

Target:
protected void initActionContext(ActionContext actionContext) { actionContext.setParameters(HttpParameters.create(request.getParameterMap()).build()); initSession(actionContext); ActionContext.setContext(actionContext); }
Source:
Mono<Void> sendEvents(Iterable<EventGridEvent> events, Context context) { return Flux.fromIterable(events) .map(EventGridEvent::toImpl) .collectList() .flatMap(list -> this.impl.publishEventsAsync(this.hostname, list, context.addData(AZ_TRACING_NAMESPACE_KEY, Constants.EVENT_GRID_TRACING_NAMESPACE_VALUE))); }

Target:
Mono<Void> sendEvents(Iterable<EventGridEvent> events, Context context) { final Context finalContext = context != null ? context : Context.NONE; return Flux.fromIterable(events) .map(EventGridEvent::toImpl) .collectList() .flatMap(list -> this.impl.publishEventsAsync(this.hostname, list, finalContext.addData(AZ_TRACING_NAMESPACE_KEY, Constants.EVENT_GRID_TRACING_NAMESPACE_VALUE))); }
Source:
public static Optional<BackupSupportingClassesFactoryProvider> findBestProvider() { ArrayList<BackupSupportingClassesFactoryProvider> list = new ArrayList<>(); load( BackupSupportingClassesFactoryProvider.class ).forEach( list::add ); list.sort( ( l, r ) -> r.getPriority() - l.getPriority() ); return list.stream().findFirst(); }

Target:
public static Optional<BackupSupportingClassesFactoryProvider> findBestProvider() { return StreamSupport.stream( load( BackupSupportingClassesFactoryProvider.class ).spliterator(), false ) .sorted( ( l, r ) -> r.getPriority() - l.getPriority() ) .findFirst(); }
Source:
public DeviceWithState deserialize(Map<String, Object> map) { Number num = MapUtils.getOrNull(map, "apiLevel"); Integer apiLevel = num != null ? num.intValue() : null; DeviceBuildInfo buildInfo = new DeviceBuildInfo( MapUtils.<String>getOrNull(map, "manufacturer"), MapUtils.<String>getOrNull(map, "model"), MapUtils.<String>getOrNull(map, "osVersion"), apiLevel, MapUtils.<String>getOrNull(map, "osBuild"), MapUtils.<String>getOrNull(map, "fingerprint"), MapUtils.<String>getOrNull(map, "tags"), MapUtils.<String>getOrNull(map, "brand"), MapUtils.<String[]>getOrNull(map, "cpuAbis") ); String time = MapUtils.getOrNull(map, "time"); Date date = null; if (time != null) { date = DateUtils.fromIso8601(time); } return new DeviceWithState( buildInfo, MapUtils.<Boolean>getOrNull(map, "jailbroken"), MapUtils.<String>getOrNull(map, "id"), MapUtils.<String>getOrNull(map, "locale"), getLong(map, "totalMemory"), getLong(map, "freeDisk"), getLong(map, "freeMemory"), MapUtils.<String>getOrNull(map, "orientation"), date ); }

Target:
public DeviceWithState deserialize(Map<String, Object> map) { DeviceBuildInfo buildInfo = new DeviceBuildInfo( MapUtils.<String>getOrNull(map, "manufacturer"), MapUtils.<String>getOrNull(map, "model"), MapUtils.<String>getOrNull(map, "osVersion"), MapUtils.getInt(map, "apiLevel"), MapUtils.<String>getOrNull(map, "osBuild"), MapUtils.<String>getOrNull(map, "fingerprint"), MapUtils.<String>getOrNull(map, "tags"), MapUtils.<String>getOrNull(map, "brand"), MapUtils.<String[]>getOrNull(map, "cpuAbis") ); String time = MapUtils.getOrNull(map, "time"); Date date = null; if (time != null) { date = DateUtils.fromIso8601(time); } return new DeviceWithState( buildInfo, MapUtils.<Boolean>getOrNull(map, "jailbroken"), MapUtils.<String>getOrNull(map, "id"), MapUtils.<String>getOrNull(map, "locale"), MapUtils.getLong(map, "totalMemory"), MapUtils.getLong(map, "freeDisk"), MapUtils.getLong(map, "freeMemory"), MapUtils.<String>getOrNull(map, "orientation"), date ); }
Source:
public String getDeadLetterReason() { final Map<String, Object> properties = amqpAnnotatedMessage.getApplicationProperties(); if (properties.containsKey(DEAD_LETTER_REASON)) { return String.valueOf(properties.get(DEAD_LETTER_REASON)); } return null; }

Target:
public String getDeadLetterReason() { return getStringValue(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_REASON_ANNOTATION_NAME.getValue()); }
Source:
public synchronized void start() { session.addActivityConsumer(consumer, Priority.ACTIVE); session.addActivityProducer(this); }

Target:
public void start() { session.addActivityConsumer(consumer, Priority.ACTIVE); session.addActivityProducer(this); }
Source:
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (!(msg instanceof HttpRequest)) return; HttpRequest httpRequest = (HttpRequest) msg; Span span = handler.handleReceive(extractor, httpRequest.headers(), httpRequest); ctx.channel().attr(NettyHttpTracing.SPAN_ATTRIBUTE).set(span); try (SpanInScope ws = tracer.withSpanInScope(span)) { super.channelRead(ctx, msg); } catch (Exception | Error e) { ctx.channel().attr(NettyHttpTracing.SPAN_ATTRIBUTE).set(null); handler.handleSend(null, e, span); throw e; } }

Target:
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (!(msg instanceof HttpRequest)) { ctx.fireChannelRead(msg); return; } HttpRequest request = (HttpRequest) msg; Span span = nextSpan(extractor.extract(request.headers()), request).kind(Span.Kind.SERVER); ctx.channel().attr(NettyHttpTracing.SPAN_ATTRIBUTE).set(span); try (SpanInScope ws = tracer.withSpanInScope(span)) { if (!span.isNoop()) { parser.request(adapter, request, span); maybeParseClientAddress(ctx.channel(), request, span); span.start(); } ctx.fireChannelRead(msg); } }
Source:
public int getPriority() { return 60000; }

Target:
public int getPriority() { return Integer.MAX_VALUE; }
Source:
public BearingWidget(Context context, QuestionDetails questionDetails, WaitingForDataRegistry waitingForDataRegistry, SensorManager sensorManager) { super(context, questionDetails); this.waitingForDataRegistry = waitingForDataRegistry; this.sensorManager = sensorManager; isSensorAvailable = checkForRequiredSensors(); textBackground = binding.answerText.getBackground(); binding.answerText.setBackground(null); String answerText = questionDetails.getPrompt().getAnswerText(); if (answerText != null && !answerText.equals("")) { binding.bearingButton.setText(getContext().getString(R.string.replace_bearing)); binding.answerText.setText(answerText); } }

Target:
public BearingWidget(Context context, QuestionDetails questionDetails, WaitingForDataRegistry waitingForDataRegistry, SensorManager sensorManager) { super(context, questionDetails); this.waitingForDataRegistry = waitingForDataRegistry; this.sensorManager = sensorManager; }
Source:
private void prepareCopyNotTemplate(MoveOrCopyImageGroupParameters parameters) { parameters.setAddImageDomainMapping(false); Guid newImageId = Guid.newGuid(); Guid newId = Guid.newGuid(); DiskImage image = getImage(); image.setId(newId); image.setImageId(newImageId); image.setDiskAlias(getDiskAlias()); image.setStorageIds(new ArrayList<>()); image.getStorageIds().add(getParameters().getStorageDomainId()); image.setQuotaId(getParameters().getQuotaId()); image.setDiskProfileId(getParameters().getDiskProfileId()); image.setImageStatus(ImageStatus.LOCKED); image.setVmSnapshotId(null); image.setParentId(Guid.Empty); image.setImageTemplateId(Guid.Empty); parameters.setDestinationImageId(newImageId); parameters.setDestImageGroupId(newId); if (getParameters().getParentCommand() == ActionType.Unknown) { parameters.setDestImages(Collections.singletonList(image)); } }

Target:
private void prepareCopyNotTemplate(MoveOrCopyImageGroupParameters parameters) { parameters.setAddImageDomainMapping(false); Guid newImageId = Guid.newGuid(); Guid newId = Guid.newGuid(); DiskImage image = getImage(); image.setId(newId); image.setImageId(newImageId); image.setDiskAlias(getDiskAlias()); image.setStorageIds(new ArrayList<>()); image.getStorageIds().add(getParameters().getStorageDomainId()); image.setQuotaId(getParameters().getQuotaId()); image.setDiskProfileId(getParameters().getDiskProfileId()); image.setImageStatus(ImageStatus.LOCKED); image.setVmSnapshotId(null); image.setParentId(Guid.Empty); image.setImageTemplateId(Guid.Empty); parameters.setDestinationImageId(newImageId); parameters.setDestImageGroupId(newId); if (getParameters().getParentCommand() == ActionType.Unknown) { parameters.setDestImages(List.of(image)); } }
Source:
public <K, V> BasicCache<K, V> getCache() { return remoteCacheManager.getCache(); }

Target:
public <K, V> RemoteCache<K, V> getCache() { return this.remoteCacheManager.getCache(); }
Source:
private static String mountFileSystemRW(String path) throws ShellNotRunningException { String command = "mount"; ArrayList<String> output = RootHelper.runShellCommandToList(command); String mountPoint = "", types = null, mountArgument = null; for (String line : output) { String[] words = line.split(" "); String mountPointOutputFromShell = words[1]; String mountPointFileSystemTypeFromShell = words[2]; String mountPointArgumentFromShell = words[3]; if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { mountPointOutputFromShell = words[2]; mountPointFileSystemTypeFromShell = words[4]; mountPointArgumentFromShell = words[5]; } if (path.startsWith(mountPointOutputFromShell)) { if (mountPointOutputFromShell.length() > mountPoint.length()) { mountPoint = mountPointOutputFromShell; types = mountPointFileSystemTypeFromShell; mountArgument = mountPointArgumentFromShell; } } } if (!mountPoint.equals("") && types != null && mountArgument != null) { if (mountArgument.contains("rw")) { return null; } else if (mountArgument.contains("ro")) { String mountCommand = "mount -o rw,remount " + mountPoint; ArrayList<String> mountOutput = RootHelper.runShellCommandToList(mountCommand); if (mountOutput.size() != 0) { return null; } else return mountPoint; } } return null; }

Target:
private static String mountFileSystemRW(String path) throws ShellNotRunningException { String command = "mount"; ArrayList<String> output = RootHelper.runShellCommandToList(command); String mountPoint = "", types = null, mountArgument = null; for (String line : output) { String[] words = line.split(" "); String mountPointOutputFromShell = words[1]; String mountPointFileSystemTypeFromShell = words[2]; String mountPointArgumentFromShell = words[3]; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { mountPointOutputFromShell = words[2]; mountPointFileSystemTypeFromShell = words[4]; mountPointArgumentFromShell = words[5]; } if (path.startsWith(mountPointOutputFromShell)) { if (mountPointOutputFromShell.length() > mountPoint.length()) { mountPoint = mountPointOutputFromShell; types = mountPointFileSystemTypeFromShell; mountArgument = mountPointArgumentFromShell; } } } if (!mountPoint.equals("") && types != null && mountArgument != null) { if (mountArgument.contains("rw")) { return null; } else if (mountArgument.contains("ro")) { String mountCommand = "mount -o rw,remount " + mountPoint; ArrayList<String> mountOutput = RootHelper.runShellCommandToList(mountCommand); if (mountOutput.size() != 0) { return null; } else return mountPoint; } } return null; }
Source:
public Object getImage(final Object object) { EObject element = EMFHelper.getEObject(object); if (element == null) { return null; } IItemLabelProvider provider = getDelegate(element); return (provider == null) ? null : provider.getImage(element); }

Target:
public Object getImage(final Object object) { EObject element = EMFHelper.getEObject(object); if (null == element) { return null; } IItemLabelProvider provider = getDelegate(element); return (provider == null) ? null : provider.getImage(element); }
Source:
public void connect() { connecting = true; connection = new Connection(host.getHostname(), host.getPort()); connection.addConnectionMonitor(this); try { connection.setCompression(compression); } catch (IOException e) { Log.e(TAG, "Could not enable compression!", e); } try { connectionInfo = connection.connect(new HostKeyVerifier()); connected = true; bridge.outputLine(manager.res.getString(R.string.terminal_kex_algorithm, connectionInfo.keyExchangeAlgorithm)); if (connectionInfo.clientToServerCryptoAlgorithm .equals(connectionInfo.serverToClientCryptoAlgorithm) && connectionInfo.clientToServerMACAlgorithm .equals(connectionInfo.serverToClientMACAlgorithm)) { bridge.outputLine(manager.res.getString(R.string.terminal_using_algorithm, connectionInfo.clientToServerCryptoAlgorithm, connectionInfo.clientToServerMACAlgorithm)); } else { bridge.outputLine(manager.res.getString( R.string.terminal_using_c2s_algorithm, connectionInfo.clientToServerCryptoAlgorithm, connectionInfo.clientToServerMACAlgorithm)); bridge.outputLine(manager.res.getString( R.string.terminal_using_s2c_algorithm, connectionInfo.serverToClientCryptoAlgorithm, connectionInfo.serverToClientMACAlgorithm)); } } catch (IOException e) { Log.e(TAG, "Problem in SSH connection thread during authentication", e); Throwable t = e.getCause(); do { bridge.outputLine(t.getMessage()); t = t.getCause(); } while (t != null); close(); onDisconnect(); connecting = false; return; } try { int tries = 0; while (connected && !connection.isAuthenticationComplete() && tries++ < AUTH_TRIES) { authenticate(); Thread.sleep(1000); } } catch (Exception e) { Log.e(TAG, "Problem in SSH connection thread during authentication", e); } connecting = false; }

Target:
public void connect() { connecting = true; try { connectInternal(); } finally { connecting = false; } }
Source:
private List<MemKey> getArrayOfMemKeys(InMemoryMap imm) { SortedKeyValueIterator<Key,Value> skvi = imm.compactionIterator(); List<MemKey> memKeys = new ArrayList<MemKey>(); try { skvi.seek(new Range(), new ArrayList<ByteSequence>(), false); while (skvi.hasTop()) { memKeys.add((MemKey) skvi.getTopKey()); skvi.next(); } } catch (IOException ex) { java.util.logging.Logger.getLogger(InMemoryMapIT.class.getName()).log(Level.SEVERE, null, ex); } return memKeys; }

Target:
private List<MemKey> getArrayOfMemKeys(InMemoryMap imm) { SortedKeyValueIterator<Key,Value> skvi = imm.compactionIterator(); List<MemKey> memKeys = new ArrayList<MemKey>(); try { skvi.seek(new Range(), new ArrayList<ByteSequence>(), false); while (skvi.hasTop()) { memKeys.add((MemKey) skvi.getTopKey()); skvi.next(); } } catch (IOException ex) { log.error("Error getting memkeys", ex); throw new RuntimeException(ex); } return memKeys; }
Source:
public static void main(String... args) { JmhRunner.runAndReport(ArrayBenchmark.class); }

Target:
public static void main(String... args) { JmhRunner.run(ArrayBenchmark.class); }
Source:
private String compress(String str) throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); DeflaterOutputStream deflater = new DeflaterOutputStream(bytes); deflater.write(str.getBytes()); deflater.flush(); deflater.close(); return new String(bytes.toByteArray()); }

Target:
byte[] compress(String str) throws IOException { final byte[] dataToCompress = str.getBytes(); final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(dataToCompress.length); try { try (GZIPOutputStream zipStream = new GZIPOutputStream(byteStream, true)) { zipStream.write(dataToCompress); } } finally { byteStream.close(); } return byteStream.toByteArray(); }
Source:
private int completeDeletions() throws IOException { int numPending = deletions.size(); int numFailures = 0; if (numPending < 1) { return 0; } List<PendingFileDeletionExec> pendingExecs = deletions. parallelStream().map(f -> new PendingFileDeletionExec(f.getAbsolutePath())).collect( Collectors.toList()); AtomicInteger currentCount = new AtomicInteger(); Map<Boolean, List<PendingFileDeletionExec>> bySuccess = pendingExecs.parallelStream().collect( Collectors.groupingByConcurrent((x) -> { printProgress(LOGGER, "pending deletions", currentCount.incrementAndGet(), numPending); try { doDelete(x); return true; } catch (IOException e) { x.exception = e; return false; } })); deletions.clear(); List<PendingFileDeletionExec> successes = bySuccess.getOrDefault( Boolean.TRUE, null); if (successes != null) { tryDeleteParents(successes); } List<PendingFileDeletionExec> failures = bySuccess.getOrDefault( Boolean.FALSE, null); if (failures != null && failures.size() > 0) { numFailures = failures.size(); double pctFailed = 100.0 * numFailures / numPending; String exmsg = String.format( "%d failures (%.1f%%) while deleting pending files", numFailures, pctFailed); throw new IOException(exmsg, failures.get(0).exception); } return numPending - numFailures; }

Target:
private int completeDeletions() throws IOException { int numPending = deletions.size(); int numFailures = 0; if (numPending < 1) { return 0; } List<PendingFileDeletionExec> pendingExecs = deletions. parallelStream().map(f -> new PendingFileDeletionExec(f.getAbsolutePath())).collect( Collectors.toList()); Map<Boolean, List<PendingFileDeletionExec>> bySuccess; try (Progress progress = new Progress(LOGGER, "pending deletions", numPending)) { bySuccess = pendingExecs.parallelStream().collect( Collectors.groupingByConcurrent((x) -> { progress.increment(); try { doDelete(x); return true; } catch (IOException e) { x.exception = e; return false; } })); } deletions.clear(); List<PendingFileDeletionExec> successes = bySuccess.getOrDefault( Boolean.TRUE, null); if (successes != null) { tryDeleteParents(successes); } List<PendingFileDeletionExec> failures = bySuccess.getOrDefault( Boolean.FALSE, null); if (failures != null && failures.size() > 0) { numFailures = failures.size(); double pctFailed = 100.0 * numFailures / numPending; String exmsg = String.format( "%d failures (%.1f%%) while deleting pending files", numFailures, pctFailed); throw new IOException(exmsg, failures.get(0).exception); } return numPending - numFailures; }
Source:
static RowMapper<?> rowMapperFor(GetGeneratedKeys ggk, Type returnType) { if (DefaultGeneratedKeyMapper.class.equals(ggk.value())) { return new DefaultGeneratedKeyMapper(returnType, ggk.columnName()); } else { try { return ggk.value().newInstance(); } catch (Exception e) { throw new UnableToCreateStatementException("Unable to instantiate row mapper for statement", e, null); } } }

Target:
static RowMapper<?> rowMapperFor(GetGeneratedKeys ggk, Type returnType) { if (DefaultGeneratedKeyMapper.class.equals(ggk.value())) { return new DefaultGeneratedKeyMapper(returnType, ggk.columnName()); } else { try { return ggk.value().getConstructor().newInstance(); } catch (Exception e) { throw new UnableToCreateStatementException("Unable to instantiate row mapper for statement", e, null); } } }
Source:
public JoinMetadata readJoinMetadata(SnapshotBase tx, String nodeId) { Optional<NodeType> type = NodeType.fromNodeId(nodeId); try { checkArgument(type.isPresent() && type.get() == NodeType.JOIN); LOG.debug("Retrieving Metadata from Cache: {}.", nodeId); return (JoinMetadata) commonNodeMetadataCache.get(nodeId, new Callable<CommonNodeMetadata>() { @Override public CommonNodeMetadata call() throws Exception { LOG.debug("Seeking Metadata from Fluo Table: {}.", nodeId); return dao.readJoinMetadata(tx, nodeId); } }); } catch (Exception e) { throw new RuntimeException("Unable to access JoinMetadata for nodeId: " + nodeId, e); } }

Target:
public JoinMetadata readJoinMetadata(SnapshotBase tx, String nodeId) { checkNotNull(nodeId); checkNotNull(tx); Optional<NodeType> type = NodeType.fromNodeId(nodeId); checkArgument(type.isPresent() && type.get() == NodeType.JOIN); try { LOG.debug("Retrieving Metadata from Cache: {}.", nodeId); return (JoinMetadata) commonNodeMetadataCache.get(nodeId, () -> { LOG.debug("Seeking Metadata from Fluo Table: {}.", nodeId); return dao.readJoinMetadata(tx, nodeId); }); } catch (Exception e) { throw new RuntimeException("Unable to access JoinMetadata for nodeId: " + nodeId, e); } }
Source:
private Object expandElements(Expander expander, Object value) { if (value instanceof Collection) { return expandCollection(expander, (Collection) value); } else if (value.getClass().isArray()) { return expandCollection(expander, Arrays.asList((Object[])value)); } return expander.expand(value); }

Target:
private Object expandElements(Expander expander, Object value) { if (value instanceof Iterable) { return expandIterable(expander, (Iterable) value); } return expander.expand(value); }
Source:
public Double sample(final RandomGenerator rng, final CopyRatioState state, final CopyRatioData dataCollection) { final Function<Double, Double> logConditionalPDF = newVariance -> { double ll = 0.; int numNotOutliers = 0; for (int segment = 0; segment < dataCollection.getNumSegments(); segment++) { final int numTargetsInSegment = dataCollection.getNumTargetsInSegment(segment); final int targetStartInSegment = dataCollection.getStartTargetInSegment(segment); for (int target = 0; target < numTargetsInSegment; target++) { final double coverage = dataCollection.getCoveragesInSegment(segment).get(target); if (!state.targetOutlierIndicator(targetStartInSegment + target)) { ll -= normalTerm(coverage, state.segmentMean(segment), newVariance); numNotOutliers++; } } } ll -= 0.5 * Math.log(newVariance) * numNotOutliers; return ll; }; return new SliceSampler(rng, logConditionalPDF, varianceMin, varianceMax, varianceSliceSamplingWidth).sample(state.variance()); }

Target:
public Double sample(final RandomGenerator rng, final CopyRatioState state, final CopyRatioData dataCollection) { final Function<Double, Double> logConditionalPDF = newVariance -> { final double gaussianLogNormalization = 0.5 * Math.log(newVariance); double ll = 0.; for (int segment = 0; segment < dataCollection.getNumSegments(); segment++) { final List<CopyRatioData.IndexedCoverage> indexedCoveragesInSegment = dataCollection.getIndexedCoveragesInSegment(segment); for (final CopyRatioData.IndexedCoverage c : indexedCoveragesInSegment) { if (!state.targetOutlierIndicator(c.getTargetIndex())) { ll -= normalTerm(c.getCoverage(), state.segmentMean(segment), newVariance) + gaussianLogNormalization; } } } return ll; }; return new SliceSampler(rng, logConditionalPDF, varianceMin, varianceMax, varianceSliceSamplingWidth).sample(state.variance()); }