auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testTimestampInsert() throws Exception { TestEnv env = new TestEnv(m_catalogJar, m_pathToDeployment, 1, 1, 0); try { env.setUp(); try { String sql = "INSERT INTO TS_CONSTRAINT_EXCEPTION VALUES ('aaa','{}');"; env.m_client.callProcedure("@AdHoc", sql).getResults(); fail("Compilation should have failed."); } catch(ProcCallException e) { <START> String expectedMsg = "Error compiling"; <END> assertTrue(e.getMessage().contains("invalid format for a constant timestamp value")); } String sql = String.format("INSERT INTO TS_CONSTRAINT_EXCEPTION VALUES ('%s','{}');", new TimestampType().toString()); VoltTable modCount = env.m_client.callProcedure("@AdHoc", sql).getResults()[0]; assertEquals(1, modCount.getRowCount()); assertEquals(1, modCount.asScalarLong()); try { modCount = env.m_client.callProcedure("@AdHoc", sql).getResults()[0]; assertEquals(1, modCount.getRowCount()); assertEquals(1, modCount.asScalarLong()); } catch(ProcCallException e) { assertTrue(e.getMessage().contains("CONSTRAINT VIOLATION")); } } finally { env.tearDown(); } }</code><technical_language>Is expectedMsg here</technical_language>

Target:
public void testTimestampInsert() throws Exception { TestEnv env = new TestEnv(m_catalogJar, m_pathToDeployment, 1, 1, 0); try { env.setUp(); try { String sql = "INSERT INTO TS_CONSTRAINT_EXCEPTION VALUES ('aaa','{}');"; env.m_client.callProcedure("@AdHoc", sql).getResults(); fail("Compilation should have failed."); } catch(ProcCallException e) { assertTrue(e.getMessage().contains("invalid format for a constant timestamp value")); } String sql = String.format("INSERT INTO TS_CONSTRAINT_EXCEPTION VALUES ('%s','{}');", new TimestampType().toString()); VoltTable modCount = env.m_client.callProcedure("@AdHoc", sql).getResults()[0]; assertEquals(1, modCount.getRowCount()); assertEquals(1, modCount.asScalarLong()); try { modCount = env.m_client.callProcedure("@AdHoc", sql).getResults()[0]; assertEquals(1, modCount.getRowCount()); assertEquals(1, modCount.asScalarLong()); } catch(ProcCallException e) { assertTrue(e.getMessage().contains("CONSTRAINT VIOLATION")); } } finally { env.tearDown(); } }
Source:
<code>public Observable<Void> writeFileRegion(FileRegion region) { <START> final ChannelFuture future = writeOnChannel(region); <END> return Observable.create(new OnSubscribe<Void>() { @Override public void call(final Subscriber<? super Void> subscriber) { future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { subscriber.onCompleted(); } else { subscriber.onError(future.cause()); } } }); } }); }</code><technical_language>writeOnChannel() adds future of write unflushed futures. This write need a flush. Instead java ChannelFuture writeFuture = getChannel().write(region);</technical_language>

Target:
public void writeFileRegion(FileRegion region) { writeOnChannel(region); }
Source:
<code>private static ConnectorPartitioningMetadata createConnectorPartitioningMetadata(ConnectorId connectorId, PartitioningMetadata partitioningMetadata) { ConnectorId partitioningConnectorId = partitioningMetadata.getPartitioningHandle().getConnectorId() .orElseThrow(() -> new IllegalArgumentException("connectorId is expected to be present in the connector partitioning handle")); <START> checkArgument(connectorId.equals(partitioningConnectorId), "Unexpected partitioning handle connector: %s", partitioningConnectorId); <END> return new ConnectorPartitioningMetadata(partitioningMetadata.getPartitioningHandle().getConnectorHandle(), partitioningMetadata.getPartitionColumns()); }</code><technical_language>useful print expected connectorId in error message well</technical_language>

Target:
private static ConnectorPartitioningMetadata createConnectorPartitioningMetadata(ConnectorId connectorId, PartitioningMetadata partitioningMetadata) { ConnectorId partitioningConnectorId = partitioningMetadata.getPartitioningHandle().getConnectorId() .orElseThrow(() -> new IllegalArgumentException("connectorId is expected to be present in the connector partitioning handle")); checkArgument( connectorId.equals(partitioningConnectorId), "Unexpected partitioning handle connector: %s. Expected: %s.", partitioningConnectorId, connectorId); return new ConnectorPartitioningMetadata(partitioningMetadata.getPartitioningHandle().getConnectorHandle(), partitioningMetadata.getPartitionColumns()); }
Source:
<code>public void prePersistStatus() { status = QueryStatus.QUEUED; <START> if (id == null || id.isEmpty() || id.equalsIgnoreCase("string")) { <END> id = UUID.randomUUID().toString(); } }</code><technical_language>do compare "string"</technical_language>

Target:
public void prePersistStatus() { status = QueryStatus.QUEUED; if (id == null || id.isEmpty()) { id = UUID.randomUUID().toString(); } }
Source:
<code>public void testCompanionAdVanish() throws Exception { Log.v(TAG, "Beginning testCompanionAdVanish"); super.playVideo(); Log.v(TAG, "Prerolls..."); <START> toCompanionAdCheck(5000); <END> assertFalse("Companion ad still present after preroll ad break.", toEndOfAdCheck()); Log.v(TAG, "Midrolls..."); toCompanionAdCheck(35000); assertFalse("Companion ad still present after midroll ad break.", toEndOfAdCheck()); Log.v(TAG, "Postrolls..."); toCompanionAdCheck(112000); assertFalse("Companion ad still present after postroll ad break.", toEndOfAdCheck()); Log.v(TAG, "Finished testCompanionAdVanish"); }</code><technical_language>tests waiting for video play numeric literal value? is, waiting for video play 5 sec, assert, wait for another 30 sec, assert, wait for another 80 sec? of tests in this test class 7 minutes execute (not counting if 30-second timeout play). Is a tests seek next test point instead</technical_language>

Target:
public void testCompanionAdVanish() throws Exception { Log.v(TAG, "Beginning testCompanionAdVanish"); super.playVideo(); Log.v(TAG, "Prerolls..."); waitForCompanionAdCheck(msecToPreroll, ADTYPE_PREROLL); assertFalse("Companion ad still present after preroll ad break.", waitForEndOfAdCheck(ADTYPE_PREROLL)); Log.v(TAG, "Midrolls..."); waitForCompanionAdCheck(msecToMidroll, ADTYPE_MIDROLL); assertFalse("Companion ad still present after midroll ad break.", waitForEndOfAdCheck(ADTYPE_MIDROLL)); Log.v(TAG, "Postrolls..."); waitForCompanionAdCheck(msecToPostroll, ADTYPE_POSTROLL); assertFalse("Companion ad still present after postroll ad break.", waitForEndOfAdCheck(ADTYPE_POSTROLL)); Log.v(TAG, "Finished testCompanionAdVanish"); }
Source:
<code>public void registerSuite(Suite s) { <START> installedSuites.add(s); <END> }</code><technical_language>In getInstalledSuites() installedSuites.addElement instead of installedSuites.add. Is a catch due needs synchronized other not</technical_language>

Target:
public void registerSuite(Suite s) { installedSuites.addElement(s); }
Source:
<code>public void replicatorBuilderAddsCookieInterceptorDefaultPort() throws Exception { ReplicatorBuilder.Pull p = ReplicatorBuilder.pull(). from(new URI("http://🍶:🍶@some-host/path%2Fsome-path-日本")). to(datastore); BasicReplicator r = (BasicReplicator)p.build(); Assert.assertEquals("http://some-host:80/path%2Fsome-path-日本", (((CouchClientWrapper)(((BasicPullStrategy)r.strategy).sourceDb)). getCouchClient(). getRootUri()). toString() ); <START> Field reqIField = ReplicatorBuilder.class.getDeclaredField("requestInterceptors"); <END> Field respIField = ReplicatorBuilder.class.getDeclaredField("responseInterceptors"); reqIField.setAccessible(true); respIField.setAccessible(true); List<HttpConnectionRequestInterceptor> reqIList = (List)reqIField.get(p); List<HttpConnectionRequestInterceptor> respIList = (List)respIField.get(p); Assert.assertEquals(1, reqIList.size()); Assert.assertEquals(CookieInterceptor.class, reqIList.get(0).getClass()); Assert.assertEquals(1, respIList.size()); Assert.assertEquals(CookieInterceptor.class, respIList.get(0).getClass()); CookieInterceptor ci = (CookieInterceptor)reqIList.get(0); Field srbField = CookieInterceptor.class.getDeclaredField("sessionRequestBody"); srbField.setAccessible(true); byte[] srb = (byte[])srbField.get(ci); String srbString = new String(srb); Assert.assertEquals("name=%F0%9F%8D%B6&password=%F0%9F%8D%B6", srbString); }</code><technical_language>I refactor this code a helper method, in replicatorBuilderAddsCookieInterceptorCustomPort</technical_language>

Target:
public void replicatorBuilderAddsCookieInterceptorDefaultPort() throws Exception { ReplicatorBuilder.Pull p = ReplicatorBuilder.pull(). from(new URI("http://🍶:🍶@some-host/path%2Fsome-path-日本")). to(datastore); BasicReplicator r = (BasicReplicator)p.build(); Assert.assertEquals("http://some-host:80/path%2Fsome-path-日本", (((CouchClientWrapper) (((BasicPullStrategy) r.strategy).sourceDb)). getCouchClient(). getRootUri()). toString() ); assertCookieInterceptorPresent(p, "name=%F0%9F%8D%B6&password=%F0%9F%8D%B6"); }
Source:
<code>public static OpcUaRequestInfo extract(DriverRecord record) { final Map<String, Object> channelConfig = record.getChannelConfig(); int nodeNamespaceIndex; String nodeId; try { nodeId = channelConfig.get(NODE_ID).toString(); } catch (final Exception e) { fail(record, message.errorRetrievingNodeId()); <START> return null; <END> } try { nodeNamespaceIndex = Integer.parseInt(channelConfig.get(NODE_NAMESPACE_INDEX).toString()); } catch (final Exception e) { fail(record, message.errorRetrievingNodeNamespace()); return null; } final DataType dataType = (DataType) record.getChannelConfig().get(CHANNEL_VALUE_TYPE.value()); if (dataType == null) { fail(record, message.errorRetrievingValueType()); return null; } return new OpcUaRequestInfo(dataType, nodeNamespaceIndex, nodeId); }</code><technical_language>improvement. return null. Optional.ofNullable(..) Optional.empty()</technical_language>

Target:
public static Optional<OpcUaRequestInfo> extract(DriverRecord record) { final Map<String, Object> channelConfig = record.getChannelConfig(); int nodeNamespaceIndex; String nodeId; try { nodeId = channelConfig.get(NODE_ID).toString(); } catch (final Exception e) { fail(record, message.errorRetrievingNodeId()); return Optional.empty(); } try { nodeNamespaceIndex = Integer.parseInt(channelConfig.get(NODE_NAMESPACE_INDEX).toString()); } catch (final Exception e) { fail(record, message.errorRetrievingNodeNamespace()); return Optional.empty(); } final DataType dataType = (DataType) channelConfig.get(CHANNEL_VALUE_TYPE.value()); if (dataType == null) { fail(record, message.errorRetrievingValueType()); return Optional.empty(); } return Optional.of(new OpcUaRequestInfo(dataType, nodeNamespaceIndex, nodeId)); }
Source:
<code>protected Object doTransform(Message<?> message) { MessageHeaders headers = message.getHeaders(); boolean removeHeaders = false; ResolvableType valueType = obtainResolvableTypeFromHeadersIfAny(headers); if (valueType != null) { removeHeaders = true; } else { valueType = this.targetType; } Object result; try { result = this.jsonObjectMapper.fromJson(message.getPayload(), valueType); } catch (IOException e) { throw new UncheckedIOException(e); } if (removeHeaders) { return getMessageBuilderFactory() .withPayload(result) .copyHeaders(headers) <START> .removeHeaders(JsonHeaders.HEADERS.toArray(new String[3])) <END> .build(); } else { return result; } }</code><technical_language>I thought [0] is preferred now, new, I know, changing. <LINK_0></technical_language>

Target:
protected Object doTransform(Message<?> message) { MessageHeaders headers = message.getHeaders(); boolean removeHeaders = false; ResolvableType valueType = obtainResolvableTypeFromHeadersIfAny(headers); if (valueType != null) { removeHeaders = true; } else { valueType = this.targetType; } Object result; try { result = this.jsonObjectMapper.fromJson(message.getPayload(), valueType); } catch (IOException e) { throw new UncheckedIOException(e); } if (removeHeaders) { return getMessageBuilderFactory() .withPayload(result) .copyHeaders(headers) .removeHeaders(JsonHeaders.HEADERS.toArray(new String[0])) .build(); } else { return result; } }
Source:
<code>public List<Permission> getPermissions(Role role) throws DataAccessException { List<Permission> rolePermissions = new ArrayList<Permission>(); String getRolePermissionsQuery = String.format("SELECT `permissionid` FROM `rolepermission` WHERE `roleid`=%d", role.id.longValue()); Connection roleConnection = DatabaseServiceProvider.provide().getNamedConnection(DatabaseType.DatabaseTypeRole.toString()); try { roleConnection.connect(); roleConnection.executeQuery(getRolePermissionsQuery); <START> while (roleConnection.fetchNextRow()) { <END> Long id = roleConnection.getCurrentRowLong("permissionid"); Permission p = PermissionServiceProvider.provide().getPermission(id); if (p != null) { rolePermissions.add(p); } } } finally { if (roleConnection != null) { roleConnection.disconnect(); } } return rolePermissions; }</code><technical_language>This line stay</technical_language>

Target:
public List<Permission> getPermissions(Role role) throws DataAccessException { List<Permission> rolePermissions = new ArrayList<Permission>(); String getRolePermissionsQuery = String.format("SELECT `permissionid` FROM `rolepermission` WHERE `roleid`=%d", role.id.longValue()); Connection roleConnection = DatabaseServiceProvider.provide().getNamedConnection(DatabaseType.DatabaseTypeRole.toString()); try { roleConnection.connect(); roleConnection.executeQuery(getRolePermissionsQuery); while (roleConnection.fetchNextRow()) { Permission p = new Permission(); p.id = roleConnection.getCurrentRowLong("permissionid"); rolePermissions.add(p); } } finally { if (roleConnection != null) { roleConnection.disconnect(); } } return rolePermissions; }
Source:
<code>protected void executeVmCommand() { this.setVmName(vmStaticDao.get(getParameters().getVmId()).getName()); VmNic iface = vmNicDao.get(getParameters().getInterfaceId()); if (iface != null) { interfaceName = iface.getName(); String interType = VmInterfaceType.forValue(iface.getType()).getDescription(); if (interType != null) { addCustomValue("InterfaceType", interType); } externalNetworkManagerFactory.create(iface).deallocateIfExternal(); } TransactionSupport.executeInNewTransaction(() -> { vmStaticDao.incrementDbGeneration(getParameters().getVmId()); vmNicDao.remove(getParameters().getInterfaceId()); vmNetworkStatisticsDao.remove(getParameters().getInterfaceId()); vmDeviceDao.remove(new VmDeviceId(getParameters().getInterfaceId(), getParameters().getVmId())); if (iface != null) { <START> getMacPool().freeMac(iface.getMacAddress()); <END> } setSucceeded(true); return null; }); }</code><technical_language>done if vm is running stateless snapshot. it? code in updateVmInterfaceCommand applied here</technical_language>

Target:
protected void executeVmCommand() { this.setVmName(vmStaticDao.get(getParameters().getVmId()).getName()); VmNic iface = vmNicDao.get(getParameters().getInterfaceId()); if (iface != null) { interfaceName = iface.getName(); String interType = VmInterfaceType.forValue(iface.getType()).getDescription(); if (interType != null) { addCustomValue("InterfaceType", interType); } externalNetworkManagerFactory.create(iface).deallocateIfExternal(); } TransactionSupport.executeInNewTransaction(() -> { vmStaticDao.incrementDbGeneration(getParameters().getVmId()); vmNicDao.remove(getParameters().getInterfaceId()); vmNetworkStatisticsDao.remove(getParameters().getInterfaceId()); vmDeviceDao.remove(new VmDeviceId(getParameters().getInterfaceId(), getParameters().getVmId())); if (iface != null) { String macOfNicBeingRemoved = iface.getMacAddress(); if (macCanBeReleased(macOfNicBeingRemoved)) { getMacPool().freeMac(macOfNicBeingRemoved); } } setSucceeded(true); return null; }); }
Source:
<code>public void testResolveFromWorkDirYamlAndYml() throws Exception { helper.givenYamlClientConfigFileInWorkDir("cluster-yaml-workdir"); <START> helper.givenYmlClientConfigFileInWorkDir("cluster-yaml-workdir"); <END> ClientConfig config = new YamlClientConfigBuilder().build(); assertEquals("cluster-yaml-workdir", config.getInstanceName()); }</code><technical_language>this cluster-yml-workdir</technical_language>

Target:
public void testResolveFromWorkDirYamlAndYml() throws Exception { helper.givenYamlClientConfigFileInWorkDir("cluster-yaml-workdir"); helper.givenYmlClientConfigFileInWorkDir("cluster-yml-workdir"); ClientConfig config = new YamlClientConfigBuilder().build(); assertEquals("cluster-yaml-workdir", config.getInstanceName()); }
Source:
<code>public void tearDown() throws Exception { <START> FileUtils.deleteDirectory(workspacesRootFile); <END> }</code><technical_language>IoUtil.deleteRecursive</technical_language>

Target:
public void tearDown() throws Exception { IoUtil.deleteRecursive(workspacesRootFile); }
Source:
<code>private static String getDetailedLog(String msg, int depth) { if (!shouldShowLogs()) { return msg; } Thread current = Thread.currentThread(); final StackTraceElement trace = current.getStackTrace()[depth]; final String filename = trace.getFileName(); return "[" + current.getName() + "][" + "(" + filename.substring(0, filename.length() - DOT_CLASS) + ".java:" <START> + trace.getLineNumber() + ")." + trace.getMethodName() + "] " + msg; <END> }</code><technical_language>move line number method name around? is this involved in linking</technical_language>

Target:
private static String getDetailedLog(String msg, int depth) { if (!shouldShowLogs()) { return msg; } Thread currentThread = Thread.currentThread(); final StackTraceElement trace = currentThread.getStackTrace()[depth]; final String filename = trace.getFileName(); final String linkableSourcePosition = String.format("(%s.java:%d)", filename.substring(0, filename.length() - DOT_CLASS), trace.getLineNumber()); final String logPrefix = String.format("[%s][%s.%s] ", currentThread.getName(), linkableSourcePosition, trace.getMethodName()); return logPrefix + msg; }
Source:
<code>private boolean shouldFreezeOrThawVm() { <START> Predicate<List<DiskImage>> hasManagedBlockDisks = disks -> !DisksFilter.filterManagedBlockStorageDisks(disks).isEmpty(); <END> return isLiveSnapshotApplicable() && (isCinderDisksExist() || hasManagedBlockDisks.test(getDisksList())) && getParameters().getParentCommand() != ActionType.LiveMigrateDisk; }</code><technical_language>I a simple method, isCinderDisksExist more readable</technical_language>

Target:
private boolean shouldFreezeOrThawVm() { return isLiveSnapshotApplicable() && (diskOfTypeExists(DiskStorageType.CINDER) || diskOfTypeExists(DiskStorageType.MANAGED_BLOCK_STORAGE)) && getParameters().getParentCommand() != ActionType.LiveMigrateDisk; }
Source:
<code>static <T> CheckedConsumer<T> decorateCheckedConsumer(AdaptiveBulkhead bulkhead, CheckedConsumer<T> consumer) { return t -> { long start = 0; boolean isFailed=false; bulkhead.acquirePermission(); try { start = Instant.now().toEpochMilli(); consumer.accept(t); } catch (Exception e) { isFailed=true; bulkhead.onError( start,TimeUnit.MILLISECONDS, e); throw e; } finally { if (start != 0 && !isFailed) { <START> bulkhead.onSuccess(start, TimeUnit.MILLISECONDS); <END> } } }; }</code><technical_language>do need onSuccess in finally part? total duration instead of start? long durationInNanos = System.nanoTime() - start;</technical_language>

Target:
static <T> CheckedConsumer<T> decorateCheckedConsumer(AdaptiveBulkhead bulkhead, CheckedConsumer<T> consumer) { return t -> { long start = 0; boolean isFailed=false; bulkhead.acquirePermission(); try { start = System.currentTimeMillis(); consumer.accept(t); } catch (Exception e) { isFailed=true; bulkhead.onError(System.nanoTime() - start, TimeUnit.NANOSECONDS, e); throw e; } finally { if (start != 0 && !isFailed) { bulkhead.onSuccess(System.nanoTime() - start, TimeUnit.NANOSECONDS); } } }; }
Source:
<code>private void getApprovalNames() throws OrmException { optionList = new ArrayList<CmdOption>(); for (ApprovalType type : approvalTypes.getApprovalTypes()) { String usage = ""; final ApprovalCategory category = type.getCategory(); <START> if (category.getFunctionName().equals("MaxWithBlock")) { <END> usage = "Score for " + category.getName() + "\n"; for (ApprovalCategoryValue v : type.getValues()) { usage += String.format("%4d", v.getValue()) + " - " + v.getName() + "\n"; } } optionList.add( new CmdOption( "--" + category.getName().toLowerCase().replace(' ', '-'), usage, category.getId().get(), type.getMin().getValue(), type.getMax().getValue(), category.getName())); } }</code><technical_language>This test is necessary removed. ApprovalCategory objects looping web, user select values from</technical_language>

Target:
private void getApprovalNames() throws OrmException { optionList = new ArrayList<CmdOption>(); for (ApprovalType type : approvalTypes.getApprovalTypes()) { String usage = ""; final ApprovalCategory category = type.getCategory(); usage = "Score for " + category.getName() + "\n"; for (ApprovalCategoryValue v : type.getValues()) { usage += String.format("%4d", v.getValue()) + " - " + v.getName() + "\n"; } optionList.add( new CmdOption( "--" + category.getName().toLowerCase().replace(' ', '-'), usage, category.getId().get(), type.getMin().getValue(), type.getMax().getValue(), category.getName())); } }
Source:
<code>@BeforeEach void init() throws IOException { credentialsFile = File.createTempFile("zipkin-server-security", ".properties"); Properties props = new Properties(); props.put(USERNAME_PROP, "foo"); props.put(PASSWORD_PROP, "bar"); try (FileOutputStream os = new FileOutputStream(credentialsFile)) { props.store(os, ""); } TestPropertyValues.of( "spring.config.name=zipkin-server", "zipkin.storage.type:elasticsearch", "zipkin.storage.elasticsearch.hosts:https://localhost:" + server.httpsPort(), "zipkin.storage.elasticsearch.credentials-file=" + credentialsFile.getAbsolutePath(), <START> "zipkin.storage.elasticsearch.credentials-refresh-interval=3000", <END> "zipkin.storage.elasticsearch.ssl.key-store=classpath:keystore.jks", "zipkin.storage.elasticsearch.ssl.key-store-password=password", "zipkin.storage.elasticsearch.ssl.trust-store=classpath:keystore.jks", "zipkin.storage.elasticsearch.ssl.trust-store-password=password") .applyTo(context); Access.registerElasticsearch(context); context.refresh(); storage = context.getBean(ElasticsearchStorage.class); }</code><technical_language>suggestion "zipkin.storage.elasticsearch.credentials-refresh-interval=3",</technical_language>

Target:
@BeforeEach void init() throws IOException { credentialsFile = pathOfResource("es-credentials"); TestPropertyValues.of( "spring.config.name=zipkin-server", "zipkin.storage.type:elasticsearch", "zipkin.storage.elasticsearch.hosts:https://localhost:" + server.httpsPort(), "zipkin.storage.elasticsearch.credentials-file=" + credentialsFile, "zipkin.storage.elasticsearch.credentials-refresh-interval=3", "zipkin.storage.elasticsearch.ssl.key-store=classpath:keystore.jks", "zipkin.storage.elasticsearch.ssl.key-store-password=password", "zipkin.storage.elasticsearch.ssl.trust-store=classpath:keystore.jks", "zipkin.storage.elasticsearch.ssl.trust-store-password=password") .applyTo(context); Access.registerElasticsearch(context); context.refresh(); storage = context.getBean(ElasticsearchStorage.class); }
Source:
<code>private void extractFromSource(SearchHit hit) { Map<String, Object> map = hit.getSourceAsMap(); <START> TreeMap<String, Object> fieldsMap = new TreeMap<>(new Comparator<String>() <END> { @Override public int compare(String key1, String key2) { int length1 = key1.split("\\.").length; int length2 = key2.split("\\.").length; if (length1 == length2) { return key1.compareTo(key2); } return length2 - length1; } }); for (Map.Entry<String, Object> entry : map.entrySet()) { fieldsMap.put(entry.getKey(), entry.getValue()); } processFields(fieldsMap); }</code><technical_language>java TreeMap<String, Object> fieldsMap = new TreeMap<>((left, right) -> { int leftLength = left.split("\\.").length; int rightLength = right.split("\\.").length; if (leftLength == rightLength) { return left.compareTo(right); } return rightLength - leftLength; });</technical_language>

Target:
private void extractFromSource(SearchHit hit) { List<Field> fields = new ArrayList<>(); for (Map.Entry<String, Object> entry : hit.getSourceAsMap().entrySet()) { fields.add(new Field(entry.getKey(), entry.getValue())); } Collections.sort(fields, Comparator.comparing(Field::getName)); for (Map.Entry<String, Object> entry : unflatten(fields).entrySet()) { setFieldIfExists(entry.getKey(), entry.getValue()); } }
Source:
<code>void register() { checkLocked(); try { owner.mbeanServer.registerMBean(this, objectName); } catch (Exception e) { <START> throw new RuntimeException("Failed to reregister bean " + mbeanName, e); <END> } }</code><technical_language>a typo "reregister -> register"</technical_language>

Target:
void register() { checkLocked(); try { owner.mbeanServer.registerMBean(this, objectName); } catch (Exception e) { throw new KafkaException("Failed to register bean " + mbeanName, e); } }
Source:
<code>public void testPutFile() throws IOException { String envVar; <START> envVar = getVar("pf_start_size"); <END> long pf_start_size = (envVar != null ? new Long(envVar) : 1024 * 1024 * 1L); envVar = getVar("pf_multiplier"); int pf_multiplier = (envVar != null ? new Integer(envVar) : 2); envVar = getVar("pf_count"); int pf_count = (envVar != null ? new Integer(envVar) : 3); envVar = getVar("pf_repeat"); int pf_repeat = (envVar != null ? new Integer(envVar) : 1); if (logger.isInfoEnabled()) { logger.info("testPutFile: pf_start_size="+pf_start_size+", pf_multiplier="+pf_multiplier +", pf_count="+pf_count+", pf_repeat="+pf_repeat); } long testContentSizeInBytes = pf_start_size; for (int i = 0; i < pf_count; i++) { File testFile = createTestFile(testContentSizeInBytes); for (int j = 0; j < pf_repeat; j++) { testPutFileImpl(testFile, true); testPutFileImpl(testFile, false); } if (cleanup) { testFile.delete(); } testContentSizeInBytes = testContentSizeInBytes * pf_multiplier; } }</code><technical_language>This easier read if getVar method generics default argument</technical_language>

Target:
public void testPutFile() throws IOException { Long pf_start_size = getVar("pf_start_size", new Long(1024 * 1024 * 1L), Long.class); Integer pf_multiplier = getVar("pf_multiplier", new Integer(2), Integer.class); Integer pf_count = getVar("pf_count", new Integer(3), Integer.class); Integer pf_repeat = getVar("pf_repeat", new Integer(1), Integer.class); if (logger.isInfoEnabled()) { logger.info("testPutFile: pf_start_size="+pf_start_size+", pf_multiplier="+pf_multiplier +", pf_count="+pf_count+", pf_repeat="+pf_repeat); } long testContentSizeInBytes = pf_start_size; for (int i = 0; i < pf_count; i++) { File testFile = createTestFile(testContentSizeInBytes); for (int j = 0; j < pf_repeat; j++) { testPutFileImpl(testFile, true); testPutFileImpl(testFile, false); } if (cleanup) { testFile.delete(); } testContentSizeInBytes = testContentSizeInBytes * pf_multiplier; } }
Source:
<code>public void performSearchWithDoiEmptyCitedByMode() throws FetcherException { BibEntry doiEmptyCitedBy = new BibEntry().withField(StandardField.DOI, "10.1.1.19.4684"); <START> assertTrue(openCitationFetcher.searchCitedBy(doiEmptyCitedBy).isEmpty()); <END> }</code><technical_language>assertEquals(Collections.emptyList(), openCitationFetcher.searchCitedBy(doiEmptyCitedBy))</technical_language>

Target:
public void performSearchWithDoiEmptyCitedByMode() throws FetcherException { BibEntry doiEmptyCitedBy = new BibEntry().withField(StandardField.DOI, "10.1.1.19.4684"); assertEquals(Collections.emptyList(), openCitationFetcher.searchCitedBy(doiEmptyCitedBy)); }
Source:
<code>public boolean validate(String name, ApplicationType appType) { Assert.hasText(name, "name must not be null or empty"); Assert.notNull(appType, "ApplicationType must not be null"); boolean result = false; AppRegistration registration = appRegistry.find(name, appType); if (registration != null) { Resource resource = appRegistry.getAppResource(registration); try { if ((resource instanceof DockerResource)) { result = validateDockerResource(dockerValidatorProperties, (DockerResource) resource); } else { new BootClassLoaderFactory(resolveAsArchive(appRegistry.getAppResource(registration)), null) .createClassLoader(); result = true; } } <START> catch (NullPointerException nex) { <END> logger.info(String.format("The app %s was marked invalid because the URL specified does not resolve to a resource", name)); } catch (Exception ex) { logger.info(String.format("The app %s was marked invalid because: ", name), ex); } } return result; }</code><technical_language>avoid throwing a NPE in place</technical_language>

Target:
public boolean validate(String name, ApplicationType appType) { Assert.hasText(name, "name must not be null or empty"); Assert.notNull(appType, "ApplicationType must not be null"); boolean result = false; AppRegistration registration = appRegistry.find(name, appType); if (registration != null) { Resource resource = appRegistry.getAppResource(registration); try { if ((resource instanceof DockerResource)) { result = validateDockerResource(dockerValidatorProperties, (DockerResource) resource); } else { new BootClassLoaderFactory(resolveAsArchive(resource), null) .createClassLoader(); result = true; } } catch (Exception ex) { logger.info(String.format("The app %s was marked invalid because: ", name), ex); } } return result; }
Source:
<code><START> public synchronized void visit(MetricsVisitor visitor) { <END> visitor.listGauge(this); }</code><technical_language>Do instance methods need synchronized? some "concurrent" data structure instead? main I worried is this visit method do arbitrary logic possibly hold lock for uncontrolled period of time</technical_language>

Target:
public void visit(MetricsVisitor visitor) { visitor.listGauge(this); }
Source:
<code>private static boolean chipsetMatchesEmulatedMachine(ChipsetType chipsetType, String emulatedMachine) { if (chipsetType == ChipsetType.I440FX) { return true; } <START> return chipsetType == ChipsetType.fromMachineType(emulatedMachine); <END> }</code><technical_language>shorten a single line: return chipsetType == ChipsetType.I440FX || chipsetType == ChipsetType.fromMachineType(emulatedMachine); a big deal side</technical_language>

Target:
private static boolean chipsetMatchesEmulatedMachine(ChipsetType chipsetType, String emulatedMachine) { return chipsetType == ChipsetType.I440FX || chipsetType == ChipsetType.fromMachineType(emulatedMachine); }
Source:
<code>public int execute() { try { Task<?> rootTask = work.getRootTask(); if (rootTask != null) { rootTask.setChildTasks(null); } work.setRootTask(this); this.parentTasks = null; int status = 0; if (work.isIncrementalLoad()) { status = executeIncrementalLoad(); if (status == 0 && !work.incrementalLoadTasksBuilder().hasMoreWork()) { writeLoadCompleteAck(work.dumpDirectory); } } else { status = executeBootStrapLoad(); <START> if (status == 0 && !work.hasBootstrapLoadTasks()) { <END> writeLoadCompleteAck(work.dumpDirectory); } } return status; } catch (SemanticException e) { LOG.error("failed", e); setException(e); return ErrorMsg.getErrorMsg(e.getMessage()).getErrorCode(); } }</code><technical_language>This common code .</technical_language>

Target:
public int execute() { Task<?> rootTask = work.getRootTask(); if (rootTask != null) { rootTask.setChildTasks(null); } work.setRootTask(this); this.parentTasks = null; if (work.isIncrementalLoad()) { return executeIncrementalLoad(); } else { return executeBootStrapLoad(); } }
Source:
<code>private AuthenticationResult tryRT() throws AuthenticationException { CacheEvent cacheEvent = new CacheEvent(EventStrings.TOKEN_CACHE_LOOKUP); cacheEvent.setTokenType(EventStrings.TOKEN_TYPE_RT); cacheEvent.setRequestId(mAuthRequest.getTelemetryRequestId()); <START> Telemetry.getInstance().startEvent(mAuthRequest.getTelemetryRequestId(), EventStrings.TOKEN_CACHE_LOOKUP); <END> final TokenCacheItem regularRTItem = mTokenCacheAccessor.getRegularRefreshTokenCacheItem(mAuthRequest.getResource(), mAuthRequest.getClientId(), mAuthRequest.getUserFromRequest()); if (regularRTItem == null) { Telemetry.getInstance().stopEvent(mAuthRequest.getTelemetryRequestId(), cacheEvent, EventStrings.TOKEN_CACHE_LOOKUP); Logger.v(TAG, "Regular token cache entry does not exist, try with MRRT."); return tryMRRT(); } cacheEvent.setTokenTypeRT(true); if (regularRTItem.getIsMultiResourceRefreshToken() || isMRRTEntryExisted()) { final String statusMessage = regularRTItem.getIsMultiResourceRefreshToken() ? "Found RT and it's also a MRRT, retry with MRRT" : "RT is found and there is a MRRT entry existed, try with MRRT"; cacheEvent.setTokenTypeMRRT(true); Telemetry.getInstance().stopEvent(mAuthRequest.getTelemetryRequestId(), cacheEvent, EventStrings.TOKEN_CACHE_LOOKUP); Logger.v(TAG, statusMessage); return tryMRRT(); } Telemetry.getInstance().stopEvent(mAuthRequest.getTelemetryRequestId(), cacheEvent, EventStrings.TOKEN_CACHE_LOOKUP); Logger.v(TAG, "Send request to use regular RT for new AT."); return acquireTokenWithCachedItem(regularRTItem); }</code><technical_language>this moved tokenCacheAccessor? #Closed</technical_language>

Target:
private AuthenticationResult tryRT() throws AuthenticationException { final TokenCacheItem regularRTItem = mTokenCacheAccessor.getRegularRefreshTokenCacheItem(mAuthRequest.getResource(), mAuthRequest.getClientId(), mAuthRequest.getUserFromRequest()); if (regularRTItem == null) { Logger.v(TAG, "Regular token cache entry does not exist, try with MRRT."); return tryMRRT(); } if (regularRTItem.getIsMultiResourceRefreshToken() || isMRRTEntryExisted()) { final String statusMessage = regularRTItem.getIsMultiResourceRefreshToken() ? "Found RT and it's also a MRRT, retry with MRRT" : "RT is found and there is a MRRT entry existed, try with MRRT"; Logger.v(TAG, statusMessage); return tryMRRT(); } Logger.v(TAG, "Send request to use regular RT for new AT."); return acquireTokenWithCachedItem(regularRTItem); }
Source:
<code>public void testProprietaryAPI() { final CreateContent invoke = new CreateContent().invoke(); final ApiClient webClient = getWebClient(true, false); WorkflowsApi client = new WorkflowsApi(webClient); final List<io.swagger.client.model.Workflow> services = client.allPublishedWorkflows(null, null, null, null, null, true); final List<io.swagger.client.model.Workflow> workflows = client.allPublishedWorkflows(null, null, null, null, null, false); Gson gson = new Gson(); String serviceString = gson.toJson(services); <START> System.out.println(serviceString); <END> assertTrue(workflows.size() >= 2 && workflows.stream().noneMatch(workflow -> workflow.getDescriptorType().getValue().equalsIgnoreCase(DescriptorLanguage.SERVICE.toString()))); assertTrue(services.size() >= 1 && services.stream().allMatch(workflow -> workflow.getDescriptorType().getValue().equalsIgnoreCase(DescriptorLanguage.SERVICE.toString()))); client.starEntry(invoke.getServiceID(), new StarRequest().star(true)); client.updateLabels(invoke.getServiceID(), "foo,batman,chicken", ""); final io.swagger.client.model.Workflow workflow = client.getWorkflow(invoke.getServiceID(), ""); assertFalse(workflow.getStarredUsers().isEmpty()); assertTrue(workflow.getLabels().stream().anyMatch(label -> "batman".equals(label.getValue()))); }</code><technical_language>Is this intended</technical_language>

Target:
public void testProprietaryAPI() { final CreateContent invoke = new CreateContent().invoke(); final ApiClient webClient = getWebClient(true, false); WorkflowsApi client = new WorkflowsApi(webClient); final List<io.swagger.client.model.Workflow> services = client.allPublishedWorkflows(null, null, null, null, null, true); final List<io.swagger.client.model.Workflow> workflows = client.allPublishedWorkflows(null, null, null, null, null, false); assertTrue(workflows.size() >= 2 && workflows.stream().noneMatch(workflow -> workflow.getDescriptorType().getValue().equalsIgnoreCase(DescriptorLanguage.SERVICE.toString()))); assertTrue(services.size() >= 1 && services.stream().allMatch(workflow -> workflow.getDescriptorType().getValue().equalsIgnoreCase(DescriptorLanguage.SERVICE.toString()))); client.starEntry(invoke.getServiceID(), new StarRequest().star(true)); client.updateLabels(invoke.getServiceID(), "foo,batman,chicken", ""); final io.swagger.client.model.Workflow workflow = client.getWorkflow(invoke.getServiceID(), ""); assertFalse(workflow.getStarredUsers().isEmpty()); assertTrue(workflow.getLabels().stream().anyMatch(label -> "batman".equals(label.getValue()))); }
Source:
<code>private void addFilterToList(final ContextMenuAdapter adapter, final List<PoiUIFilter> list, final PoiUIFilter f) { list.add(f); ContextMenuItem.ItemBuilder builder = new ContextMenuItem.ItemBuilder(); builder.setListener(new ContextMenuAdapter.ItemClickListener() { @Override public boolean onContextMenuClick(ArrayAdapter<ContextMenuItem> adapter, int itemId, int position, boolean isChecked) { <START> if (isChecked) <END> getApplication().getPoiFilters().addSelectedPoiFilter(f); else getApplication().getPoiFilters().removeSelectedPoiFilter(f); return true; } }); builder.setTitle(f.getName()); builder.setSelected(getApplication().getPoiFilters().isPoiFilterSelected(f)); if (RenderingIcons.containsBigIcon(f.getIconId())) { builder.setIcon(RenderingIcons.getBigIconResourceId(f.getIconId())); } else { builder.setIcon(R.drawable.mx_user_defined); } builder.setColor(R.color.osmand_orange); adapter.addItem(builder.createItem()); }</code><technical_language>put braces for branches</technical_language>

Target:
private void addFilterToList(final ContextMenuAdapter adapter, final List<PoiUIFilter> list, final PoiUIFilter f) { list.add(f); ContextMenuItem.ItemBuilder builder = new ContextMenuItem.ItemBuilder(); builder.setListener(new ContextMenuAdapter.ItemClickListener() { @Override public boolean onContextMenuClick(ArrayAdapter<ContextMenuItem> adapter, int itemId, int position, boolean isChecked) { if (isChecked) { getApplication().getPoiFilters().addSelectedPoiFilter(f); } else { getApplication().getPoiFilters().removeSelectedPoiFilter(f); } return true; } }); builder.setTitle(f.getName()); builder.setSelected(getApplication().getPoiFilters().isPoiFilterSelected(f)); if (RenderingIcons.containsBigIcon(f.getIconId())) { builder.setIcon(RenderingIcons.getBigIconResourceId(f.getIconId())); } else { builder.setIcon(R.drawable.mx_user_defined); } builder.setColor(R.color.osmand_orange); adapter.addItem(builder.createItem()); }
Source:
<code>private boolean hasCrashedGSPP( TreeNode<?,?> treeNode, PageCursor cursor ) throws IOException { boolean isTreeNode; int keyCount; do { isTreeNode = TreeNode.nodeType( cursor ) == TreeNode.NODE_TYPE_TREE_NODE; keyCount = treeNode.keyCount( cursor ); } while ( cursor.shouldRetry() ); if ( !isTreeNode ) { return false; } boolean hasCrashed; do { hasCrashed = hasCrashedGSPP( cursor, TreeNode.BYTE_POS_NEWGEN ) || hasCrashedGSPP( cursor, TreeNode.BYTE_POS_LEFTSIBLING ) || hasCrashedGSPP( cursor, TreeNode.BYTE_POS_RIGHTSIBLING ); if ( !hasCrashed && TreeNode.isInternal( cursor ) ) { for ( int i = 0; i <= keyCount && i <= maxKeyCount && !hasCrashed; i++ ) { <START> hasCrashed |= hasCrashedGSPP( cursor, treeNode.childOffset( i ) ); <END> } } } while ( cursor.shouldRetry() ); return hasCrashed; }</code><technical_language>line hasCrashed |= hasCrashedGSPP( cursor, treeNode.childOffset( i ) ); changed hasCrashed = hasCrashedGSPP( cursor, treeNode.childOffset( i ) ); continue while !hasCrashed</technical_language>

Target:
private boolean hasCrashedGSPP( TreeNode<?,?> treeNode, PageCursor cursor ) throws IOException { boolean isTreeNode; int keyCount; do { isTreeNode = TreeNode.nodeType( cursor ) == TreeNode.NODE_TYPE_TREE_NODE; keyCount = treeNode.keyCount( cursor ); } while ( cursor.shouldRetry() ); PageCursorUtil.checkOutOfBounds( cursor ); if ( !isTreeNode ) { return false; } boolean hasCrashed; do { hasCrashed = hasCrashedGSPP( cursor, TreeNode.BYTE_POS_NEWGEN ) || hasCrashedGSPP( cursor, TreeNode.BYTE_POS_LEFTSIBLING ) || hasCrashedGSPP( cursor, TreeNode.BYTE_POS_RIGHTSIBLING ); if ( !hasCrashed && TreeNode.isInternal( cursor ) ) { for ( int i = 0; i <= keyCount && i <= internalMaxKeyCount && !hasCrashed; i++ ) { hasCrashed = hasCrashedGSPP( cursor, treeNode.childOffset( i ) ); } } } while ( cursor.shouldRetry() ); PageCursorUtil.checkOutOfBounds( cursor ); return hasCrashed; }
Source:
<code>public Collection<Session> values() { removeClosedSessions(); <START> return ImmutableSet.copyOf(sessions); <END> }</code><technical_language>Set#copyOf</technical_language>

Target:
public Collection<Session> values() { return sessions.stream().filter(Session::isOpen).collect(Collectors.toSet()); }
Source:
<code>private X509CRL loadRevokedCertificates(CertificateFactory cf, String crlFile) throws IOException, CRLException { X509CRL crl = null; try { FileInputStream fis = new FileInputStream(crlFile); crl = (X509CRL) cf.generateCRL(fis); <START> fis.close(); <END> } catch (FileNotFoundException ex) { } return crl; }</code><technical_language>this close in a finally block</technical_language>

Target:
private X509CRL loadRevokedCertificates(CertificateFactory cf, String crlFile) throws IOException, CRLException { X509CRL crl = null; FileInputStream fis = null; try { new FileInputStream(crlFile); crl = (X509CRL) cf.generateCRL(fis); fis.close(); } catch (FileNotFoundException ex) { } finally { if ( fis != null ) { fis.close(); } } return crl; }
Source:
<code>void proceedVmReportedOnOtherHost() { switch(vdsmVm.getVmDynamic().getStatus()) { case MigratingTo: if (dbVm.getRunOnVds() == null) { log.info("VM '{}' is found as migrating on VDS '{}'({}) ", vdsmVm.getVmDynamic().getId(), vdsManager.getVdsId(), vdsManager.getVdsName()); dbVm.updateRuntimeData(vdsmVm.getVmDynamic(), vdsManager.getVdsId()); saveDynamic(dbVm); if (!vdsManager.isInitialized()) { resourceManager.removeVmFromDownVms(vdsManager.getVdsId(), vdsmVm.getVmDynamic().getId()); } } else { log.info("VM '{}' is migrating to VDS '{}'({}) ignoring it in the refresh until migration is done", vdsmVm.getVmDynamic().getId(), vdsManager.getVdsId(), vdsManager.getVdsName()); } return; case MigratingFrom: return; case Paused: if (vdsmVm.getVmDynamic().getPauseStatus() == VmPauseStatus.POSTCOPY) { return; } break; case WaitForLaunch: if (dbVm.getStatus() == VMStatus.Unknown) { return; } break; default: } if (isVmMigratingToThisVds() && vdsmVm.getVmDynamic().getStatus().isRunning()) { succeededToRun = true; } <START> if (vdsmVm.getVmDynamic().getStatus().isUpOrPaused()) { <END> succeededToRun = true; } dbVm.updateRuntimeData(vdsmVm.getVmDynamic(), vdsManager.getVdsId()); saveDynamic(dbVm); updateStatistics(); if (!vdsManager.isInitialized()) { resourceManager.removeVmFromDownVms(vdsManager.getVdsId(), vdsmVm.getVmDynamic().getId()); } }</code><technical_language>is a trade-off for - VdsEventListener#updateSlaPolicies. work if change #245 isRunningOrPaused instead</technical_language>

Target:
void proceedVmReportedOnOtherHost() { switch(vdsmVm.getVmDynamic().getStatus()) { case MigratingTo: if (dbVm.getRunOnVds() == null) { log.info("VM '{}' is found as migrating on VDS '{}'({}) ", vdsmVm.getVmDynamic().getId(), vdsManager.getVdsId(), vdsManager.getVdsName()); dbVm.updateRuntimeData(vdsmVm.getVmDynamic(), vdsManager.getVdsId()); saveDynamic(dbVm); if (!vdsManager.isInitialized()) { resourceManager.removeVmFromDownVms(vdsManager.getVdsId(), vdsmVm.getVmDynamic().getId()); } } else { log.info("VM '{}' is migrating to VDS '{}'({}) ignoring it in the refresh until migration is done", vdsmVm.getVmDynamic().getId(), vdsManager.getVdsId(), vdsManager.getVdsName()); } return; case MigratingFrom: return; case Paused: if (vdsmVm.getVmDynamic().getPauseStatus() == VmPauseStatus.POSTCOPY) { return; } break; case WaitForLaunch: if (dbVm.getStatus() == VMStatus.Unknown) { return; } break; default: } if (isVmMigratingToThisVds() && vdsmVm.getVmDynamic().getStatus().isRunningOrPaused()) { succeededToRun = true; } if (vdsmVm.getVmDynamic().getStatus() == VMStatus.Up) { succeededToRun = true; } dbVm.updateRuntimeData(vdsmVm.getVmDynamic(), vdsManager.getVdsId()); saveDynamic(dbVm); updateStatistics(); if (!vdsManager.isInitialized()) { resourceManager.removeVmFromDownVms(vdsManager.getVdsId(), vdsmVm.getVmDynamic().getId()); } }
Source:
<code>private void postPushUnregister(BroadcastReceiver pushReceiver, final ClientManager clientMgr, final boolean showLoginPage, final String refreshToken, final String loginServer, final Account account, Activity frontActivity) { if (numPostPushUnregisterCalls <= 1) { try { context.unregisterReceiver(pushReceiver); } catch (Exception e) { SalesforceSDKLogger.e(TAG, "Exception occurred while un-registering", e); } removeAccount(clientMgr, showLoginPage, refreshToken, loginServer, account, frontActivity); } else { <START> numPostPushUnregisterCalls = 0; <END> } }</code><technical_language>work in cases. For instance: * if broadcast receiver numPostPushUnregisterCalls++, postPushUnregister() else sets numPostPushUnregisterCalls 0. point, background thread sleeping, numPostPushUnregisterCalls++, postPushUnregister(), if (numPostPushUnregisterCalls <= 1) entered a time then. * if broadcast receiver numPostPushUnregisterCalls++, background thread numPostPushUnregisterCalls++, postPushUnregister() runs. In case if (numPostPushUnregisterCalls <= 1) entered</technical_language>

Target:
private void postPushUnregister(BroadcastReceiver pushReceiver, final ClientManager clientMgr, final boolean showLoginPage, final String refreshToken, final String loginServer, final Account account, Activity frontActivity) { try { context.unregisterReceiver(pushReceiver); } catch (Exception e) { SalesforceSDKLogger.e(TAG, "Exception occurred while un-registering", e); } removeAccount(clientMgr, showLoginPage, refreshToken, loginServer, account, frontActivity); }
Source:
<code>public int getOffset() { int offset = row; <START> ++row; <END> return offset; }</code><technical_language>weird increment row getOffset. this class inheriting Offset ReadableOffset</technical_language>

Target:
public int getOffset() { int offset = row; row++; return offset; }
Source:
<code>public ExtendedQueryResult<T> maxResults(int max) { lastPaginatedQuery = null; <START> if (!context.getRepositoryMethod().isQuery()) { <END> maxResults = max; pageSize = max; } else { context.addJpaQueryPostProcessor(new MaxResultPostProcessor(max)); } return this; }</code><technical_language>negative logic</technical_language>

Target:
public ExtendedQueryResult<T> maxResults(int max) { lastPaginatedQuery = null; if (context.getRepositoryMethod().isQuery()) { context.addJpaQueryPostProcessor(new MaxResultPostProcessor(max)); } else { maxResults = max; pageSize = max; } return this; }
Source:
<code>protected Object exchange(URI uri, HttpMethod httpMethod, HttpEntity<?> httpRequest, Object expectedResponseType) { SettableListenableFuture<Object> replyMessageFuture = new SettableListenableFuture<>(); ListenableFuture<? extends ResponseEntity<?>> responseFuture; if (expectedResponseType instanceof ParameterizedTypeReference<?>) { responseFuture = this.asyncRestTemplate.exchange(uri, httpMethod, httpRequest, (ParameterizedTypeReference<?>) expectedResponseType); } else { responseFuture = this.asyncRestTemplate.exchange(uri, httpMethod, httpRequest, (Class<?>) expectedResponseType); } <START> responseFuture.addCallback(new ListenableFutureCallback<ResponseEntity<?>>() { <END> @Override public void onFailure(Throwable ex) { replyMessageFuture.setException(ex); } @Override public void onSuccess(ResponseEntity<?> result) { replyMessageFuture.set(AsyncHttpRequestExecutingMessageHandler.this.getReply(result)); } }); return replyMessageFuture; }</code><technical_language>this variant simplify readability? responseFuture.addCallback( result -> replyMessageFuture.set(getReply(result)), replyMessageFuture::setException);</technical_language>

Target:
protected Object exchange(URI uri, HttpMethod httpMethod, HttpEntity<?> httpRequest, Object expectedResponseType) { SettableListenableFuture<Object> replyMessageFuture = new SettableListenableFuture<>(); ListenableFuture<? extends ResponseEntity<?>> responseFuture; if (expectedResponseType instanceof ParameterizedTypeReference<?>) { responseFuture = this.asyncRestTemplate.exchange(uri, httpMethod, httpRequest, (ParameterizedTypeReference<?>) expectedResponseType); } else { responseFuture = this.asyncRestTemplate.exchange(uri, httpMethod, httpRequest, (Class<?>) expectedResponseType); } responseFuture.addCallback( result -> replyMessageFuture.set(getReply(result)), replyMessageFuture::setException); return replyMessageFuture; }