auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private int onSpinMisses(int spins) { START if (UPDATE_STATISTICS) spinMisses.increment(); END if (spins == YIELD_SPINS) { spins = 0; Thread.yield(); } else { spins++; JDKSpecific.onSpinWait(); } return spins; } I'm concerned that this might not be inlined.

Target:
private int onSpinMisses(int spins) { if (UPDATE_STATISTICS) spinMisses.increment(); if (spins == YIELD_SPINS) { Thread.yield(); return 0; } JDKSpecific.onSpinWait(); return spins + 1; }
Source:
private static String resolveKafkaService() { START final StringBuilder sb = new StringBuilder() END .append(resolve(KAFKA_SERVICE_HOST)) .append(":") .append(resolve(KAFKA_SERVICE_PORT)); return sb.toString(); } No need to assign to a variable

Target:
private static String resolveKafkaService() { return new StringBuilder() .append(resolve(KAFKA_SERVICE_HOST)) .append(":") .append(resolve(KAFKA_SERVICE_PORT)).toString(); }
Source:
public void onBackPressed() { if (referencesViewPager.getCurrentItem() > 0) { referencesViewPager.setCurrentItem(referencesViewPager.getCurrentItem() - 1, true); START } END } This correctly cycles back through the pager when the Back button is pressed. However, when the first position is reached, the Back button has no effect (i.e. the dialog should close when Back is pressed). To handle the final Back case, you could add an `else` here and say the following: else { super.onBackPressed(); }

Target:
public void onBackPressed() { if (referencesViewPager.getCurrentItem() > 0) { referencesViewPager.setCurrentItem(referencesViewPager.getCurrentItem() - 1, true); } else { super.onBackPressed(); } }
Source:
public int hashCode() { START int result = name != null ? name.hashCode() : 0; END result = 31 * result + (sqlObjectType != null ? sqlObjectType.hashCode() : 0); result = 31 * result + (sqlObjectMethod != null ? sqlObjectMethod.hashCode() : 0); return result; } ditto on readability here: ``` int result = name == null ? 0 : name.hashCode(); ```

Target:
public int hashCode() { int result = name == null ? 0 : name.hashCode(); result = 31 * result + (sqlObjectType != null ? sqlObjectType.hashCode() : 0); result = 31 * result + (sqlObjectMethod != null ? sqlObjectMethod.hashCode() : 0); return result; }
Source:
public Implementation() { plugin = this; START pageRegistry = new PageRegistry(); pageRegistry.addPageProvider(new DefaultPageProvider()); END } Should be done inside start().

Target:
public Implementation() { plugin = this; }
Source:
public Symbol cast(DataType<?> targetType, boolean tryCast) { if (targetType.equals(valueType())) { return this; START } else if (ArrayType.unnest(targetType).equals(DataTypes.UNTYPED_OBJECT) END && valueType().id() == DataTypes.UNTYPED_OBJECT.id()) { return this; } return CastFunctionResolver.generateCastFunction(this, targetType, tryCast); } Looks better to me to have it here :+1:

Target:
public Symbol cast(DataType<?> targetType, boolean tryCast) { if (targetType.equals(valueType())) { return this; } else if (ArrayType.unnest(targetType).equals(DataTypes.UNTYPED_OBJECT) && valueType().id() == targetType.id()) { return this; } return CastFunctionResolver.generateCastFunction(this, targetType, tryCast); }
Source:
public static boolean validate() { boolean valid = true; for (Map.Entry<String, String> entry : toMap().entrySet()) { String propertyName = entry.getKey(); if (!PropertyKey.isValid(propertyName)) { START LOG.warn("Unsupported property {}" + propertyName); END valid = false; } } return valid; } `LOG.warn("Unsupported property {}", propertyName);`

Target:
public static boolean validate() { boolean valid = true; for (Map.Entry<String, String> entry : toMap().entrySet()) { String propertyName = entry.getKey(); if (!PropertyKey.isValid(propertyName)) { LOG.warn("Unsupported property {}", propertyName); valid = false; } } return valid; }
Source:
public String BuildJSON() { if (swagger != null) { updateHostAndBasePath(); } else { synchronized (this) { START log.info("Initiating Swagger specification creation"); END toggleLogs(RestConstants.SWAGGER_LOGS_OFF); try { initSwagger(); addPaths(); addDefaultDefinitions(); // addSubclassOperations(); //FIXME uncomment after fixing the method } catch (Exception e) { log.error("Error while creating Swagger specification", e); } finally { toggleLogs(RestConstants.SWAGGER_LOGS_ON); log.info("Swagger specification creation complete"); } } } return createJSON(); } Wrapping the else body in a new method will make it even cleaner.

Target:
private void BuildJSON() { synchronized (this) { log.info("Initiating Swagger specification creation"); toggleLogs(RestConstants.SWAGGER_LOGS_OFF); try { initSwagger(); addPaths(); addDefaultDefinitions(); // addSubclassOperations(); //FIXME uncomment after fixing the method } catch (Exception e) { log.error("Error while creating Swagger specification", e); } finally { toggleLogs(RestConstants.SWAGGER_LOGS_ON); log.info("Swagger specification creation complete"); } } }
Source:
static List<TypeName> list(Type[] types) { List<TypeName> result = new ArrayList<>(types.length); //noinspection ForLoopReplaceableByForEach START for (int i = 0; i < types.length; i++) { END result.add(get(types[i])); } return result; } This is bytecode equivalent to using the for-each syntax on an array.

Target:
static List<TypeName> list(Type[] types) { List<TypeName> result = new ArrayList<>(types.length); for (Type type : types) { result.add(get(type)); } return result; }
Source:
private boolean loadDataInMemory() { String value = Optional.ofNullable(GeoServerExtensions.getProperty("WMTS_HISTOGRAM_IN_MEMORY")) START .orElse("false"); END return Boolean.getBoolean(value); } If ``value`` is ``NULL``, ``Boolean.getBoolean(value)`` will return ``FALSE`` anyway, but I understand that this is more explicit.

Target:
private boolean loadDataInMemory() { String value = GeoServerExtensions.getProperty("WMTS_HISTOGRAM_IN_MEMORY"); return Boolean.getBoolean(value); }
Source:
public Map<String, Integer> getRemainingQueries() { START synchronized (this) { END Map<String, Integer> queriesInfo = new HashMap<String, Integer>(); queriesInfo.put("queriesCount", queries.size()); queriesInfo.put("fragmentsCount", runningFragments.size()); return queriesInfo; } } Since the entire body is synchronized, put the `synchronized` on the method itself.

Target:
public synchronized Map<String, Integer> getRemainingQueries() { Map<String, Integer> queriesInfo = new HashMap<String, Integer>(); queriesInfo.put("queriesCount", queries.size()); queriesInfo.put("fragmentsCount", runningFragments.size()); return queriesInfo; }
Source:
public void next() { START RadioDroidApp radioDroidApp = (RadioDroidApp) this.getApplication(); END DataRadioStation station = radioDroidApp.getFavouriteManager().getNextById(currentStationID); if (station != null) new RadioDroidBrowserService.GetRealLinkAndPlayTask(itsContext, station, itsBinder).execute(); } You may remove `this.`

Target:
public void next() { RadioDroidApp radioDroidApp = (RadioDroidApp) getApplication(); DataRadioStation station = radioDroidApp.getFavouriteManager().getNextById(currentStationID); if (station != null) new GetRealLinkAndPlayTask(itsContext, station, itsBinder).execute(); }
Source:
public void connectDisconnect() throws IOException { final FtpFacade facade = FtpFacadeTest.mockFacade(); final FTPClient ftp = new FTPClient(); try { facade.listen(); ftp.connect("localhost"); START final int reply = ftp.getReplyCode(); END MatcherAssert.assertThat( FTPReply.isPositiveCompletion(reply), Matchers.equalTo(true) ); MatcherAssert.assertThat( ftp.logout(), Matchers.equalTo(true) ); } finally { facade.close(); } } please inline this variable

Target:
public void connectDisconnect() throws IOException { final FtpFacade facade = FtpFacadeTest.mockFacade(); final FTPClient ftp = new FTPClient(); try { facade.listen(); ftp.connect("localhost"); MatcherAssert.assertThat( FTPReply.isPositiveCompletion(ftp.getReplyCode()), Matchers.equalTo(true) ); MatcherAssert.assertThat( ftp.logout(), Matchers.equalTo(true) ); } finally { facade.close(); } }
Source:
@Override public void close() { EndpointGroup endpointGroup = EndpointGroupRegistry.get("elasticsearch"); if (endpointGroup != null) { endpointGroup.close(); EndpointGroupRegistry.unregister("elasticsearch"); } START factory.close(); END } Could put this in a `finally` or local try-with-resources in case `endpointGroup.close()` throws for some reason, though it's extremely careful.

Target:
@Override public void close() { EndpointGroup endpointGroup = EndpointGroupRegistry.get("elasticsearch"); if (endpointGroup != null) { endpointGroup.close(); EndpointGroupRegistry.unregister("elasticsearch"); } }
Source:
void doPrefetch(long relativeOffset, long size) throws IOException { long sizeToRead = Math.min(size, getMessageInfo().getSize() - relativeOffset); prefetchedData = ByteBuffer.allocate((int) sizeToRead); START getChannel().position(offset.getOffset() + relativeOffset); END getChannel().read(prefetchedData); prefetchedDataRelativeOffset = relativeOffset; } I'm not sure this will work in a concurrent environment. Isn't this a shared channel? Can you instead use [this](https://docs.oracle.com/javase/8/docs/api/java/nio/channels/FileChannel.html#read-java.nio.ByteBuffer-long-)?

Target:
void doPrefetch(long relativeOffset, long size) throws IOException { long sizeToRead = Math.min(size, getMessageInfo().getSize() - relativeOffset); prefetchedData = ByteBuffer.allocate((int) sizeToRead); getChannel().read(prefetchedData, offset.getOffset() + relativeOffset); prefetchedDataRelativeOffset = relativeOffset; }
Source:
public ProcessorExpressionRoute(String expression, Processor processor) { super(processor); START requireNonNull(expression, "expression can't be null"); END this.expression = expression; } this returns the expression, you can combine this line and the next

Target:
public ProcessorExpressionRoute(String expression, Processor processor) { super(processor); this.expression = requireNonNull(expression, "expression can't be null"); }
Source:
public CachingHasher build() throws IllegalArgumentException { START List<long[]> cache = new ArrayList<long[]>(); END for (byte[] buff : buffers) { long[] result = new long[2]; result[0] = function.apply(buff, 0); result[1] = function.apply(buff, 1) - result[0]; cache.add(result); } return new CachingHasher(function, cache); } use final

Target:
public final CachingHasher build() throws IllegalArgumentException { List<long[]> cache = new ArrayList<long[]>(); for (byte[] buff : buffers) { long[] result = new long[2]; result[0] = function.apply(buff, 0); result[1] = function.apply(buff, 1) - result[0]; cache.add(result); } return new CachingHasher(function, cache); }
Source:
START public Object merge( Object parent ) { END if (parent == null) { return this; } if (parent instanceof MockHttpServletRequestBuilder) { this.mergeable = (Mergeable) parent; return this.mergeable; } else { throw new IllegalArgumentException("Cannot merge with [" + parent.getClass().getName() + "]"); } } Remove extra space for consistent formatting ```suggestion public Object merge(Object parent ) { ```

Target:
public Object merge(Object parent) { if (parent == null) { return this; } if (parent instanceof Mergeable ) { this.parent = (Mergeable) parent; return this; } else { throw new IllegalArgumentException("Cannot merge with [" + parent.getClass().getName() + "]"); } }
Source:
public Parser<I, Stream<A>, E> repeat1() { START return bind(a -> repeat().map(new F<Stream<A>, Stream<A>>() { END public Stream<A> f(final Stream<A> as) { return as.cons(a); } })); } Lambda here?

Target:
public Parser<I, Stream<A>, E> repeat1() { return bind(a -> repeat().map(as -> as.cons(a))); }
Source:
public String getLanguage() { START if (null == this.language) { return ""; //$NON-NLS-1$ } return this.language; END } You can do it in one line. More lisibility.

Target:
public String getLanguage() { return this.language!=null ? this.language : "" ; //$NON-NLS-1$ }
Source:
public boolean execute(short a, BlockComponentHolder b) { try { START for (Component c : b.values()) { END c.onAttached(); } } catch (Exception e) { Spout.getLogger().log(Level.SEVERE, "Unhandled exception attaching block component", e); } return true; } Formatting is off here, try should be around each onAttached() so that 1 bad component does not break all of the components.

Target:
public boolean execute(short a, BlockComponentHolder b) { for (Component c : b.values()) { try { c.onAttached(); } catch (Exception e) { Spout.getLogger().log(Level.SEVERE, "Unhandled exception attaching block component", e); } } return true; }
Source:
protected static double averageMetricOverOperations(ASTClassOrInterfaceDeclaration node, OperationMetricKey key, MetricVersion version, boolean includeNested) { List<ASTMethodOrConstructorDeclaration> operations = findOperations(node, includeNested); double total = 0; for (ASTMethodOrConstructorDeclaration op : operations) { double val = Metrics.get(key, op, version); START total += val == Double.NaN ? 1 : val; END } return total / operations.size(); } Is the "1" here correct? I guess, it should be the same like in "sumMetricOverOperations" -> 0 if there is no value?

Target:
protected static double averageMetricOverOperations(ASTClassOrInterfaceDeclaration node, OperationMetricKey key, MetricVersion version, boolean includeNested) { List<ASTMethodOrConstructorDeclaration> operations = findOperations(node, includeNested); double total = 0; for (ASTMethodOrConstructorDeclaration op : operations) { double val = Metrics.get(key, op, version); total += val == Double.NaN ? 0 : val; } return total / operations.size(); }
Source:
public void setupSelectComponent(final DataTypeSelect typeSelect) { type.innerHTML = ""; START HTMLElement element = typeSelect.getElement(); END if (element instanceof HTMLDivElement) { new MenuInitializer((HTMLDivElement) element, ".btn-group").init(); } type.appendChild(typeSelect.getElement()); } I think we could add a final here: ```suggestion final HTMLElement element = typeSelect.getElement(); ```

Target:
public void setupSelectComponent(final DataTypeSelect typeSelect) { type.innerHTML = ""; final HTMLElement element = typeSelect.getElement(); new MenuInitializer(element, ".btn-group").init(); type.appendChild(element); }
Source:
public boolean isTriggerExpired() { START isExpired = isExpired || expireCondition.isMet(); END return isExpired; } This is counterintuitive. Why do we need to reassign `isExpired`? Can `expireCondition.isMet()` become `false` after returning `true`?

Target:
public boolean isTriggerExpired() { return expireCondition.isMet(); }
Source:
public void setMonitorEventTypes(String monitorEventTypes) { HazelcastIntegrationDefinitionValidator.validateEnumType( ClusterMonitorType.class, monitorEventTypes); final Set<String> monitorTypes = StringUtils START .commaDelimitedListToSet(monitorEventTypes); END Assert.notEmpty(monitorTypes, "'monitorTypes' must have elements"); this.monitorTypes = monitorTypes; } I think `validate...` method can return the `Set<ClusterMonitorType>` already avoiding double `commaDelimitedListToSet` call. In addition I think we should add `vararg` methods for the Java Config convenience. But that should be done in the separate JIRA.

Target:
public void setMonitorEventTypes(String monitorEventTypes) { final Set<String> monitorTypes = HazelcastIntegrationDefinitionValidator.validateEnumType( ClusterMonitorType.class, monitorEventTypes); Assert.notEmpty(monitorTypes, "'monitorTypes' must have elements"); this.monitorTypes = monitorTypes; }
Source:
START final AbstractInsnNode skipNonOpcodes(AbstractInsnNode cursor) { END while (cursor != null && (cursor.getType() == AbstractInsnNode.FRAME || cursor.getType() == AbstractInsnNode.LABEL || cursor.getType() == AbstractInsnNode.LINE)) { cursor = cursor.getNext(); } return cursor; } As this method does not change state (unlike the others) I would prefer to declare it `static`.

Target:
static AbstractInsnNode skipNonOpcodes(AbstractInsnNode cursor) { while (cursor != null && (cursor.getType() == AbstractInsnNode.FRAME || cursor.getType() == AbstractInsnNode.LABEL || cursor.getType() == AbstractInsnNode.LINE)) { cursor = cursor.getNext(); } return cursor; }
Source:
public boolean isValid() { START if (this.urlString == null || httpMethod == null) { END return true; } else { return false; } } `return this.urlString == null || httpMethod == null;`

Target:
protected boolean isValid() { return this.urlString == null || httpMethod == null; }
Source:
public UnitOfWorkAspect newAspect(ImmutableMap<String, SessionFactory> sessionFactories) { START return new UnitOfWorkAspect(this.sessionFactories); END } Shouldn't it be `sessionFactories` instead of `this.sessionFactories`? If yes, would it be possible to overload `newAspect` instead of changing its signature?

Target:
public UnitOfWorkAspect newAspect(ImmutableMap<String, SessionFactory> sessionFactories) { return new UnitOfWorkAspect(sessionFactories); }
Source:
public boolean isMarshallable(Object o) { // Protostream can handle all of these type as well if (o instanceof String || o instanceof Long || o instanceof Integer || o instanceof Double || o instanceof Float START || o instanceof Boolean || o instanceof byte[] || o instanceof Enum) { END return true; } return getSerializationContext().canMarshall(o.getClass()); } Enum should not be handled here, should be left to `SerializationContext.canMarshall()` because it needs to check that a custom marshaller was defined for the Enum.

Target:
public boolean isMarshallable(Object o) { // Protostream can handle all of these type as well if (o instanceof String || o instanceof Long || o instanceof Integer || o instanceof Double || o instanceof Float || o instanceof Boolean || o instanceof byte[]) { return true; } return getSerializationContext().canMarshall(o.getClass()); }
Source:
private void resetScope() { MortarScope root = START Mortar.createRootScope(false, ObjectGraph.create(new ModuleAndBlueprint("root"))); END activityScope = Mortar.requireActivityScope(root, new ModuleAndBlueprint("activity")); } static import of createRootScope, and requireActivityScope below?

Target:
private void resetScope() { MortarScope root = createRootScope(false, ObjectGraph.create(new ModuleAndBlueprint("root"))); activityScope = requireActivityScope(root, new ModuleAndBlueprint("activity")); }
Source:
public Builder withOutputFileset(String fileset){ START this.outputFilesets.add(fileset); END return this; } can you add safety checks against `null` or empty strings, plz?

Target:
public Builder withOutputFileset(String fileset){ if (fileset!=null && !fileset.isEmpty()){ this.outputFilesets.add(fileset); } return this; }
Source:
START public String getDeepRepresentation(CtElement elem) { END EqualVisitor prThis = new EqualVisitor(); prThis.scan(elem); return prThis.getRepresentation(); } This doesn't work. e.g., when you want build the deep representation of a method like this one: ``` java public void toProvider(Provider<? extends T> provider) { } ``` The result of `getDeepRepresentation` will be: `void toProvider(javax.inject.Provider,)voidprovider{}`.

Target:
private String getDeepRepresentation(CtElement elem) { EqualVisitor prThis = new EqualVisitor(); prThis.scan(elem); return prThis.getRepresentation(); }
Source:
public KSyntax2GrammarStatesFilter(Context context) { super(KSyntax2GrammarStatesFilter.class.getName(), context); // create a NonTerminal for every declared sort START for (String sort : context.definedSorts) { END NonTerminal nt = new NonTerminal(new NonTerminalId(sort)); grammar.add(nt); } } Can you please check to verify that definedSorts is computed by means of processing every production in the definition? Otherwise this might not work as expected.

Target:
public KSyntax2GrammarStatesFilter(Context context) { super(KSyntax2GrammarStatesFilter.class.getName(), context); // create a NonTerminal for every declared sort for (String sort : context.definedSorts) { grammar.add(new NonTerminal(sort)); } }
Source:
protected void clearContent() { START fXYPresentationProvider.clear(); END getSwtChart().getAxisSet().getXAxis(0).getTick().setFormat(null); super.clearContent(); } The order of colors is changed when the content is changed (e.g. checking/unchecking a counter).

Target:
protected void clearContent() { getSwtChart().getAxisSet().getXAxis(0).getTick().setFormat(null); super.clearContent(); }
Source:
protected void onNewIntent(Intent intent) { // This is called when the user press Home again while already browsing MainActivity // onResume() will be called right after, hiding the kissbar if any. // http://developer.android.com/reference/android/app/Activity.html#onNewIntent(android.content.Intent) // Animation can't happen in this method, since the activity is not resumed yet, so they'll happen in the onResume() // https://github.com/Neamar/KISS/issues/569 if (!searchEditText.getText().toString().isEmpty()) { Log.i(TAG, "Clearing search field"); searchEditText.setText(""); } // Hide kissbar when coming back to kiss if (isViewingAllApps()) { displayKissBar(false); } // Close the backButton context menu START MainActivity.this.closeContextMenu(); END } why not just call directly `closeContextMenu()`?

Target:
protected void onNewIntent(Intent intent) { // This is called when the user press Home again while already browsing MainActivity // onResume() will be called right after, hiding the kissbar if any. // http://developer.android.com/reference/android/app/Activity.html#onNewIntent(android.content.Intent) // Animation can't happen in this method, since the activity is not resumed yet, so they'll happen in the onResume() // https://github.com/Neamar/KISS/issues/569 if (!searchEditText.getText().toString().isEmpty()) { Log.i(TAG, "Clearing search field"); searchEditText.setText(""); } // Hide kissbar when coming back to kiss if (isViewingAllApps()) { displayKissBar(false); } // Close the backButton context menu closeContextMenu(); }
Source:
START private void validateRetentionPolicy(String retentionPolicy) throws FalconException { END if (!retentionPolicy.equalsIgnoreCase("delete")) { throw new FalconException("Retention policy \"" + retentionPolicy + "\" is invalid"); } } Make the method static

Target:
public static void validateRetentionPolicy(String retentionPolicy) throws FalconException { if (!retentionPolicy.equalsIgnoreCase("delete")) { throw new FalconException("Retention policy \"" + retentionPolicy + "\" is invalid"); } }
Source:
public byte[] getData() { START Object base = slice.getBase(); END checkState(base instanceof byte[], "unexpected serialization type %s", base.getClass()); byte[] bytes = (byte[]) base; if (slice.isCompact()) { return bytes; } // do a copy return slice.getBytes(); } Should this above three lines actually happen in this `if` branch? I don't see why we would need to get `base` if the slice is not compact.

Target:
public byte[] getData() { if (slice.isCompact()) { Object base = slice.getBase(); checkState(base instanceof byte[], "unexpected serialization type %s", base.getClass()); return (byte[]) base; } // do a copy return slice.getBytes(); }
Source:
public HeaderExtension getAbsoluteSendTimeExtension(RawPacket packet) { START if( packet.getExtensionBit() && packet.getHeaderExtensionType() END == getAbsSendTimeExtensionID() ) { return packet.getHeaderExtension(getAbsSendTimeExtensionID()); } return null; } We should check whether the AbsSendTimeEngine is configured with an extension ID (e.g. getExtensionID() != -1).

Target:
public HeaderExtension getAbsoluteSendTimeExtension(RawPacket packet) { if( packet.getExtensionBit() && getAbsSendTimeExtensionID() != -1 ) { return packet.getHeaderExtension(getAbsSendTimeExtensionID()); } return null; }
Source:
START public RedisPublishingMessageHandler(RedisConnectionFactory connectionFactory) { END Assert.notNull(connectionFactory, "connectionFactory must not be null"); this.template = new RedisTemplate(); this.template.setConnectionFactory(connectionFactory); this.template.setEnableDefaultSerializer(false); this.template.afterPropertiesSet(); } `@SuppressWarnings("rawtypes")`

Target:
public RedisPublishingMessageHandler(RedisConnectionFactory connectionFactory) { Assert.notNull(connectionFactory, "connectionFactory must not be null"); this.template = new RedisTemplate<Object, Object>(); this.template.setConnectionFactory(connectionFactory); this.template.setEnableDefaultSerializer(false); this.template.afterPropertiesSet(); }
Source:
public AnnotationCommandTargetResolver build() { START try { END return resolver; } finally { resolver = null; // builder can only be used once. } } I think it's nicer to call the `AnnotationCommandTargetResolver` constructor here, with, as suggested earlier, `this` as the sole parameter, so that the `AnnotationCommandTargetResolver` constructor can pull the `identifierAnnotation` and `versionAnnotation` from it.

Target:
public AnnotationCommandTargetResolver build() { return new AnnotationCommandTargetResolver(this); }
Source:
protected void doPoll(SourcePollingChannelAdapter adapter) { try { Method method = AbstractPollingEndpoint.class.getDeclaredMethod("doPoll"); method.setAccessible(true); method.invoke(adapter); } catch (Exception e) { START e.printStackTrace(); END fail("Failed to invoke doPoll(): " + e.toString()); } } No `e.printStackTrace()`, please, at all. It doesn't provide much info and just pollutes logs on CI builds

Target:
protected void doPoll(SourcePollingChannelAdapter adapter) { try { Method method = AbstractPollingEndpoint.class.getDeclaredMethod("doPoll"); method.setAccessible(true); method.invoke(adapter); } catch (Exception e) { fail("Failed to invoke doPoll(): " + e.toString()); } }
Source:
public CLOption(String opt, String val, String param) { START super(); END this.opt = opt; this.val = val; this.param = param; } nitpick: redundant

Target:
public CLOption(String opt, String val, String param) { this.opt = opt; this.val = val; this.param = param; }
Source:
private RemoteCacheManager createExecClient() { org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = super.createHotRodClientConfigurationBuilder(servers.get(0).getPort()); clientBuilder.marshaller(new UTF8StringMarshaller()); START clientBuilder.protocolVersion(getProtocolVersion()); END return new InternalRemoteCacheManager(clientBuilder.build()); } Method deprecated. Use `clientBuilder.version()` instead.

Target:
private RemoteCacheManager createExecClient() { org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = super.createHotRodClientConfigurationBuilder(servers.get(0).getPort()); clientBuilder.marshaller(new UTF8StringMarshaller()); clientBuilder.version(getProtocolVersion()); return new InternalRemoteCacheManager(clientBuilder.build()); }
Source:
START static synchronized Iterable<TerminalInfoView> getViews() { END return new ArrayList<TerminalInfoView>(views); } Visibility missing. Synchronized comes before static Why return an Iterable here? It would be better just to return a List<TerminatlInfoView>

Target:
private static synchronized Iterable<TerminalInfoView> getViews() { return new ArrayList<TerminalInfoView>(views); }
Source:
private void setWidgetsEnabled(final boolean enabled, final Control... controls) { for (Control control : controls) { control.setEnabled(enabled); } // set the focus on the fist element of the group. if (controls.length > 0 START && enabled) END { for (Control control : controls) { if (control instanceof Text) { control.setFocus(); break; } } } } This might as well become if (enable) since the for loop will end gracefully whether it's > 0 or not.

Target:
private void setWidgetsEnabled(final boolean enabled, final Control... controls) { for (Control control : controls) { control.setEnabled(enabled); } // set the focus on the fist element of the group. if (enabled) { for (Control control : controls) { if (control instanceof Text) { control.setFocus(); break; } } } }
Source:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object object = method.invoke(producer, args); if (method.getName().equals("produce") && spiedClasses.contains(object.getClass())) { START object = spy(object); END } return object; } oh yea. A spy :)

Target:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object object = method.invoke(producer, args); if (object != null && method.getName().equals("produce") && spiedClasses.contains(object.getClass())) { object = spy(object); } return object; }
Source:
private boolean filterInvalid(Position position) { return filterInvalid && !position.getValid() START || position.getLatitude() > 90 || position.getLongitude() > 180 END || position.getLatitude() < -90 || position.getLongitude() < -180; } You should only filter if the filter is enabled. Please be very careful and test your code before submitting anything.

Target:
private boolean filterInvalid(Position position) { if (filterInvalid == true) { return !position.getValid() || position.getLatitude() > 90 || position.getLongitude() > 180 || position.getLatitude() < -90 || position.getLongitude() < -180; } return false; }
Source:
public CreateDDiagramElementCommand(final TransactionalEditingDomain domain, final EObject semantic, final EdgeMapping mapping, final EdgeTarget source, final EdgeTarget target) { this(domain, semantic); edgeCandidate = new DEdgeCandidate(mapping, semantic, source, target, RefreshIdsHolder.getOrCreateHolder(getParentDiagram())); /* store source as container to retrieve later parent diagram */ START this.container = (DragAndDropTarget) source; END } getparentDiagram() will be null.. you have to set the container before calling the method.

Target:
public CreateDDiagramElementCommand(final TransactionalEditingDomain domain, final EObject semantic, final EdgeMapping mapping, final EdgeTarget source, final EdgeTarget target) { this(domain, semantic); /* store source as container to retrieve later parent diagram */ this.container = (DragAndDropTarget) source; edgeCandidate = new DEdgeCandidate(mapping, semantic, source, target, RefreshIdsHolder.getOrCreateHolder(getParentDiagram())); }
Source:
public static GermplasmListNewColumnsInfo createGermplasmListNewColumnsInfo(final String columnHeader, final String columnValue) { final GermplasmListNewColumnsInfo germplasmListNewColumnsInfo = new GermplasmListNewColumnsInfo(1); START final LinkedHashMap<String, List<ListDataColumnValues>> columnValuesMap = new LinkedHashMap<>(); END final List<ListDataColumnValues> listDataColumnValues = new ArrayList<>(); listDataColumnValues.add(new ListDataColumnValues(columnHeader, 1, columnValue)); columnValuesMap.put(columnHeader, listDataColumnValues); germplasmListNewColumnsInfo.setColumnValuesMap(columnValuesMap); germplasmListNewColumnsInfo.addColumn(columnHeader); return germplasmListNewColumnsInfo; } Declare `columnValuesMap` as `Map`

Target:
public static GermplasmListNewColumnsInfo createGermplasmListNewColumnsInfo(final String columnHeader, final String columnValue) { final GermplasmListNewColumnsInfo germplasmListNewColumnsInfo = new GermplasmListNewColumnsInfo(1); final Map<String, List<ListDataColumnValues>> columnValuesMap = new LinkedHashMap<>(); final List<ListDataColumnValues> listDataColumnValues = new ArrayList<>(); listDataColumnValues.add(new ListDataColumnValues(columnHeader, 1, columnValue)); columnValuesMap.put(columnHeader, listDataColumnValues); germplasmListNewColumnsInfo.setColumnValuesMap(columnValuesMap); germplasmListNewColumnsInfo.addColumn(columnHeader); return germplasmListNewColumnsInfo; }
Source:
public Tuple<Table> table(final String tableName, HiveConf conf) throws HiveException { // Column statistics won't be accurate if we are dumping only metadata START boolean getColStats = !conf.getBoolVar(HiveConf.ConfVars.REPL_DUMP_METADATA_ONLY); END return new Tuple<>(functionForSpec, () -> db.getTable(dbName, tableName, false, false, getColStats)); } If it is metadata only dump, then need to reset all the table parameters related to stats to false.

Target:
public Tuple<Table> table(final String tableName, HiveConf conf) throws HiveException { // Column statistics won't be accurate if we are dumping only metadata boolean getColStats = !conf.getBoolVar(HiveConf.ConfVars.REPL_DUMP_METADATA_ONLY); return new Tuple<>(functionForSpec, () -> db.getTable(dbName, tableName, true, false, getColStats)); }
Source:
START public List<DeprecatedRuleKeyDto> selectAllDeprecatedRuleKeys(DbSession session) { END return mapper(session).selectAllDeprecatedRuleKeys(); } What about returning a `Set` to emphasis that there is no specific order in the returned collection?

Target:
public Set<DeprecatedRuleKeyDto> selectAllDeprecatedRuleKeys(DbSession session) { return mapper(session).selectAllDeprecatedRuleKeys(); }
Source:
public static KerberosHadoopAuthentication createKerberosHadoopAuthentication(KerberosAuthentication kerberosAuthentication, HdfsConfigurationUpdater updater) { Configuration configuration = getInitialConfiguration(); updater.updateConfiguration(configuration); // In order to enable KERBEROS authentication method for HDFS // UserGroupInformation.authenticationMethod static field must be set to KERBEROS // It is further used in many places in DfsClient configuration.set("hadoop.security.authentication", "kerberos"); // Set the static configuration to get the rules. try { START HadoopKerberosName.setConfiguration(configuration); END } catch (IOException exception) { throw new UncheckedIOException(exception); } UserGroupInformation.setConfiguration(configuration); return new KerberosHadoopAuthentication(kerberosAuthentication); } It is being calles inside the `UserGroupInformation.setConfiguration`. Please remove that. https://github.com/prestodb/presto/pull/11380#discussion_r214222456

Target:
public static KerberosHadoopAuthentication createKerberosHadoopAuthentication(KerberosAuthentication kerberosAuthentication, HdfsConfigurationUpdater updater) { Configuration configuration = getInitialConfiguration(); updater.updateConfiguration(configuration); // In order to enable KERBEROS authentication method for HDFS // UserGroupInformation.authenticationMethod static field must be set to KERBEROS // It is further used in many places in DfsClient configuration.set("hadoop.security.authentication", "kerberos"); UserGroupInformation.setConfiguration(configuration); return new KerberosHadoopAuthentication(kerberosAuthentication); }
Source:
public void tearDown() throws Exception { if (this.fileWatcher != null) { this.fileWatcher.close(); } // Cleanup directories final Path workDir = PATH.getParent(); if (Files.exists(workDir)) { START Files.deleteIfExists(PATH); END } } Does `TemporaryFolder` not take care of cleanup automagically? Is this not one of the reasons to use it?

Target:
public void tearDown() throws Exception { if (this.fileWatcher != null) { this.fileWatcher.close(); } }
Source:
public List<String> firstTen(final String... args) { final List<String> list = new ArrayList<String>(args.length); list.addAll(Arrays.asList(args)); START final List<String> result = new LinkedList<>(); END result.addAll(list.subList(0, InvalidDiamondsUsage.TEN)); return result; } @vkuchyn didn't get, why these 2 lines are still here? I thought they were added to cover "happy path", no? If yes, they should be removed

Target:
public List<String> firstTen(final String... args) { final List<String> list = new ArrayList<String>(args.length); list.addAll(Arrays.asList(args)); return list; }
Source:
List<Object> getColumn(int columnIndex) { START ArrayList<Object> result = new ArrayList<Object>(); END for (Object[] compoundDatum : compoundData) { result.add(compoundDatum[columnIndex]); } return result; } List

Target:
public List<Object> getColumn(int columnIndex) { List<Object> result = new ArrayList<>(); for (Object[] compoundDatum : compoundData) { result.add(compoundDatum[columnIndex]); } return result; }
Source:
private static CharSequence getScreenSecuritySummary(Context context) { final int screenSecurityResId = R.string.preferences__screen_security_summary; final String onRes = context.getString(R.string.ApplicationPreferencesActivity_on); final String offRes = context.getString(R.string.ApplicationPreferencesActivity_off); if (TextSecurePreferences.isScreenSecurityEnabled(context)) return context.getString(screenSecurityResId, onRes); START return context.getString(screenSecurityResId, offRes); END } use if else or the ternary

Target:
private static CharSequence getScreenSecuritySummary(Context context) { final int screenSecurityResId = R.string.preferences__screen_security_summary; final String onRes = context.getString(R.string.ApplicationPreferencesActivity_on); final String offRes = context.getString(R.string.ApplicationPreferencesActivity_off); if (TextSecurePreferences.isScreenSecurityEnabled(context)) { return context.getString(screenSecurityResId, onRes); } else { return context.getString(screenSecurityResId, offRes); } }
Source:
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // If the total item count is zero and the previous isn't, assume the // list is invalidated and should be reset back to initial state if (totalItemCount < mPreviousTotalItemCount) { mCurrentPage = mStartingPageIndex; mPreviousTotalItemCount = totalItemCount; if (totalItemCount == 0) { START mLoading = true; END } } // If it's still loading, we check to see if the dataset count has // changed, if so we conclude it has finished loading and update the current page // number and total item count. if (mLoading && (totalItemCount > mPreviousTotalItemCount)) { mLoading = false; mPreviousTotalItemCount = totalItemCount; mCurrentPage++; } // If it isn't currently loading, we check to see if we have breached // the visibleThreshold and need to reload more data. // If we do need to reload some more data, we execute onLoadMore to fetch the data. if (!mLoading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + mVisibleThreshold)) { mLoading = onLoadMore(mCurrentPage + 1, totalItemCount); } } Does this mean that initially we try to load the data using this callback? We are also loading it manually, right? How do we prevent loading twice?

Target:
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // If the total item count is zero and the previous isn't, assume the // list is invalidated and should be reset back to initial state if (totalItemCount < mPreviousTotalItemCount) { mCurrentPage = mStartingPageIndex; mPreviousTotalItemCount = totalItemCount; if (totalItemCount == 0) { mLoading = true; } } // If it's still loading, we check to see if the dataset count has // changed, if so we conclude it has finished loading and update the current page // number and total item count. if (mLoading && (totalItemCount > mPreviousTotalItemCount)) { mLoading = false; mPreviousTotalItemCount = totalItemCount; mCurrentPage++; } // If it isn't currently loading, we check to see if we have breached // the visibleThreshold and need to reload more data. // If we do need to reload some more data, we execute onLoadMore to fetch the data. if (!mLoading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + mVisibleThreshold)) { mLoading = onLoadMore(mCurrentPage + 1); } }
Source:
private String buildJsArray(List<ContentType> types) { START String typeStr = String.join(",", types.stream().map(t -> t.id() ).collect(Collectors.toList())); END return typeStr ; } Return the String.join directly without creating the new String

Target:
private String buildJsArray(List<ContentType> types) { return String.join(",", types.stream().map(t -> t.id() ).collect(Collectors.toList())); }
Source:
public void setWhiteListedAgencies(String s) { if (s != null && !s.equals("")) START whiteListedAgencies = new HashSet<String>(Arrays.asList(s.split(","))); END } This is a tiny micro-optimization but I'll mention it since it might add to readability: `Sets.newHashSet(s.split(",")`

Target:
public void setWhiteListedAgencies(String s) { if (!s.isEmpty()) { whiteListedAgencies = new HashSet<>(); Collections.addAll(whiteListedAgencies, s.split(",")); } }
Source:
private Throwable unwrap(Object error) { try { return ((ErrorResponse) error).getCause(); START } catch (Exception e) { END return (Throwable) error; } } I'm a bit confused about the exception catching here. The getCause can't fail.. So either error is null, or it isn't an ErrorResponse; both cases can be handled with a check.

Target:
private Throwable unwrap(Object error) { if (error instanceof ErrorResponse) { return ((ErrorResponse) error).getCause(); } return (Throwable) error; }
Source:
public void run() { try { this.thread.dispatch(); } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); Logger.warn(this, "%s", ex); // @checkstyle IllegalCatch (1 line) } catch (final Throwable ex) { START Logger.error(this, "%s", ExceptionUtils.getStackTrace(ex)); END } } swallowing the exception? is it intentionally or by mistake?

Target:
public void run() { try { this.thread.dispatch(); } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); Logger.warn(this, "%s", ex); } }
Source:
public boolean isRedirectRequested(HttpResponse httpResponse, HttpContext httpContext) { START return proxiedHandler.isRedirectRequested(httpResponse, httpContext); END } `proxiedHandler` can be `null` here and in the next method, right?

Target:
public boolean isRedirectRequested(HttpResponse httpResponse, HttpContext httpContext) { return proxiedHandler != null ? proxiedHandler.isRedirectRequested(httpResponse, httpContext) : false; }
Source:
public Post() { START this.postContent = randomAlphanumeric(100); END } Should be set in field declaration.

Target:
public Post()
Source:
START private boolean acceptGroup(NuxeoPrincipal originatingPrincipal, String groupName) { END return originatingPrincipal.isAdministrator() || originatingPrincipal.getAllGroups().contains(groupName); } `private` -> `protected`

Target:
protected boolean acceptGroup(NuxeoPrincipal originatingPrincipal, String groupName) { return originatingPrincipal.isAdministrator() || originatingPrincipal.getAllGroups().contains(groupName); }
Source:
public void start() throws Exception { START load(); END VIEW_INJECTED_VARS.setEnabled(getConfiguration().isEnablePermissions()); } what for you call load?

Target:
public void start() throws Exception { VIEW_INJECTED_VARS.setEnabled(getConfiguration().isEnablePermissions()); }
Source:
public static SchemaPath getCompoundPath(String... strings) { NameSegment s = null; final int length = strings.length; // loop through strings in reverse order START for (int i = 0; i < length; i++) { END s = new NameSegment(strings[length - 1 - i], s); } return new SchemaPath(s); } Could you change this to (i=length-1; i >= 0; i--) such that you don't have to the extra subtraction below.

Target:
public static SchemaPath getCompoundPath(String... strings) { NameSegment s = null; // loop through strings in reverse order for (int i = strings.length - 1; i >= 0; i--) { s = new NameSegment(strings[i], s); } return new SchemaPath(s); }
Source:
private void initListeners() { this.restoreToSavePointListener = new RestoreToLastSavePointListener(session); this.restoreToSavePointListener.register(); this.saveSessionListener = new SaveSessionWhenNoDialectEditorsListener(session); START this.saveSessionListener.register(); END } Code in register() could be done directly in constructor of SaveSessionWhenNoDialectEditorsListener

Target:
private void initListeners() { this.restoreToSavePointListener = new RestoreToLastSavePointListener(session); this.saveSessionListener = new SaveSessionWhenNoDialectEditorsListener(session); this.saveSessionListener.register(); }
Source:
private void prepare(ControlWidget screen) { InjectionHelper.inject(screen); START translator.updateWidget(screen); END screen.onOpened(); } Suggest retaining untranslated strings and translating during rendering.

Target:
private void prepare(ControlWidget screen) { InjectionHelper.inject(screen); screen.onOpened(); }
Source:
public void setWriteBuffer(ByteBuffer buffer) { START writeBuffer = null; END writeBuffer = buffer; } This is unnecessary

Target:
public void setWriteBuffer(ByteBuffer buffer) { writeBuffer = buffer; }
Source:
protected Supplier<?> putSupplier(Map<String,String> map, int key) { return (()-> { try { START lock.lock(); END return map.put("key" + key, "value" + key); } finally { lock.unlock(); } }); } We don't want to lock inside the try (see the [JavaDoc](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html)). The reason is that if lock.lock() did in fact throw a RuntimeException, then the unlock could cause some unexpected results (since it's re-entrant, it could unlock one more level than intended, for example).

Target:
protected Supplier<?> putSupplier(Map<String,String> map, int key) { return (()-> { lock.lock(); try { return map.put("key" + key, "value" + key); } finally { lock.unlock(); } }); }
Source:
public void init() { service = new TransformationEngineService(); EKBModelGraph graph = EKBModelGraph.getInstance(); START ModelRegistryService registry = ModelRegistryService.getInstance(null); END registry.setEkbClassLoader(new EKBTestClassLoader()); registry.setGraphDb(graph); service.setModelRegistry(registry); service.setGraphDb(graph); graph.addModel(getModelADescription()); graph.addModel(getModelBDescription()); graph.addModel(getModelCDescription()); } same for thos changes

Target:
public void init() { service = new TransformationEngineService(); EKBModelGraph graph = EKBModelGraph.getInstance(); ModelRegistryService registry = ModelRegistryService.getInstance(context); registry.setEkbClassLoader(new EKBTestClassLoader()); registry.setGraphDb(graph); service.setModelRegistry(registry); service.setGraphDb(graph); graph.addModel(getModelADescription()); graph.addModel(getModelBDescription()); graph.addModel(getModelCDescription()); }
Source:
public void makeOmeTiff(final String name, final CoreMetadata info) throws FormatException, IOException { final String id = getId(name); final OMETiffWriter out = createWriter(name, info, id); writeData(name, info, id, out); START out.close(); END } Can we move to https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html yet?

Target:
public void makeOmeTiff(final String name, final CoreMetadata info) throws FormatException, IOException { final String id = getId(name); try (OMETiffWriter out = createWriter(name, info, id)) { writeData(name, info, id, out); } }
Source:
private String removeUnprintableChars(String text) { StringBuilder stringbuilder = new StringBuilder(); START for(char c0 : text.toCharArray()) { END if (c0 != 167 && c0 != 127) { stringbuilder.append(c0); } } return stringbuilder.toString(); } Again, variable name

Target:
private String removeUnprintableChars(String text) { StringBuilder stringbuilder = new StringBuilder(); for(char c0 : text.toCharArray()) if (c0 != 167 && c0 != 127) stringbuilder.append(c0); return stringbuilder.toString(); }
Source:
public void startLog() { START (new RangerLoadBegin(sourceDbName, targetDbName, estimatedNumPolicies)).log(LogTag.RANGER_LOAD_START); END } nit: Remove extra brackets

Target:
public void startLog() { new RangerLoadBegin(sourceDbName, targetDbName, estimatedNumPolicies).log(LogTag.RANGER_LOAD_START); }
Source:
public QueryContext(final UserSession session, final DrillbitContext drillbitContext, QueryId queryId) { START this(session, drillbitContext, queryId, null); END } please remove redundant ```final``` modifiers for parameters.

Target:
public QueryContext(final UserSession session, final DrillbitContext drillbitContext, QueryId queryId) { this(session, drillbitContext, queryId, 0); }
Source:
public Stream<Output> bloomFulltextNodes( @Name( "terms" ) List<String> terms ) throws Exception { START Stream<Output> stream; END try ( ReadOnlyFulltext indexReader = provider.getReader( BLOOM_NODES, FulltextProvider.FulltextIndexType.NODES ) ) { stream = queryAsStream( terms, indexReader ); } return stream; } i would just simply do this (here and method below): ``` try ( ReadOnlyFulltext indexReader = provider.getReader( BLOOM_NODES, FulltextProvider.FulltextIndexType.NODES ) ) { return queryAsStream( terms, indexReader ); } ```

Target:
public Stream<Output> bloomFulltextNodes( @Name( "terms" ) List<String> terms ) throws Exception { try ( ReadOnlyFulltext indexReader = provider.getReader( BLOOM_NODES, FulltextProvider.FulltextIndexType.NODES ) ) { return queryAsStream( terms, indexReader ); } }