auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>void resolvePluginDependencies() throws IOException { <START> List<Dependency> missingDependencies = new ArrayList<Dependency>(); <END> for (Dependency d : dependencies) { if (parent.getPlugin(d.shortName) == null) missingDependencies.add(d); } if (!missingDependencies.isEmpty()) throw new MissingDependencyException(missingDependencies); for (Dependency d : optionalDependencies) { if (parent.getPlugin(d.shortName) != null) dependencies.add(d); } }</code><technical_language>Source is 1.7 level, diamond operator</technical_language>

Target:
void resolvePluginDependencies() throws IOException { List<Dependency> missingDependencies = new ArrayList<>(); for (Dependency d : dependencies) { if (parent.getPlugin(d.shortName) == null) missingDependencies.add(d); } if (!missingDependencies.isEmpty()) throw new MissingDependencyException(this.shortName, missingDependencies); for (Dependency d : optionalDependencies) { if (parent.getPlugin(d.shortName) != null) dependencies.add(d); } }
Source:
<code>private boolean hasSunlight(Player p) { <START> World world = p.getWorld(); <END> return (world.getTime() < 12300 || world.getTime() > 23850) && p.getEyeLocation().getBlock().getLightFromSky() == 15; }</code><technical_language>check if env is end (or check default world) return 0 (also, return true in nether, sunlight supposed a "hell" thing. I do this dealers choice). This quicker block initialisation is done below</technical_language>

Target:
private boolean hasSunlight(Player p) { World world = p.getWorld(); if (world.getEnvironment() != Environment.NORMAL) { return false; } return (world.getTime() < 12300 || world.getTime() > 23850) && p.getEyeLocation().getBlock().getLightFromSky() == 15; }
Source:
<code>public static Properties getConnectionArguments(@Nullable String connectionArguments, @Nullable String user, @Nullable String password) { KeyValueListParser kvParser = new KeyValueListParser("\\s*;\\s*", "="); Map<String, String> connectionArgumentsMap = new HashMap<>(); if (!Strings.isNullOrEmpty(connectionArguments)) { for (KeyValue<String, String> keyVal : kvParser.parse(connectionArguments)) { String key = keyVal.getKey(); String val = keyVal.getValue(); <START> connectionArgumentsMap.put(key, val); <END> } } if (user != null) { connectionArgumentsMap.put("user", user); connectionArgumentsMap.put("password", password); } Properties properties = new Properties(); properties.putAll(connectionArgumentsMap); return properties; }</code><technical_language>need extract variable if in in block connectionArgumentsMap.put(keyVal.getKey(), keyVal.getValue());</technical_language>

Target:
public static Properties getConnectionArguments(@Nullable String connectionArguments, @Nullable String user, @Nullable String password) { KeyValueListParser kvParser = new KeyValueListParser("\\s*;\\s*", "="); Map<String, String> connectionArgumentsMap = new HashMap<>(); if (!Strings.isNullOrEmpty(connectionArguments)) { for (KeyValue<String, String> keyVal : kvParser.parse(connectionArguments)) { connectionArgumentsMap.put(keyVal.getKey(), keyVal.getValue()); } } if (user != null) { connectionArgumentsMap.put("user", user); connectionArgumentsMap.put("password", password); } Properties properties = new Properties(); properties.putAll(connectionArgumentsMap); return properties; }
Source:
<code>public AnalysisJobBuilder addSourceColumn(MetaModelInputColumn inputColumn) { if (!_sourceColumns.contains(inputColumn)) { _sourceColumns.add(inputColumn); <START> List<SourceColumnChangeListener> listeners = new ArrayList<>(_sourceColumnListeners); <END> for (SourceColumnChangeListener listener : listeners) { listener.onAdd(inputColumn); } } return this; }</code><technical_language>touched it, it... Final! :)</technical_language>

Target:
public AnalysisJobBuilder addSourceColumn(MetaModelInputColumn inputColumn) { if (!_sourceColumns.contains(inputColumn)) { _sourceColumns.add(inputColumn); final List<SourceColumnChangeListener> listeners = new ArrayList<>(_sourceColumnListeners); for (SourceColumnChangeListener listener : listeners) { listener.onAdd(inputColumn); } } return this; }
Source:
<code>public static int secondsToTicks(int seconds) { <START> return 20 * seconds; <END> }</code><technical_language>Put 20's in a constant, e.g. TICKS_PER_SECOND</technical_language>

Target:
public static int secondsToTicks(int seconds) { return TICKS_PER_SECOND * seconds; }
Source:
<code>public void removeContainer(final String containerId, final boolean removeVolumes) throws DockerException, InterruptedException { <START> removeContainer(containerId, RemoveContainerParam.removeVolumes()); <END> }</code><technical_language>this ignore boolean removeVolumes parameter method</technical_language>

Target:
public void removeContainer(final String containerId, final boolean removeVolumes) throws DockerException, InterruptedException { removeContainer(containerId, RemoveContainerParam.removeVolumes(removeVolumes)); }
Source:
<code>Store getStore(PartitionId id) throws StoreException { BlobStore store = stores.get(id); if (store == null) { <START> throw new StoreException("Could not find partition " + id + " on disk " + disk, <END> StoreErrorCodes.Partition_Not_Found); } if (!store.isStarted()) { throw new StoreException("Store for partition " + id + " on disk " + disk + " has not been started successfully", StoreErrorCodes.Store_Not_Started); } return store; }</code><technical_language>need throw exceptions - return null</technical_language>

Target:
Store getStore(PartitionId id) { BlobStore store = stores.get(id); return (store != null && store.isStarted()) ? store : null; }
Source:
<code>public void registerAttributes(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerReadOnlyAttribute(NAME, ReadResourceNameOperationStepHandler.INSTANCE); resourceRegistration.registerReadWriteAttribute(RELATIVE_TO, null, new PathWriteAttributeHandler(pathManager, RELATIVE_TO, services)); SimpleAttributeDefinition pathAttr = specified ? PATH_SPECIFIED : PATH_NAMED; resourceRegistration.registerReadWriteAttribute(pathAttr, null, new PathWriteAttributeHandler(pathManager, pathAttr, services)); resourceRegistration.registerReadOnlyAttribute(READ_ONLY, null); <START> PathSizeMetricHandler.registerMetric(resourceRegistration, pathManager, PATH, RELATIVE_TO); <END> }</code><technical_language>need narrow variants of of PathResourceDefinition register this, meaningful in some. For example, for meaningful for domain.xml path resources (NamedPathResourceDefinition) is a domain-wide FS location. questionable for host.xml too; e.g. a path is relative-to jboss.server.base.dir means in HC process; converted a server process means something</technical_language>

Target:
public void registerAttributes(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerReadOnlyAttribute(NAME, ReadResourceNameOperationStepHandler.INSTANCE); resourceRegistration.registerReadWriteAttribute(RELATIVE_TO, null, new PathWriteAttributeHandler(pathManager, RELATIVE_TO)); SimpleAttributeDefinition pathAttr = specified ? PATH_SPECIFIED : PATH_NAMED; resourceRegistration.registerReadWriteAttribute(pathAttr, null, new PathWriteAttributeHandler(pathManager, pathAttr)); resourceRegistration.registerReadOnlyAttribute(READ_ONLY, null); }
Source:
<code>public void add( Collection<? extends IndexEntryUpdate<?>> updates ) throws IOException, IndexEntryConflictException { Map<CoordinateReferenceSystem,List<IndexEntryUpdate<?>>> batchMap = new HashMap<>(); for ( IndexEntryUpdate<?> update : updates ) { PointValue point = (PointValue) update.values()[0]; List<IndexEntryUpdate<?>> batch = batchMap.computeIfAbsent( point.getCoordinateReferenceSystem(), k -> new ArrayList<>() ); batch.add( update ); } for ( Map.Entry<CoordinateReferenceSystem,List<IndexEntryUpdate<?>>> entry : batchMap.entrySet() ) { <START> select( entry.getKey() ).add( entry.getValue() ); <END> } }</code><technical_language>please correct if i wrong here: batch of updates try a lock select correct populator cache while is required time need populator for key. i populator accessed thread (population job itself) - local cache of selected populators, change soon created</technical_language>

Target:
public void add( Collection<? extends IndexEntryUpdate<?>> updates ) throws IOException, IndexEntryConflictException { Map<CoordinateReferenceSystem,List<IndexEntryUpdate<?>>> batchMap = new HashMap<>(); for ( IndexEntryUpdate<?> update : updates ) { PointValue point = (PointValue) update.values()[0]; List<IndexEntryUpdate<?>> batch = batchMap.computeIfAbsent( point.getCoordinateReferenceSystem(), k -> new ArrayList<>() ); batch.add( update ); } for ( Map.Entry<CoordinateReferenceSystem,List<IndexEntryUpdate<?>>> entry : batchMap.entrySet() ) { PartPopulator partPopulator = select( entry.getKey() ); partPopulator.add( entry.getValue() ); } }
Source:
<code>public void uri() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels"); MockHttpServletResponse response = new MockHttpServletResponse(); request.setQueryString("booking=42"); FilterChain filterChain = new NoOpFilterChain(); filter.doFilter(request, response, filterChain); assertThat(filter.beforeRequestMessage).isNotNull(); <START> assertThat(filter.beforeRequestMessage.contains("/hotel")).isTrue(); <END> assertThat(filter.beforeRequestMessage.contains("booking=42")).isFalse(); assertThat(filter.afterRequestMessage).isNotNull(); assertThat(filter.afterRequestMessage.contains("/hotel")).isTrue(); assertThat(filter.afterRequestMessage.contains("booking=42")).isFalse(); }</code><technical_language>suggestion assertThat(filter.beforeRequestMessage).contains("/hotel"); This is analogous aforementioned .startsWith() change. Please apply affected methods</technical_language>

Target:
public void uri() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels"); MockHttpServletResponse response = new MockHttpServletResponse(); request.setQueryString("booking=42"); FilterChain filterChain = new NoOpFilterChain(); filter.doFilter(request, response, filterChain); assertThat(filter.beforeRequestMessage).contains("/hotel"); assertThat(filter.beforeRequestMessage).doesNotContain("booking=42"); assertThat(filter.afterRequestMessage).contains("/hotel"); assertThat(filter.afterRequestMessage).doesNotContain("booking=42"); }
Source:
<code>private HttpRequest signSAS(String method, String container, String name, @Nullable GetOptions options, long expires, @Nullable Long contentLength, @Nullable String contentType) { checkNotNull(method, "method"); checkNotNull(container, "container"); checkNotNull(name, "name"); String nowString = timeStampProvider.get(); Date now = dateService.rfc1123DateParse(nowString); Date expiration = new Date(now.getTime() + TimeUnit.SECONDS.toMillis(expires)); String iso8601 = dateService.iso8601SecondsDateFormat(expiration); String signedPermission; if (method.equals("PUT")) { signedPermission = "w"; } else if (method.equals("DELETE")) { signedPermission = "d"; } else { signedPermission = "r"; } HttpRequest.Builder request = HttpRequest.builder() .method(method) .endpoint(Uris.uriBuilder(storageUrl).appendPath(container).appendPath(name).query(this.credential).build()) .replaceHeader(HttpHeaders.DATE, nowString); if (contentLength != null) { request.replaceHeader(HttpHeaders.CONTENT_LENGTH, contentLength.toString()); } if (contentType != null) { request.replaceHeader("x-ms-blob-content-type", contentType); } if (options != null) { request.headers(options.buildRequestHeaders()); } if (method.equals("PUT")) { request.replaceHeader("x-ms-blob-type", "BlockBlob"); } HttpRequest req = request.build(); return req; <START> } <END></code><technical_language>of this method is a copy of existing one. Break original in reusable methods reuse code</technical_language>

Target:
private HttpRequest signSAS(String method, String container, String name, @Nullable GetOptions options, long expires, @Nullable Long contentLength, @Nullable String contentType) { checkNotNull(method, "method"); checkNotNull(container, "container"); checkNotNull(name, "name"); String nowString = timeStampProvider.get(); HttpRequest.Builder request = HttpRequest.builder() .method(method) .endpoint(Uris.uriBuilder(storageUrl).appendPath(container).appendPath(name).query(this.credential).build()) .replaceHeader(HttpHeaders.DATE, nowString); request = setHeaders(request, method, options, contentLength, contentType); return request.build(); }
Source:
<code>public List<ArtifactResult> getArtifactsWithDep(String dependency, Collection<String> excludes) throws RepositoryException { Artifact artifact = new DefaultArtifact(dependency); DependencyFilter classpathFilter = DependencyFilterUtils.classpathFilter(JavaScopes.COMPILE); PatternExclusionsDependencyFilter exclusionFilter = new PatternExclusionsDependencyFilter(excludes); CollectRequest collectRequest = new CollectRequest(); collectRequest.setRoot(new Dependency(artifact, JavaScopes.COMPILE)); synchronized (repos) { for (RemoteRepository repo : repos) { collectRequest.addRepository(repo); } } DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, DependencyFilterUtils.andFilter(exclusionFilter, classpathFilter)); try { return system.resolveDependencies(session, dependencyRequest).getArtifactResults(); <START> } catch (Exception ex) { <END> throw new RepositoryException( String.format("Cannot fetch dependencies for %s", dependency), ex); } }</code><technical_language>NPE? Exception cache more exception types</technical_language>

Target:
public List<ArtifactResult> getArtifactsWithDep(String dependency, Collection<String> excludes) throws RepositoryException { Artifact artifact = new DefaultArtifact(dependency); DependencyFilter classpathFilter = DependencyFilterUtils.classpathFilter(JavaScopes.COMPILE); PatternExclusionsDependencyFilter exclusionFilter = new PatternExclusionsDependencyFilter(excludes); CollectRequest collectRequest = new CollectRequest(); collectRequest.setRoot(new Dependency(artifact, JavaScopes.COMPILE)); synchronized (repos) { for (RemoteRepository repo : repos) { collectRequest.addRepository(repo); } } DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, DependencyFilterUtils.andFilter(exclusionFilter, classpathFilter)); try { return system.resolveDependencies(session, dependencyRequest).getArtifactResults(); } catch (NullPointerException | DependencyResolutionException ex) { throw new RepositoryException( String.format("Cannot fetch dependencies for %s", dependency), ex); } }
Source:
<code>public int compareTo(@Nullable ITmfStateValue object) { if (object == null) { return 1; } int result = 0; switch (object.getType()) { case INTEGER: double otherDoubleValue = ((IntegerStateValue) object).unboxInt(); <START> result = Double.compare(this.value, otherDoubleValue); <END> break; case DOUBLE: otherDoubleValue = ((DoubleStateValue) object).unboxDouble(); result = Double.compare(this.value, otherDoubleValue); break; case LONG: otherDoubleValue = ((LongStateValue) object).unboxLong(); result = Double.compare(this.value, otherDoubleValue); break; case NULL: result = 1; break; case STRING: result = -1; break; default: break; } return result; }</code><technical_language>do return Double.compare(...) here, need for 'result' variable (this avoids needing break's too)</technical_language>

Target:
public int compareTo(@Nullable ITmfStateValue object) { if (object == null) { throw new StateValueTypeException("A Double state value cannot be compared to null."); } switch (object.getType()) { case INTEGER: double otherDoubleValue = ((IntegerStateValue) object).unboxInt(); return Double.compare(this.value, otherDoubleValue); case DOUBLE: otherDoubleValue = ((DoubleStateValue) object).unboxDouble(); return Double.compare(this.value, otherDoubleValue); case LONG: otherDoubleValue = ((LongStateValue) object).unboxLong(); return Double.compare(this.value, otherDoubleValue); case NULL: return 1; case STRING: throw new StateValueTypeException("A Double state value cannot be compared to a String state value."); default: return 0; } }
Source:
<code>private static boolean hasIrregularPattern(String literalValue) { List<String> groups = Arrays.asList(cleanup(literalValue).split("_")); return groups.size() > 1 <START> && groups.subList(1, groups.size()).stream() <END> .map(String::length) .distinct() .count() != 1; }</code><technical_language>group if length is other groups, i.e. 10000_000_000 noncompliant IMO. Other minor detail: skip instead of subList more concise streams</technical_language>

Target:
private static boolean hasIrregularPattern(String literalValue) { List<String> groups = Arrays.asList(cleanup(literalValue).split("_")); if (groups.size() <= 1) { return false; } int firstGroupLength = groups.get(0).length(); List<Integer> lengths = groups.stream().skip(1).map(String::length).distinct().collect(Collectors.toList()); return lengths.size() != 1 || lengths.get(0) < firstGroupLength; }
Source:
<code>public void testCherryPickMerge() throws Exception { Git git = new Git(db); commitFile("file", "1\n2\n3\n", "master"); commitFile("file", "1\n2\n3\n", "side"); checkoutBranch("refs/heads/side"); RevCommit commitD = commitFile("file", "1\n2\n3\n4\n5\n", "side2"); commitFile("file", "a\n2\n3\n", "side"); MergeResult mergeResult = git.merge().include(commitD).call(); ObjectId commitM = mergeResult.getNewHead(); checkoutBranch("refs/heads/master"); RevCommit commitT = commitFile("another", "t", "master"); try { git.cherryPick().include(commitM).call(); fail("merges should not be cherry-picked by default"); <START> } catch (GitAPIException e) { <END> } try { git.cherryPick().include(commitM).setMainlineParentNumber(3).call(); fail("specifying a non-existent parent should fail"); } catch (Exception e) { } CherryPickResult result = git.cherryPick().include(commitM) .setMainlineParentNumber(1).call(); assertEquals(CherryPickStatus.OK, result.getStatus()); checkFile(new File(db.getWorkTree(), "file"), "1\n2\n3\n4\n5\n"); git.reset().setMode(ResetType.HARD).setRef(commitT.getName()).call(); result = git.cherryPick().include(commitM).setMainlineParentNumber(2) .call(); assertEquals(CherryPickStatus.OK, result.getStatus()); checkFile(new File(db.getWorkTree(), "file"), "a\n2\n3\n"); }</code><technical_language>Try more specific. is common catch wrong exception. GitAPIException anything</technical_language>

Target:
public void testCherryPickMerge() throws Exception { Git git = new Git(db); commitFile("file", "1\n2\n3\n", "master"); commitFile("file", "1\n2\n3\n", "side"); checkoutBranch("refs/heads/side"); RevCommit commitD = commitFile("file", "1\n2\n3\n4\n5\n", "side2"); commitFile("file", "a\n2\n3\n", "side"); MergeResult mergeResult = git.merge().include(commitD).call(); ObjectId commitM = mergeResult.getNewHead(); checkoutBranch("refs/heads/master"); RevCommit commitT = commitFile("another", "t", "master"); try { git.cherryPick().include(commitM).call(); fail("merges should not be cherry-picked by default"); } catch (MultipleParentsNotAllowedException e) { } try { git.cherryPick().include(commitM).setMainlineParentNumber(3).call(); fail("specifying a non-existent parent should fail"); } catch (JGitInternalException e) { assertTrue(e.getMessage().endsWith( "does not have a parent number 3.")); } CherryPickResult result = git.cherryPick().include(commitM) .setMainlineParentNumber(1).call(); assertEquals(CherryPickStatus.OK, result.getStatus()); checkFile(new File(db.getWorkTree(), "file"), "1\n2\n3\n4\n5\n"); git.reset().setMode(ResetType.HARD).setRef(commitT.getName()).call(); CherryPickResult result2 = git.cherryPick().include(commitM) .setMainlineParentNumber(2).call(); assertEquals(CherryPickStatus.OK, result2.getStatus()); checkFile(new File(db.getWorkTree(), "file"), "a\n2\n3\n"); }
Source:
<code>private static @Nullable List<String> getOutputFromCommand(List<String> command) { try { Path tempFile = Files.createTempFile("output", null); ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); builder.redirectOutput(Redirect.to(tempFile.toFile())); Process p = builder.start(); int ret = p.waitFor(); <START> List<String> lines = checkNotNull(Files.readAllLines(tempFile, Charset.defaultCharset())); <END> Files.delete(tempFile); return (ret == 0 ? lines : null); } catch (IOException | InterruptedException e) { return null; } }</code><technical_language>stdout = new BufferedReader(new InputStreamReader(p.getInputStream())); stolen Addr2line..</technical_language>

Target:
private static @Nullable List<String> getOutputFromCommand(List<String> command) { try { ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); Process p = builder.start(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); int ret = p.waitFor(); List<String> lines = br.lines().collect(Collectors.toList()); return (ret == 0 ? lines : null); } catch (IOException | InterruptedException e) { return null; } }
Source:
<code>public Map<String, Map.Entry<String, URI>> getParticipants() { try (BatchContext context = this.batcher.resumeBatch(this.batch)) { Sessions<String, Map.Entry<String, URI>> sessions = this.sso.getSessions(); Map<String, Map.Entry<String, URI>> map = new HashMap<>(); for (String deployment : sessions.getDeployments()) { <START> if (map.put(deployment, sessions.getSession(deployment)) != null) { <END> throw new IllegalStateException("Duplicate key"); } } return Collections.unmodifiableMap(map); } }</code><technical_language>Remove this conditional + exception. Uniqueness is guaranteed here</technical_language>

Target:
public Map<String, Map.Entry<String, URI>> getParticipants() { try (BatchContext context = this.batcher.resumeBatch(this.batch)) { Sessions<String, Map.Entry<String, URI>> sessions = this.sso.getSessions(); Map<String, Map.Entry<String, URI>> map = new HashMap<>(); for (String deployment : sessions.getDeployments()) { map.put(deployment, sessions.getSession(deployment)); } return Collections.unmodifiableMap(map); } }
Source:
<code>public static DataType<?> guessType(Object value) { if (value == null) { return UNDEFINED; } else if (value instanceof Map) { return UNTYPED_OBJECT; } else if (value instanceof List) { return valueFromList((List) value); } else if (value.getClass().isArray()) { return valueFromList(Arrays.asList((Object[]) value)); <START> } else if (value instanceof StringType) { return STRING; <END> } return POJO_TYPE_MAPPING.get(value.getClass()); }</code><technical_language>sense add a String.class entry POJO_TYPE_MAPPING instead</technical_language>

Target:
public static DataType<?> guessType(Object value) { if (value == null) { return UNDEFINED; } else if (value instanceof Map) { return UNTYPED_OBJECT; } else if (value instanceof List) { return valueFromList((List) value); } else if (value.getClass().isArray()) { return valueFromList(Arrays.asList((Object[]) value)); } return POJO_TYPE_MAPPING.get(value.getClass()); }
Source:
<code>protected void verifyEmailSent(String email, String subject) { <START> if (!TestProperties.INCLUDE_EMAIL_VERIFICATION) { <END> return; } if (!TestProperties.TEST_EMAIL.equals(email)) { fail("Email verification is allowed only on preset test email."); } EmailAccount emailAccount = new EmailAccount(email); try { emailAccount.getUserAuthenticated(); int retryLimit = 5; boolean actual = emailAccount.isEmailWithSubjectPresent(subject); while (!actual && retryLimit > 0) { retryLimit--; ThreadHelper.waitFor(1000); actual = emailAccount.isEmailWithSubjectPresent(subject); } assertTrue(actual); } catch (Exception e) { fail("Failed to verify email sent:" + e); } }</code><technical_language>TestProperties.isDevServer() is another hard requirement. condition is a dev server is explicitly requested verify emails</technical_language>

Target:
protected void verifyEmailSent(String email, String subject) { if (TestProperties.isDevServer() || !TestProperties.INCLUDE_EMAIL_VERIFICATION) { return; } if (!TestProperties.TEST_EMAIL.equals(email)) { fail("Email verification is allowed only on preset test email."); } EmailAccount emailAccount = new EmailAccount(email); try { emailAccount.getUserAuthenticated(); int retryLimit = 5; boolean actual = emailAccount.isRecentEmailWithSubjectPresent(subject, TestProperties.TEST_SENDER_EMAIL); while (!actual && retryLimit > 0) { retryLimit--; ThreadHelper.waitFor(1000); actual = emailAccount.isRecentEmailWithSubjectPresent(subject, TestProperties.TEST_SENDER_EMAIL); } assertTrue(actual); } catch (Exception e) { fail("Failed to verify email sent:" + e); } }
Source:
<code>private void showMainWindow(String repoId) { <START> boolean shouldCreateSampleBoard = logic.getStoredRepos().size() == 0; <END> logic.openPrimaryRepository(repoId); logic.setDefaultRepo(repoId); repoSelector.setText(repoId); triggerEvent(new PrimaryRepoChangedEvent(repoId)); triggerEvent(new BoardSavedEvent()); if (TestController.isTestMode()) { if (TestController.isTestChromeDriver()) { browserComponent = new BrowserComponent(this, true); browserComponent.initialise(); } else { browserComponent = new BrowserComponentStub(this); } } else { browserComponent = new BrowserComponent(this, false); browserComponent.initialise(); } setExpandedWidth(false); panels.init(guiController, panelsScrollPane); ensureSelectedPanelHasFocus(); initialisePickers(); if (shouldCreateSampleBoard && (!TestController.isTestMode() || TestController.isTestStartupBoard())){ launchSampleBoard(); } }</code><technical_language>logic.getStoredRepos().isEmpty()</technical_language>

Target:
private void showMainWindow(String repoId) { boolean isAFirstTimeUser = logic.getStoredRepos().isEmpty(); logic.openPrimaryRepository(repoId); logic.setDefaultRepo(repoId); repoSelector.setText(repoId); triggerEvent(new PrimaryRepoChangedEvent(repoId)); triggerEvent(new BoardSavedEvent()); if (TestController.isTestMode()) { if (TestController.isTestChromeDriver()) { browserComponent = new BrowserComponent(this, true); browserComponent.initialise(); } else { browserComponent = new BrowserComponentStub(this); } } else { browserComponent = new BrowserComponent(this, false); browserComponent.initialise(); } setExpandedWidth(false); panels.init(guiController, panelsScrollPane); ensureSelectedPanelHasFocus(); initialisePickers(); if (isAFirstTimeUser && TestController.shouldOpenSampleBoard()){ createAndLoadSampleBoard(); } }
Source:
<code>public void testTranslateStreamTableJoinWithoutJoinOperator() { Map<String, String> config = SamzaSqlTestConfig.fetchStaticConfigsWithFactories(configs, 1); String sql = "Insert into testavro.enrichedPageViewTopic" + " select p.name as profileName, pv.pageKey" + " from testavro.PAGEVIEW as pv, testavro.PROFILE.`$table` as p" + " where p.id = pv.profileId"; config.put(SamzaSqlApplicationConfig.CFG_SQL_STMT, sql); Config samzaConfig = SamzaSqlApplicationRunner.computeSamzaConfigs(true, new MapConfig(config)); SamzaSqlApplicationConfig samzaSqlApplicationConfig = new SamzaSqlApplicationConfig(new MapConfig(config)); QueryTranslator translator = new QueryTranslator(samzaSqlApplicationConfig); SamzaSqlQueryParser.QueryInfo queryInfo = samzaSqlApplicationConfig.getQueryInfo().get(0); <START> StreamAppDescriptorImpl mockSpec = spy(new StreamAppDescriptorImpl(appDesc -> { }, samzaConfig)); <END> translator.translate(queryInfo, mockSpec); }</code><technical_language>this need a spy if mocking else</technical_language>

Target:
public void testTranslateStreamTableJoinWithoutJoinOperator() { Map<String, String> config = SamzaSqlTestConfig.fetchStaticConfigsWithFactories(configs, 1); String sql = "Insert into testavro.enrichedPageViewTopic" + " select p.name as profileName, pv.pageKey" + " from testavro.PAGEVIEW as pv, testavro.PROFILE.`$table` as p" + " where p.id = pv.profileId"; config.put(SamzaSqlApplicationConfig.CFG_SQL_STMT, sql); Config samzaConfig = SamzaSqlApplicationRunner.computeSamzaConfigs(true, new MapConfig(config)); SamzaSqlApplicationConfig samzaSqlApplicationConfig = new SamzaSqlApplicationConfig(new MapConfig(config)); QueryTranslator translator = new QueryTranslator(samzaSqlApplicationConfig); SamzaSqlQueryParser.QueryInfo queryInfo = samzaSqlApplicationConfig.getQueryInfo().get(0); StreamApplicationDescriptorImpl streamAppDesc = new StreamApplicationDescriptorImpl(appDesc -> { }, samzaConfig); translator.translate(queryInfo, streamAppDesc); }
Source:
<code>private void sendMessageForFeedEntry(String url, SyndEntry entry, String regex) { Map<String, Object> parameters = new HashMap<>(); Map<String, Object> rawContent = new HashMap<>(); Map<String, Object> extractedContent = new HashMap<>(); parameters.put("url", url); parameters.put("published_date", entry.getPublishedDate()); parameters.put("updated_date", entry.getUpdatedDate()); if (entry.getContents() != null) { Integer index = 1; for (SyndContent content : entry.getContents()) { rawContent.put(index.toString(), content.getValue()); String extractedContentString = extractContent(content.getValue(), regex); <START> if (!StringUtils.isBlank(extractedContentString)) { <END> extractedContent.put(index.toString(), extractedContentString); } index++; } } else { LOGGER.warn("NULL content for entry {}", entry.getUri()); } parameters.put("raw_content", rawContent); parameters.put("extracted_content", extractedContent); MotechEvent event = new MotechEvent(Constants.FEED_CHANGE_MESSAGE, parameters); LOGGER.debug("sending message {}", event); eventRelay.sendEventMessage(event); }</code><technical_language>isNotBlank</technical_language>

Target:
private void sendMessageForFeedEntry(String url, SyndEntry entry, String regex) { Map<String, Object> parameters = new HashMap<>(); Map<String, Object> rawContent = new HashMap<>(); Map<String, Object> extractedContent = new HashMap<>(); parameters.put("url", url); parameters.put("published_date", entry.getPublishedDate()); parameters.put("updated_date", entry.getUpdatedDate()); if (entry.getContents() != null) { Integer index = 1; for (SyndContent content : entry.getContents()) { rawContent.put(index.toString(), content.getValue()); String extractedContentString = extractContent(content.getValue(), regex); if (StringUtils.isNotBlank(extractedContentString)) { extractedContent.put(index.toString(), extractedContentString); } index++; } } else { LOGGER.warn("NULL content for entry {}", entry.getUri()); } parameters.put("raw_content", rawContent); parameters.put("extracted_content", extractedContent); MotechEvent event = new MotechEvent(Constants.FEED_CHANGE_MESSAGE, parameters); LOGGER.debug("sending message {}", event); eventRelay.sendEventMessage(event); }
Source:
<code>List<StoreKey> getSuccessfullyPutChunkIds() { return indexToChunkIds.values().stream().map(b -> b.getFirst()).collect( <START> Collectors.toList()); <END> }</code><technical_language>Please format here. method reference simplify: indexToChunkIds.values().stream().map(Pair::getFirst).collect(Collectors.toList())</technical_language>

Target:
List<StoreKey> getSuccessfullyPutChunkIds() { return indexToChunkIdsAndChunkSizes.values().stream().map(Pair::getFirst).collect(Collectors.toList()); }
Source:
<code>public void cancelAllManagementCalls() { InterruptedException stopper = new InterruptedException(); while (!managementCallAnswers.isEmpty()) { <START> managementCallAnswers.forEach((k, v) -> { <END> CompletableFuture<ContextualReturn<?>> removed = managementCallAnswers.remove(k); if (removed != null) { removed.completeExceptionally(stopper); } }); } }</code><technical_language>iterate keyset, instead of entrySet : managementCallAnswers.keys().foreach</technical_language>

Target:
public void cancelAllManagementCalls() { InterruptedException stopper = new InterruptedException(); while (!managementCallAnswers.isEmpty()) { managementCallAnswers.keySet().forEach(k -> { CompletableFuture<ContextualReturn<?>> removed = managementCallAnswers.remove(k); if (removed != null) { removed.completeExceptionally(stopper); } }); } }
Source:
<code>public long next() throws IOException { long result; if (used == numInRun) { readHeader(); } if (repeat) { <START> result = repeatBase + (used) * delta; <END> } else { result = input.readVarint(signed); } used++; return result; }</code><technical_language>remove (): * delta</technical_language>

Target:
public long next() throws IOException { long result; if (used == numValuesInRun) { readHeader(); } if (repeat) { result = repeatBase + used * delta; } else { result = input.readVarint(signed); } used++; return result; }
Source:
<code>public void addAdditionalRefs(final Repository repo) throws IOException { for (Ref ref : repo.getRefDatabase().getAdditionalRefs()) { Set<Ref> set = reverseRefMap.get(ref.getObjectId()); <START> if (set == null) { <END> set = Collections.singleton(ref); } else { set = new HashSet<Ref>(set); set.add(ref); } reverseRefMap.put(ref.getObjectId(), set); } }</code><technical_language>style nit: braces single line blocks</technical_language>

Target:
public void addAdditionalRefs(final Repository repo) throws IOException { for (Ref ref : repo.getRefDatabase().getAdditionalRefs()) { Set<Ref> set = reverseRefMap.get(ref.getObjectId()); if (set == null) set = Collections.singleton(ref); else { set = new HashSet<Ref>(set); set.add(ref); } reverseRefMap.put(ref.getObjectId(), set); } }
Source:
<code>public Object getValueAt(int row, int col) { Transaction transaction = getTransaction(row); Money amount = transaction.getAmount(); Money balance = Money.zero(); for(int i = 0; i <= row; i++) { balance = balance.plus(getTransaction(i).getAmount()); } if(col == COL_CATEGORY) { return transaction.getCategoryName(); } if(col == COL_DESC) { return transaction.getDescription(); } if(col == COL_DEBIT) { if(amount.isNegative()) { <START> return amount.multipliedBy(-1).toAmountAndSymbolString(); <END> } else { return ""; } } if(col == COL_CREDIT) { if(amount.isPositive()) { return amount.toAmountAndSymbolString(); } else { return ""; } } if(col == COL_BALANCE) { return balance.toAmountAndSymbolString(); } if(col == COL_DATE) { SimpleDateFormat shortDateFormat = new SimpleDateFormat("MM/dd/yyyy"); return shortDateFormat.format(transaction.getDate()); } return "?"; }</code><technical_language>if a getAbsoluteAmount() nicer</technical_language>

Target:
public Object getValueAt(int row, int col) { Transaction transaction = getTransaction(row); Money amount = transaction.getAmount(); Money balance = Money.zero(); for(int i = 0; i <= row; i++) { balance = balance.plus(getTransaction(i).getAmount()); } if(col == COL_CATEGORY) { return transaction.getCategoryName(); } if(col == COL_DESC) { return transaction.getDescription(); } if(col == COL_DEBIT) { if(amount.isNegative()) { return amount.absolute().toAmountAndSymbolString(); } else { return ""; } } if(col == COL_CREDIT) { if(amount.isPositive()) { return amount.toAmountAndSymbolString(); } else { return ""; } } if(col == COL_BALANCE) { return balance.toAmountAndSymbolString(); } if(col == COL_DATE) { SimpleDateFormat shortDateFormat = new SimpleDateFormat("MM/dd/yyyy"); return shortDateFormat.format(transaction.getDate()); } return "?"; }
Source:
<code>public void shouldPerformBoostOperation() { List<IndexQuery> indexQueries = new ArrayList<>(); String documentId = randomNumeric(5); SampleEntity sampleEntity1 = new SampleEntity(); sampleEntity1.setId(documentId); sampleEntity1.setRate(700); sampleEntity1.setMessage("bar foo"); sampleEntity1.setVersion(System.currentTimeMillis()); IndexQuery indexQuery1 = new IndexQuery(); indexQuery1.setId(documentId); indexQuery1.setObject(sampleEntity1); indexQueries.add(indexQuery1); String documentId2 = randomNumeric(5); SampleEntity sampleEntity2 = new SampleEntity(); sampleEntity2.setId(documentId2); sampleEntity2.setRate(800); sampleEntity2.setMessage("foo"); sampleEntity2.setVersion(System.currentTimeMillis()); IndexQuery indexQuery2 = new IndexQuery(); indexQuery2.setId(documentId2); indexQuery2.setObject(sampleEntity2); indexQueries.add(indexQuery2); operations.bulkIndex(indexQueries, index); operations.refresh(SampleEntity.class); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("foo").boost(1)); <START> Page<SearchHit<SampleEntity>> page = operations.queryForPage(criteriaQuery, SampleEntity.class, index); <END> assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1); }</code><technical_language>sense introduce a SearchPage type avoid deep generic parametrization</technical_language>

Target:
public void shouldPerformBoostOperation() { List<IndexQuery> indexQueries = new ArrayList<>(); String documentId = randomNumeric(5); SampleEntity sampleEntity1 = new SampleEntity(); sampleEntity1.setId(documentId); sampleEntity1.setRate(700); sampleEntity1.setMessage("bar foo"); sampleEntity1.setVersion(System.currentTimeMillis()); IndexQuery indexQuery1 = new IndexQuery(); indexQuery1.setId(documentId); indexQuery1.setObject(sampleEntity1); indexQueries.add(indexQuery1); String documentId2 = randomNumeric(5); SampleEntity sampleEntity2 = new SampleEntity(); sampleEntity2.setId(documentId2); sampleEntity2.setRate(800); sampleEntity2.setMessage("foo"); sampleEntity2.setVersion(System.currentTimeMillis()); IndexQuery indexQuery2 = new IndexQuery(); indexQuery2.setId(documentId2); indexQuery2.setObject(sampleEntity2); indexQueries.add(indexQuery2); operations.bulkIndex(indexQueries, index); operations.refresh(SampleEntity.class); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("foo").boost(1)); Page<SearchHit<SampleEntity>> page = operations.searchForPage(criteriaQuery, SampleEntity.class, index); assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1); }
Source:
<code>public void clickTemplateModalButton() { <START> scrollElementToCenterAndClick(addTemplateModalLoadButton); <END> }</code><technical_language>find <li> id click it</technical_language>

Target:
public void clickTemplateModalButton() { addTemplateModalLoadButton.click(); }
Source:
<code>public void testResolvePutsOnly() { Operation<Long, String> expected = new PutOperation<>(1L, "Matthew", 0L); Chain chain = getChainFromOperations( new PutOperation<>(1L, "Albin", 0L), <START> new PutOperation<>(1L, "Suresh", 0L), <END> new PutOperation<>(1L, "Matthew", 0L)); ChainResolver<Long, String> resolver = createChainResolver(ExpiryPolicyBuilder.noExpiration()); ResolvedChain<Long, String> resolvedChain = resolver.resolve(chain, 1L, 0L); Result<Long, String> result = resolvedChain.getResolvedResult(1L); assertEquals(expected, result); assertThat(resolvedChain.isCompacted(), is(true)); assertThat(resolvedChain.getCompactionCount(), is(2)); }</code><technical_language>other tests, this test compose chain expected</technical_language>

Target:
public void testResolvePutsOnly() { Operation<Long, String> expected = new PutOperation<>(1L, "Matthew", 0L); Chain chain = getChainFromOperations( new PutOperation<>(1L, "Albin", 0L), new PutOperation<>(1L, "Suresh", 0L), expected); ChainResolver<Long, String> resolver = createChainResolver(ExpiryPolicyBuilder.noExpiration()); ResolvedChain<Long, String> resolvedChain = resolver.resolve(chain, 1L, 0L); Result<Long, String> result = resolvedChain.getResolvedResult(1L); assertEquals(expected, result); assertThat(resolvedChain.isCompacted(), is(true)); assertThat(resolvedChain.getCompactionCount(), is(2)); }
Source:
<code>public void toString_customMethod() { realm.beginTransaction(); CustomMethods cm = realm.createObject(CustomMethods.class); cm.setName("Foo"); realm.commitTransaction(); <START> String expected = "custom toString"; <END> assertEquals(expected, cm.toString()); }</code><technical_language>move this a constant in CustomMethods class</technical_language>

Target:
public void toString_customMethod() { realm.beginTransaction(); CustomMethods cm = realm.createObject(CustomMethods.class); cm.setName("Foo"); realm.commitTransaction(); String expected = CustomMethods.CUSTOM_TO_STRING; assertEquals(expected, cm.toString()); }
Source:
<code><T> Optional<ConnectionHandler<T>> getConnectionHandler(T connection) { <START> lock.lock(); <END> try { return ofNullable(connections.get(new Reference<>(connection))).map(c -> (ConnectionHandler<T>) (((Pair) c).getSecond())); } finally { lock.unlock(); } }</code><technical_language>ConcurrentUtils.withLock()</technical_language>

Target:
<T> Optional<ConnectionHandler<T>> getConnectionHandler(T connection) { return ofNullable(connections.getIfPresent(new Reference<>(connection))) .map(c -> (ConnectionHandler<T>) (((Pair) c).getSecond())); }
Source:
<code>public static Configuration propagateAccountOptions( Configuration source, String accountName) throws IOException { if (StringUtils.isEmpty(accountName)) { <START> throw new IOException("Account name cannot be empty"); <END> } final String accountPrefix = AZURE_AD_ACCOUNT_PREFIX + accountName +'.'; LOG.debug("Propagating entries under {}", accountPrefix); final Configuration dest = new Configuration(source); for (Map.Entry<String, String> entry : source) { final String key = entry.getKey(); final String value = entry.getValue(); if (!key.startsWith(accountPrefix) || accountPrefix.equals(key)) { continue; } final String stripped = key.substring(accountPrefix.length()); String origin = "[" + StringUtils.join( source.getPropertySources(key), ", ") +"]"; final String generic = AZURE_AD_PREFIX + stripped; LOG.debug("Updating from {}", generic, origin); dest.set(generic, value, key + " via " + origin); } return dest; }</code><technical_language>generally happy {{Precondition.checkArgument()}} here, raises IllegalArgumentException. that, tests for specific exception</technical_language>

Target:
public static Configuration propagateAccountOptions(Configuration source, String accountName) { Preconditions.checkArgument(StringUtils.isNotEmpty(accountName), "accountName"); final String accountPrefix = AZURE_AD_ACCOUNT_PREFIX + accountName +'.'; LOG.debug("Propagating entries under {}", accountPrefix); final Configuration dest = new Configuration(source); for (Map.Entry<String, String> entry : source) { final String key = entry.getKey(); final String value = entry.getValue(); if (!key.startsWith(accountPrefix) || accountPrefix.equals(key)) { continue; } final String stripped = key.substring(accountPrefix.length()); String origin = "[" + StringUtils.join( source.getPropertySources(key), ", ") +"]"; final String generic = AZURE_AD_PREFIX + stripped; LOG.debug("Updating from {}", generic, origin); dest.set(generic, value, key + " via " + origin); } return dest; }
Source:
<code>public void onMatch(RelOptRuleCall call) { final Join join = call.rel(0); final Union unionRel; RelNode otherInput; boolean unionOnLeft; if (call.rel(1) instanceof Union) { unionRel = call.rel(1); otherInput = call.rel(2); unionOnLeft = true; } else { otherInput = call.rel(1); unionRel = call.rel(2); unionOnLeft = false; } if (!unionRel.all) { return; } if (!join.getVariablesSet().isEmpty()) { return; } if (unionOnLeft) { if (join.getJoinType().generatesNullsOnLeft()) { return; } } else { if (join.getJoinType().generatesNullsOnRight() <START> || join.getJoinType() == JoinRelType.ANTI) { <END> return; } } List<RelNode> newUnionInputs = new ArrayList<>(); for (RelNode input : unionRel.getInputs()) { RelNode joinLeft; RelNode joinRight; if (unionOnLeft) { joinLeft = input; joinRight = otherInput; } else { joinLeft = otherInput; joinRight = input; } newUnionInputs.add( join.copy( join.getTraitSet(), join.getCondition(), joinLeft, joinRight, join.getJoinType(), join.isSemiJoinDone())); } final SetOp newUnionRel = unionRel.copy(unionRel.getTraitSet(), newUnionInputs, true); call.transformTo(newUnionRel); }</code><technical_language>sense</technical_language>

Target:
public void onMatch(RelOptRuleCall call) { final Join join = call.rel(0); final Union unionRel; RelNode otherInput; boolean unionOnLeft; if (call.rel(1) instanceof Union) { unionRel = call.rel(1); otherInput = call.rel(2); unionOnLeft = true; } else { otherInput = call.rel(1); unionRel = call.rel(2); unionOnLeft = false; } if (!unionRel.all) { return; } if (!join.getVariablesSet().isEmpty()) { return; } if (unionOnLeft) { if (join.getJoinType().generatesNullsOnLeft()) { return; } } else { if (join.getJoinType().generatesNullsOnRight() || !join.getJoinType().projectsRight()) { return; } } List<RelNode> newUnionInputs = new ArrayList<>(); for (RelNode input : unionRel.getInputs()) { RelNode joinLeft; RelNode joinRight; if (unionOnLeft) { joinLeft = input; joinRight = otherInput; } else { joinLeft = otherInput; joinRight = input; } newUnionInputs.add( join.copy( join.getTraitSet(), join.getCondition(), joinLeft, joinRight, join.getJoinType(), join.isSemiJoinDone())); } final SetOp newUnionRel = unionRel.copy(unionRel.getTraitSet(), newUnionInputs, true); call.transformTo(newUnionRel); }
Source:
<code>public static String uncompress(ByteString data) { try { <START> if (data == null || data.length() == 0) { <END> return null; } InflaterInputStream inflaterStream = new InflaterInputStream( new ByteArrayInputStream(data.getBytes(), 4, data.length())); return IOUtils.toString(inflaterStream); } catch (IOException e) { return null; } }</code><technical_language>For data.length==0, is empty string</technical_language>

Target:
public static String uncompress(ByteString data) { try { if (data == null) { return null; } else if (data.length() == 0) { return ""; } InflaterInputStream inflaterStream = new InflaterInputStream( new ByteArrayInputStream(data.getBytes(), 4, data.length())); return IOUtils.toString(inflaterStream); } catch (IOException e) { return null; } }
Source:
<code>public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().setHeader(SYNC_TOKEN, getSyncTokenHeader()); return next.process().flatMap(httpResponse -> { final String syncTokenValue = httpResponse.getHeaders().getValue(SYNC_TOKEN); if (syncTokenValue == null) { return Mono.just(httpResponse); } final String[] syncTokens = syncTokenValue.split(","); for (final String syncTokenStr : syncTokens) { final SyncToken syncToken = new SyncToken().fromSyncTokenString(syncTokenStr); <START> if (syncToken == null) { return Mono.just(httpResponse); } <END> final String tokenId = syncToken.getId(); final long tokenSequenceNumber = syncToken.getSequenceNumber(); if (syncTokenMap.containsKey(tokenId)) { final SyncToken existSyncToken = syncTokenMap.get(tokenId); if (existSyncToken.getSequenceNumber() < tokenSequenceNumber) { syncTokenMap.replace(tokenId, existSyncToken, syncToken); } } else { syncTokenMap.put(tokenId, syncToken); } } return Mono.just(httpResponse); }); }</code><technical_language>sense quick out of sync tokens if fails parse correctly</technical_language>

Target:
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().setHeader(SYNC_TOKEN, getSyncTokenHeader()); return next.process().flatMap(httpResponse -> { final String syncTokenValue = httpResponse.getHeaders().getValue(SYNC_TOKEN); if (syncTokenValue == null) { return Mono.just(httpResponse); } final String[] syncTokens = syncTokenValue.split(COMMA); for (final String syncTokenString : syncTokens) { if (CoreUtils.isNullOrEmpty(syncTokenString)) { continue; } final SyncToken syncToken; try { syncToken = new SyncToken(syncTokenString); } catch (Exception ex){ logger.warning(SKIP_INVALID_TOKEN, syncTokenString); continue; } final String tokenId = syncToken.getId(); syncTokenMap.compute(tokenId, (key, existingSyncToken) -> { if (existingSyncToken == null || syncToken.getSequenceNumber() > existingSyncToken.getSequenceNumber()) { return syncToken; } return existingSyncToken; }); } return Mono.just(httpResponse); }); }
Source:
<code><START> protected ExprEval eval(ExprEval param, int scale) <END> { if (param.type() == ExprType.LONG) { return ExprEval.of(BigDecimal.valueOf(param.asLong()).setScale(scale, RoundingMode.HALF_UP).longValue()); } else if (param.type() == ExprType.DOUBLE) { return ExprEval.of(BigDecimal.valueOf(param.asDouble()).setScale(scale, RoundingMode.HALF_UP).doubleValue()); } else { return ExprEval.of(null); } }</code><technical_language>private instead of protected, if so, preferred</technical_language>

Target:
private ExprEval eval(ExprEval param, int scale) { if (param.type() == ExprType.LONG) { return ExprEval.of(BigDecimal.valueOf(param.asLong()).setScale(scale, RoundingMode.HALF_UP).longValue()); } else if (param.type() == ExprType.DOUBLE) { return ExprEval.of(BigDecimal.valueOf(param.asDouble()).setScale(scale, RoundingMode.HALF_UP).doubleValue()); } else { return ExprEval.of(null); } }