auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public JSONObject getSnapshot() { JSONObject snapshot = new JSONObject(); START DataNodeId dataNodeId = getDataNodeId(); END snapshot.put(REPLICA_NODE, dataNodeId.getHostname() + ":" + dataNodeId.getPort()); snapshot.put(REPLICA_PARTITION, getPartitionId().toPathString()); snapshot.put(REPLICA_PATH, getReplicaPath()); snapshot.put(CAPACITY_BYTES, getCapacityInBytes()); return snapshot; } Minor: don't really need to call getDataNodeId() since it's a class member.

Target:
public JSONObject getSnapshot() { JSONObject snapshot = new JSONObject(); snapshot.put(REPLICA_NODE, dataNodeId.getHostname() + ":" + dataNodeId.getPort()); snapshot.put(REPLICA_PARTITION, getPartitionId().toPathString()); snapshot.put(REPLICA_PATH, getReplicaPath()); snapshot.put(CAPACITY_BYTES, getCapacityInBytes()); return snapshot; }
Source:
protected String createPassFile(String value) throws IOException { File temp = File.createTempFile("ovirt", ".tmp"); String filePath = temp.getAbsolutePath(); temp.setReadable(true, true); temp.setWritable(true, true); START temp.setExecutable(false); END BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write(value); out.close(); return filePath; } This doesn't work. These Java 6 enhancements only help if you want to *add* permissions to the file, not if you wan't to remove them.

Target:
protected String createPassFile(String value) throws IOException { File temp = File.createTempFile("ovirt", ".tmp"); String filePath = temp.getAbsolutePath(); temp.setReadable(true, true); temp.setWritable(true, true); BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write(value); out.close(); return filePath; }
Source:
public void retireIdentifierSource_shouldRetireAnIdentifierSourceFromTheSystem() throws Exception { START IdentifierSource identifierSource = identifierSourceService.getIdentifierSource(1); END Assert.assertFalse(identifierSourceService.getIdentifierSource(1).isRetired()); identifierSourceService.retireIdentifierSource(identifierSource, "testing"); Assert.assertTrue(identifierSourceService.getIdentifierSource(1).isRetired()); } Can you avoid repeating 1 in several places?

Target:
public void retireIdentifierSource_shouldRetireAnIdentifierSourceFromTheSystem() throws Exception { IdentifierSource identifierSource = identifierSourceService.getIdentifierSource(2); Assert.assertFalse(identifierSourceService.getIdentifierSource(2).isRetired()); identifierSourceService.retireIdentifierSource(identifierSource, "testing"); Assert.assertTrue(identifierSourceService.getIdentifierSource(2).isRetired()); }
Source:
public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final LinkedSpan<T> other = (LinkedSpan<T>) obj; START return Objects.equals(this.linkedEntries, other.linkedEntries) && END this.sentenceid == other.sentenceid && Objects.equals(this.searchTerm, other.searchTerm); } Can you remove this? OPENNLP-922 changes that in one style across all equals and hashCode implementations.

Target:
public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final LinkedSpan<T> other = (LinkedSpan<T>) obj; if (!Objects.equals(this.linkedEntries, other.linkedEntries)) { return false; } return this.sentenceid == other.sentenceid && Objects.equals(this.searchTerm, other.searchTerm); }
Source:
private Expression simplifyExpression(Session session, Expression predicate, TypeProvider types) { Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes(session, predicate, types); ExpressionInterpreter interpreter = ExpressionInterpreter.expressionOptimizer(predicate, metadata, session, expressionTypes); Object value = interpreter.optimize(NoOpSymbolResolver.INSTANCE); START if (value instanceof Expression) { END return (Expression) value; } if (value == null) { // expression evaluates to SQL null, which in Filter is equivalent to false value = false; } return literalEncoder.toExpression(value, BOOLEAN); } `literalEncoder.toExpression()` already returns the Expression if the value is an instanceof Expression, and a NullLiteral if it equals null. I would get rid of the if statements and always return `literalEncoder.toExpression(value,BOOLEAN)`. And add a `visitNullLiteral` to FilterExpressionStatsCalculatingVisitor.

Target:
private Expression simplifyExpression(Session session, Expression predicate, TypeProvider types) { // TODO reuse com.facebook.presto.sql.planner.iterative.rule.SimplifyExpressions.rewrite Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes(session, predicate, types); ExpressionInterpreter interpreter = ExpressionInterpreter.expressionOptimizer(predicate, metadata, session, expressionTypes); Object value = interpreter.optimize(NoOpSymbolResolver.INSTANCE); if (value == null) { // Expression evaluates to SQL null, which in Filter is equivalent to false. This assumes the expression is a top-level expression (eg. not in NOT). value = false; } return literalEncoder.toExpression(value, BOOLEAN); }
Source:
public boolean post(String topic, Object data) { Event event = constructEvent(topic, data); EventAdmin eventAdmin = Activator.getDefault().getEventAdmin(); if (eventAdmin == null && logger != null) { logger.error(NLS.bind(ServiceMessages.NO_EVENT_ADMIN, event.toString())); START return false; END } eventAdmin.postEvent(event); return true; } That is incorrect, in case the logger and eventAdmin is null we get a NPE

Target:
public boolean post(String topic, Object data) { Event event = constructEvent(topic, data); EventAdmin eventAdmin = Activator.getDefault().getEventAdmin(); if (eventAdmin == null) { if (logger != null) { logger.error(NLS.bind(ServiceMessages.NO_EVENT_ADMIN, event.toString())); } return false; } eventAdmin.postEvent(event); return true; }
Source:
public void testTypeAccessInLambdaNoClassPath() { final Launcher runLaunch = new Launcher(); runLaunch.getEnvironment().setNoClasspath(true); runLaunch.addInputResource("./src/test/resources/noclasspath/lambdas/TypeAccessInLambda.java"); runLaunch.buildModel(); assertEquals("The token 'Strings' has not been parsed as CtTypeAccess", runLaunch.getModel().getElements(new Filter<CtTypeAccess>() { @Override public boolean matches(final CtTypeAccess element) { return element.getAccessedType().getSimpleName().equals("Strings"); } START }).size(), 1); END } The expected value (1) must be the second parameter of `assertEquals`

Target:
public void testTypeAccessInLambdaNoClassPath() { final Launcher runLaunch = new Launcher(); runLaunch.getEnvironment().setNoClasspath(true); runLaunch.addInputResource("./src/test/resources/noclasspath/lambdas/TypeAccessInLambda.java"); runLaunch.buildModel(); assertEquals("The token 'Strings' has not been parsed as CtTypeAccess", 1, runLaunch.getModel().getElements(new Filter<CtTypeAccess>() { @Override public boolean matches(final CtTypeAccess element) { return element.getAccessedType().getSimpleName().equals("Strings"); } }).size()); }
Source:
public RecipientListRouter rlRouter() { RecipientListRouter router = new RecipientListRouter(); START router.setChannels(Arrays.asList(new MessageChannel[] { barChannel(), bazChannel() })); END router.setDefaultOutputChannel(discards()); return router; } ![redundantarraycreation](https://cloud.githubusercontent.com/assets/1071590/15787201/e1d4932a-298e-11e6-9dc8-243abf4e1f9f.jpg)

Target:
public RecipientListRouter rlRouter() { RecipientListRouter router = new RecipientListRouter(); router.setChannels(Arrays.asList(barChannel(), bazChannel())); router.setDefaultOutputChannel(discards()); return router; }
Source:
START protected List<MetricFamilySamples> familySamplesList(Collector.Type type, List<MetricFamilySamples.Sample> samples) { END MetricFamilySamples mfs = new MetricFamilySamples(fullname, type, help, samples); List<MetricFamilySamples> mfsList = new ArrayList<MetricFamilySamples>(1); mfsList.add(mfs); return mfsList; } This should probably be package rather than protected

Target:
List<MetricFamilySamples> familySamplesList(Collector.Type type, List<MetricFamilySamples.Sample> samples) { MetricFamilySamples mfs = new MetricFamilySamples(fullname, type, help, samples); List<MetricFamilySamples> mfsList = new ArrayList<MetricFamilySamples>(1); mfsList.add(mfs); return mfsList; }
Source:
START private VmTemplate createVmTemplate() { END VmTemplate template = new VmTemplate(); template.setname("test-template"); template.setorigin(OriginType.OVIRT); template.setId(new Guid()); template.setdescription("test-description"); template.setDbGeneration(2L); return template; } should be static

Target:
private static VmTemplate createVmTemplate() { VmTemplate template = new VmTemplate(); template.setname("test-template"); template.setorigin(OriginType.OVIRT); template.setId(new Guid()); template.setdescription("test-description"); template.setDbGeneration(2L); return template; }
Source:
private static IType getDeclType(ICPPASTSimpleDeclSpecifier spec) { IASTExpression expr = spec.getDeclTypeExpression(); if (expr == null) { return null; } int specifierType = spec.getType(); START if (specifierType == IASTSimpleDeclSpecifier.t_decltype || specifierType == IASTSimpleDeclSpecifier.t_decltype_auto) { END return getDeclType(expr); } return expr.getExpressionType(); } Why handle t_decltype_auto here? We should never get in here for decltype(auto) because getDeclTypeExpression() will be null.

Target:
private static IType getDeclType(ICPPASTSimpleDeclSpecifier spec) { IASTExpression expr = spec.getDeclTypeExpression(); if (expr == null) { return null; } int specifierType = spec.getType(); if (specifierType == IASTSimpleDeclSpecifier.t_decltype) { return getDeclType(expr); } return expr.getExpressionType(); }
Source:
public Number getLineMiterLimit() { START if (paint.get("line-miter_limit") != null) { END return (Number) paint.get("line-miter-limit"); } else { return 2; } } I think the underscore should be a dash

Target:
public Number getLineMiterLimit() { if (paint.get("line-miter-limit") != null) { return (Number) paint.get("line-miter-limit"); } else { return 2; } }
Source:
public void start() { if (started.compareAndSet(false, true)) { register(); scheduler = Utils.newScheduler(1, false); scheduler.scheduleAtFixedRate(new NettyMetricCollector(), 0, config.nettyMetricsRefreshIntervalSeconds, TimeUnit.SECONDS); START logger.trace("Schedule netty metric collector"); END } } change this to INFO level

Target:
public void start() { if (started.compareAndSet(false, true)) { register(); scheduler = Utils.newScheduler(1, false); scheduler.scheduleAtFixedRate(new NettyMetricCollector(), 0, config.nettyMetricsRefreshIntervalSeconds, TimeUnit.SECONDS); logger.info("Schedule netty metric collector"); } }
Source:
public String getFile(@PathVariable("id") final String id, final HttpServletRequest request) { String encodedId; try { // When forwarding, the downstream ApplicationContext will perform URL decoding. // If the job ID contains special characters (such as '+'), they will be interpreted as url-encoded and // decoded, resulting in an invalid job ID that cannot be found. // To prevent this, always perform URL encoding on the ID before forwarding. encodedId = URLEncoder.encode(id, "UTF-8"); } catch (UnsupportedEncodingException e) { log.warn("Failed to encode id: {}", id, e); START encodedId = id; END } final String path = "/api/v3/jobs/" + encodedId + "/" + ControllerUtils.getRemainingPath(request); return "forward:" + path; } At this point any reason we wouldn't throw the exception up and return error to client?

Target:
public String getFile( @PathVariable("id") final String id, final HttpServletRequest request ) throws UnsupportedEncodingException { // When forwarding, the downstream ApplicationContext will perform URL decoding. // If the job ID contains special characters (such as '+'), they will be interpreted as url-encoded and // decoded, resulting in an invalid job ID that cannot be found. // To prevent this, always perform URL encoding on the ID before forwarding. final String encodedId = URLEncoder.encode(id, "UTF-8"); final String path = "/api/v3/jobs/" + encodedId + "/" + ControllerUtils.getRemainingPath(request); return "forward:" + path; }
Source:
private Integer deserializeValue(Map<String, Object> entry, String curveKey, int conversionRate) { Map<String, Double> parameters = (Map<String, Double>) entry.get(curveKey); if (parameters == null) { return null; } Double average = parameters.get(VdsProperties.HOST_QOS_AVERAGE); START return (average == null) ? null : (int) (average / conversionRate); END } How is it possible to get a non-integer value? Is there a way to set the value via the host? If there is, it would be more accurate to save the qos parameters on HostNetworkQos as doubles. Or even saving it as integer but in bits and just displaying it to the user in Mb. I don't understand the benefit of sending/receiving bits as doubles through the api with vdsm.

Target:
private Integer deserializeValue(Map<String, Object> entry, String curveKey, int conversionRate) { Map<String, Integer> parameters = (Map<String, Integer>) entry.get(curveKey); if (parameters == null) { return null; } Integer average = parameters.get(VdsProperties.HOST_QOS_AVERAGE); return (average == null) ? null : (average / conversionRate); }
Source:
public NotifyingFuture<V> attachListener(final FutureListener<V> listener) { future.whenComplete((value, throwable) -> { START if (throwable == null) { END listener.futureDone(this); } else { listener.futureDone(this); } }); return this; } Seems this if else block here can just be replaced by `listener.futureDone(this);`

Target:
public NotifyingFuture<V> attachListener(final FutureListener<V> listener) { future.whenComplete((value, throwable) -> { listener.futureDone(this); }); return this; }
Source:
public TranslatedExpression<T> translate(FunctionMetadata functionMetadata, RowExpression original, List<TranslatedExpression<T>> translatedArguments) { if (!isFunctionPresent(functionMetadata)) { return untranslated(original); } try { return new TranslatedExpression<>(Optional.of((T) functionMapping.get(functionMetadata).invokeWithArguments(translatedArguments)), original, translatedArguments); } START catch (Throwable t) { END return untranslated(original); } } Just let it throw the error.

Target:
public TranslatedExpression<T> translate(FunctionMetadata functionMetadata, RowExpression original, List<TranslatedExpression<T>> translatedArguments) throws Throwable { if (!functionMapping.containsKey(functionMetadata)) { return new TranslatedExpression<>(Optional.empty(), original, translatedArguments); } return new TranslatedExpression<>(Optional.of((T) functionMapping.get(functionMetadata).invokeWithArguments(translatedArguments)), original, translatedArguments); }
Source:
public void maintenance() { Guid clusterId = getClusterIdOfSelectedHosts(); if (clusterId == null) { maintenance(false, false, null); } else { AsyncDataProvider.getInstance().getClusterById(new AsyncQuery<>( cluster -> { if (cluster != null) { START maintenance(true, cluster.supportsGlusterService(), clusterId); END } }), clusterId); } } Since it is always true, can be get rid of this variable?

Target:
public void maintenance() { Guid clusterId = getClusterIdOfSelectedHosts(); if (clusterId == null) { maintenance(false, null); } else { AsyncDataProvider.getInstance().getClusterById(new AsyncQuery<>( cluster -> { if (cluster != null) { maintenance(cluster.supportsGlusterService(), clusterId); } }), clusterId); } }
Source:
public DagBuilder(final String name, final DagProcessor dagProcessor) { requireNonNull(name, "The name of the DagBuilder can't be null"); START requireNonNull(name, "The dagProcessor of the DagBuilder can't be null"); END this.dag = new Dag(name, dagProcessor); } Should this be `requireNonNull(dagProcessor, ` ?

Target:
public DagBuilder(final String name, final DagProcessor dagProcessor) { requireNonNull(name, "The name of the DagBuilder can't be null"); requireNonNull(dagProcessor, "The dagProcessor of the DagBuilder can't be null"); this.dag = new Dag(name, dagProcessor); }
Source:
private void selectStrutsFunctionality(HttpServletRequest request) { Functionality functionality = RenderersAnnotationProcessor.getFunctionalityForType(getFunctionalityType()); MenuFunctionality menuItem = MenuFunctionality.findFunctionality(functionality.getProvider(), functionality.getKey()); START if (!menuItem.isAvailableForCurrentUser()) { END throw AuthorizationException.unauthorized(); } BennuPortalDispatcher.selectFunctionality(request, menuItem); } You should add a `null` check here, as the selected functionality may not be installed, yielding a `null` Menu Item.

Target:
private void selectStrutsFunctionality(HttpServletRequest request) { Functionality functionality = RenderersAnnotationProcessor.getFunctionalityForType(getFunctionalityType()); MenuFunctionality menuItem = MenuFunctionality.findFunctionality(functionality.getProvider(), functionality.getKey()); if (menuItem == null || !menuItem.isAvailableForCurrentUser()) { throw AuthorizationException.unauthorized(); } BennuPortalDispatcher.selectFunctionality(request, menuItem); }
Source:
private void logFailureResponseObject(MockHttpException httpEx, String url, long callDelay) { LogLevel logLevel = restAdapter.logLevel; RestAdapter.Log log = restAdapter.log; if (logLevel.log()) { log.log(String.format("<--- MOCK %s %s (%sms)", httpEx.code, url, callDelay)); if (logLevel.ordinal() >= LogLevel.FULL.ordinal()) { START log.log(httpEx.responseBody + ""); // Hack to convert toString while supporting null. END log.log("<--- END MOCK"); } } } String.valueOf

Target:
private void logFailureResponseObject(MockHttpException httpEx, String url, long callDelay) { LogLevel logLevel = restAdapter.logLevel; RestAdapter.Log log = restAdapter.log; if (logLevel.log()) { log.log(String.format("<--- MOCK %s %s (%sms)", httpEx.code, url, callDelay)); if (logLevel.ordinal() >= LogLevel.FULL.ordinal()) { log.log(String.valueOf(httpEx.responseBody)); log.log("<--- END MOCK"); } } }
Source:
public void newSelection(final TmfPieChartViewer context) { if (context.isDisposed()) { return; } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { START synchronized (context.getMutexLayoutChange()) { END if (!context.isDisposed()) { context.updateTimeRangeSelectionPieChart(); context.getTimeRangePC().redraw(); context.layout(); } } } }); } just use context

Target:
public void newSelection(final TmfPieChartViewer context) { if (context.isDisposed()) { return; } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { synchronized (context) { if (!context.isDisposed()) { context.updateTimeRangeSelectionPieChart(); context.getTimeRangePC().redraw(); context.layout(); } } } }); }
Source:
private void lookupCoordinatorAndRetry(TransactionManager.TxnRequestHandler nextRequestHandler) { if (!nextRequestHandler.needsCoordinator()) { // For non-coordinator requests, sleep here to prevent a tight loop when no node is available time.sleep(retryBackoffMs); metadata.requestUpdate(); } START transactionManager.lookupCoordinator(nextRequestHandler); END transactionManager.retry(nextRequestHandler); } It reads a bit strange to fall through to `lookupCoordinator` if we know the request doesn't need the coordinator. Maybe clearer with a slight restructure: ```java transactionManager.retry(nextRequestHandler); if (nextRequestHandler.needsCoordinator()) { transactionManager.lookupCoordinator(nextRequestHandler); } else { // For non-coordinator requests, sleep here to prevent a tight loop when no node is available time.sleep(retryBackoffMs); metadata.requestUpdate(); } ```

Target:
private void lookupCoordinatorAndRetry(TransactionManager.TxnRequestHandler nextRequestHandler) { if (nextRequestHandler.needsCoordinator()) { transactionManager.lookupCoordinator(nextRequestHandler); } else { // For non-coordinator requests, sleep here to prevent a tight loop when no node is available time.sleep(retryBackoffMs); metadata.requestUpdate(); } transactionManager.retry(nextRequestHandler); }
Source:
public void testGetVersion() throws Exception { BugzillaRestClient client = new BugzillaRestClient(actualFixture.location()); assertNotNull(client.getClient()); assertNull(client.getClient().getLoginToken()); BugzillaRestVersion version = client.getVersion(new NullOperationMonitor()); assertTrue("expeccted: " + actualFixture.getVersion() + " actual: " + version.toString(), START actualFixture.getVersion().compareTo(version.toString()) == 0); END } (spelling) I guess there is a reason you can't use asserEquals here as oppossed to compareTo? Not sure why the semantics should be different there.

Target:
public void testGetVersion() throws Exception { BugzillaRestClient client = new BugzillaRestClient(actualFixture.location()); assertNotNull(client.getClient()); assertNull(client.getClient().getLoginToken()); BugzillaRestVersion version = client.getVersion(new NullOperationMonitor()); assertEquals("expeccted: " + actualFixture.getVersion() + " actual: " + version.toString(), actualFixture.getVersion(), version.toString()); }
Source:
private String locateTool(String tool) { START String[] roots = { "/usr/bin/", "/usr/local/bin/", "/Users/christian/.nvm/versions/node/v6.6.0/bin/" }; END for (String root : roots) { if (new File(root + tool).exists()) { return root + tool; } } return null; } Not sure we need a reference to your particular nodes setup

Target:
private String locateTool(String tool) { String[] roots = { "/usr/bin/", "/usr/local/bin/" }; for (String root : roots) { if (new File(root + tool).exists()) { return root + tool; } } return null; }
Source:
public void setAcl(FileSystem hdfs, String path, AccessControlList acl) throws IOException { // convert AccessControlList into hdfsAcl List<AclEntry> aclSpecs = new ArrayList<>(); for (alluxio.security.authorization.AclEntry entry : acl.getEntries()) { AclEntry hdfsAclEntry = getHdfsAclEntry(entry); aclSpecs.add(hdfsAclEntry); } // set hdfsAcl; try { hdfs.setAcl(new Path(path), aclSpecs); } catch (UnsupportedOperationException e) { START LOG.warn("Setting ACL on HDFS with acl disabled"); END } } this logging may be spammy, so we should not log this.

Target:
public void setAcl(FileSystem hdfs, String path, AccessControlList acl) throws IOException { // convert AccessControlList into hdfsAcl List<AclEntry> aclSpecs = new ArrayList<>(); for (alluxio.security.authorization.AclEntry entry : acl.getEntries()) { AclEntry hdfsAclEntry = getHdfsAclEntry(entry); aclSpecs.add(hdfsAclEntry); } // set hdfsAcl; try { hdfs.setAcl(new Path(path), aclSpecs); } catch (UnsupportedOperationException e) { // noop if hdfs does not support acl } }
Source:
public void sendUserListMessage(UserList userlist){ UserListMessage ulm = new UserListMessage(userlist); broadcastMessageToFans(ulm); START Log.i("Messaging Service", "User List Message Sent"); END } Lets use a TAG variable

Target:
public void sendUserListMessage(UserList userlist){ UserListMessage ulm = new UserListMessage(userlist); broadcastMessageToFans(ulm); }
Source:
private int nextCorrelationId() { START if (SaslClientAuthenticator.isReserved(correlation)) correlation = SaslClientAuthenticator.MAX_RESERVED_CORRELATION_ID + 1; END return correlation++; } make it if-then-else since we dont't need the increment in the line below? Also split this line since we don't include the statement in the same line as `if`.

Target:
int nextCorrelationId() { if (SaslClientAuthenticator.isReserved(correlation)) { // the numeric overflow is fine as negative values is acceptable correlation = SaslClientAuthenticator.MAX_RESERVED_CORRELATION_ID + 1; } return correlation++; }
Source:
public void uniqueCorrelationIDs() throws MuleException { CoreEvent firstEvent = getEventBuilder().message(of("first")).build(); CoreEvent secondEvent = getEventBuilder().message(of("second")).build(); assertThat("Duplicated correlationID", firstEvent.getContext().getCorrelationId(), START not(Is.is(secondEvent.getContext().getCorrelationId()))); END } static import for `is`

Target:
public void uniqueCorrelationIDs() throws MuleException { CoreEvent firstEvent = getEventBuilder().message(of("first")).build(); CoreEvent secondEvent = getEventBuilder().message(of("second")).build(); assertThat("Duplicated correlationID", firstEvent.getContext().getCorrelationId(), not(is(secondEvent.getContext().getCorrelationId()))); }
Source:
private void setupActivityFromState(final Bundle state) { if (state != null) { START if (!shouldShowDualPane) { END toggleNavigationDrawer(state.getBoolean(STATE_DRAWER_OPENED, false)); } } } Single if can be used here too

Target:
private void setupActivityFromState(final Bundle state) { if (state != null && !shouldShowDualPane) { toggleNavigationDrawer(state.getBoolean(STATE_DRAWER_OPENED, false)); } }
Source:
public VdcActionParametersBase getParameters(Host incoming, VDS entity) { VdsStatic updated = getMapper(modelType, VdsStatic.class).map(incoming, entity.getStaticData()); START UpdateVdsActionParameters updateParams = new UpdateVdsActionParameters(updated, "root", "", false); END if (incoming.isSetOverrideIptables()) { updateParams.setOverrideFirewall(incoming.isOverrideIptables()); } return updateParams; } why hardcode?

Target:
public VdcActionParametersBase getParameters(Host incoming, VDS entity) { VdsStatic updated = getMapper(modelType, VdsStatic.class).map(incoming, entity.getStaticData()); UpdateVdsActionParameters updateParams = new UpdateVdsActionParameters(updated, "", false); if (incoming.isSetOverrideIptables()) { updateParams.setOverrideFirewall(incoming.isOverrideIptables()); } return updateParams; }
Source:
START private boolean isSamePrefix(String a, String b) { END int as = a.lastIndexOf('/'); int bs = b.lastIndexOf('/'); return a.substring(0, as + 1).equals(b.substring(0, bs + 1)); } Style-nit: This method can be static.

Target:
private static boolean isSamePrefix(String a, String b) { int as = a.lastIndexOf('/'); int bs = b.lastIndexOf('/'); return a.substring(0, as + 1).equals(b.substring(0, bs + 1)); }
Source:
public void stop(ComponentContext context) throws InterruptedException { super.stop(context); START redirectResolver = new DefaultRedirectResolver(); END } Do we need it after stop ? If not, it makes more sense to put it in `start` method (and maybe remove the field init).

Target:
public void stop(ComponentContext context) throws InterruptedException { super.stop(context); redirectResolver = null; }
Source:
START public synchronized void initCamelCronService() { END if (this.service == null) { this.service = CronHelper.resolveCamelCronService( getCamelContext(), this.cronService ); if (this.service == null) { throw new RuntimeCamelException("Cannot find any CamelCronService: please add a valid implementation, such as 'camel-quartz', in order to use the 'camel-cron' component"); } try { getCamelContext().addService(this.service, true, false); } catch (Exception e) { throw new RuntimeCamelException(e); } } } I am not a fan of this, cant we move this to doStart so its initialized there?

Target:
public void initCamelCronService() { if (this.service == null) { this.service = CronHelper.resolveCamelCronService( getCamelContext(), this.cronService ); if (this.service == null) { throw new RuntimeCamelException("Cannot find any CamelCronService: please add a valid implementation, such as 'camel-quartz', in order to use the 'camel-cron' component"); } try { getCamelContext().addService(this.service, true, false); } catch (Exception e) { throw new RuntimeCamelException(e); } } }
Source:
public void teardownTest() throws InterruptedException { //give time for operations to finish firewallPolicyApi().delete(currentFirewallPolicy.id()); START Thread.sleep(15000); END assertNodeAvailable(currentServer); deleteServer(currentServer.id()); } Doing this in a live test is a symptom of something that users will probably have to do themselves. better use the build-in `Predicates2.retry` construct to wait until the server is deleted and consider binding it to the guice context so it can be reused where needed.

Target:
public void teardownTest() throws InterruptedException { assertNodeAvailable(currentServer); firewallPolicyApi().delete(currentFirewallPolicy.id()); assertNodeAvailable(currentServer); deleteServer(currentServer.id()); }
Source:
public Object next() { if ( position >= len ) { throw new NoSuchElementException(); } Object result = Array.get( array, position ); position++; START return result; END } In what way is this an improvement?

Target:
public Object next() { if ( position >= len ) { throw new NoSuchElementException(); } int offset = position++; return Array.get( array, offset ); }
Source:
protected int getNumOfElementOnPage(By cssSelectorBy) { changeImplicitWait(500, TimeUnit.MILLISECONDS); START int numElementOnPage = 0; END try { numElementOnPage = driver.findElements(cssSelectorBy).size(); } catch (Exception ex) { numElementOnPage = 0; } finally { restoreDeaultImplicitWait(); } return numElementOnPage; } Why are you assigning 0 to numElementOnPage, as you assign some value again in the next line?

Target:
protected int getNumOfElementOnPage(By cssSelectorBy) { changeImplicitWait(500, TimeUnit.MILLISECONDS); int numElementOnPage; try { numElementOnPage = driver.findElements(cssSelectorBy).size(); } catch (Exception ex) { numElementOnPage = 0; } finally { restoreDeaultImplicitWait(); } return numElementOnPage; }
Source:
public void set(String field, final String value) { START if (!"".equals(field)) { END if (isUserDefinedField(field)) { userDefinedFields.put(field, value); String fieldName = getUserDefinedFieldName(field); if (fieldName != null) { userDefinedFieldNames.add(new ControlField(fieldName)); } field = fieldName; } if (field != null) { values.put(field, value); } } } I don't understand this, why testing if the field name is not empty? Shouldn't this be removed?

Target:
public void set(String field, final String value) { if (field != null && isUserDefinedField(field)) { userDefinedFields.put(field, value); String fieldName = getUserDefinedFieldName(field); if (fieldName != null) { userDefinedFieldNames.add(new ControlField(fieldName)); } field = fieldName; } if (field != null && !"".equals(field)) { values.put(field, value); } }
Source:
public Result(String targetContentEncoding, EmbeddedChannel contentEncoder) { ObjectUtil.checkNotNull(targetContentEncoding, "targetContentEncoding"); ObjectUtil.checkNotNull(contentEncoder, "contentEncoder"); this.targetContentEncoding = targetContentEncoding; START this.contentEncoder = contentEncoder; END } nit: you can merge lines above as `checkNotNull` will return the given argument

Target:
public Result(String targetContentEncoding, EmbeddedChannel contentEncoder) { this.targetContentEncoding = ObjectUtil.checkNotNull(targetContentEncoding, "targetContentEncoding"); this.contentEncoder = ObjectUtil.checkNotNull(contentEncoder, "contentEncoder"); }
Source:
public boolean onPrepareOptionsMenu(Menu menu) { LibraryAdapter adapter = mCurrentAdapter; boolean isLibraryAdapter = (adapter != null && adapter.getMediaType() != MediaUtils.TYPE_FILE); START menu.findItem(MENU_GO_HOME).setVisible(!isLibraryAdapter); END menu.findItem(MENU_SORT).setEnabled(adapter != null); return super.onPrepareOptionsMenu(menu); } Just change this to ``` setVisible(adapter != null && adapter.getMediaType() == MediaUtils.TYPE_FILE) ``` and get rid of isLibraryAdapter

Target:
public boolean onPrepareOptionsMenu(Menu menu) { LibraryAdapter adapter = mCurrentAdapter; menu.findItem(MENU_GO_HOME).setVisible( adapter != null && adapter.getMediaType() == MediaUtils.TYPE_FILE); menu.findItem(MENU_SORT).setEnabled(adapter != null); return super.onPrepareOptionsMenu(menu); }
Source:
public void login() { START page.login(validAdminPassword, validAdminLogin); END } Looks strange.

Target:
public void login() { page.login(validAdminLogin, validAdminPassword); }
Source:
START protected static String truncateValueToMaxLength(String inputValue, int maxLength) { END if (StringUtils.length(inputValue) <= maxLength) { return inputValue; } else { return inputValue.substring(0, maxLength); } } Could you use StringUtils.truncate instead?

Target:
protected String truncateValueToMaxLength(String inputValue, int maxLength) { return StringUtils.substring(inputValue, 0, maxLength); }
Source:
private void init() { // Creating ObjectChecker must be deferred. Unit tests change // behavior of is{Windows,MacOS} in constructor of subclass. START if (platformChecker == null) { END setPlatformChecker(); } } style nit: we don't use braces around single line blocks

Target:
private void init() { // Creating ObjectChecker must be deferred. Unit tests change // behavior of is{Windows,MacOS} in constructor of subclass. if (platformChecker == null) setPlatformChecker(); }
Source:
private static II getLivingSubjectId(PRPAMT201306UV02LivingSubjectId id) { II oII = null; START if (id != null && id.getValue() != null && id.getValue().size() > 0) { END oII = id.getValue().get(0); } return oII; } Again, prefer "isEmpty()" over a "size()" comparison.

Target:
private static II getLivingSubjectId(PRPAMT201306UV02LivingSubjectId id) { II oII = null; if (id != null && id.getValue() != null && !id.getValue().isEmpty()) { oII = id.getValue().get(0); } return oII; }
Source:
public MediaType getContentType() { if (this.readOnly && this.cachedContentType != null) { return this.cachedContentType; } else { String value = getFirst(CONTENT_TYPE); MediaType contentType = (StringUtils.hasLength(value) ? MediaType.parseMediaType(value) : null); if (this.readOnly) { this.cachedContentType = contentType; } return contentType; START } END } This can be improved. The `this.readOnly` check shows that this method is mixing two concerns: map lookup and caching. I would prefer if caching was done in a separate wrapper class(`ReadOnlyHttpHeaders`), that is returned when `HttpHeaders.readOnlyHttpHeaders` is called (instead of backing the map with an unmodifiable `MultiValueMap`).

Target:
public MediaType getContentType() { String value = getFirst(CONTENT_TYPE); return (StringUtils.hasLength(value) ? MediaType.parseMediaType(value) : null); }
Source:
protected String[] fillTypeCombo() { START ArrayList<String> END list = new ArrayList<>(); for(DataType dataType : EventTypeLibrary.getInstance().getEventTypes()){ list.add(dataType.getName()); } return list.toArray(new String[0]); } change to List

Target:
protected String[] fillTypeCombo() { List<String> list = new ArrayList<>(); for(DataType dataType : EventTypeLibrary.getInstance().getEventTypes()){ list.add(dataType.getName()); } return list.toArray(new String[0]); }
Source:
public NettyTransportConnectionStats(EmbeddedCacheManager cacheManager, ChannelGroup acceptedChannels, String threadNamePrefix) { this.cacheManager = cacheManager; START this.isGlobalStatsEnabled = cacheManager != null ? cacheManager.getCacheManagerConfiguration().globalJmxStatistics().enabled() : false; END this.acceptedChannels = acceptedChannels; this.threadNamePrefix = threadNamePrefix; } Can be simplified to `cacheManager != null && cacheManager.getCacheManagerConfiguration().globalJmxStatistics().enabled()`

Target:
public NettyTransportConnectionStats(EmbeddedCacheManager cacheManager, ChannelGroup acceptedChannels, String threadNamePrefix) { this.cacheManager = cacheManager; this.isGlobalStatsEnabled = cacheManager != null && cacheManager.getCacheManagerConfiguration().globalJmxStatistics().enabled(); this.acceptedChannels = acceptedChannels; this.threadNamePrefix = threadNamePrefix; }
Source:
public static Scheduler computation() { START synchronized (computationGuard) { END if (computationScheduler == null) { Scheduler c = RxJavaPlugins.getInstance().getSchedulersHook().getComputationScheduler(); if (c != null) { computationScheduler = c; } else { computationScheduler = new EventLoopsScheduler(); } } return computationScheduler; } } I don't like putting a synchronized block in the line of fire on something like this that doesn't need to be. This is a global lock and exactly the type of stuff I find in our production environments.

Target:
public static Scheduler computation() { Scheduler s = computationScheduler; if (s != null) { return s; } synchronized (computationGuard) { if (computationScheduler == null) { Scheduler c = RxJavaPlugins.getInstance().getSchedulersHook().getComputationScheduler(); if (c != null) { computationScheduler = c; } else { computationScheduler = new EventLoopsScheduler(); } } return computationScheduler; } }
Source:
public Change munge(String entityId, Collection<Statement> statements) { START munge(entityId, END statements, emptySet(), emptySet(), null, null); } missing return

Target:
public Change munge(String entityId, Collection<Statement> statements) { return munge(entityId, statements, emptySet(), emptySet(), null, null); }
Source:
public void testMaxSizePassed() throws ArrayIndexOutOfBoundsException { START try{SizeLimitedVector slv = new SizeLimitedVector(1); slv.add(13); slv.add(14); } catch (ArrayIndexOutOfBoundsException e) { fail("array capacity is passed, capacity was 1, but 2 elements got added"); } END } The whole point of the SizeLimitedVector is that you can append as many things to it as you like but it only stores the last X amount.

Target:
public void testMaxSizePassed() throws ArrayIndexOutOfBoundsException { SizeLimitedVector slv = new SizeLimitedVector(1); slv.add(13); slv.add(14); assertEquals(slv.get(0), 14); }
Source:
public Double getTotalCpuReqTask(ExecutorDetails exec) { if (hasExecInTopo(exec)) { return _resourceList .get(exec) .get(Config.TOPOLOGY_COMPONENT_CPU_PCORE_PERCENT); } START LOG.warn("cannot find - {}", exec); END return null; } Again I don't think this log message adds much.

Target:
public Double getTotalCpuReqTask(ExecutorDetails exec) { if (hasExecInTopo(exec)) { return _resourceList .get(exec) .get(Config.TOPOLOGY_COMPONENT_CPU_PCORE_PERCENT); } return null; }
Source:
public static void writeStyle(final InputStream in, final Resource styleFile) throws IOException { BufferedOutputStream out = null; try { out = new BufferedOutputStream(styleFile.out()); IOUtils.copy(in, out); out.flush(); } finally { START out.close(); END } } Perhaps try-with-resources? And there are also tabs here that could be fixed.

Target:
public static void writeStyle(final InputStream in, final Resource styleFile) throws IOException { try (BufferedOutputStream out = new BufferedOutputStream(styleFile.out())) { IOUtils.copy(in, out); out.flush(); } }
Source:
private void RestoreVmFromBaseSnapshot(VM vm) { if (DbFacade.getInstance().getDiskImageDAO().getAllStatelessVmImageMapsForVm(vm.getId()).size() > 0) { START log.infoFormat("Deleting snapshots for stateless vm {0}", vm.getId()); END Backend.getInstance().runInternalAction(VdcActionType.RestoreStatelessVm, new VmOperationParameterBase(vm.getId()), new CommandContext(getCompensationContext())); } } Please dont use this {0} , and use String.format instead.

Target:
private void RestoreVmFromBaseSnapshot(VM vm) { if (getDiskImageDAO().getAllStatelessVmImageMapsForVm(vm.getId()).size() > 0) { log.infoFormat("Deleting snapshots for stateless vm {0}", vm.getId()); Backend.getInstance().runInternalAction(VdcActionType.RestoreStatelessVm, new VmOperationParameterBase(vm.getId()), new CommandContext(getCompensationContext())); } }
Source:
public void setParams(Object[] params) { if (params.length != 1) { throw new IllegalArgumentException("expecting one parameter"); } START setParams((Map<Object, Number>) params[0]); END } Please use Map<?,?>

Target:
public void setParams(Object[] params) { if (params.length != 1) { throw new IllegalArgumentException("expecting one parameter"); } setParams((Map<?, ?>) params[0]); }
Source:
public LuceneAnalysisDefinitionTranslationMapBuilder(Class<D> targetClass) { START super(); END this.targetClass = targetClass; } No `super();` needed.

Target:
public LuceneAnalysisDefinitionTranslationMapBuilder(Class<D> targetClass) { this.targetClass = targetClass; }
Source:
public void should_balance_requests_across_connections() throws InterruptedException { // Generate just the right load to completely fill the pool. All requests should succeed. int simultaneousRequests = POOL_SIZE * REQUESTS_PER_CONNECTION; for (int i = 0; i < simultaneousRequests; i++) { reschedule(null, null); } START SECONDS.sleep(5); END done.countDown(); Throwable unexpectedError = unexpectedErrorRef.get(); if (unexpectedError != null) { fail("At least one request failed unexpectedly", unexpectedError); } } Introduction 5 seconds delay in a test seems like a lot, maybe instead we could create a new `AtomicInteger successfullRequests = simultaneousRequests`, increment it in every successful session execute, and change the sleep to: `awaitUntil( () successfullRequests == simultaneousRequests)`? The test will keep the characteristic because we will be waiting until all succeed OR error will happen. wdyt?

Target:
public void should_balance_requests_across_connections() throws InterruptedException { // Generate just the right load to completely fill the pool. All requests should succeed. int simultaneousRequests = POOL_SIZE * REQUESTS_PER_CONNECTION; for (int i = 0; i < simultaneousRequests; i++) { reschedule(null, null); } SECONDS.sleep(1); done.countDown(); Throwable unexpectedError = unexpectedErrorRef.get(); if (unexpectedError != null) { fail("At least one request failed unexpectedly", unexpectedError); } }
Source:
public void generateSourceMaps() throws Exception { when(xwikiPropertiesSource.getProperty("lesscss.generateInlineSourceMaps", false)).thenReturn(true); boolean b = mocker.getComponentUnderTest().isGenerateInlineSourceMaps(); START assertTrue(b == true); END } ``` assertTrue(b); ```

Target:
public void generateSourceMaps() throws Exception { when(xwikiPropertiesSource.getProperty("lesscss.generateInlineSourceMaps", false)).thenReturn(true); boolean b = mocker.getComponentUnderTest().isGenerateInlineSourceMaps(); assertTrue(b); }
Source:
private IStatus getFormPresenterStatus() { IStatus saveStatus = Status.OK_STATUS; if (formPresenterSupport != null && formPresenterSupport.getCurrentStatus() != null) { saveStatus = formPresenterSupport.getCurrentStatus(); } START return saveStatus; END } i don't think that `formPresenterSupport` can be `null`. If i miss something, then these null checks must be also added to `dispose` method

Target:
private IStatus getFormPresenterStatus() { IStatus status = Status.OK_STATUS; if (formPresenterSupport.getCurrentStatus() != null) { status = formPresenterSupport.getCurrentStatus(); } return status; }
Source:
protected void fallbackOnDefaultCache() { CacheService cacheService = Framework.getService(CacheService.class); if (cacheService != null) { if (descriptor.cacheEntryName == null) { cache.setEntryCacheName("cache-" + getName()); START cacheService.registerCache("cache-" + getName()); END } if (descriptor.cacheEntryWithoutReferencesName == null) { cache.setEntryCacheWithoutReferencesName("cacheWithoutReference-" + getName()); cacheService.registerCache("cacheWithoutReference-" + getName()); } } } Put `"cache-" + getName()` in a local variable to avoid repetition.

Target:
protected void fallbackOnDefaultCache() { CacheService cacheService = Framework.getService(CacheService.class); if (cacheService != null) { if (descriptor.cacheEntryName == null) { String cacheEntryName = "cache-" + getName(); cache.setEntryCacheName(cacheEntryName); cacheService.registerCache(cacheEntryName); } if (descriptor.cacheEntryWithoutReferencesName == null) { String cacheEntryWithoutReferencesName = "cacheWithoutReference-" + getName(); cache.setEntryCacheWithoutReferencesName(cacheEntryWithoutReferencesName); cacheService.registerCache(cacheEntryWithoutReferencesName); } } }
Source:
public void addInformation(ItemStack stack, World world, List<String> tooltip, ITooltipFlag flag) { START if (stack.hasTagCompound()) { END Binding binding = getBinding(stack); if (binding != null) { tooltip.add(new TextComponentTranslation("tooltip.bloodmagic.currentOwner", binding.getOwnerName()).getFormattedText()); } } } There is no reason for these formatting changes

Target:
public void addInformation(ItemStack stack, World world, List<String> tooltip, ITooltipFlag flag) { if (!stack.hasTagCompound()) return; Binding binding = getBinding(stack); if (binding != null) tooltip.add(new TextComponentTranslation("tooltip.bloodmagic.currentOwner", binding.getOwnerName()).getFormattedText()); }
Source:
private static String normaliseTypeName(String dataType) { START if (dataType.indexOf("(")<=0) END dataType = dataType.toUpperCase().trim(); else dataType = dataType.toUpperCase().trim().substring(0,dataType.indexOf("(")); return dataType; } There no whitespace around `<=`. Also - good to enclose blocks of that that if/else in {}.

Target:
private static String normaliseTypeName(String dataType) { if (dataType.indexOf("(") <= 0) { dataType = dataType.toUpperCase().trim(); } else { dataType = dataType.toUpperCase().trim().substring(0,dataType.indexOf("(")); } return dataType; }
Source:
START public String sendHttpGetToBroker(String table, String path) END { return doHttpActionWithHeaders( Request.builder().prepareGet().setUri(URI.create(String.format("http://%s/%s", getBrokerHost(table), path))), Optional.empty(), Optional.empty()); } private

Target:
private String sendHttpGetToBroker(String table, String path) { return doHttpActionWithHeaders( Request.builder().prepareGet().setUri(URI.create(String.format("http://%s/%s", getBrokerHost(table), path))), Optional.empty(), Optional.empty()); }
Source:
START public FluoConfiguration resolveFluoConfiguration(String appName) { END try { return getAppConfiguration(appName); } catch (FluoException e) { FluoConfiguration config = new FluoConfiguration(getFluoConfiguration()); config.setApplicationName(appName); return config; } } Not sure if this would be the best place to print it. I was thinking it may be useful to print which config file it ended up using.

Target:
public FluoConfiguration resolveFluoConfiguration(String appName) { return resolveFluoConfiguration(appName, true); }
Source:
public String getCachedString() { START String rv; END if (variableData.expression == null || variableData.expression.length() == 0) rv = "_"; else if (Double.isNaN(getCachedValue())) rv = "*"; else rv = "" + (int) getCachedValue(); return rv; } This variable is useless. Please just use `return` in your `if/…` branches.

Target:
public String getCachedString() { final String rv; if (variableData.expression == null || variableData.expression.length() == 0) { rv = "_"; } else if (Double.isNaN(getCachedValue())) { rv = "*"; } else { rv = String.valueOf((int) getCachedValue()); } return rv; }
Source:
public static boolean anyRunning() { IConsole ic[] = ConsolePlugin.getDefault().getConsoleManager().getConsoles(); ScriptConsole console; for(int i=0; i<ic.length; i++) { if (ic[i] instanceof ScriptConsole){ console = (ScriptConsole)ic[i]; if(console.isRunning()) START return true; END } } return false; } Please use even for one line if clauses.

Target:
public static boolean anyRunning() { IConsole ic[] = ConsolePlugin.getDefault().getConsoleManager().getConsoles(); ScriptConsole console; for(int i=0; i<ic.length; i++) { if (ic[i] instanceof ScriptConsole){ console = (ScriptConsole)ic[i]; if(console.isRunning()){ return true; } } } return false; }
Source:
private void checkVersionForProfileLI(PackageSetting ps, PackageParser.Package pkg) { if (isUpgrade() && ps != null && pkg != null) { if (ps.versionCode != pkg.mVersionCode) { Slog.d(TAG, ps.name + " clear profile due to version change " + ps.versionCode + " != " + pkg.mVersionCode); clearAppProfilesLIF(pkg, UserHandle.USER_ALL); START END return true; } if (DEBUG_INSTALL) { Slog.d(TAG, "Package " + ps.name + " keep profile"); } } } oups, bad rebase.

Target:
private void checkVersionForProfileLI(PackageSetting ps, PackageParser.Package pkg) { if (isUpgrade() && ps != null && pkg != null) { if (ps.versionCode != pkg.mVersionCode) { Slog.d(TAG, ps.name + " clear profile due to version change " + ps.versionCode + " != " + pkg.mVersionCode); clearAppProfilesLIF(pkg, UserHandle.USER_ALL); return; } if (DEBUG_INSTALL) { Slog.d(TAG, "Package " + ps.name + " keep profile"); } } }