auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public StatsDEmitterConfig( @JsonProperty("hostname") String hostname, @JsonProperty("port") Integer port, @JsonProperty("prefix") String prefix, @JsonProperty("separator") String separator, @JsonProperty("includeHost") Boolean includeHost, @JsonProperty("dimensionMapPath") String dimensionMapPath, @JsonProperty("blankHolder") String blankHolder, @JsonProperty("dogstatsd") Boolean dogstatsd, @JsonProperty("dogstatsdConstantTags") List<String> dogstatsdConstantTags ) { this.hostname = Preconditions.checkNotNull(hostname, "StatsD hostname cannot be null."); this.port = Preconditions.checkNotNull(port, "StatsD port cannot be null."); this.prefix = prefix != null ? prefix : ""; this.separator = separator != null ? separator : "."; this.includeHost = includeHost != null ? includeHost : false; this.dimensionMapPath = dimensionMapPath; this.blankHolder = blankHolder != null ? blankHolder : "-"; this.dogstatsd = dogstatsd != null ? dogstatsd : false; <START> this.dogstatsdConstantTags = dogstatsdConstantTags != null ? dogstatsdConstantTags : new ArrayList<>(0); <END> }</code><technical_language>nit: Collections.emptyList()</technical_language>

Target:
public StatsDEmitterConfig( @JsonProperty("hostname") String hostname, @JsonProperty("port") Integer port, @JsonProperty("prefix") String prefix, @JsonProperty("separator") String separator, @JsonProperty("includeHost") Boolean includeHost, @JsonProperty("dimensionMapPath") String dimensionMapPath, @JsonProperty("blankHolder") String blankHolder, @JsonProperty("dogstatsd") Boolean dogstatsd, @JsonProperty("dogstatsdConstantTags") List<String> dogstatsdConstantTags ) { this.hostname = Preconditions.checkNotNull(hostname, "StatsD hostname cannot be null."); this.port = Preconditions.checkNotNull(port, "StatsD port cannot be null."); this.prefix = prefix != null ? prefix : ""; this.separator = separator != null ? separator : "."; this.includeHost = includeHost != null ? includeHost : false; this.dimensionMapPath = dimensionMapPath; this.blankHolder = blankHolder != null ? blankHolder : "-"; this.dogstatsd = dogstatsd != null ? dogstatsd : false; this.dogstatsdConstantTags = dogstatsdConstantTags != null ? dogstatsdConstantTags : Collections.emptyList(); }
Source:
<code>private void setCookieAndRecordMetrics(UserSession session) { writeSessionInfoToMetrics(session); response().setCookie(BridgeConstants.SESSION_TOKEN_HEADER, session.getSessionToken(), BridgeConstants.BRIDGE_SESSION_EXPIRE_IN_SECONDS, "/", <START> bridgeConfig.getHostnameWithPostfix("webservices"), true, true); <END> RequestInfo requestInfo = getRequestInfoBuilder(session) .withSignedInOn(DateUtils.getCurrentDateTime()).build(); cacheProvider.updateRequestInfo(requestInfo); }</code><technical_language>This work local. 1. want getHostnameWithPostfix() resolves webservices-local.sagebridge.org, resolve anything. I want getWebservicesUrl(). 2. Local HTTPS. set flags based bridgeConfig.getEnv() != LOCAL? (Same in BaseController.)</technical_language>

Target:
private void setCookieAndRecordMetrics(UserSession session) { writeSessionInfoToMetrics(session); boolean useSsl = bridgeConfig.getEnvironment() != Environment.LOCAL; response().setCookie(BridgeConstants.SESSION_TOKEN_HEADER, session.getSessionToken(), BridgeConstants.BRIDGE_SESSION_EXPIRE_IN_SECONDS, "/", bridgeConfig.get("webservices.url"), useSsl, useSsl); RequestInfo requestInfo = getRequestInfoBuilder(session) .withSignedInOn(DateUtils.getCurrentDateTime()).build(); cacheProvider.updateRequestInfo(requestInfo); }
Source:
<code>protected void requestCredentialsUpdate(Context context) { try { OwnCloudClient client; OwnCloudAccount ocAccount = new OwnCloudAccount(getAccount(), context); client = (OwnCloudClientManagerFactory.getDefaultSingleton(). removeClientFor(ocAccount)); if (client != null) { OwnCloudCredentials cred = client.getCredentials(); if (cred != null) { AccountManager am = AccountManager.get(context); if (cred.authTokenExpires()) { am.invalidateAuthToken( getAccount().type, cred.getAuthToken() ); } else { am.clearPassword(getAccount()); } } } Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class); updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount()); updateAccountCredentials.putExtra( AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN); updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); <START> startActivityForResult(updateAccountCredentials, UPDATE_CREDENTIALS_REQUEST_CODE); <END> } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) { Toast.makeText(context, R.string.auth_account_does_not_exist, Toast.LENGTH_SHORT).show(); } }</code><technical_language>This change is needed anymore, right</technical_language>

Target:
protected void requestCredentialsUpdate(Context context) { try { OwnCloudClient client; OwnCloudAccount ocAccount = new OwnCloudAccount(getAccount(), context); client = (OwnCloudClientManagerFactory.getDefaultSingleton(). removeClientFor(ocAccount)); if (client != null) { OwnCloudCredentials cred = client.getCredentials(); if (cred != null) { AccountManager am = AccountManager.get(context); if (cred.authTokenExpires()) { am.invalidateAuthToken( getAccount().type, cred.getAuthToken() ); } else { am.clearPassword(getAccount()); } } } Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class); updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount()); updateAccountCredentials.putExtra( AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN); updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); startActivity(updateAccountCredentials); } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) { Toast.makeText(context, R.string.auth_account_does_not_exist, Toast.LENGTH_SHORT).show(); } }
Source:
<code>public InsertByIdWithDurability<T> withExpiry(final Duration expiry) { return new ExecutableInsertByIdSupport<>(template, domainType, collection, persistTo, replicateTo, <START> durabilityLevel, expiry); <END> }</code><technical_language>Assert.notNull(expiry,..) checking sense</technical_language>

Target:
public InsertByIdWithDurability<T> withExpiry(final Duration expiry) { Assert.notNull(expiry, "expiry must not be null."); return new ExecutableInsertByIdSupport<>(template, domainType, collection, persistTo, replicateTo, durabilityLevel, expiry); }
Source:
<code>private Handler<Void> handlerInContext(Handler<Void> handler) { <START> return vv -> connection.getContext().runOnContext(v -> handler.handle(null)); <END> }</code><technical_language>i java return vv -> connection.getContext().runOnContext(handler); result avoid 1 extra lambda</technical_language>

Target:
private Handler<Void> handlerInContext(Handler<Void> handler) { return vv -> connection.getContext().runOnContext(handler); }
Source:
<code>public void accepts( org.opengis.feature.FeatureVisitor visitor, org.opengis.util.ProgressListener progress) throws IOException { Name typeName = transformer.getSource().getName(); if (typeName != null) { try { SimpleFeatureSource fs = (SimpleFeatureSource) source.getDataStore().getFeatureSource(typeName); <START> if (fs instanceof ContentFeatureSource) { <END> ((ContentFeatureSource) fs).accepts(query, visitor, progress); return; } } catch (IOException e) { LOGGER.info("Failed to invoke method ContentFeatureSource.accepts()"); } } super.accepts(visitor, progress); }</code><technical_language>actual need check if a content feature source, SimpleFeatureSource method need</technical_language>

Target:
public void accepts( org.opengis.feature.FeatureVisitor visitor, org.opengis.util.ProgressListener progress) throws IOException { Name typeName = transformer.getSource().getName(); if (isTypeCompatible(visitor, transformer.getSchema())) { source.getDataStore() .getFeatureSource(typeName) .getFeatures() .accepts(visitor, progress); } else { super.accepts(visitor, progress); } }
Source:
<code>public String getName() { <START> return name().toLowerCase(); <END> }</code><technical_language>toLowerCase(Locale.ROOT) "toLowerCase" default locale (which lowercase incorrectly depending language)</technical_language>

Target:
public String getName() { return name().toLowerCase(Locale.ROOT); }
Source:
<code>private static CasualtyDetails calculateRolledAaCasualties( final List<Unit> availableTargets, final AaPowerStrengthAndRolls unitPowerAndRollsMap, final DiceRoll dice, final IDelegateBridge bridge) { final int hits = dice.getHits(); final Collection<Unit> hitTargets; if (unitPowerAndRollsMap.calculateTotalRolls() == availableTargets.size() && hits < availableTargets.size()) { hitTargets = findRolledTargets(availableTargets, dice); } else if (hits < availableTargets.size()) { hitTargets = findRandomTargets(availableTargets, bridge, hits); } else { hitTargets = availableTargets; } <START> return buildCasualtyDetails(availableTargets, hitTargets); <END> }</code><technical_language>a style preference part, another extent I 'single-return' point design well. I some this method block clear returning can. For example, 'else' statement avoid some extra thought realize availableTargets' is equal 'hitTargets'. Personally find single-return point design is good for longer methods, complicated return for reasons places. For short methods, is fine IMO: if return else if return else return example is more clear single return variable, ie: var returnVal; if returnVal = a else if returnVal =b else returnVal =c return returnVal</technical_language>

Target:
private static Collection<Unit> calculateRolledAaCasualties( final List<Unit> availableTargets, final AaPowerStrengthAndRolls unitPowerAndRollsMap, final DiceRoll dice, final IDelegateBridge bridge) { if (unitPowerAndRollsMap.calculateTotalRolls() == availableTargets.size() && dice.getHits() < availableTargets.size()) { return findRolledTargets(availableTargets, dice); } else if (dice.getHits() < availableTargets.size()) { return findRandomTargets(availableTargets, bridge, dice.getHits()); } else { return availableTargets; } }
Source:
<code>public static boolean isGridMenuEnabled(){ SharedPreferences properties = CommCareApplication._().getCurrentApp().getAppPreferences(); <START> return properties.getString(GRID_MENUS_ENABLED, BuildConfig.DEBUG ? CommCarePreferences.YES : CommCarePreferences.NO).equals(CommCarePreferences.YES); <END> }</code><technical_language>I want this default. This default setting basically "If debug mode is enabled (IE: a dev machine), default for superuser flag is 'on'". want default "no"</technical_language>

Target:
public static boolean isGridMenuEnabled(){ SharedPreferences properties = CommCareApplication._().getCurrentApp().getAppPreferences(); return properties.getString(GRID_MENUS_ENABLED, CommCarePreferences.NO).equals(CommCarePreferences.YES); }
Source:
<code>private void handleRunningTestState(String testID) throws BenchFlowTestIDDoesNotExistException { logger.info("handleRunningTestState for " + testID); boolean exit = false; BenchFlowTestState testState; TestRunningState testRunningState = testModelDAO.getTestRunningState(testID); TestRunningState prevTestRunningState; setTimeoutIfNeeded(testID); while (!exit) { prevTestRunningState = testRunningState; try { testState = handleTestRunningState(testID); } catch (BenchFlowTestIDDoesNotExistException e) { e.printStackTrace(); break; } testRunningState = testModelDAO.getTestRunningState(testID); logger.info("handleRunningTestState: testState == " + testState); if (testState != null && (testState == WAITING || testState == TERMINATED)) { exit = true; } <START> else if (prevTestRunningState != null && testRunningState != null <END> && prevTestRunningState == TestRunningState.DETERMINE_EXECUTE_EXPERIMENTS && testRunningState == TestRunningState.HANDLE_EXPERIMENT_RESULT || testRunningState == TestRunningState.TERMINATING) { exit = true; } } }</code><technical_language>this works? point is I check for sequence of state in current code, is change account this? Add some parenthesis well</technical_language>

Target:
private void handleRunningTestState(String testID) throws BenchFlowTestIDDoesNotExistException { logger.info("handleRunningTestState for " + testID); boolean exit = false; BenchFlowTestState testState; TestRunningState testRunningState; setTimeoutIfNeeded(testID); while (!exit) { try { testState = handleTestRunningState(testID); } catch (BenchFlowTestIDDoesNotExistException e) { e.printStackTrace(); break; } testRunningState = testModelDAO.getTestRunningState(testID); logger.info("handleRunningTestState: testState == " + testState); logger.info("handleRunningTestState: testRunningState == " + testRunningState); if (testState == WAITING || testState == TERMINATED) { exit = true; } else if (testRunningState == TestRunningState.HANDLE_EXPERIMENT_RESULT || testRunningState == TestRunningState.TERMINATING) { exit = true; } } }
Source:
<code>public void shouldValidateMultipleIssuers() { String token = "eyJhbGciOiJIUzI1NiIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.mZ0m_N1J4PgeqWmi903JuUoDRZDBPB7HwkS4nVyWH1M"; DecodedJWT jwt = JWTVerifier.init(Algorithm.HMAC256("secret")) .withIssuer("otherIssuer", "auth0") .build() .verify(token); <START> <END> assertThat(jwt, is(notNullValue())); }</code><technical_language>save Verifier instance in a variable verify 2 tokens, 2 issuers. in test</technical_language>

Target:
public void shouldValidateMultipleIssuers() { String auth0Token = "eyJhbGciOiJIUzI1NiIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.mZ0m_N1J4PgeqWmi903JuUoDRZDBPB7HwkS4nVyWH1M"; String otherIssuertoken = "eyJhbGciOiJIUzI1NiIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJvdGhlcklzc3VlciJ9.k4BCOJJl-c0_Y-49VD_mtt-u0QABKSV5i3W-RKc74co"; JWTVerifier verifier = JWTVerifier.init(Algorithm.HMAC256("secret")) .withIssuer("otherIssuer", "auth0") .build(); assertThat(verifier.verify(auth0Token), is(notNullValue())); assertThat(verifier.verify(otherIssuertoken), is(notNullValue())); }
Source:
<code>public void getUserBalancesShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MOCK_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); <START> return null; <END> } }).build(); final UserService userService = adapter.create(UserService.class); userService.getUserBalances(new RetrofitPromise<Balance>()); latch.await(); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/me", MOCK_URL)); Assert.assertEquals(bodyRef.get().getMethod(), "GET"); }</code><technical_language>Add newline return</technical_language>

Target:
public void getUserBalancesShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MOCK_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); return null; } }).build(); final UserService userService = adapter.create(UserService.class); userService.getUserBalances(new RetrofitPromise<Balance>()); latch.await(); Assert.assertEquals(bodyRef.get().getMethod(), "GET"); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/me", MOCK_URL)); }
Source:
<code>public void initialize(LdbcConfiguration conf) { String formatDateTimeString = DatagenParams.getDateTimeFormat(); gmtDateTimeFormatter = DateTimeFormatter.ofPattern(formatDateTimeString).withZone(DateUtils.UTC); String formatDateString = DatagenParams.getDateFormat(); <START> gmtDateFormatter = DateTimeFormatter.ofPattern(formatDateString).withZone(DateUtils.UTC); <END> }</code><technical_language>While UTC is good choice for epochs, GMT comply spec. ![image](<LINK_0></technical_language>

Target:
public void initialize(LdbcConfiguration conf) { String formatDateTimeString = DatagenParams.getDateTimeFormat(); gmtDateTimeFormatter = DateTimeFormatter.ofPattern(formatDateTimeString).withZone(GMT); String formatDateString = DatagenParams.getDateFormat(); gmtDateFormatter = DateTimeFormatter.ofPattern(formatDateString).withZone(GMT); }
Source:
<code>public OpenTxnsResponse open_txns(OpenTxnRequest rqst) throws TException { OpenTxnsResponse response = getTxnHandler().openTxns(rqst); List<Long> txnIds = response.getTxn_ids(); if (!listeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(listeners, EventType.OPEN_TXN, new OpenTxnEvent(txnIds.iterator(), this)); } if (!transactionalListeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventType.OPEN_TXN, <START> new OpenTxnEvent(txnIds.iterator(), this)); <END> } return response; }</code><technical_language>Noticed txnIds is passed List->Iter->NewList->Iter->NewList methods. This model copies. Instead, pass list (txnIds) build openTxnMessage</technical_language>

Target:
public OpenTxnsResponse open_txns(OpenTxnRequest rqst) throws TException { OpenTxnsResponse response = getTxnHandler().openTxns(rqst); List<Long> txnIds = response.getTxn_ids(); if (txnIds != null && listeners != null && !listeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(listeners, EventType.OPEN_TXN, new OpenTxnEvent(txnIds, this)); } return response; }
Source:
<code>public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; <START> if (getClass() != obj.getClass()) return false; <END> BigFraction otherValue = ((ILScore)obj).getValue(); return this.value.equals(otherValue); }</code><technical_language>Is this needed? this removed for efficiency reasons (but I this method is used...)</technical_language>

Target:
public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; BigFraction otherValue = ((ILScore)obj).getValue(); return this.value.equals(otherValue); }
Source:
<code>private <T> T getEntity(Response r, Class<T> clazz) { try { String response = r.readEntity(String.class); int responseCode = getResponseCode(response); if (responseCode == CatalogResponse.ResponseMessage.ENTITY_NOT_FOUND.getCode()) { return null; } <START> else if(responseCode == CatalogResponse.ResponseMessage.EXCEPTION.getCode()) { <END> throw new RuntimeException("Error occurred "+ getResponseMessage(response)); } else { ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(response); return mapper.treeToValue(node.get("entity"), clazz); } } catch (Exception ex) { throw new RuntimeException(ex); } }</code><technical_language>other error status codes in ResponseMessage, put responseCode != CatalogResponse.ResponseMessage.SUCCESS.getCode()</technical_language>

Target:
private <T> T getEntity(Response r, Class<T> clazz) { try { String response = r.readEntity(String.class); int responseCode = getResponseCode(response); if (responseCode == CatalogResponse.ResponseMessage.ENTITY_NOT_FOUND.getCode()) { return null; } else if(responseCode != CatalogResponse.ResponseMessage.SUCCESS.getCode()) { throw new RuntimeException("Error occurred "+ getResponseMessage(response)); } else { ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(response); return mapper.treeToValue(node.get("entity"), clazz); } } catch (IOException ex) { throw new RuntimeException(ex); } }
Source:
<code>private boolean isSpanAnnotation(BratAnnotation ann) { <START> if (ann instanceof SpanAnnotation && <END> (nameTypes == null || nameTypes.size() == 0 || nameTypes.contains(ann.getType()))) { return true; } return false; }</code><technical_language>clear expect: - enable name type filtering, in case pass null nameTypes parameter - If empty set is passed IllegalArgumentException thrown, sense filter</technical_language>

Target:
private boolean isSpanAnnotation(BratAnnotation ann) { if (ann instanceof SpanAnnotation && (nameTypes == null || nameTypes.contains(ann.getType()))) { return true; } return false; }
Source:
<code>public HiveMetadataFactory( HiveClientConfig hiveClientConfig, ExtendedHiveMetastore metastore, HdfsEnvironment hdfsEnvironment, HivePartitionManager partitionManager, @ForHiveClient ExecutorService executorService, TypeManager typeManager, LocationService locationService, TableParameterCodec tableParameterCodec, JsonCodec<PartitionUpdate> partitionUpdateCodec, TypeTranslator typeTranslator, NodeVersion nodeVersion) { this( metastore, hdfsEnvironment, partitionManager, hiveClientConfig.getDateTimeZone(), hiveClientConfig.getMaxConcurrentFileRenames(), hiveClientConfig.getAllowCorruptWritesForTesting(), hiveClientConfig.isSkipDeletionForAlter(), hiveClientConfig.isBucketWritingEnabled(), hiveClientConfig.getWritesToNonManagedTablesEnabled(), hiveClientConfig.getCreatesOfNonManagedTablesEnabled(), hiveClientConfig.getPerTransactionMetastoreCacheMaximumSize(), typeManager, locationService, tableParameterCodec, partitionUpdateCodec, executorService, typeTranslator, nodeVersion.toString(), <START> hiveClientConfig.getMaxPartitionsPerScan()); <END> }</code><technical_language>move field/arg other config properties</technical_language>

Target:
public HiveMetadataFactory( HiveClientConfig hiveClientConfig, ExtendedHiveMetastore metastore, HdfsEnvironment hdfsEnvironment, HivePartitionManager partitionManager, @ForHiveClient ExecutorService executorService, TypeManager typeManager, LocationService locationService, TableParameterCodec tableParameterCodec, JsonCodec<PartitionUpdate> partitionUpdateCodec, TypeTranslator typeTranslator, NodeVersion nodeVersion) { this( metastore, hdfsEnvironment, partitionManager, hiveClientConfig.getDateTimeZone(), hiveClientConfig.getMaxConcurrentFileRenames(), hiveClientConfig.getAllowCorruptWritesForTesting(), hiveClientConfig.isSkipDeletionForAlter(), hiveClientConfig.isBucketWritingEnabled(), hiveClientConfig.getWritesToNonManagedTablesEnabled(), hiveClientConfig.getCreatesOfNonManagedTablesEnabled(), hiveClientConfig.getPerTransactionMetastoreCacheMaximumSize(), hiveClientConfig.getMaxPartitionsPerScan(), typeManager, locationService, tableParameterCodec, partitionUpdateCodec, executorService, typeTranslator, nodeVersion.toString()); }
Source:
<code>private static boolean isCloudStackOnlyVag(SolidFireConnection sfConnection, SolidFireVag sfVag) { long[] volumeIds = sfVag.getVolumeIds(); <START> if (volumeIds == null || volumeIds.length == 0) { <END> return true; } List<Long> knownSfAccountsForCs = new ArrayList<>(); for (long volumeId : volumeIds) { SolidFireVolume sfVolume = getVolume(sfConnection, volumeId); long sfAccountId = sfVolume.getAccountId(); if (!knownSfAccountsForCs.contains(sfAccountId)) { SolidFireAccount sfAccount = getAccountById(sfConnection, sfAccountId); if (sfAccount.getName().startsWith(SF_CS_ACCOUNT_PREFIX)) { knownSfAccountsForCs.add(sfAccountId); } else { return false; } } } return true; }</code><technical_language>org.apache.commons.lang3.ArrayUtils.isEmpty(long[]) here</technical_language>

Target:
private static boolean isCloudStackOnlyVag(SolidFireConnection sfConnection, SolidFireVag sfVag) { long[] volumeIds = sfVag.getVolumeIds(); if (ArrayUtils.isEmpty(volumeIds)) { return true; } List<Long> knownSfAccountsForCs = new ArrayList<>(); for (long volumeId : volumeIds) { SolidFireVolume sfVolume = getVolume(sfConnection, volumeId); long sfAccountId = sfVolume.getAccountId(); if (!knownSfAccountsForCs.contains(sfAccountId)) { SolidFireAccount sfAccount = getAccountById(sfConnection, sfAccountId); if (sfAccount.getName().startsWith(SF_CS_ACCOUNT_PREFIX)) { knownSfAccountsForCs.add(sfAccountId); } else { return false; } } } return true; }
Source:
<code>protected static boolean nonFatal(Throwable throwable) { <START> return throwable instanceof StackOverflowError || !(throwable instanceof VirtualMachineError || throwable instanceof ThreadDeath <END> || throwable instanceof InterruptedException || throwable instanceof LinkageError); }</code><technical_language>is StackOverflow a fatal error? is reason treat Errors fatal default</technical_language>

Target:
protected static boolean nonFatal(Throwable throwable) { return throwable instanceof StackOverflowError || !(throwable instanceof VirtualMachineError || throwable instanceof ThreadDeath || throwable instanceof InterruptedException || throwable instanceof LinkageError || throwable instanceof CancellationException); }
Source:
<code>public static boolean isPrimitive(Type type) { <START> return indexOf(type, 0) != -1; <END> }</code><technical_language>this type instanceof Class<?> && ((Class<?>) type).isPrimitive()</technical_language>

Target:
public static boolean isPrimitive(Type type) { return type instanceof Class<?> && ((Class<?>)type).isPrimitive(); }
Source:
<code>public void testShallowFile() throws Exception { FileRepository repository = createBareRepository(); ObjectDirectory dir = repository.getObjectDatabase(); String commit = "d3148f9410b071edd4a4c85d2a43d1fa2574b0d2"; try (PrintWriter writer = new PrintWriter( new File(repository.getDirectory(), Constants.SHALLOW))) { writer.println(commit); } Set<ObjectId> shallowCommits = dir.getShallowCommits(); assertTrue(shallowCommits.remove(ObjectId.fromString(commit))); assertTrue(shallowCommits.isEmpty()); <START> try (PrintWriter writer = new PrintWriter( new File(repository.getDirectory(), Constants.SHALLOW))) { writer.println("X3148f9410b071edd4a4c85d2a43d1fa2574b0d2"); } try { dir.getShallowCommits(); Assert.fail(); } catch (IOException ex) { } <END> }</code><technical_language>I put expected fail case in a separate test method</technical_language>

Target:
public void testShallowFile() throws Exception { FileRepository repository = createBareRepository(); ObjectDirectory dir = repository.getObjectDatabase(); String commit = "d3148f9410b071edd4a4c85d2a43d1fa2574b0d2"; try (PrintWriter writer = new PrintWriter( new File(repository.getDirectory(), Constants.SHALLOW))) { writer.println(commit); } Set<ObjectId> shallowCommits = dir.getShallowCommits(); assertTrue(shallowCommits.remove(ObjectId.fromString(commit))); assertTrue(shallowCommits.isEmpty()); }
Source:
<code>public void run() { try { int batchSize = config.getBatchSize(); TimelineMetrics metrics = new TimelineMetrics(); while (eventsQueue.size() > 0 && !exec.isShutdown()) { try { final TimelineMetric metricEvent = eventsQueue.poll( config.getWaitForEventTime(), TimeUnit.MILLISECONDS ); if (metricEvent != null) { metrics.addOrMergeTimelineMetric(metricEvent); if (metrics.getMetrics().size() == batchSize) { emitMetrics(metrics); log.debug( "sent [%d] events", metrics.getMetrics().size() ); metrics = new TimelineMetrics(); } } } catch (InterruptedException e) { log.error(e, e.getMessage()); <START> if (e instanceof InterruptedException) { <END> Thread.currentThread().interrupt(); } } if (metrics.getMetrics().size() > 0) { emitMetrics(metrics); log.debug( "sent [%d] events", metrics.getMetrics().size() ); } } } catch (Exception e) { log.error(e, e.getMessage()); if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } } }</code><technical_language>this check is redundant</technical_language>

Target:
public void run() { try { int batchSize = config.getBatchSize(); TimelineMetrics metrics = new TimelineMetrics(); while (eventsQueue.size() > 0 && !exec.isShutdown()) { try { final TimelineMetric metricEvent = eventsQueue.poll( config.getWaitForEventTime(), TimeUnit.MILLISECONDS ); if (metricEvent != null) { metrics.addOrMergeTimelineMetric(metricEvent); if (metrics.getMetrics().size() == batchSize) { emitMetrics(metrics); log.debug( "sent [%d] events", metrics.getMetrics().size() ); metrics = new TimelineMetrics(); } } } catch (InterruptedException e) { log.error(e, e.getMessage()); Thread.currentThread().interrupt(); } } if (metrics.getMetrics().size() > 0) { emitMetrics(metrics); log.debug( "sent [%d] events", metrics.getMetrics().size() ); } } catch (Exception e) { log.error(e, e.getMessage()); if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } } }
Source:
<code>public ResultScanner getScanner(Scan scan) throws IOException { AnviltopServices.ReadTableRequest.Builder request = scanAdapter.adapt(scan); request.setProjectId(options.getProjectId()); request.setTableName(tableName.getQualifierAsString()); try { AnviltopResultScanner scanner = client.readTable(request.build()); return anviltopResultScannerAdapter.adapt(scanner); } catch (ServiceException e) { throw new IOException( makeGenericExceptionMessage( "getScanner", options.getProjectId(), tableName.getQualifierAsString(), <START> new byte[0]), <END> e); } }</code><technical_language>new byte[0] is kind of ugly. another method it</technical_language>

Target:
public ResultScanner getScanner(Scan scan) throws IOException { AnviltopServices.ReadTableRequest.Builder request = scanAdapter.adapt(scan); request.setProjectId(options.getProjectId()); request.setTableName(tableName.getQualifierAsString()); try { AnviltopResultScanner scanner = client.readTable(request.build()); return anviltopResultScannerAdapter.adapt(scanner); } catch (ServiceException e) { throw new IOException( makeGenericExceptionMessage( "getScanner", options.getProjectId(), tableName.getQualifierAsString()), e); } }
Source:
<code>public List<DataManipulator<?, ?>> getCustomManipulators() { final List<DataManipulator<?, ?>> list = Lists.newArrayList(); list.addAll(this.manipulators.stream() <START> .map(DataManipulator::copy) <END> .collect(Collectors.toList())); return list; }</code><technical_language>No. Remember I anonymous classes</technical_language>

Target:
public List<DataManipulator<?, ?>> getCustomManipulators() { final List<DataManipulator<?, ?>> list = Lists.newArrayList(); for (DataManipulator<?, ?> manipulator : this.manipulators) { list.add(manipulator.copy()); } return list; }
Source:
<code>public MetricAggregator provide() <START> { <END> return new SuccessRateAggregator(); }</code><technical_language>code style</technical_language>

Target:
public MetricAggregator provide() { return new MetricAggregator<Number>() { private long passNum = 0; private long failNum = 0; @Override public void append(Number calculated) { if (calculated.intValue() != 0) passNum++; else failNum++; } @Override public Double getAggregated() { if ((failNum + passNum) == 0) return new Double(0.0); else return new Double((double) (passNum) / (double) (failNum + passNum)); } @Override public void reset() { } @Override public String getName() { return "aggSR"; } }; }
Source:
<code>private void initializeDefaultListeners() { ExitCodeListener exitCodeListener = new ExitCodeListener(this); m_testListeners.put(ExitCodeListener.class, exitCodeListener); if (m_useDefaultListeners) { <START> addListener((ITestNGListener) exitCodeListener); <END> addReporter(SuiteHTMLReporter.class); addReporter(Main.class); addReporter(FailedReporter.class); addReporter(XMLReporter.class); if (System.getProperty("oldTestngEmailableReporter") != null) { addReporter(EmailableReporter.class); } else if (System.getProperty("noEmailableReporter") == null) { addReporter(EmailableReporter2.class); } addReporter(JUnitReportReporter.class); if (m_verbose != null && m_verbose > 4) { addListener(new VerboseReporter("[TestNG] ")); } } }</code><technical_language>do add here</technical_language>

Target:
private void initializeDefaultListeners() { addListener((ITestNGListener) new ExitCodeListener(this)); if (m_useDefaultListeners) { addReporter(SuiteHTMLReporter.class); addReporter(Main.class); addReporter(FailedReporter.class); addReporter(XMLReporter.class); if (System.getProperty("oldTestngEmailableReporter") != null) { addReporter(EmailableReporter.class); } else if (System.getProperty("noEmailableReporter") == null) { addReporter(EmailableReporter2.class); } addReporter(JUnitReportReporter.class); if (m_verbose != null && m_verbose > 4) { addListener(new VerboseReporter("[TestNG] ")); } } }
Source:
<code>public void actionPerformed(ActionEvent event) { if (event.getParameters() == null) { Log.error(getClass(), localization.canNotOpenFileWithoutParams()); return; } final String pathToOpen = event.getParameters().get(FILE_PARAM_ID); if (pathToOpen == null) { Log.error(getClass(), localization.fileToOpenIsNotSpecified()); return; } appContext .getWorkspaceRoot() .getFile(pathToOpen) .then( optionalFile -> { if (optionalFile.isPresent()) { if (actionCompletedCallback != null) { actionCompletedCallback.onSuccess(null); } editorAgent.openEditor( optionalFile.get(), new EditorAgent.OpenEditorCallback() { @Override public void onEditorOpened(EditorPartPresenter editor) { <START> new Timer() { <END> @Override public void run() { scrollToLine(editor, event.getParameters().get(LINE_PARAM_ID)); } }.schedule(300); } @Override public void onInitializationFailed() @Override public void onEditorActivated(EditorPartPresenter editor) { new Timer() { @Override public void run() { scrollToLine(editor, event.getParameters().get(LINE_PARAM_ID)); } }.schedule(300); } }); } else { if (actionCompletedCallback != null) { actionCompletedCallback.onFailure(null); } notificationManager.notify( localization.unableOpenResource(pathToOpen), FAIL, FLOAT_MODE); } }); }</code><technical_language>Move new Timer() { ... scrollToLine method</technical_language>

Target:
public void actionPerformed(ActionEvent event) { if (event.getParameters() == null) { Log.error(getClass(), localization.canNotOpenFileWithoutParams()); return; } final String pathToOpen = event.getParameters().get(FILE_PARAM_ID); if (pathToOpen == null) { Log.error(getClass(), localization.fileToOpenIsNotSpecified()); return; } appContext .getWorkspaceRoot() .getFile(pathToOpen) .then( optionalFile -> { if (optionalFile.isPresent()) { if (actionCompletedCallback != null) { actionCompletedCallback.onSuccess(null); } editorAgent.openEditor( optionalFile.get(), new EditorAgent.OpenEditorCallback() { @Override public void onEditorOpened(EditorPartPresenter editor) { scrollToLine(editor, event.getParameters().get(LINE_PARAM_ID)); } @Override public void onInitializationFailed() @Override public void onEditorActivated(EditorPartPresenter editor) { scrollToLine(editor, event.getParameters().get(LINE_PARAM_ID)); } }); } else { if (actionCompletedCallback != null) { actionCompletedCallback.onFailure(null); } notificationManager.notify( localization.unableOpenResource(pathToOpen), FAIL, FLOAT_MODE); } }); }
Source:
<code>public IndexDefinition createIndexDefinition( Label label, String... propertyKeys ) { KernelTransaction transaction = safeAcquireTransaction( transactionSupplier ); try ( Statement ignore = transaction.acquireStatement() ) { try { IndexDefinition indexDefinition = new IndexDefinitionImpl( this, label, propertyKeys, false ); TokenWrite tokenWrite = transaction.tokenWrite(); int labelId = tokenWrite.labelGetOrCreateForName( indexDefinition.getLabel().name() ); int[] propertyKeyIds = getOrCreatePropertyKeyIds( tokenWrite, indexDefinition ); LabelSchemaDescriptor descriptor = SchemaDescriptorFactory.forLabel( labelId, propertyKeyIds ); transaction.schemaWrite().indexCreate( descriptor ); return indexDefinition; } catch ( IllegalTokenNameException e ) { throw new IllegalArgumentException( e ); } <START> catch ( SchemaKernelException e ) <END> { throw new ConstraintViolationException( e.getUserMessage( new SilentTokenNameLookup( transaction.tokenRead() ) ), e ); } } }</code><technical_language>This is a nicer catch</technical_language>

Target:
public IndexDefinition createIndexDefinition( Label label, String... propertyKeys ) { KernelTransaction transaction = safeAcquireTransaction( transactionSupplier ); try ( Statement ignore = transaction.acquireStatement() ) { try { IndexDefinition indexDefinition = new IndexDefinitionImpl( this, label, propertyKeys, false ); TokenWrite tokenWrite = transaction.tokenWrite(); int labelId = tokenWrite.labelGetOrCreateForName( indexDefinition.getLabel().name() ); int[] propertyKeyIds = getOrCreatePropertyKeyIds( tokenWrite, indexDefinition ); LabelSchemaDescriptor descriptor = SchemaDescriptorFactory.forLabel( labelId, propertyKeyIds ); transaction.schemaWrite().indexCreate( descriptor ); return indexDefinition; } catch ( IllegalTokenNameException e ) { throw new IllegalArgumentException( e ); } catch ( InvalidTransactionTypeKernelException | SchemaKernelException e ) { throw new ConstraintViolationException( e.getUserMessage( new SilentTokenNameLookup( transaction.tokenRead() ) ), e ); } } }
Source:
<code>private int computeSellValue(Item item, boolean total) { int value = 0; int currentStock; int defaultStock = 0; int stockDiff = 0; if(container.contains(item)) { <START> currentStock = container.computeAmountForId(item.getId()); <END> if(amountMap[container.computeIndexForId(item.getId()).getAsInt()].isPresent()) defaultStock = amountMap[container.computeIndexForId(item.getId()).getAsInt()].getAsInt(); if((currentStock - defaultStock) > 10) stockDiff = 10; else if((currentStock - defaultStock) < -10) stockDiff = -10; else stockDiff = currentStock - defaultStock; } double lowAlch = item.getItemDef().getValue() * 0.4; for(int i = 0; i < (total ? item.getAmount() : 1); i++) { value += lowAlch - ((stockDiff * 0.075) * lowAlch); if(stockDiff < 10) stockDiff++; } return value <= 0 ? 1 : value; }</code><technical_language>Initialize int currentStock = ...;</technical_language>

Target:
private int computeSellValue(Item item, boolean total) { int stockDiff = 0; if(container.contains(item)) { int currentStock = container.computeAmountForId(item.getId()); var index = container.computeIndexForId(item.getId()); int defaultStock = index.isPresent() ? amountMap[index.getAsInt()].orElse(0): 0; if((currentStock - defaultStock) > 10) { stockDiff = 10; } else if((currentStock - defaultStock) < -10) { stockDiff = -10; } else { stockDiff = currentStock - defaultStock; } } double lowAlch = item.getItemDef().getValue() * 0.4; int value = 0; for(int i = 0; i < (total ? item.getAmount() : 1); i++) { value += lowAlch - ((stockDiff * 0.075) * lowAlch); if(stockDiff < 10) stockDiff++; } return value <= 0 ? 1 : value; }
Source:
<code><START> private List<Task> getBaselineTasks() { <END> List<Task> tasks = new ArrayList<Task>(); for (MCMCWrapper model : d_models.values()) { tasks.add(model.getActivityTask()); } return tasks; }</code><technical_language>this function returns tasks run, baseline tasks</technical_language>

Target:
private List<Task> getBaselineTasks() { List<Task> tasks = new ArrayList<Task>(); for (MCMCWrapper model : d_models.values()) { if(model.getModel() instanceof AbstractBaselineModel) { tasks.add(model.getActivityTask()); } } return tasks; }
Source:
<code>public AdapterPair adapterTrimIlluminaPairedReads(final SAMRecord read1, final SAMRecord read2, final int minMatchBases, final double maxErrorRate) { final AdapterPair ret = ClippingUtility.adapterTrimIlluminaPairedReads(read1, read2, minMatchBases, maxErrorRate, adapters.get()); if (ret != null && !thresholdReached) { if(!preAdapterPrunedRecords.containsKey(ret)) { preAdapterPrunedRecords.put(ret, new ArrayList<>()); } preAdapterPrunedRecords.get(ret).add(read1); preAdapterPrunedRecords.get(ret).add(read2); tallyFoundAdapter(ret); <START> } <END> return ret; }</code><technical_language>Is worth pulling this block a separate method, avoid duplication</technical_language>

Target:
public AdapterPair adapterTrimIlluminaPairedReads(final SAMRecord read1, final SAMRecord read2, final int minMatchBases, final double maxErrorRate) { final AdapterPair ret = ClippingUtility.adapterTrimIlluminaPairedReads(read1, read2, minMatchBases, maxErrorRate, adapters.get()); tallyAndFixAdapters(ret, read1, read2); return ret; }
Source:
<code>public static PDPrintStyle getLineStyle (JSONObject oskariStyle) { PDPrintStyle style = new PDPrintStyle(); <START> JSONObject stroke = JSONHelper.optJSONObject(oskariStyle, "stroke", () -> new JSONObject()); <END> setStrokeStyle(style, stroke); setLabelStyle(style, oskariStyle); style.setLineCap(LINE_CAP_STYLE.getOrDefault(JSONHelper.optString(stroke,"lineCap"), 0)); return style; }</code><technical_language>if this work/read if PDPrintStyle default values return early instead of creating new objects rest of code work properly</technical_language>

Target:
public static PDPrintStyle getLineStyle (JSONObject oskariStyle) { JSONObject stroke = oskariStyle.optJSONObject("stroke"); PDPrintStyle style = new PDPrintStyle(); setStrokeStyle(style, stroke); setLabelStyle(style, oskariStyle); return style; }
Source:
<code>public Page(String wikiName) { this.wikiName = wikiName; <START> this.wikiPath = null; <END> }</code><technical_language>Redundant</technical_language>

Target:
public Page(String wikiName) { this.wikiName = wikiName; }
Source:
<code>public void assertWorkDir(Map<String, String> i) throws CorruptObjectException, IOException { TreeWalk walk = new TreeWalk(db); <START> walk.setRecursive(true); <END> walk.addTree(new FileTreeIterator(db)); String expectedValue; String path; int nrFiles = 0; FileTreeIterator ft; while (walk.next()) { ft = walk.getTree(0, FileTreeIterator.class); path = ft.getEntryPathString(); expectedValue = i.get(path); assertNotNull("found unexpected file for path " + path + " in workdir", expectedValue); File file = new File(db.getWorkTree(), path); assertTrue(file.exists()); if (file.isFile()) { FileInputStream is = new FileInputStream(file); byte[] buffer = new byte[(int) file.length()]; int offset = 0; int numRead = 0; while (offset < buffer.length && (numRead = is.read(buffer, offset, buffer.length - offset)) >= 0) { offset += numRead; } is.close(); assertArrayEquals("unexpected content for path " + path + " in workDir. ", buffer, i.get(path).getBytes()); nrFiles++; } } assertEquals("WorkDir has not the right size.", i.size(), nrFiles); }</code><technical_language>strange. setting setRecursive(true) get entries for folders. chance write tests tests existence of empty folder fail empty folder exists unexpectedly. I suggest enhancement this method rebase change it</technical_language>

Target:
public void assertWorkDir(Map<String, String> i) throws CorruptObjectException, IOException { TreeWalk walk = new TreeWalk(db); walk.setRecursive(false); walk.addTree(new FileTreeIterator(db)); String expectedValue; String path; int nrFiles = 0; FileTreeIterator ft; while (walk.next()) { ft = walk.getTree(0, FileTreeIterator.class); path = ft.getEntryPathString(); expectedValue = i.get(path); File file = new File(db.getWorkTree(), path); assertTrue(file.exists()); if (file.isFile()) { assertNotNull("found unexpected file for path " + path + " in workdir", expectedValue); FileInputStream is = new FileInputStream(file); byte[] buffer = new byte[(int) file.length()]; int offset = 0; int numRead = 0; while (offset < buffer.length && (numRead = is.read(buffer, offset, buffer.length - offset)) >= 0) { offset += numRead; } is.close(); assertArrayEquals("unexpected content for path " + path + " in workDir. ", buffer, i.get(path).getBytes()); nrFiles++; } else if (file.isDirectory()) { if (file.list().length == 0) { assertEquals("found unexpected empty folder for path " + path + " in workDir. ", "/", i.get(path)); nrFiles++; } } if (walk.isSubtree()) { walk.enterSubtree(); } } assertEquals("WorkDir has not the right size.", i.size(), nrFiles); }
Source:
<code>public Entity call() throws Exception { Iterable<Entity> entitiesToSearch = null; switch (scope) { case THIS: return getEntity(); case PARENT: return getEntity().getParent(); case GLOBAL: entitiesToSearch = ((EntityManagerInternal)getEntity().getManagementContext().getEntityManager()) .getAllEntitiesInApplication( entity().getApplication() ); break; case DESCENDANT: entitiesToSearch = Entities.descendants(getEntity()); break; case ANCESTOR: entitiesToSearch = Entities.ancestors(getEntity()); break; case SIBLING: entitiesToSearch = getEntity().getParent().getChildren(); break; case CHILD: entitiesToSearch = getEntity().getChildren(); break; default: throw new IllegalStateException("Unexpected scope "+scope); } Predicate<Entity> configEqualTo = EntityPredicates.configEqualTo(BrooklynCampConstants.PLAN_ID, componentId); Predicate<Entity> classNameEquals = EntityPredicates.classNameEquals(componentId); <START> Optional<Entity> result = Iterables.tryFind(entitiesToSearch, Predicates.or(configEqualTo, classNameEquals)); <END> if (result.isPresent()) return result.get(); throw new NoSuchElementException("No entity matching id or type " + componentId+ (scope==Scope.GLOBAL ? "" : ", in scope "+scope+" wrt "+getEntity()+ (scopeComponent!=null ? " ("+scopeComponent+" from "+entity()+")" : ""))); }</code><technical_language>If string matches id a class name, good guarantee match id dependent order walks entities. for more verbose: Optional<Entity> result = Iterables.tryFind(entitiesToSearch, configEqualTo); if (!result.isPresent()) result = Iterables.tryFind(entitiesToSearch, classNameEquals);</technical_language>

Target:
public Entity call() throws Exception { Iterable<Entity> entitiesToSearch = null; switch (scope) { case THIS: return getEntity(); case PARENT: return getEntity().getParent(); case GLOBAL: entitiesToSearch = ((EntityManagerInternal)getEntity().getManagementContext().getEntityManager()) .getAllEntitiesInApplication( entity().getApplication() ); break; case DESCENDANT: entitiesToSearch = Entities.descendants(getEntity()); break; case ANCESTOR: entitiesToSearch = Entities.ancestors(getEntity()); break; case SIBLING: entitiesToSearch = getEntity().getParent().getChildren(); break; case CHILD: entitiesToSearch = getEntity().getChildren(); break; default: throw new IllegalStateException("Unexpected scope "+scope); } Predicate<Entity> configEqualTo = EntityPredicates.configEqualTo(BrooklynCampConstants.PLAN_ID, componentId); Optional<Entity> result = Iterables.tryFind(entitiesToSearch, configEqualTo); if (result.isPresent()) return result.get(); Predicate<Entity> typeNameEquals = EntityPredicates.typeNameEquals(componentId); result = Iterables.tryFind(entitiesToSearch, typeNameEquals); if (result.isPresent()) return result.get(); throw new NoSuchElementException("No entity matching id or type " + componentId+ (scope==Scope.GLOBAL ? "" : ", in scope "+scope+" wrt "+getEntity()+ (scopeComponent!=null ? " ("+scopeComponent+" from "+entity()+")" : ""))); }
Source:
<code>public ControlPoint[] getManageableControlPoints() { <START> final Point2DArray controlPoints = getControlPoints(); <END> if (null != controlPoints) { final int size = controlPoints.size() - 2; final ControlPoint[] cps = new ControlPoint[size]; for (int i = 1; i <= size; i++) { final com.ait.lienzo.client.core.types.Point2D controlPoint = controlPoints.get(i); cps[i - 1] = ControlPoint.build(controlPoint.getX(), controlPoint.getY()); } return cps; } return new ControlPoint[0]; }</code><technical_language>Improvement, stream more clear. idea Point2DArray StreamSupport.stream(controlPoints.spliterator(), false) mapping a new Array of ControlPoint</technical_language>

Target:
public ControlPoint[] getManageableControlPoints() { final Point2DArray controlPoints = getControlPoints(); if (null != controlPoints && controlPoints.size() > 2) { return StreamSupport.stream(controlPoints.spliterator(), false) .limit(controlPoints.size() - 1) .skip(1) .map(controlPoint -> ControlPoint.build(controlPoint.getX(), controlPoint.getY())) .toArray(ControlPoint[]::new); } return new ControlPoint[0]; }
Source:
<code>private Element getRowElement(final String uuid) { <START> return getElement().parentNode.querySelector("[data-row-uuid=\"" + uuid + "\"]"); <END> }</code><technical_language>I worth introduce data-row-uuid a string constant</technical_language>

Target:
private Element getRowElement(final String uuid) { return getElement().parentNode.querySelector("[" + UUID_ATTR + "=\"" + uuid + "\"]"); }