auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void getCardsShouldReturnTheListOfCards() throws Exception { final AtomicReference<List<Card>> bodyRefResponse = new AtomicReference<>(); final AtomicReference<Request> bodyRefRequest = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); User user = Fixtures.loadUser(); BitreserveRestAdapter mockRestDapter = new BitreserveRestAdapter("foobar"); mockRestDapter.setAdapter(new RestAdapter.Builder().setEndpoint(GlobalConfigurations.SERVER_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { String responseString = "[ { \"id\": \"FOO\" }, { \"id\": \"BAR\" } ]"; bodyRefRequest.set(request); return new Response("some/url", 200, "reason", new ArrayList<retrofit.client.Header>() { { add(new retrofit.client.Header("foo", "bar")); } }, new TypedByteArray("application/json", responseString.getBytes())); } }).build()); user.setBitreserveRestAdapter(mockRestDapter); user.getCards().then(new PromiseAction<List<Card>>() { @Override public void call(List<Card> cards) { bodyRefResponse.set(cards); latch.countDown(); } }).fail(new PromiseAction<Exception>() { @Override public void call(Exception e) { latch.countDown(); } }); latch.await(); <START> List<Card> cardsResponse = bodyRefResponse.get(); <END> Request request = bodyRefRequest.get(); Assert.assertEquals(request.getMethod(), "GET"); Assert.assertEquals(request.getUrl(), "<LINK_0>"); Assert.assertEquals(cardsResponse.size(), 2); Assert.assertEquals(cardsResponse.get(0).getId(), "FOO"); Assert.assertEquals(cardsResponse.get(1).getId(), "BAR"); }</code><technical_language>Rename variable cards</technical_language>

Target:
public void getCardsShouldReturnTheListOfCards() throws Exception { final AtomicReference<List<Card>> bodyRefResponse = new AtomicReference<>(); final AtomicReference<Request> bodyRefRequest = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); User user = Fixtures.loadUser(); BitreserveRestAdapter mockRestAdapter = new BitreserveRestAdapter("foobar"); mockRestAdapter.setAdapter(new RestAdapter.Builder().setEndpoint(GlobalConfigurations.SERVER_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { String responseString = "[ { \"id\": \"FOO\" }, { \"id\": \"BAR\" } ]"; bodyRefRequest.set(request); return new Response("some/url", 200, "reason", new ArrayList<retrofit.client.Header>(), new TypedByteArray("application/json", responseString.getBytes())); } }).build()); user.setBitreserveRestAdapter(mockRestAdapter); user.getCards().then(new PromiseAction<List<Card>>() { @Override public void call(List<Card> cards) { bodyRefResponse.set(cards); latch.countDown(); } }).fail(new PromiseAction<Exception>() { @Override public void call(Exception e) { latch.countDown(); } }); latch.await(); List<Card> cards = bodyRefResponse.get(); Request request = bodyRefRequest.get(); Assert.assertEquals(request.getMethod(), "GET"); Assert.assertEquals(request.getUrl(), "<LINK_0>"); Assert.assertEquals(cards.size(), 2); Assert.assertEquals(cards.get(0).getId(), "FOO"); Assert.assertEquals(cards.get(1).getId(), "BAR"); }
Source:
<code>StoredRevision insertRevision(int projId, Revision revision) throws ResourceConflictException; void insertRevisionArchiveData(int revId, byte[] data) throws ResourceConflictException; StoredWorkflowDefinition insertWorkflowDefinition(int projId, int revId, WorkflowDefinition workflow, ZoneId workflowTimeZone) throws ResourceConflictException; interface ScheduleUpdateAction { <START> public ScheduleTime apply(ScheduleStatus oldStatus, Schedule newSchedule); <END> }</code><technical_language>remove public</technical_language>

Target:
StoredRevision insertRevision(int projId, Revision revision) throws ResourceConflictException; void insertRevisionArchiveData(int revId, byte[] data) throws ResourceConflictException; StoredWorkflowDefinition insertWorkflowDefinition(int projId, int revId, WorkflowDefinition workflow, ZoneId workflowTimeZone) throws ResourceConflictException; interface ScheduleUpdateAction <T extends Schedule> { ScheduleTime apply(ScheduleStatus oldStatus, T newSchedule); }
Source:
<code>public UnitVmModel flush() { <START> UnitVmModel model = driver.flush(); <END> model.getNicsWithLogicalNetworks().getItemsChangedEvent().removeListener(vnicsChangedListener); profilesInstanceTypeEditor.flush(); priorityEditor.flush(); return model; }</code><technical_language>resolved in editor (to avoid similar issues other widgets)? E.g. AddRemoveRowWidget -> flush() - 'model.setItems(values)' invokes ItemsChangedEvent, try clearing listeners beforehand</technical_language>

Target:
public UnitVmModel flush() { priorityEditor.flush(); profilesInstanceTypeEditor.flush(); return driver.flush(); }
Source:
<code>public void onBarrierStateChanged(final String version, ZkBarrierForVersionUpgrade.State state) { LOG.info("JobModel version " + version + " obtained consensus successfully!"); metrics.barrierStateChange.inc(); if (ZkBarrierForVersionUpgrade.State.DONE.equals(state)) { <START> metrics.singleBarrierRebalancingTime.update(System.nanoTime() - startTime); <END> debounceTimer.scheduleAfterDebounceTime( barrierAction, 0, () -> onNewJobModelConfirmed(version)); } else { if (ZkBarrierForVersionUpgrade.State.TIMED_OUT.equals(state)) { LOG.info("Barrier for version " + version + " timed out."); } } }</code><technical_language>I update timer metric in case of a time out state change. way, correlate metric state change - if difference in time == barrier_timeout-ms, barrier timed out. do think? I want point out a potential issue here: startTime is initialized in doProcessorChange is invoked in leader JC. For other processors, 0 result high incorrect timer value. obvious code. leader receives barrierCreation notification. So, create startTime handler initialize in ZkBarrierListenerImpl#onBarrierCreated. this sound reasonable you</technical_language>

Target:
public void onBarrierStateChanged(final String version, ZkBarrierForVersionUpgrade.State state) { LOG.info("JobModel version " + version + " obtained consensus successfully!"); metrics.barrierStateChange.inc(); metrics.singleBarrierRebalancingTime.update(System.nanoTime() - startTime); if (ZkBarrierForVersionUpgrade.State.DONE.equals(state)) { debounceTimer.scheduleAfterDebounceTime( barrierAction, 0, () -> onNewJobModelConfirmed(version)); } else { if (ZkBarrierForVersionUpgrade.State.TIMED_OUT.equals(state)) { LOG.info("Barrier for version " + version + " timed out."); } } }
Source:
<code>public boolean advancePhase(float minWeight) { boolean changed = false; for (QueryTree child : children) { changed |= child.advancePhase(minWeight); } <START> children.sort(Comparator.comparingDouble(QueryTree::weight)); <END> return changed; }</code><technical_language>If changed is false, do children need resorted</technical_language>

Target:
public boolean advancePhase(float minWeight) { boolean changed = false; for (QueryTree child : children) { changed |= child.advancePhase(minWeight); } if (changed == false) { return false; } children.sort(Comparator.comparingDouble(QueryTree::weight)); return changed; }
Source:
<code>public String getFirehoseId() { if (config != null) { <START> return serviceName.replaceFirst(config.getFirehoseIdPrefix(), ""); <END> } return null; }</code><technical_language>need strip colon</technical_language>

Target:
public String getFirehoseId() { if (config != null) { return serviceName.replaceFirst(String.format("%s:", config.getFirehoseIdPrefix()), ""); } return null; }
Source:
<code>public ListenableFuture<Map<Cell, byte[]>> getAsync(TableReference tableRef, Set<Cell> cells) { <START> Timer.Context timer = getTimer("get").time(); <END> checkGetPreconditions(tableRef); if (Iterables.isEmpty(cells)) { return Futures.immediateFuture(ImmutableMap.of()); } hasReads = true; ImmutableMap.Builder<Cell, byte[]> resultBuilder = ImmutableMap.builder(); SortedMap<Cell, byte[]> writes = writesByTable.get(tableRef); if (writes != null) { for (Cell cell : cells) { if (writes.containsKey(cell)) { resultBuilder.put(cell, writes.get(cell)); } } } Map<Cell, byte[]> writtenLocally = resultBuilder.build(); return Futures.transform( getFromKeyValueServiceAsync(tableRef, Sets.difference(cells, writtenLocally.keySet())), keyValueResult -> { ImmutableMap<Cell, byte[]> result = ImmutableMap.<Cell, byte[]>builder() .putAll(writtenLocally) .putAll(keyValueResult) .build(); long getMillis = TimeUnit.NANOSECONDS.toMillis(timer.stop()); if (perfLogger.isDebugEnabled()) { perfLogger.debug("get({}, cells) found cells (some possibly deleted), took ms", tableRef, cells.size(), result.size(), getMillis); } validatePreCommitRequirementsOnReadIfNecessary(tableRef, getStartTimestamp()); return removeEmptyColumns(result, tableRef); }, MoreExecutors.directExecutor()); }</code><technical_language>want new timer, monitor rollout performance</technical_language>

Target:
public ListenableFuture<Map<Cell, byte[]>> getAsync(TableReference tableRef, Set<Cell> cells) { return getWithLoader("getAsync", tableRef, cells, keyValueService::getAsync); }
Source:
<code>public void add(final T rec) { if (doneAdding) { throw new IllegalStateException("Cannot add after calling doneAdding()"); } if (iterationStarted) { throw new IllegalStateException("Cannot add after calling iterator()"); <START> } <END> if (numRecordsInRam == maxRecordsInRam) { long startMem = 0; if (sampleRecordSize) { Runtime.getRuntime().gc(); startMem = Runtime.getRuntime().freeMemory(); } spillToDisk(); if (sampleRecordSize) { Runtime.getRuntime().gc(); long endMem = Runtime.getRuntime().freeMemory(); long usedBytes = endMem - startMem; log.debug(String.format("%d records in ram required approximately %s memory or %s per record. ", maxRecordsInRam, StringUtil.humanReadableByteCount(usedBytes), StringUtil.humanReadableByteCount(usedBytes / maxRecordsInRam))); } } ramRecords[numRecordsInRam++] = rec; }</code><technical_language>Bike-shedding: original name? new reads more int me</technical_language>

Target:
public void add(final T rec) { if (doneAdding) { throw new IllegalStateException("Cannot add after calling doneAdding()"); } if (iterationStarted) { throw new IllegalStateException("Cannot add after calling iterator()"); } if (numRecordsInRam == maxRecordsInRam) { long startMem = 0; if (printRecordSizeSampling) { Runtime.getRuntime().gc(); startMem = Runtime.getRuntime().freeMemory(); } spillToDisk(); if (printRecordSizeSampling) { Runtime.getRuntime().gc(); long endMem = Runtime.getRuntime().freeMemory(); long usedBytes = endMem - startMem; log.debug(String.format("%d records in ram required approximately %s memory or %s per record. ", maxRecordsInRam, StringUtil.humanReadableByteCount(usedBytes), StringUtil.humanReadableByteCount(usedBytes / maxRecordsInRam))); } } ramRecords[numRecordsInRam++] = rec; }
Source:
<code>public void createTopic(String connectionString, int numberOfPartitions, Properties topicConfig) { Validate.notNull(connectionString, "destination should not be null"); Validate.notNull(topicConfig, "topicConfig should not be null"); KafkaDestination kafkaDestination = KafkaDestination.parse(connectionString); String topicName = kafkaDestination.getTopicName(); try { if (!AdminUtils.topicExists(_zkUtils, topicName)) { int replicationFactor = Integer.parseInt(topicConfig.getProperty("replicationFactor", DEFAULT_REPLICATION_FACTOR)); LOG.info( <START> String.format("Creating topic with name %s partitions=%d with properties %s", topicName, numberOfPartitions, <END> topicConfig)); if (!topicConfig.containsKey(TOPIC_RETENTION_MS)) { topicConfig.put(TOPIC_RETENTION_MS, String.valueOf(_retention.toMillis())); } AdminUtils.createTopic(_zkUtils, topicName, numberOfPartitions, replicationFactor, topicConfig, RackAwareMode.Disabled$.MODULE$); } else { LOG.warn(String.format("Topic with name %s already exists", topicName)); } } catch (Throwable e) { LOG.error(String.format("Creating topic %s failed with exception %s ", topicName, e)); throw e; } }</code><technical_language>nit: replace String.format '{}'</technical_language>

Target:
public void createTopic(String connectionString, int numberOfPartitions, Properties topicConfig) { Validate.notNull(connectionString, "destination should not be null"); Validate.notNull(topicConfig, "topicConfig should not be null"); KafkaDestination kafkaDestination = KafkaDestination.parse(connectionString); String topicName = kafkaDestination.getTopicName(); try { if (!AdminUtils.topicExists(_zkUtils, topicName)) { int replicationFactor = Integer.parseInt(topicConfig.getProperty("replicationFactor", DEFAULT_REPLICATION_FACTOR)); LOG.info("Creating topic with name partitions={} with properties %s", topicName, numberOfPartitions, topicConfig); if (!topicConfig.containsKey(TOPIC_RETENTION_MS)) { topicConfig.put(TOPIC_RETENTION_MS, String.valueOf(_retention.toMillis())); } AdminUtils.createTopic(_zkUtils, topicName, numberOfPartitions, replicationFactor, topicConfig, RackAwareMode.Disabled$.MODULE$); } else { LOG.warn("Topic with name already exists", topicName); } } catch (Throwable e) { LOG.error("Creating topic failed with exception {}", topicName, e); throw e; } }
Source:
<code>public void testLoadDataObjects() { <START> final WorkspaceProject project = mock(WorkspaceProject.class); final Path p1 = mock(Path.class); final String file1 = "file1.java"; when(p1.getFileName()).thenReturn(file1); final Path p2 = mock(Path.class); final String file2 = "file2.java"; when(p2.getFileName()).thenReturn(file2); final List<Path> files = Arrays.asList(p1, p2); when(pathsHelper.getDataObjectsPaths(project)).thenReturn(files); final List<DataObject> dataObjects = service.loadDataObjects(project); <END> assertEquals(2, dataObjects.size()); assertEquals(file1, dataObjects.get(0).getClassType()); assertEquals(file2, dataObjects.get(1).getClassType()); }</code><technical_language>please rename p1, p2 path1 path2</technical_language>

Target:
public void testLoadDataObjects() { final WorkspaceProject project = mock(WorkspaceProject.class); final String file1 = "file1.java"; final String file2 = "file2.java"; final List<Path> files = Arrays.asList(getPath(file1), getPath(file2)); when(pathsHelper.getDataObjectsPaths(project)).thenReturn(files); final List<DataObject> dataObjects = service.loadDataObjects(project); assertEquals(2, dataObjects.size()); assertEquals(file1, dataObjects.get(0).getClassType()); assertEquals(file2, dataObjects.get(1).getClassType()); }
Source:
<code>public static void setUp() throws Exception { SpannerOptions options = SpannerOptions.newBuilder().build(); spanner = options.getService(); dbClient = spanner.getDatabaseAdminClient(); dbId = DatabaseId.of(options.getProjectId(), instanceId, databaseId); <START> deleteStaleTestDatabases(instanceId, System.getProperty("spanner.sample.database")); <END> }</code><technical_language>reuse baseDbId instead of property again</technical_language>

Target:
public static void setUp() throws Exception { SpannerOptions options = SpannerOptions.newBuilder().build(); spanner = options.getService(); dbClient = spanner.getDatabaseAdminClient(); dbId = DatabaseId.of(options.getProjectId(), instanceId, databaseId); deleteStaleTestDatabases(instanceId, baseDbId); }
Source:
<code>public FactoryDto findFactory(String name) throws ApiException, IOException { String queryParamPrefix = "find?name=" + name; HttpJsonResponse request; try { request = requestFactory.fromUrl(factoryApiEndpoint + queryParamPrefix).request(); } catch (NotFoundException e) { return null; } List<FactoryDto> dtos = request.asList(FactoryDto.class); <START> return dtos.isEmpty() ? null : dtos.get(0); <END> }</code><technical_language>Return of</technical_language>

Target:
public List<FactoryDto> findFactory(String name) throws ApiException, IOException { String queryParamPrefix = "find?name=" + name; HttpJsonResponse request; try { request = requestFactory.fromUrl(factoryApiEndpoint + queryParamPrefix).request(); } catch (NotFoundException e) { return emptyList(); } return request.asList(FactoryDto.class); }
Source:
<code>public void createSetOfLocalizedEnumAttribute() throws Exception { executeTest(SetType.class, AttributeDefinitionBuilder .of("set-of-localized-enum-attribute", LABEL, new SetType(new LocalizedEnumType(LOCALIZED_ENUM_VALUES))) .searchable(false) <START> .build(), attributeDefinitionFromServer -> { <END> final SetType setType = (SetType) attributeDefinitionFromServer.getAttributeType(); final LocalizedEnumType elementType = (LocalizedEnumType) setType.getElementType(); assertThat(elementType.getValues()).isEqualTo(LOCALIZED_ENUM_VALUES); }); }</code><technical_language>Thanks for adjusting dots line start</technical_language>

Target:
public void createSetOfLocalizedEnumAttribute() throws Exception { executeTest(SetType.class, AttributeDefinitionBuilder .of("set-of-localized-enum-attribute", LABEL, SetType.of(LocalizedEnumType.of(LOCALIZED_ENUM_VALUES))) .searchable(false) .build(), attributeDefinitionFromServer -> { final SetType setType = (SetType) attributeDefinitionFromServer.getAttributeType(); final LocalizedEnumType elementType = (LocalizedEnumType) setType.getElementType(); assertThat(elementType.getValues()).isEqualTo(LOCALIZED_ENUM_VALUES); }); }
Source:
<code>private EmailPopulatingBuilder addFormat( final EmailPopulatingBuilder builder, final RenderedReport rendered ) throws IOException { final String mimeType = rendered.getFormat().getMimeType(); final InputStream content = rendered.getBytes(); <START> if (mimeType.equals("text/html")) { <END> return builder.withHTMLText(readString(content)); } return builder.withAttachment("report", readBytes(content), mimeType); }</code><technical_language>MediaType.HTML_UTF_8.toString() Guava (unless a standard java unaware of)</technical_language>

Target:
private EmailPopulatingBuilder addFormat( final EmailPopulatingBuilder builder, final RenderedReport rendered ) throws IOException { final MediaType mimeType = rendered.getFormat().getMimeType(); final ByteSource content = rendered.getBytes(); if (mimeType.equals(MediaType.HTML_UTF_8)) { return builder.withHTMLText(content.asCharSource(StandardCharsets.UTF_8).read()); } return builder.withAttachment("report", content.read(), mimeType.toString()); }
Source:
<code>String getPropertyKey() { String url = Jenkins.getActiveInstance().getRootUrl(); if (url!=null) return url; LOGGER.log(Level.WARNING, "The instance is not configured using a rootUrl, the key that represents your instance will not be stable"); if(randomId == null){ synchronized (this){ <START> if(randomId == null){ <END> randomId = Secret.fromString("key").getEncryptedValue(); } } } return randomId; }</code><technical_language>Double-checked locking, harmless due of volatile. needlessly complicated I think</technical_language>

Target:
String getPropertyKey() { Jenkins j = Jenkins.getActiveInstance(); String url = j.getRootUrl(); if (url!=null) return url; LOGGER.log(Level.WARNING, "The instance is not configured using a rootUrl, the key that represents your instance will not be stable"); return j.getLegacyInstanceId(); }
Source:
<code>public static DimensionType getById(int dimensionId) { <START> final Optional<DimensionType> optDimensionType = DimensionManager.getDimensionType(dimensionId); <END> if (!optDimensionType.isPresent()) { throw new IllegalArgumentException("Invalid dimension id " + dimensionId); } return optDimensionType.get(); }</code><technical_language>orElseThrow method of Optional</technical_language>

Target:
public static DimensionType getById(int dimensionId) { return DimensionManager.getDimensionType(dimensionId).orElseThrow(() -> new IllegalArgumentException("Invalid dimension id " + dimensionId)); }
Source:
<code>public Response get() { HealthCheckRegistry checks = this.environment.healthChecks(); SortedMap<String, HealthCheck.Result> results = checks.runHealthChecks(); if (results.entrySet().stream().anyMatch(r -> !r.getValue().isHealthy())) { <START> logger.warn("Health checks failed: {}", results); <END> return Response.serverError().entity(results).build(); } return Response.ok(results).build(); }</code><technical_language>failing health checks warn themselves, want depend hitting /_status get warn messages</technical_language>

Target:
public Response get() { HealthCheckRegistry checks = this.environment.healthChecks(); SortedMap<String, HealthCheck.Result> results = checks.runHealthChecks(); List<String> failing = results.entrySet().stream() .filter(r -> !r.getValue().isHealthy()) .map(Map.Entry::getKey) .collect(toList()); if (!failing.isEmpty()) { logger.warn("Health checks failed: {}", results); String message = "failing health checks: " + Arrays.toString(failing.toArray()); StatusResponse sr = new StatusResponse("critical", message, results); return Response.serverError().entity(sr).build(); } StatusResponse sr = new StatusResponse("ok", "ok", results); return Response.ok(sr).build(); }
Source:
<code>public void close() { if (dataReader != null && dataReader.isRunning()) dataReader.stopReader(); connectionInterface.close(); <START> logger.info("Connection interface closed."); <END> }</code><technical_language>open close methods of XBeeDevice, refer _connection interface_ device itself? I opening closing XBee, if I worried is below. And, do need more explicit, this information Connection interface open/closed, do XBeeDevice referring if working several</technical_language>

Target:
public void close() { if (dataReader != null && dataReader.isRunning()) dataReader.stopReader(); connectionInterface.close(); logger.info(toString() + "Connection interface closed."); }
Source:
<code>public void failed(Throwable cause) { try (SetThreadName ignored = new SetThreadName("TaskInfoFetcher-%s", taskId)) { lastUpdateNanos.set(System.nanoTime()); try { if (!isDone(getTaskInfo())) { errorTracker.requestFailed(cause); } } catch (Error e) { onFail.accept(e); throw e; } catch (RuntimeException e) { onFail.accept(e); updateTaskInfo(taskInfo.get().withTaskStatus(failWith(taskInfo.get().getTaskStatus(), FAILED, ImmutableList.of(toFailure(cause))))); } } <START> } <END></code><technical_language>following: // onFail callback update task info failed state. // recoverable grouped execution, a single failed task fail query. updating task info query finish in tests failed task is stuck in RUNNING state. // TODO: This issue in test TestHiveRecoverableGroupedExecution a worker is closed. Investigate this is issue for production query recovery. This explains is missing onFail, a problem (since fail query now). "RequestErrorTracker#requestFailed throws backoff threshold is reached." explains exception thrown, in opinion is a level detail. key is task failed, task info is updated. a problem query fail. task stuck :/</technical_language>

Target:
public void failed(Throwable cause) { try (SetThreadName ignored = new SetThreadName("TaskInfoFetcher-%s", taskId)) { lastUpdateNanos.set(System.nanoTime()); try { if (!isDone(getTaskInfo())) { errorTracker.requestFailed(cause); } } catch (Error e) { onFail.accept(e); throw e; } catch (RuntimeException e) { onFail.accept(e); } } }
Source:
<code>public void boot(boolean create,Properties startParams) throws StandardException{ Configuration.setConfiguration(null); SConfiguration config = SIDriver.driver().getConfiguration(); if (startParams == null) { startParams = new Properties(); } if (System.getProperty("derby.drda.timeSlice") == null) System.setProperty("derby.drda.timeSlice","60000"); String logStatementText = System.getProperty("derby.language.logStatementText"); if (logStatementText == null) { if (config.debugLogStatementContext()) { <START> System.setProperty("com.splicemachine.enableLegacyAsserts", Boolean.TRUE.toString()); <END> startParams.put("derby.language.logStatementText", Boolean.TRUE.toString()); } else { startParams.put("derby.language.logStatementText", Boolean.FALSE.toString()); } } if (config.debugDumpClassFile()) { System.setProperty("com.splicemachine.enableLegacyAsserts",Boolean.TRUE.toString()); SanityManager.DEBUG_SET("DumpClassFile"); } if (config.debugDumpBindTree()) { System.setProperty("com.splicemachine.enableLegacyAsserts",Boolean.TRUE.toString()); SanityManager.DEBUG_SET("DumpBindTree"); } if (config.debugDumpOptimizedTree()) { System.setProperty("com.splicemachine.enableLegacyAsserts",Boolean.TRUE.toString()); SanityManager.DEBUG_SET("DumpOptimizedTree"); } configureAuthentication(); create=Boolean.TRUE.equals(EngineLifecycleService.isCreate.get()); if(create){ SpliceLogUtils.info(LOG,"Creating the Splice Machine database"); }else{ SpliceLogUtils.info(LOG,"Booting the Splice Machine database"); } super.boot(create,startParams); }</code><technical_language>debugLogStatementContext is true default now, this change default of com.splicemachine.enableLegacyAsserts</technical_language>

Target:
public void boot(boolean create,Properties startParams) throws StandardException{ Configuration.setConfiguration(null); SConfiguration config = SIDriver.driver().getConfiguration(); if (startParams == null) { startParams = new Properties(); } if (System.getProperty("derby.drda.timeSlice") == null) System.setProperty("derby.drda.timeSlice","60000"); String logStatementText = System.getProperty("derby.language.logStatementText"); if (logStatementText == null) { startParams.put("derby.language.logStatementText", Boolean.toString(config.debugLogStatementContext())); } if (config.debugDumpClassFile()) { System.setProperty("com.splicemachine.enableLegacyAsserts",Boolean.TRUE.toString()); SanityManager.DEBUG_SET("DumpClassFile"); } if (config.debugDumpBindTree()) { System.setProperty("com.splicemachine.enableLegacyAsserts",Boolean.TRUE.toString()); SanityManager.DEBUG_SET("DumpBindTree"); } if (config.debugDumpOptimizedTree()) { System.setProperty("com.splicemachine.enableLegacyAsserts",Boolean.TRUE.toString()); SanityManager.DEBUG_SET("DumpOptimizedTree"); } configureAuthentication(); create=Boolean.TRUE.equals(EngineLifecycleService.isCreate.get()); if(create){ SpliceLogUtils.info(LOG,"Creating the Splice Machine database"); }else{ SpliceLogUtils.info(LOG,"Booting the Splice Machine database"); } super.boot(create,startParams); }
Source:
<code>protected boolean isDataStall() { boolean result = false; if (!mNetworkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) && (SystemClock.elapsedRealtime() - getLastProbeTime() < mDataStallMinEvaluateTime)) { return false; } if (dataStallEvaluateTypeEnabled(DATA_STALL_EVALUATION_TYPE_DNS)) { if (mDnsStallDetector.isDataStallSuspected(mConsecutiveDnsTimeoutThreshold, mDataStallValidDnsTimeThreshold)) { result = true; logNetworkEvent(NetworkEvent.NETWORK_CONSECUTIVE_DNS_TIMEOUT_FOUND); } } if (dataStallEvaluateTypeEnabled(DATA_STALL_EVALUATION_TYPE_TCP)) { if (getTcpSocketTracker().getSentSinceLastRecv() > 0) { <START> result = false; <END> } else if (getTcpSocketTracker().isDataStallSuspected()) { result = true; } } if (VDBG_STALL) { log("isDataStall: result=" + result + ", consecutive dns timeout count=" + mDnsStallDetector.getConsecutiveTimeoutCount() + ", tcp packets received=" + getTcpSocketTracker().getSentSinceLastRecv() + ", tcp fail rate=" + getTcpSocketTracker().getLatestPacketFailRate()); } return result; }</code><technical_language>If this overrides DNS, do skip evaluating DNS</technical_language>

Target:
protected boolean isDataStall() { Boolean result = null; if (!mNetworkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) && (SystemClock.elapsedRealtime() - getLastProbeTime() < mDataStallMinEvaluateTime)) { return false; } if (dataStallEvaluateTypeEnabled(DATA_STALL_EVALUATION_TYPE_TCP)) { if (getTcpSocketTracker().getSentSinceLastRecv() > 0) { result = false; } if ((result == null) && getTcpSocketTracker().isDataStallSuspected()) { result = true; } } if ((result == null) && dataStallEvaluateTypeEnabled(DATA_STALL_EVALUATION_TYPE_DNS)) { if (mDnsStallDetector.isDataStallSuspected(mConsecutiveDnsTimeoutThreshold, mDataStallValidDnsTimeThreshold)) { result = true; logNetworkEvent(NetworkEvent.NETWORK_CONSECUTIVE_DNS_TIMEOUT_FOUND); } } if (VDBG_STALL) { log("isDataStall: result=" + result + ", consecutive dns timeout count=" + mDnsStallDetector.getConsecutiveTimeoutCount() + ", tcp packets received=" + getTcpSocketTracker().getSentSinceLastRecv() + ", tcp fail rate=" + getTcpSocketTracker().getLatestPacketFailRate()); } return (result == null) ? false : result; }
Source:
<code>public InetAddress getLocalAddress() throws IOException { return InetAddress.getByName( <START> new RqHeaders.Base(this).header("X-Takes-LocalAddress") <END> .iterator().next() ); }</code><technical_language>I RqHeaders.Smart#single() (and methods below)</technical_language>

Target:
public InetAddress getLocalAddress() throws IOException { return InetAddress.getByName( new RqHeaders.Smart(new RqHeaders.Base(this)) .single("X-Takes-LocalAddress") ); }
Source:
<code>protected boolean isVmLeaseExistsOnStorageDomain(Guid leaseStorageDomainId) { ActionReturnValue retVal = runInternalAction(ActionType.GetVmLeaseInfo, new VmLeaseParameters(getStoragePoolId(), leaseStorageDomainId, getParameters().getVmId())); if (retVal.getSucceeded() && retVal.getActionReturnValue() != null) { log.info("Managed to fetch VM '{}' lease info from storage domains <START> '{}', <END> '{}'", getParameters().getVmId(), leaseStorageDomainId, retVal.getActionReturnValue()); getVm().setLeaseInfo(retVal.getActionReturnValue()); return true; } return false; }</code><technical_language>Add ': ' clear this is result</technical_language>

Target:
protected boolean isVmLeaseExistsOnStorageDomain(Guid leaseStorageDomainId) { ActionReturnValue retVal = runInternalAction(ActionType.GetVmLeaseInfo, new VmLeaseParameters(getStoragePoolId(), leaseStorageDomainId, getParameters().getVmId())); if (retVal.getSucceeded() && retVal.getActionReturnValue() != null) { log.info("Managed to fetch VM '{}' lease info from the storage domain '{}': '{}'", getParameters().getVmId(), leaseStorageDomainId, retVal.getActionReturnValue()); getVm().setLeaseInfo(retVal.getActionReturnValue()); return true; } return false; }
Source:
<code>public void complete(Predicate<SubscriptionQueryMessage<?, ?, ?>> filter) { registeringSubscriptionQueryReadSafe(filter, () -> updateHandlers.keySet() .stream() .filter(filter) .forEach(query -> { <START> UpdateHandler<?, ?> updateHandler = updateHandlers.get(query); <END> updateHandlers.remove(query); updateHandler.onCompleted(); })); }</code><technical_language>remove() function return UpdateHandler want call onCompleted() on</technical_language>

Target:
public void complete(Predicate<SubscriptionQueryMessage<?, ?, ?>> filter) { updateHandlers.keySet() .stream() .filter(filter) .forEach(query -> Optional.ofNullable(updateHandlers.get(query)) .ifPresent(updateHandler -> { try { updateHandler.complete(); } catch (Exception e) { emitError(query, e, updateHandler); } })); }
Source:
<code>private void updateConditionSets(List<Expression> expressions, TagNode node) { Optional<String> condition = node.getAttributes().stream() .map(Attribute::getName) <START> .filter(text -> text.contains(SLY_TEST)) <END> .findFirst(); if (condition.isPresent() && !condition.get().equals(SLY_TEST)) { condition = Optional.of(condition.get().substring(14)); namedConditions.add(condition.get()); } else { unnamedConditions.addAll(expressions.stream() .map(Expression::getRawText) .map(text -> text.replaceAll("[${}]", "")) .filter(text -> !namedConditions.contains(text)) .collect(Collectors.toSet())); } }</code><technical_language>constant left side of equals</technical_language>

Target:
private void updateConditionSets(List<Expression> expressions, TagNode node) { String condition = node.getAttributes().stream() .map(Attribute::getName) .filter(text -> text.contains(SLY_TEST)) .findFirst() .orElse(""); if (!SLY_TEST.equals(condition) && SLY_TEST_LENGTH < condition.length()) { condition = condition.substring(SLY_TEST_LENGTH); namedConditions.add(condition); } else { unnamedConditions.addAll(clearExpressions(expressions).stream() .filter(text -> !namedConditions.contains(text)) .collect(Collectors.toSet())); } }
Source:
<code>public String stemWord(String word) { word = word.toLowerCase(eoLocale); String suffix = word; if (isExceptionOrNumber(suffix)) { return word; } int localMinStemLength = Math.max(minStemLength, firstVowelPos(suffix) + 1); int pluralDirectOffset = calcPluralDirectOffset(suffix); if (pluralDirectOffset > 0) { suffix = suffix.substring(0, suffix.length() - pluralDirectOffset); if (pluralDirectChecks.contains(suffix) || stemmerExceptions.contains(suffix)) { return suffix; } } suffix = findLongestSuffix(suffix, word, minStemLength + pluralDirectOffset); int stemLength = 0; if <START> (!suffix.equals("")) { <END> stemLength = word.length() - suffix.length() - pluralDirectOffset; if (suffix.charAt(0) == '-' && suffix.length() + pluralDirectOffset < word.length()) { return word.substring(0, stemLength); } } if (stemLength < localMinStemLength) { return word; } return word.substring(0, stemLength); }</code><technical_language>isEmpty()</technical_language>

Target:
public String stemWord(String word) { if (word == null) { return word; } word = word.toLowerCase(eoLocale); if (isExceptionOrNumber(word)) { return word; } String suffix = word; int localMinStemLength = Math.max(minStemLength, firstVowelPos(suffix) + 1); int pluralDirectOffset = calcPluralDirectOffset(suffix); if (pluralDirectOffset > 0) { suffix = suffix.substring(0, suffix.length() - pluralDirectOffset); if (pluralDirectChecks.contains(suffix) || stemmerExceptions.contains(suffix)) { return suffix; } } suffix = findLongestSuffix(suffix, word, localMinStemLength, pluralDirectOffset); int stemLength = 0; if (!suffix.isEmpty()) { stemLength = word.length() - suffix.length() - pluralDirectOffset; if (suffix.charAt(0) == '-' && suffix.length() + pluralDirectOffset < word.length()) { return word.substring(0, stemLength); } } if (stemLength < localMinStemLength) { return word; } return word.substring(0, stemLength); }
Source:
<code>public WorkflowResource(HttpClient client, SessionFactory sessionFactory, PermissionsInterface permissionsInterface, EntryResource entryResource, DockstoreWebserviceConfiguration configuration) { super(client, sessionFactory, configuration, Workflow.class); this.toolDAO = new ToolDAO(sessionFactory); this.labelDAO = new LabelDAO(sessionFactory); this.fileFormatDAO = new FileFormatDAO(sessionFactory); this.permissionsInterface = permissionsInterface; this.entryResource = entryResource; elasticManager = new ElasticManager(); zenodoUrl = configuration.getZenodoUrl(); zenodoClientID = configuration.getZenodoClientID(); zenodoClientSecret = configuration.getZenodoClientSecret(); dockstoreUrl = URIHelper.createBaseUrl(configuration.getExternalConfig().getScheme(), configuration.getExternalConfig().getHostname(), configuration.getExternalConfig().getUiPort()); try { dockstoreGA4GHBaseUrl = ToolsImplCommon.baseURL(configuration); } catch (URISyntaxException e) { LOG.error("Could create Dockstore base URL. Error is " + e.getMessage(), e); throw new CustomWebApplicationException("Could create Dockstore base URL. " + "Error is " + e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } <START> MetadataResourceHelper.setConfig(configuration); <END> }</code><technical_language>Remove this set in DockstoreWebserviceApplication</technical_language>

Target:
public WorkflowResource(HttpClient client, SessionFactory sessionFactory, PermissionsInterface permissionsInterface, EntryResource entryResource, DockstoreWebserviceConfiguration configuration) { super(client, sessionFactory, configuration, Workflow.class); this.toolDAO = new ToolDAO(sessionFactory); this.labelDAO = new LabelDAO(sessionFactory); this.fileFormatDAO = new FileFormatDAO(sessionFactory); this.permissionsInterface = permissionsInterface; this.entryResource = entryResource; elasticManager = new ElasticManager(); zenodoUrl = configuration.getZenodoUrl(); zenodoClientID = configuration.getZenodoClientID(); zenodoClientSecret = configuration.getZenodoClientSecret(); dockstoreUrl = URIHelper.createBaseUrl(configuration.getExternalConfig().getScheme(), configuration.getExternalConfig().getHostname(), configuration.getExternalConfig().getUiPort()); try { dockstoreGA4GHBaseUrl = ToolsImplCommon.baseURL(configuration); } catch (URISyntaxException e) { LOG.error("Could create Dockstore base URL. Error is " + e.getMessage(), e); throw new CustomWebApplicationException("Could create Dockstore base URL. " + "Error is " + e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } }
Source:
<code>public ContentDirectoryMonitor( CamelContext camelContext, AttributeRegistry attributeRegistry, int maxRetries, int delayBetweenRetries, Executor configurationExecutor, Security security) { <START> this.camelContext = Objects.requireNonNull(camelContext, "CamelContext cannot be null"); <END> this.attributeRegistry = attributeRegistry; this.maxRetries = maxRetries; this.delayBetweenRetries = delayBetweenRetries; this.configurationExecutor = configurationExecutor; this.security = security; systemSubjectBinder = new SystemSubjectBinder(security); setBlacklist(); }</code><technical_language>string name of variable case. So, camelContext, CamelContext</technical_language>

Target:
public ContentDirectoryMonitor( CamelContext camelContext, AttributeRegistry attributeRegistry, int maxRetries, int delayBetweenRetries, Executor configurationExecutor, Security security) { this.camelContext = Objects.requireNonNull(camelContext, "camelContext cannot be null"); this.attributeRegistry = attributeRegistry; this.maxRetries = maxRetries; this.delayBetweenRetries = delayBetweenRetries; this.configurationExecutor = configurationExecutor; this.security = security; systemSubjectBinder = new SystemSubjectBinder(security); setBlacklist(); }
Source:
<code>public boolean hasEqualExtents(Grid comparisonGrid){ <START> if (this.zoom != comparisonGrid.zoom || this.west != comparisonGrid.west || this.north != comparisonGrid.north || <END> this.width != comparisonGrid.width || this.height != comparisonGrid.height) return false; else return true; }</code><technical_language>if statement returning explicit true false values (which feels a bit a double-negative a chain of != return a false), cleaner define this return this.zoom == comparisonGrid.zoom && this.west == comparisonGrid.west && this.north == comparisonGrid.north && this.width == comparisonGrid.width && this.height == comparisonGrid.height;</technical_language>

Target:
public boolean hasEqualExtents(Grid comparisonGrid){ return this.zoom == comparisonGrid.zoom && this.west == comparisonGrid.west && this.north == comparisonGrid.north && this.width == comparisonGrid.width && this.height == comparisonGrid.height; }
Source:
<code>protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable() <START> .addProperty(SearchConfig.DIRECTORY_TYPE, SearchConfig.HEAP); <END> return TestCacheManagerFactory.createCacheManager(builder); }</code><technical_language>need HEAP</technical_language>

Target:
protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.indexing().enable(); return TestCacheManagerFactory.createCacheManager(builder); }
Source:
<code>private void runGroupsQuery(JSONArray resultArray, String queryString, String formattedInput, int maxResults) throws Exception { List<String> queryResult = runQuery(queryString, formattedInput, maxResults); for (String groupName : queryResult) { Group group = this.groupManager.getGroup(groupName); List<AttachmentReference> attachmentRefs = this.bridge.getAttachmentReferences(group.getReference()); String avatarURL = ""; if (attachmentRefs.size() > 0) { avatarURL = this.bridge.getAttachmentURL(attachmentRefs.get(0), true); } else { XWikiContext xcontext = this.xcontextProvider.get(); XWiki xwiki = xcontext.getWiki(); avatarURL = xwiki.getSkinFile("icons/xwiki/noavatargroup.png", xcontext); } JSONObject o = createObject(groupName, group.getReference().getName(), avatarURL, GROUP); <START> resultArray.put(o); <END> if (resultArray.length() == maxResults) { break; } } }</code><technical_language>This is important, if resultArray maxResults entries end maxResults + 1 entries. Making this check start of loop iteration save some work (if maxResults users group search skipped completely this method is called)</technical_language>

Target:
private void runGroupsQuery(JSONArray resultArray, String queryString, String formattedInput, int maxResults) throws Exception { List<String> queryResult = runQuery(queryString, formattedInput, maxResults); for (String groupName : queryResult) { Group group = this.groupManager.getGroup(groupName); List<AttachmentReference> attachmentRefs = this.bridge.getAttachmentReferences(group.getReference()); String avatarURL = ""; if (attachmentRefs.size() > 0) { avatarURL = this.bridge.getAttachmentURL(attachmentRefs.get(0), true); } else { XWikiContext xcontext = this.xcontextProvider.get(); XWiki xwiki = xcontext.getWiki(); avatarURL = xwiki.getSkinFile("icons/xwiki/noavatargroup.png", xcontext); } JSONObject o = createObject(groupName, group.getReference().getName(), avatarURL, GROUP); resultArray.put(o); } }
Source:
<code>public void findEdgesInShape(final GHIntHashSet edgeIds, final Shape shape, EdgeFilter filter) { GHPoint center = shape.getCenter(); QueryResult qr = locationIndex.findClosest(center.getLat(), center.getLon(), filter); if (!qr.isValid()) throw new IllegalArgumentException("Shape " + shape + " does not cover graph"); if (shape.contains(qr.getSnappedPoint().lat, qr.getSnappedPoint().lon)) edgeIds.add(qr.getClosestEdge().getEdge()); final boolean isPolygon = shape instanceof Polygon; BreadthFirstSearch bfs = new BreadthFirstSearch() { final NodeAccess na = graph.getNodeAccess(); final Shape localShape = shape; @Override protected boolean goFurther(int nodeId) { if (isPolygon) { BBox bbox = localShape.getBounds(); double lat = na.getLatitude(nodeId); double lon = na.getLongitude(nodeId); return lat <= bbox.maxLat && lat >= bbox.minLat && lon <= bbox.maxLon && lon >= bbox.minLon; } return localShape.contains(na.getLatitude(nodeId), na.getLongitude(nodeId)); } @Override protected boolean checkAdjacent(EdgeIteratorState edge) { if (localShape.contains(na.getLatitude(edge.getAdjNode()), na.getLongitude(edge.getAdjNode()))) { edgeIds.add(edge.getEdge()); return true; } <START> return isPolygon; <END> } }; bfs.start(graph.createEdgeExplorer(filter), qr.getClosestNode()); }</code><technical_language>do return isPolygon here</technical_language>

Target:
public void findEdgesInShape(final GHIntHashSet edgeIds, final Shape shape, EdgeFilter filter) { GHPoint center = shape.getCenter(); QueryResult qr = locationIndex.findClosest(center.getLat(), center.getLon(), filter); if (!qr.isValid()) throw new IllegalArgumentException("Shape " + shape + " does not cover graph"); if (shape.contains(qr.getSnappedPoint().lat, qr.getSnappedPoint().lon)) edgeIds.add(qr.getClosestEdge().getEdge()); final boolean isPolygon = shape instanceof Polygon; BreadthFirstSearch bfs = new BreadthFirstSearch() { final NodeAccess na = graph.getNodeAccess(); final Shape localShape = shape; @Override protected boolean goFurther(int nodeId) { if (isPolygon) return isInsideBBox(nodeId); return localShape.contains(na.getLatitude(nodeId), na.getLongitude(nodeId)); } @Override protected boolean checkAdjacent(EdgeIteratorState edge) { int adjNodeId = edge.getAdjNode(); if (localShape.contains(na.getLatitude(adjNodeId), na.getLongitude(adjNodeId))) { edgeIds.add(edge.getEdge()); return true; } return isPolygon && isInsideBBox(adjNodeId); } private boolean isInsideBBox(int nodeId) { BBox bbox = localShape.getBounds(); double lat = na.getLatitude(nodeId); double lon = na.getLongitude(nodeId); return lat <= bbox.maxLat && lat >= bbox.minLat && lon <= bbox.maxLon && lon >= bbox.minLon; } }; bfs.start(graph.createEdgeExplorer(filter), qr.getClosestNode()); }
Source:
<code>private void subscribeUpstreamChains(Context downstreamContext) { <START> innerFlux.subscriberContext(downstreamContext).subscribe(); <END> upstreamFlux.subscriberContext(downstreamContext).subscribe(); }</code><technical_language>for torubleshooting, add error handler subscribe uncaught error logged</technical_language>

Target:
private void subscribeUpstreamChains(Context downstreamContext) { innerFlux.subscriberContext(downstreamContext) .doOnError(e -> LOGGER.error("Exception during foreach execution: " + e.getCause())) .subscribe(); upstreamFlux.subscriberContext(downstreamContext).subscribe(); }
Source:
<code>public StoreConfig(VerifiableProperties verifiableProperties) { storeKeyFactory = verifiableProperties.getString("store.key.factory", "com.github.ambry.shared.BlobIdFactory"); storeDataFlushIntervalSeconds = verifiableProperties.getLong("store.data.flush.interval.seconds", 60); storeIndexMaxMemorySizeBytes = verifiableProperties.getInt("store.index.max.memory.size.bytes", 20*1024*1024); storeDataFlushDelaySeconds = verifiableProperties.getInt("store.data.flush.delay.seconds", 5); storeIndexMaxNumberOfInmemElements = verifiableProperties.getInt("store.index.max.number.of.inmem.elements", 10000); storeIndexBloomMaxFalsePositiveProbability = verifiableProperties.getDoubleInRange( "store.index.bloom.max.false.positive.probability", 0.01, 0.0, 1.0); storeMaxNumberOfEntriesToReturnFromJournal = verifiableProperties.getInt( <START> "store.max.number.of.entries.to.return.from.journal", 5000); <END> }</code><technical_language>protect config of 0 specifiy "...journal", 1, 5000)</technical_language>

Target:
public StoreConfig(VerifiableProperties verifiableProperties) { storeKeyFactory = verifiableProperties.getString("store.key.factory", "com.github.ambry.shared.BlobIdFactory"); storeDataFlushIntervalSeconds = verifiableProperties.getLong("store.data.flush.interval.seconds", 60); storeIndexMaxMemorySizeBytes = verifiableProperties.getInt("store.index.max.memory.size.bytes", 20*1024*1024); storeDataFlushDelaySeconds = verifiableProperties.getInt("store.data.flush.delay.seconds", 5); storeIndexMaxNumberOfInmemElements = verifiableProperties.getInt("store.index.max.number.of.inmem.elements", 10000); storeIndexBloomMaxFalsePositiveProbability = verifiableProperties.getDoubleInRange( "store.index.bloom.max.false.positive.probability", 0.01, 0.0, 1.0); storeMaxNumberOfEntriesToReturnFromJournal = verifiableProperties.getIntInRange( "store.max.number.of.entries.to.return.from.journal", 5000, 1, 10000); }