auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static List<Schema.Field> getSchemaFields(ResultSet resultSet, @Nullable String schemaStr) throws SQLException { Schema resultsetSchema = Schema.recordOf("resultset", getSchemaFields(resultSet)); if (!Strings.isNullOrEmpty(schemaStr)) { try { Schema schema = Schema.parseJson(schemaStr); for (Schema.Field field : schema.getFields()) { Schema.Field resultsetField = resultsetSchema.getField(field.getName()); if (resultsetField == null) { throw new IllegalArgumentException(String.format("Schema field %s is not present in input record", field.getName())); } Schema resultsetFieldSchema = resultsetField.getSchema().isNullable() ? resultsetField.getSchema().getNonNullable() : resultsetField.getSchema(); Schema simpleSchema = field.getSchema().isNullable() ? field.getSchema().getNonNullable() : field.getSchema(); if (!resultsetFieldSchema.equals(simpleSchema)) { throw new IllegalArgumentException(String.format("Schema field %s has type %s but in input record found " + "type %s ", field.getName(), simpleSchema.getType(), resultsetFieldSchema.getType())); } } return schema.getFields(); } catch (IOException e) { <START> throw new IllegalArgumentException(String.format("Can not covert schema string %s to Schema", schemaStr), e); <END> } } return resultsetSchema.getFields(); }</code><technical_language>for messaging consistency: convert schema string -> Unable parse schema string</technical_language>

Target:
public static List<Schema.Field> getSchemaFields(ResultSet resultSet, @Nullable String schemaStr) throws SQLException { Schema resultsetSchema = Schema.recordOf("resultset", getSchemaFields(resultSet)); Schema schema; if (!Strings.isNullOrEmpty(schemaStr)) { try { schema = Schema.parseJson(schemaStr); } catch (IOException e) { throw new IllegalArgumentException(String.format("Unable to parse schema string %s", schemaStr), e); } for (Schema.Field field : schema.getFields()) { Schema.Field resultsetField = resultsetSchema.getField(field.getName()); if (resultsetField == null) { throw new IllegalArgumentException(String.format("Schema field %s is not present in input record", field.getName())); } Schema resultsetFieldSchema = resultsetField.getSchema().isNullable() ? resultsetField.getSchema().getNonNullable() : resultsetField.getSchema(); Schema simpleSchema = field.getSchema().isNullable() ? field.getSchema().getNonNullable() : field.getSchema(); if (!resultsetFieldSchema.equals(simpleSchema)) { throw new IllegalArgumentException(String.format("Schema field %s has type %s but in input record found " + "type %s ", field.getName(), simpleSchema.getType(), resultsetFieldSchema.getType())); } } return schema.getFields(); } return resultsetSchema.getFields(); }
Source:
<code>public Map<Integer, Set<Integer>> getStoreIdToBlockIds() { <START> return null; <END> }</code><technical_language>nit: avoid return null unused. Instead return Collections.emptyMap()</technical_language>

Target:
public Map<Integer, Set<Integer>> getStoreIdToBlockIds() { return Collections.emptyMap(); }
Source:
<code>public String getPagingData() { <START> if(getPagination() == null) <END> return ""; return getPagination().getTag(); }</code><technical_language>Please add braces if expression reformat</technical_language>

Target:
public String getPagingData() { if (getPagination() == null) { return ""; } return getPagination().getTag(); }
Source:
<code>private boolean consoleDeviceChanged() { List<VmDevice> consoleDevices = getVmDeviceDao().getVmDeviceByVmIdTypeAndDevice(getParameters().getVmId(), <START> VmDeviceGeneralType.CONSOLE, VmDeviceType.CONSOLE.getName()); <END> return getParameters().isConsoleEnabled() == consoleDevices.isEmpty(); }</code><technical_language>getVmDeviceByVmIdAndType</technical_language>

Target:
private boolean consoleDeviceChanged() { List<VmDevice> consoleDevices = getVmDeviceDao().getVmDeviceByVmIdAndType(getParameters().getVmId(), VmDeviceGeneralType.CONSOLE); return getParameters().isConsoleEnabled() == consoleDevices.isEmpty(); }
Source:
<code>public ServerSocket createServerSocket(String name) throws IOException { <START> return this.factory.createServerSocket(name); <END> }</code><technical_language>@danberindei I suggest syncing this class version in WildFly: <LINK_0></technical_language>

Target:
public ServerSocket createServerSocket(String name) throws IOException { return this.register(this.factory.createServerSocket(name)); }
Source:
<code>public boolean includes(char[] simpleName) { boolean result = sortedArrayContains(this.simpleNameReferences, simpleName, CHAR_ARR_COMPARATOR); <START> if (REFERENCE_COLLECTION_DEBUG) { <END> if (result != debugIncludes(simpleName)) { String message = "Mismatch: " + String.valueOf(simpleName) + (result ? " should not " : " should ") + " be included in " + Arrays.asList(CharOperation.toStrings(this.simpleNameReferences)); throw new IllegalStateException(message); } } return result; }</code><technical_language>I move debug code blocks dedicated debug methods</technical_language>

Target:
public boolean includes(char[] simpleName) { boolean result = sortedArrayContains(this.simpleNameReferences, simpleName, CHAR_ARR_COMPARATOR); if (REFERENCE_COLLECTION_DEBUG) { assertIncludes(result, simpleName); } return result; }
Source:
<code>public boolean onKeyEvent(NUIKeyEvent event) { <START> if (event.isDown() && TabbingManager.focusedWidget.equals(this)) { <END> int keyId = event.getKey().getId(); if (keyId == Keyboard.KeyId.RIGHT || keyId == Keyboard.KeyId.UP) { this.changeValue(getIncrement()); return true; } else if (keyId == Keyboard.KeyId.LEFT || keyId == Keyboard.KeyId.DOWN) { this.changeValue(-1 * getIncrement()); return true; } } return super.onKeyEvent(event); }</code><technical_language>point null checks. If good here</technical_language>

Target:
public boolean onKeyEvent(NUIKeyEvent event) { if (event.isDown() && this.equals(TabbingManager.focusedWidget)) { int keyId = event.getKey().getId(); if (keyId == Keyboard.KeyId.RIGHT || keyId == Keyboard.KeyId.UP) { this.changeValue(getIncrement()); return true; } else if (keyId == Keyboard.KeyId.LEFT || keyId == Keyboard.KeyId.DOWN) { this.changeValue(-1 * getIncrement()); return true; } } return super.onKeyEvent(event); }
Source:
<code>private Configuration getConfigurationForExportSystem(String pid) { Configuration config = mock(Configuration.class); Dictionary<String, Object> props = new Hashtable<>(); try { props.put( DirectoryWatcher.FILENAME, ddfHome.resolve("etc").toRealPath().resolve(String.format("%s.config", pid)).toUri()); } catch (IOException e) { fail("Unable to resolve configuration path"); } props.put("service.pid", pid); props.put("schema", "<LINK_0>"); if (pid.equals(METACARD_VALIDITY_FILTER_PLUGIN_PID)) { <START> props.put("attributeMap", new String[] {"invalid-state=data-manager", "system-user"}); <END> props.put("filterWarnings", "false"); props.put("filterErrors", "true"); } when(config.getProperties()).thenReturn(props); when(config.getPid()).thenReturn(pid); return config; }</code><technical_language>Technically, 2 String elements a single String element. If put a element in this array this new String[] {"invalid-state=data-manager,system-user", "test-claim=test-role1,test-role2"} output assert line 427 "invalid-state=localhost-data-manager,system-user,test-claim=test-role1,test-role2"</technical_language>

Target:
private Configuration getConfigurationForExportSystem(String pid) { Configuration config = mock(Configuration.class); Dictionary<String, Object> props = new Hashtable<>(); try { props.put( DirectoryWatcher.FILENAME, ddfHome.resolve("etc").toRealPath().resolve(String.format("%s.config", pid)).toUri()); } catch (IOException e) { fail("Unable to resolve configuration path"); } props.put("service.pid", pid); props.put("schema", "<LINK_0>"); if (pid.equals(METACARD_VALIDITY_FILTER_PLUGIN_PID)) { props.put( "attributeMap", new String[] { "invalid-state=data-manager,system-user", "invalid-state=hostname-data-manager,system-user" }); props.put("filterWarnings", "false"); props.put("filterErrors", "true"); } when(config.getProperties()).thenReturn(props); when(config.getPid()).thenReturn(pid); return config; }
Source:
<code>public void cleanupExpiredPools() { List<Pool> pools = poolCurator.listExpiredPools(); log.info("Expired pools: " + pools.size()); List<Pool> toDelete = new LinkedList<Pool>(); for (Pool p : pools) { if (p.hasAttribute("pool_derived")) { continue; } <START> log.debug("Cleaning up expired pool: " + p.getId() + " (" + p.getEndDate() + ")"); <END> toDelete.add(p); if (!subAdapter.isReadOnly()) { Subscription sub = subAdapter.getSubscription(p.getSubscriptionId()); if (sub != null) { subAdapter.deleteSubscription(sub); } } } deletePools(toDelete); }</code><technical_language>SLF4J here: log.debug("Cleaning expired pool: ({})", p.getId(), p.getEndDate());</technical_language>

Target:
public void cleanupExpiredPools() { List<Pool> pools = poolCurator.listExpiredPools(); log.info("Expired pools: " + pools.size()); List<Pool> toDelete = new LinkedList<Pool>(); for (Pool p : pools) { if (p.hasAttribute("pool_derived")) { continue; } log.debug("Cleaning up expired pool: ({})", p.getId(), p.getEndDate()); toDelete.add(p); if (!subAdapter.isReadOnly()) { Subscription sub = subAdapter.getSubscription(p.getSubscriptionId()); if (sub != null) { subAdapter.deleteSubscription(sub); } } } deletePools(toDelete); }
Source:
<code>public void processElement(DoFn<Read, KV<Contig, Read>>.ProcessContext c) throws Exception { final Read read = c.element(); long pos = read.getAlignment().getPosition().getPosition(); if (lastPos > pos) { <START> LOG.info("Out of order read at pos "+ lastPos + " " + pos); <END> } lastPos = pos; minPos = Math.min(minPos, pos); maxPos = Math.max(maxPos, pos); count++; c.output( KV.of( shardKeyForRead(read, lociPerShard), read)); readCountAggregator.addValue(1); if (isUnmapped(read)) { unmappedReadCountAggregator.addValue(1); } }</code><technical_language>is implication of this event if occurs? A malformed input BAM file? a bug in pipeline? This event is logged, action is taken</technical_language>

Target:
public void processElement(DoFn<Read, KV<Contig, Read>>.ProcessContext c) throws Exception { final Read read = c.element(); long pos = read.getAlignment().getPosition().getPosition(); minPos = Math.min(minPos, pos); maxPos = Math.max(maxPos, pos); count++; c.output( KV.of( shardKeyForRead(read, lociPerShard), read)); readCountAggregator.addValue(1); if (isUnmapped(read)) { unmappedReadCountAggregator.addValue(1); } }
Source:
<code>public LocationHierarchyLevel makePlaceHolder(String id, String name) { LocationHierarchyLevel locationHierarchyLevel = new LocationHierarchyLevel(); locationHierarchyLevel.setUuid(id); locationHierarchyLevel.setName(name); <START> locationHierarchyLevel.setKeyIdentifier(-1); <END> return locationHierarchyLevel; }</code><technical_language>locationHierarchyLevel.setKeyIdentifier(id.hashCode()); unique</technical_language>

Target:
public LocationHierarchyLevel makePlaceHolder(String id, String name) { LocationHierarchyLevel locationHierarchyLevel = new LocationHierarchyLevel(); locationHierarchyLevel.setUuid(id); locationHierarchyLevel.setName(name); locationHierarchyLevel.setKeyIdentifier(id.hashCode()); return locationHierarchyLevel; }
Source:
<code>public static void tryFailure(Promise<?> p, Throwable cause, InternalLogger logger) { if (!p.tryFailure(cause) && logger != null) { Throwable err = p.cause(); if (err == null) { logger.warn("Failed to mark a promise as failure because it has succeeded already: {}", p, cause); } else { <START> if (logger.isWarnEnabled()) { <END> logger.warn( "Failed to mark a promise as failure because it has failed already: {}, unnotified cause: {}", p, ThrowableUtil.stackTraceToString(err), cause); } } } }</code><technical_language>merge this else else if</technical_language>

Target:
public static void tryFailure(Promise<?> p, Throwable cause, InternalLogger logger) { if (!p.tryFailure(cause) && logger != null) { Throwable err = p.cause(); if (err == null) { logger.warn("Failed to mark a promise as failure because it has succeeded already: {}", p, cause); } else if (logger.isWarnEnabled()) { logger.warn( "Failed to mark a promise as failure because it has failed already: {}, unnotified cause: {}", p, ThrowableUtil.stackTraceToString(err), cause); } } }
Source:
<code>public List<permissions> getAllForEntity(Guid id, Guid userID, boolean isFiltered) { <START> Integer appMode = Config.<Integer> GetValue(ConfigValues.ApplicationMode); <END> MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("id", id).addValue("user_id", userID).addValue("is_filtered", isFiltered) .addValue("app_mode", appMode.intValue()); return getCallsHandler().executeReadList("GetPermissionsByEntityId", PermissionRowMapper.instance, parameterSource); }</code><technical_language>I GetValue returns "int" only, need assign Integer. assign int type pass parameter creation code</technical_language>

Target:
public List<permissions> getAllForEntity(Guid id, Guid userID, boolean isFiltered) { int appMode = Config.<Integer> GetValue(ConfigValues.ApplicationMode); MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("id", id).addValue("user_id", userID).addValue("is_filtered", isFiltered) .addValue("app_mode", appMode); return getCallsHandler().executeReadList("GetPermissionsByEntityId", PermissionRowMapper.instance, parameterSource); }
Source:
<code>private void executeBuild(List<String> arguments, ProjectConnection connection, String[] tasks) { List<String> args = Lists.newArrayListWithCapacity(2 + arguments.size()); args.add("-i"); args.add("-u"); args.addAll(arguments); BuildLauncher launcher = connection.newBuild().forTasks(tasks) .withArguments(args.toArray(new String[args.size()])); StringBuilder jvmArguments = new StringBuilder(); String debugIntegrationTest = System.getenv("DEBUG_INNER_TEST"); if (!Strings.isNullOrEmpty(debugIntegrationTest) && debugIntegrationTest.equals(name)) { jvmArguments.append("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005"); } if (JacocoAgent.isJacocoEnabled()) { <START> if (jvmArguments.length() != 0) { jvmArguments.append(' '); } <END> jvmArguments.append(JacocoAgent.getJvmArg()); } if (jvmArguments.length() > 0) { launcher.setJvmArguments(jvmArguments.toString()); } if (stdout != null) { launcher.setStandardOutput(stdout); } launcher.run(); }</code><technical_language>Instead of manually adding white space, I create a list of String pass setJvmArguments array</technical_language>

Target:
private void executeBuild(List<String> arguments, ProjectConnection connection, String[] tasks) { List<String> args = Lists.newArrayListWithCapacity(2 + arguments.size()); args.add("-i"); args.add("-u"); args.addAll(arguments); BuildLauncher launcher = connection.newBuild().forTasks(tasks) .withArguments(args.toArray(new String[args.size()])); List<String> jvmArguments = new ArrayList<String>(); String debugIntegrationTest = System.getenv("DEBUG_INNER_TEST"); if (!Strings.isNullOrEmpty(debugIntegrationTest) && debugIntegrationTest.equals(name)) { jvmArguments.add("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005"); } if (JacocoAgent.isJacocoEnabled()) { jvmArguments.add(JacocoAgent.getJvmArg()); } if (!jvmArguments.isEmpty()) { launcher.setJvmArguments(jvmArguments.toArray(new String[jvmArguments.size()])); } if (stdout != null) { launcher.setStandardOutput(stdout); } launcher.run(); }
Source:
<code>public String validateJdkRootDirectory(String jdkRootDirectory) { <START> if( jdkRootDirectory == null || jdkRootDirectory.isEmpty()) { <END> return Messages.NoJdkDirectoryFoundMsg; } File directory = new File(jdkRootDirectory); if (!directory.exists() || !directory.isDirectory()) { return Messages.directoryNotExistMsg; } File toolsJarFile = new File(jdkRootDirectory + TOOLS_JAR); if (!toolsJarFile.exists()) { return Messages.notJdkRootDirectoryMsg; } String libraryPath = getJreLibraryPath(jdkRootDirectory); if (libraryPath == null) { return Messages.notJdkRootDirectoryMsg; } return null; }</code><technical_language>jdkRootDirectory.trim().isEmpty() is</technical_language>

Target:
public String validateJdkRootDirectory(String jdkRootDirectory) { if( jdkRootDirectory == null || jdkRootDirectory.trim().isEmpty()) { return Messages.NoJdkDirectoryFoundMsg; } File directory = new File(jdkRootDirectory); if (!directory.exists() || !directory.isDirectory()) { return Messages.directoryNotExistMsg; } File toolsJarFile = new File(jdkRootDirectory + TOOLS_JAR); if (!toolsJarFile.exists()) { return Messages.notJdkRootDirectoryMsg; } String libraryPath = getJreLibraryPath(jdkRootDirectory); if (libraryPath == null) { return Messages.notJdkRootDirectoryMsg; } return null; }
Source:
<code>private FilterExpression buildIsEmptyOperator(Path path, List<String> arguments) { String arg = arguments.get(0); try { boolean wantsEmpty = CoerceUtil.coerce(arg, boolean.class); if (wantsEmpty) { return new IsEmptyPredicate(path); } return new NotEmptyPredicate(path); } catch (InvalidValueException ignored) { <START> throw new RSQLParseException(String.format("Invalid value for operator =isnull= '%s'", arg)); <END> } }</code><technical_language>copy pasted =isnull=. =isempty=</technical_language>

Target:
private FilterExpression buildIsEmptyOperator(Path path, List<String> arguments) { String arg = arguments.get(0); try { boolean wantsEmpty = CoerceUtil.coerce(arg, boolean.class); if (wantsEmpty) { return new IsEmptyPredicate(path); } return new NotEmptyPredicate(path); } catch (InvalidValueException ignored) { throw new RSQLParseException(String.format("Invalid value for operator =isempty= '%s'", arg)); } }
Source:
<code>public void handleException(Exception e, HttpServletResponse response, HttpServletRequest request) throws IOException { storeException(request, response, e); <START> ResponseStatus responseStatus = getAncestors(e.getClass()) <END> .stream() .filter(clazz -> clazz.getAnnotation(ResponseStatus.class) != null) .map(clazz -> clazz.getAnnotation(ResponseStatus.class)) .findFirst() .orElse(null); if (responseStatus != null) { logger.error(responseStatus.value().getReasonPhrase(), e); String message = e.getMessage(); if (message == null || message.trim().isEmpty()) { message = responseStatus.reason(); } response.sendError(responseStatus.value().value(), message); } else { logger.error("Internal Server Error", e); response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage()); } }</code><technical_language>worth some of stuff in here? <LINK_0> give consistency default framework behaviour</technical_language>

Target:
public void handleException(Exception e, HttpServletResponse response, HttpServletRequest request) throws IOException { storeException(request, response, e); ResponseStatus responseStatus = AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class); if (responseStatus != null) { HttpStatus httpStatus = responseStatus.value(); logger.error(httpStatus.getReasonPhrase(), e); String message = e.getMessage(); if (message == null || message.trim().isEmpty()) { message = responseStatus.reason(); } response.sendError(httpStatus.value(), message); } else { logger.error("Internal Server Error", e); response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage()); } }
Source:
<code>private void publishError( BoltResponseMessageHandler<IOException> out, Neo4jError error ) { try { if ( error.isFatal() ) { out.onFatal( error.status(), error.message() ); } else { out.onFailure( error.status(), error.message() ); } } catch ( PackOutputClosedException e ) { <START> if ( error.status() == Status.Transaction.Terminated ) <END> { log.warn( "Client %s disconnected while query was running. Session has been cleaned up. " + "This can be caused by temporary network problems, but if you see this often, " + "ensure your applications are properly waiting for operations to complete before exiting.", e.clientAddress() ); return; } log.warn( "Unable to send error back to the client. " + e.getMessage(), error.cause() ); } catch ( Throwable t ) { t.addSuppressed( error.cause() ); log.error( "Unable to send error back to the client", t ); } }</code><technical_language>Worth checking LockClientStopped pretty meaning. vote for a static set of "OK" statuses set.contains(error.status()) here</technical_language>

Target:
private void publishError( BoltResponseMessageHandler<IOException> out, Neo4jError error ) { try { if ( error.isFatal() ) { out.onFatal( error.status(), error.message() ); } else { out.onFailure( error.status(), error.message() ); } } catch ( PackOutputClosedException e ) { if ( CLIENT_MID_OP_DISCONNECT_ERRORS.contains( error.status() ) ) { log.warn( "Client %s disconnected while query was running. Session has been cleaned up. " + "This can be caused by temporary network problems, but if you see this often, " + "ensure your applications are properly waiting for operations to complete before exiting.", e.clientAddress() ); return; } log.warn( "Unable to send error back to the client. " + e.getMessage(), error.cause() ); } catch ( Throwable t ) { t.addSuppressed( error.cause() ); log.error( "Unable to send error back to the client", t ); } }
Source:
<code>public void testHttpEchoServer() throws Throwable { final Lifecycle lifecycle = new Lifecycle(); try { final HttpClientConfig config = HttpClientConfig.builder().build(); final HttpClient client = HttpClientInit.createClient(config, lifecycle); final ListenableFuture<StatusResponseHolder> response = client .go( new Request(HttpMethod.GET, new URL(StringUtils.format("http://localhost:%d/", echoServerSocket.getLocalPort()))), new StatusResponseHandler(StandardCharsets.UTF_8) ); Throwable e = null; try { response.get(); } catch (ExecutionException e1) { e = e1.getCause(); } <START> Assert.assertTrue("ChannelException thrown by 'get'", e instanceof ChannelException); <END> Assert.assertEquals("Expected error message", "Channel disconnected", e.getMessage()); } finally { lifecycle.stop(); } }</code><technical_language>Please ExpectedException instead</technical_language>

Target:
public void testHttpEchoServer() throws Throwable { final Lifecycle lifecycle = new Lifecycle(); try { final HttpClientConfig config = HttpClientConfig.builder().build(); final HttpClient client = HttpClientInit.createClient(config, lifecycle); final ListenableFuture<StatusResponseHolder> response = client .go( new Request(HttpMethod.GET, new URL(StringUtils.format("http://localhost:%d/", echoServerSocket.getLocalPort()))), new StatusResponseHandler(StandardCharsets.UTF_8) ); expectedException.expect(ExecutionException.class); expectedException.expectMessage("java.lang.IllegalArgumentException: invalid version format: GET"); response.get(); } finally { lifecycle.stop(); } }
Source:
<code>public DnsServiceProvider getDnsServiceProvider(final Network network) { <START> final String DnsProvider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.Dns); <END> if (DnsProvider == null) { s_logger.debug("Network " + network + " doesn't support service " + Service.Dhcp.getName()); return null; } return (DnsServiceProvider) _networkModel.getElementImplementingProvider(DnsProvider); }</code><technical_language>Variables start lowecase</technical_language>

Target:
public DnsServiceProvider getDnsServiceProvider(final Network network) { final String dnsProvider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.Dns); if (dnsProvider == null) { s_logger.debug("Network " + network + " doesn't support service " + Service.Dhcp.getName()); return null; } return (DnsServiceProvider) _networkModel.getElementImplementingProvider(dnsProvider); }
Source:
<code>public void run() { try { output = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name()); } catch (IOException e) { <START> output = ExceptionUtils.getStackTrace(e); <END> } }</code><technical_language>I is letting this method throw exception</technical_language>

Target:
public void run() { try { output = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name()); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
<code>String dkimSignatureTemplate() { final StringBuilder sb = new StringBuilder(); sb.append("v=1; "); sb.append("a=").append(this.dkimSignOptions.getSignAlgo().getDKIMAlgoName()).append("; "); MessageCanonic bodyCanonic = this.dkimSignOptions.getBodyCanonic(); MessageCanonic headerCanonic = this.dkimSignOptions.getHeaderCanonic(); sb.append("c=").append(headerCanonic.getCanonic()).append("/").append(bodyCanonic.getCanonic()).append("; "); String sdid = dkimQuotedPrintable(this.dkimSignOptions.getSdid()); sb.append("d=").append(sdid).append("; "); String auid = this.dkimSignOptions.getAuid(); if (auid != null) { sb.append("i=").append(dkimQuotedPrintable(auid)).append("; "); } else { sb.append("i=").append("@").append(sdid).append("; "); } sb.append("s=").append(dkimQuotedPrintable(this.dkimSignOptions.getSelector())).append("; "); String signHeadersString = String.join(":", this.dkimSignOptions.getSignedHeaders()); sb.append("h=").append(signHeadersString).append("; "); if (this.dkimSignOptions.getBodyLimit() > 0) { sb.append("l=").append(this.dkimSignOptions.getBodyLimit()).append("; "); } if (this.dkimSignOptions.isSignatureTimestamp() || this.dkimSignOptions.getExpireTime() > 0) { <START> long time = new Date().getTime() / 1000; END> sb.append("t=").append(time).append("; "); if (this.dkimSignOptions.getExpireTime() > 0) { long expire = time + this.dkimSignOptions.getExpireTime(); sb.append("x=").append(expire).append("; "); } } return sb.toString(); }</code><technical_language>System.currentmillis</technical_language>

Target:
String dkimSignatureTemplate() { final StringBuilder sb = new StringBuilder(); sb.append("v=1; "); sb.append("a=").append(this.dkimSignOptions.getSignAlgo().dkimAlgoName()).append("; "); MessageCanonic bodyCanonic = this.dkimSignOptions.getBodyCanonic(); MessageCanonic headerCanonic = this.dkimSignOptions.getHeaderCanonic(); sb.append("c=").append(headerCanonic.canonic()).append("/").append(bodyCanonic.canonic()).append("; "); String sdid = dkimQuotedPrintable(this.dkimSignOptions.getSdid()); sb.append("d=").append(sdid).append("; "); String auid = this.dkimSignOptions.getAuid(); if (auid != null) { sb.append("i=").append(dkimQuotedPrintable(auid)).append("; "); } else { sb.append("i=").append("@").append(sdid).append("; "); } sb.append("s=").append(dkimQuotedPrintable(this.dkimSignOptions.getSelector())).append("; "); String signHeadersString = String.join(":", this.dkimSignOptions.getSignedHeaders()); sb.append("h=").append(signHeadersString).append("; "); if (this.dkimSignOptions.getBodyLimit() > 0) { sb.append("l=").append(this.dkimSignOptions.getBodyLimit()).append("; "); } if (this.dkimSignOptions.isSignatureTimestamp() || this.dkimSignOptions.getExpireTime() > 0) { long time = System.currentTimeMillis() / 1000; sb.append("t=").append(time).append("; "); if (this.dkimSignOptions.getExpireTime() > 0) { long expire = time + this.dkimSignOptions.getExpireTime(); sb.append("x=").append(expire).append("; "); } } return sb.toString(); }
Source:
<code>private void processOptions() throws IllegalArgumentException { <START> if (committer == null) { <END> committer = new PersonIdent(repo); } if (author == null) { author = committer; } if (message == null) { throw new IllegalArgumentException("commit message not specified"); } }</code><technical_language>Style-nit: avoid curly braces single statements</technical_language>

Target:
private void processOptions() throws IllegalArgumentException { if (message == null) throw new IllegalArgumentException(COMMIT_MESSAGE_NOT_SPECIFIED); }
Source:
<code>public boolean containsKey(final String key) { <START> return super.get(key.toLowerCase()) != null; <END> }</code><technical_language>super.containsKey(key.toLowerCase()) ? ConcurrentHashMap provides containsKey</technical_language>

Target:
public boolean containsKey(final String key) { return this.map.containsKey(key.toLowerCase()); }
Source:
<code>public void showInterstitial() { mMediationInterstitialListener.onAdOpened(UnityAdapter.this); Activity activityReference = mActivityWeakReference == null ? null : mActivityWeakReference.get(); <START> if (activityReference != null) { if (UnityAds.isReady(getPlacementId())) { UnityAds.show(activityReference, getPlacementId()); } else { Log.w(TAG, "Unity Ads failed to show interstitial ad for placement ID '" + getPlacementId() + "'. Placement is not ready."); mMediationInterstitialListener.onAdClosed(UnityAdapter.this); } } else { Log.w(TAG, "Failed to show interstitial ad for placement ID '" + getPlacementId() + "' from Unity Ads: Activity context is null."); mMediationInterstitialListener.onAdClosed(UnityAdapter.this); } <END> }</code><technical_language>cleaned up: if (activityReference == null) { // error. return; } if (!UnityAds.isReady()) { // error return; } UnityAds.show()</technical_language>

Target:
public void showInterstitial() { mMediationInterstitialListener.onAdOpened(UnityAdapter.this); Activity activityReference = mActivityWeakReference == null ? null : mActivityWeakReference.get(); if (activityReference == null) { Log.w(TAG, "Failed to show interstitial ad for placement ID '" + mPlacementId + "' from Unity Ads: Activity context is null."); mMediationInterstitialListener.onAdClosed(UnityAdapter.this); return; } if (!UnityAds.isReady(mPlacementId)) { Log.w(TAG, "Unity Ads failed to show interstitial ad for placement ID '" + mPlacementId + "'. Placement is not ready."); mMediationInterstitialListener.onAdClosed(UnityAdapter.this); return; } UnityAds.show(activityReference, mPlacementId); }
Source:
<code><START> public void updateTableView( List<Object[]> rows ) { <END> updateTableView( rows, tableView ); }</code><technical_language>Is this method else? cope this discard overloaded below, this.tableView it</technical_language>

Target:
public void updateTableView( List<Object[]> rows ) { int itemCount = tableView.table.getItemCount(); for ( int i = 0; i < rows.size(); i++ ) { TableItem item = i < itemCount ? tableView.table.getItem( i ) : new TableItem( tableView.table, SWT.NONE ); applyRowDataToTableItem( rows.get( i ), item ); } tableView.table.setItemCount( rows.size() ); tableView.setRowNums(); }
Source:
<code>public void packRefs() throws IOException { Set<Entry<String, Ref>> refEntries = repo.getAllRefs().entrySet(); if (pm == null) pm = NullProgressMonitor.INSTANCE; <START> pm.beginTask("pack refs", refEntries.size()); <END> try { Collection<RefDirectoryUpdate> updates = new LinkedList<RefDirectoryUpdate>(); for (Map.Entry<String, Ref> entry : refEntries) { Ref ref = entry.getValue(); if (!ref.isSymbolic() && ref.getStorage().isLoose()) { updates.add(new RefDirectoryUpdate((RefDirectory) repo .getRefDatabase(), ref)); } pm.update(1); } ((RefDirectory) repo.getRefDatabase()).pack(updates); } finally { pm.endTask(); } }</code><technical_language>externalize this string for translation</technical_language>

Target:
public void packRefs() throws IOException { Collection<Ref> refs = repo.getAllRefs().values(); ArrayList<String> refsToBePacked = new ArrayList<String>(refs.size()); int packRefsCnt = 0; pm.beginTask(JGitText.get().packRefs, refs.size()); try { for (Ref ref : refs) { if (!ref.isSymbolic() && ref.getStorage().isLoose()) { refsToBePacked.add(ref.getName()); packRefsCnt++; } pm.update(1); } ((RefDirectory) repo.getRefDatabase()).pack(refsToBePacked .toArray(new String[packRefsCnt])); } finally { pm.endTask(); } }
Source:
<code>public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { BigtableOptions bigtableOptions = configuration.toBigtableOptions(); long totalEstimatedSizeBytes = 0; Scan scan = configuration.getScan(); byte[] scanStartKey = scan.getStartRow(); byte[] scanEndKey = scan.getStopRow(); List<SourceWithKeys> splits = new ArrayList<>(); <START> try (BigtableSession session = new BigtableSession(bigtableOptions)) { <END> BigtableClusterName clusterName = bigtableOptions.getClusterName(); BigtableTableName tableName = clusterName.toTableName(configuration.getTableId()); SampleRowKeysRequest.Builder request = SampleRowKeysRequest.newBuilder(); request.setTableName(tableName.toString()); List<SampleRowKeysResponse> sampleRowKeys = session.getDataClient().sampleRowKeys(request.build()); byte[] startKey = HConstants.EMPTY_START_ROW; long lastOffset = 0; for (SampleRowKeysResponse response : sampleRowKeys) { byte[] currentEndKey = response.getRowKey().toByteArray(); if (Bytes.equals(startKey, currentEndKey) && startKey.length != 0) { continue; } long offset = response.getOffsetBytes(); if ((scanStartKey.length == 0 || currentEndKey.length == 0 || Bytes.compareTo(scanStartKey, currentEndKey) < 0) && (scanEndKey.length == 0 || Bytes.compareTo(scanEndKey, startKey) > 0)) { totalEstimatedSizeBytes += (offset - lastOffset); } lastOffset = offset; startKey = currentEndKey; } byte[] endKey = HConstants.EMPTY_END_ROW; if (!Bytes.equals(startKey, endKey)) { splits.add(new SourceWithKeys(startKey, endKey, 0)); } } return totalEstimatedSizeBytes; }</code><technical_language>is multiple times, this a separate function returning List<SampleRowKeysResponse>? - try (BigtableSession session = new BigtableSession(bigtableOptions)) { - BigtableClusterName clusterName = bigtableOptions.getClusterName(); - BigtableTableName tableName = clusterName.toTableName(configuration.getTableId()); - SampleRowKeysRequest.Builder request = SampleRowKeysRequest.newBuilder(); - request.setTableName(tableName.toString()); - List<SampleRowKeysResponse> sampleRowKeys = - session.getDataClient().sampleRowKeys(request.build());</technical_language>

Target:
public long getEstimatedSizeBytes(PipelineOptions options) throws Exception { long totalEstimatedSizeBytes = 0; Scan scan = configuration.getScan(); byte[] scanStartKey = scan.getStartRow(); byte[] scanEndKey = scan.getStopRow(); byte[] startKey = HConstants.EMPTY_START_ROW; long lastOffset = 0; for (SampleRowKeysResponse response : getSampleRowKeys()) { byte[] currentEndKey = response.getRowKey().toByteArray(); if (Bytes.equals(startKey, currentEndKey) && startKey.length != 0) { continue; } long offset = response.getOffsetBytes(); if (isWithinRange(scanStartKey, scanEndKey, startKey, currentEndKey)) { totalEstimatedSizeBytes += (offset - lastOffset); } lastOffset = offset; startKey = currentEndKey; } return totalEstimatedSizeBytes; }
Source:
<code><START> public CrawlFilter(@ServiceUrl String serviceUrl, <END> @ServiceKey String key, Logger log) { this.serviceUrl = serviceUrl; this.key = key; this.log = log; }</code><technical_language>rm public</technical_language>

Target:
CrawlFilter(@ServiceUrl String serviceUrl, @ServiceKey String key, Logger log) { this.serviceUrl = serviceUrl; this.key = key; this.log = log; }
Source:
<code>StatDetails(Stream<StatDetails> details) { this.latencies = details.flatMap(stat -> stat.latencies.stream()) <START> .collect(Collectors.groupingBy(LatencyStat::getBucket, <END> Collectors.groupingBy(LatencyStat::getPercentile, Collectors.averagingDouble(LatencyStat::getLatencyMs)))) .entrySet().stream().flatMap(bucketEntry -> bucketEntry.getValue().entrySet().stream().map(latencyEntry -> new LatencyStat(bucketEntry.getKey(), latencyEntry.getKey(), latencyEntry.getValue()))) .collect(Collectors.toList()); }</code><technical_language>static import this more fluent</technical_language>

Target:
StatDetails(Stream<StatDetails> details) { this.latencies = details.flatMap(stat -> stat.latencies.stream()) .collect(groupingBy(LatencyStat::getBucket, groupingBy(LatencyStat::getPercentile, averagingDouble(stat -> stat.getLatency().nanos())))) .entrySet().stream().flatMap(bucketEntry -> bucketEntry.getValue().entrySet().stream().map(latencyEntry -> { TimeValue tv = TimeValue.timeValueNanos(Math.round(latencyEntry.getValue())); return new LatencyStat(bucketEntry.getKey(), latencyEntry.getKey(), tv); })) .collect(toList()); }
Source:
<code>public byte[] marshal(ByteBuffer bb) throws Exception { <START> return bb.array(); <END> }</code><technical_language>This call relies optional behavior of ByteBuffer. safer original code: @XmlAttribute public byte[] getBytes() { m_bytes.rewind(); byte[] retval = new byte[m_bytes.remaining()]; m_bytes.get(retval); m_bytes.rewind(); return retval; } If want preserve position of buffer, add code for (but a problem here)</technical_language>

Target:
public byte[] marshal(ByteBuffer bb) { if (bb.hasArray()) { return bb.array(); } else { final int originalPosition = bb.position(); bb.rewind(); byte[] bytes = new byte[bb.remaining()]; bb.get(bytes); bb.position(originalPosition); return bytes; } }
Source:
<code>public List<ServiceReference> listServiceReferences(Class<?> clazz) { List<ServiceReference> result = new ArrayList<ServiceReference>(); try { CollectionUtils.addAll(result, bundleContext.getServiceReferences(clazz.getName(), null)); <START> } catch (InvalidSyntaxException e) { <END> throw new IllegalArgumentException(e); } return result; }</code><technical_language>rules do throw InvalidSyntax IllegalArgument IllegalState exception. Sry, this randomized</technical_language>

Target:
public List<ServiceReference> listServiceReferences(Class<?> clazz) { List<ServiceReference> result = new ArrayList<ServiceReference>(); try { ServiceReference[] serviceReferences = bundleContext.getServiceReferences(clazz.getName(), null); if (serviceReferences == null) { return result; } CollectionUtils.addAll(result, serviceReferences); } catch (InvalidSyntaxException e) { throw new IllegalArgumentException(e); } return result; }
Source:
<code>public void runMigrations(File migrationDirectory) { LOGGER.debug("Starting the flyway modules migrations from {}.", migrationDirectory.getAbsolutePath()); if (!migrationDirectory.exists()) { LOGGER.debug("The migration directory doesn't exist. Skipping migration."); return; } ClassLoader cl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(mdsSqlProperties.getProperty(CONNECTION_DRIVER_KEY)); dataSource.setUrl(mdsSqlProperties.getProperty(CONNECTION_URL_KEY)); dataSource.setUsername(mdsSqlProperties.getProperty(CONNECTION_USER_NAME_KEY)); dataSource.setPassword(mdsSqlProperties.getProperty(CONNECTION_USER_PASSWORD_KEY)); Flyway flyway = new Flyway(); flyway.setDataSource(dataSource); flyway.setLocations(Constants.EntitiesMigration.FILESYSTEM_PREFIX + migrationDirectory.getAbsolutePath()); flyway.setSqlMigrationPrefix(Constants.EntitiesMigration.ENTITY_MIGRATIONS_PREFIX); flyway.setOutOfOrder(true); flyway.setInitOnMigrate(true); flyway.migrate(); <START> Thread.currentThread().setContextClassLoader(cl); <END> LOGGER.info("Modules migration completed."); }</code><technical_language>this in finally, is this necessary way</technical_language>

Target:
public void runMigrations(File migrationDirectory) { LOGGER.debug("Starting the flyway modules migrations from {}.", migrationDirectory.getAbsolutePath()); if (!migrationDirectory.exists()) { LOGGER.debug("The migration directory doesn't exist. Skipping migration."); return; } ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(mdsSqlProperties.getProperty(CONNECTION_DRIVER_KEY)); dataSource.setUrl(mdsSqlProperties.getProperty(CONNECTION_URL_KEY)); dataSource.setUsername(mdsSqlProperties.getProperty(CONNECTION_USER_NAME_KEY)); dataSource.setPassword(mdsSqlProperties.getProperty(CONNECTION_USER_PASSWORD_KEY)); Flyway flyway = new Flyway(); flyway.setDataSource(dataSource); flyway.setLocations(Constants.EntitiesMigration.FILESYSTEM_PREFIX + migrationDirectory.getAbsolutePath()); flyway.setSqlMigrationPrefix(Constants.EntitiesMigration.ENTITY_MIGRATIONS_PREFIX); flyway.setOutOfOrder(true); flyway.setInitOnMigrate(true); flyway.migrate(); } finally { Thread.currentThread().setContextClassLoader(cl); LOGGER.info("Modules migration completed."); } }
Source:
<code><START> private SslContext getSSLContext() { <END> long now = System.currentTimeMillis(); if (isServerCtx && (certRefreshTime <= 0 || now > (certLastRefreshTime + certRefreshTime))) { if (tTLSCertificatePath.checkAndRefresh() || tLSKeyStoreFilePath.checkAndRefresh() || tLSKeyStorePasswordFilePath.checkAndRefresh() || tLSTrustStoreFilePath.checkAndRefresh() || tLSTrustStorePasswordFilePath.checkAndRefresh()) { try { updateServerContext(); } catch (Exception e) { LOG.info("Failed to refresh tls certs", e); } } } return sslContext; }</code><technical_language>synchronized? a race condition for certRefreshTime</technical_language>

Target:
private synchronized SslContext getSSLContext() { long now = System.currentTimeMillis(); if (isServerCtx && (certRefreshTime > 0 && now > (certLastRefreshTime + certRefreshTime))) { if (tTLSCertificatePath.checkAndRefresh() || tLSKeyStoreFilePath.checkAndRefresh() || tLSKeyStorePasswordFilePath.checkAndRefresh() || tLSTrustStoreFilePath.checkAndRefresh() || tLSTrustStorePasswordFilePath.checkAndRefresh()) { try { updateServerContext(); } catch (Exception e) { LOG.info("Failed to refresh tls certs", e); } } } return sslContext; }
Source:
<code>public B setConfiguredProperty(ConfiguredPropertyDescriptor configuredProperty, Object value) { final boolean changed = setConfiguredPropertyIfChanged(configuredProperty, value); if (changed) { if (configuredProperty.isInputColumn()) { <START> for (TransformedInputColumn<?> transformedInputColumn : getTransformedInputColumns(value)) { <END> getAnalysisJobBuilder().getTransformerComponentBuilders().stream().filter( transformer -> (isProvidingColumn(transformedInputColumn, transformer))).forEach( transformer -> transformer.addChangeListener( new ComponentBuilderTransformerChangeListener(this, configuredProperty))); } } onConfigurationChanged(); } return (B) this; }</code><technical_language>a weird non-functional for loop a functional expression inside</technical_language>

Target:
public B setConfiguredProperty(ConfiguredPropertyDescriptor configuredProperty, Object value) { final boolean changed = setConfiguredPropertyIfChanged(configuredProperty, value); if (changed) { if (configuredProperty.isInputColumn()) { registerListenerIfLinkedToTransformer(configuredProperty, value); } onConfigurationChanged(); } return (B) this; }
Source:
<code>public void setAndGetIncludedPath() { String path = "/*"; IncludedPath includedPath = new IncludedPath(path); List<Index> indexes = new ArrayList<>(); indexes.add(Index.range(DataType.STRING, -1)); indexes.add(Index.range(DataType.NUMBER, -1)); includedPath.setIndexes(indexes); List<Index> includedPathIndexes = new ArrayList<>(includedPath.getIndexes()); <START> Assertions.assertThat(includedPathIndexes).hasSize(2); <END> Assertions.assertThat(((RangeIndex) includedPathIndexes.get(0)).getDataType()).isEqualTo(DataType.STRING); Assertions.assertThat(((RangeIndex) includedPathIndexes.get(0)).getPrecision()).isEqualTo(-1); Assertions.assertThat(((RangeIndex) includedPathIndexes.get(1)).getDataType()).isEqualTo(DataType.NUMBER); Assertions.assertThat(((RangeIndex) includedPathIndexes.get(1)).getPrecision()).isEqualTo(-1); Assertions.assertThat(includedPath.getPath()).isEqualTo(path); }</code><technical_language>please static import repeat Assertions</technical_language>

Target:
public void setAndGetIncludedPath() { String path = "/*"; IncludedPath includedPath = new IncludedPath(path); List<Index> indexes = new ArrayList<>(); indexes.add(Index.range(DataType.STRING, -1)); indexes.add(Index.range(DataType.NUMBER, -1)); includedPath.setIndexes(indexes); List<Index> includedPathIndexes = new ArrayList<>(includedPath.getIndexes()); assertThat(includedPathIndexes).hasSize(2); assertThat(((RangeIndex) includedPathIndexes.get(0)).getDataType()).isEqualTo(DataType.STRING); assertThat(((RangeIndex) includedPathIndexes.get(0)).getPrecision()).isEqualTo(-1); assertThat(((RangeIndex) includedPathIndexes.get(1)).getDataType()).isEqualTo(DataType.NUMBER); assertThat(((RangeIndex) includedPathIndexes.get(1)).getPrecision()).isEqualTo(-1); assertThat(includedPath.getPath()).isEqualTo(path); }
Source:
<code>static <T> Stringifier<T> getStringifier(Type typeOfT) { final Optional<Stringifier<T>> stringifierOptional = getInstance().get(typeOfT); if (!stringifierOptional.isPresent()) { final String errMsg = format("No stringifier registered for the type: %s", typeOfT); <START> throw new MissingStringifierException(errMsg); <END> } final Stringifier<T> stringifier = stringifierOptional.get(); return stringifier; }</code><technical_language>This branch covered</technical_language>

Target:
static <T> Stringifier<T> getStringifier(Type typeOfT) { checkNotNull(typeOfT); final Optional<Stringifier<T>> stringifierOptional = getInstance().get(typeOfT); if (!stringifierOptional.isPresent()) { final String errMsg = format("No stringifier registered for the type: %s", typeOfT); throw new MissingStringifierException(errMsg); } final Stringifier<T> stringifier = stringifierOptional.get(); return stringifier; }
Source:
<code>public LiteralRule(Condition condition, Action action, UUID chainId) { super(condition, action, chainId); if (action != Action.ACCEPT && action != Action.DROP <START> && action <END> != Action.REJECT && action != Action.RETURN) throw new IllegalArgumentException("A literal rule's action " + "must be one of: ACCEPT, DROP, REJECT or RETURN."); }</code><technical_language>trailing curly brace is missing here. && action != Action.REJECT && action != Action.RETURN) {</technical_language>

Target:
public LiteralRule(Condition condition, Action action, UUID chainId) { super(condition, action, chainId); if (action != Action.ACCEPT && action != Action.DROP && action != Action.REJECT && action != Action.RETURN) { throw new IllegalArgumentException("A literal rule's action " + "must be one of: ACCEPT, DROP, REJECT or RETURN."); } }
Source:
<code>public List<QueryResult> lookup( List<GHPoint> points, FlagEncoder encoder ) { double distanceInMeter = ghRequest.getHints().getDouble("round_trip.distance", 1000); <START> long seed = ghRequest.getHints().getLong("round_trip.seed", 0L); <END> GHPoint start = ghRequest.getPoints().get(0); TourStrategy strategy = new SinglePointTour(new Random(seed), distanceInMeter); queryResults = new ArrayList<>(2 + strategy.getNumberOfGeneratedPoints()); EdgeFilter edgeFilter = new DefaultEdgeFilter(encoder); QueryResult startQR = locationIndex.findClosest(start.lat, start.lon, edgeFilter); queryResults.add(startQR); GHPoint last = points.get(0); for (int i = 0; i < strategy.getNumberOfGeneratedPoints(); i++) { QueryResult result = generateValidPoint(last, strategy.getDistanceForIteration(i), strategy.getHeadingForIteration(i), edgeFilter); if (result == null) { ghResponse.addError(new IllegalStateException("Could not find a valid point after " + maxRetries + " tries, for the point:" + last)); return Collections.emptyList(); } last = result.getSnappedPoint(); queryResults.add(result); } queryResults.add(startQR); return queryResults; }</code><technical_language>seed all, if seed passed algorithm? generating a random seed if seed is available</technical_language>

Target:
public List<QueryResult> lookup( List<GHPoint> points, FlagEncoder encoder ) { double distanceInMeter = ghRequest.getHints().getDouble("round_trip.distance", 1000); long seed = ghRequest.getHints().getLong("round_trip.seed", 0L); if (points.isEmpty()) { ghResponse.addError(new IllegalStateException("For round trip calculation one point is required")); return Collections.emptyList(); } GHPoint start = ghRequest.getPoints().get(0); TourStrategy strategy = new SinglePointTour(new Random(seed), distanceInMeter); queryResults = new ArrayList<>(2 + strategy.getNumberOfGeneratedPoints()); EdgeFilter edgeFilter = new DefaultEdgeFilter(encoder); QueryResult startQR = locationIndex.findClosest(start.lat, start.lon, edgeFilter); queryResults.add(startQR); GHPoint last = points.get(0); for (int i = 0; i < strategy.getNumberOfGeneratedPoints(); i++) { QueryResult result = generateValidPoint(last, strategy.getDistanceForIteration(i), strategy.getHeadingForIteration(i), edgeFilter); if (result == null) { ghResponse.addError(new IllegalStateException("Could not find a valid point after " + maxRetries + " tries, for the point:" + last)); return Collections.emptyList(); } last = result.getSnappedPoint(); queryResults.add(result); } queryResults.add(startQR); return queryResults; }