auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void run() { START Socket socket; END OutputStream outputStream = null; try { socket = serverSocket.accept(); String response = getResponse(socket); outputStream = socket.getOutputStream(); writeResponseHeader(outputStream); write(response.getBytes(), outputStream); outputStream.flush(); } catch (IOException e) { // e.printStackTrace(); } finally { // we should not close the connection, let the client close the // connection StreamUtils.quietlyClose(outputStream); } } again: removing the explicit initialization: worse, not better

Target:
public void run() { Socket socket = null; OutputStream outputStream = null; try { socket = serverSocket.accept(); String response = getResponse(socket); outputStream = socket.getOutputStream(); writeResponseHeader(outputStream); write(response.getBytes(), outputStream); outputStream.flush(); } catch (IOException e) { // e.printStackTrace(); } finally { // we should not close the connection, let the client close the // connection StreamUtils.quietlyClose(outputStream); } }
Source:
public final boolean mightBeRacilyClean(final int smudge_s, final int smudge_ns) { // If the index has a modification time then it came from disk // and was not generated from scratch in memory. In such cases // the entry is 'racily clean' if the entry's cached modification // time is equal to or later than the index modification time. In // such cases the work file is too close to the index to tell if // it is clean or not based on the modification time alone. // final int base = infoOffset + P_MTIME; final int mtime = NB.decodeInt32(info, base); START if (smudge_s < mtime) END return true; if (smudge_s == mtime) return smudge_ns <= NB.decodeInt32(info, base + 4); return false; } Should we also delete this rule? IIRC the only reason we had it was to ensure already smudged entries stayed smudged. If we change our smudge logic to be length based this no longer makes any sense, and is actually a source of bugs by always selecting modified files as potentially racily clean.

Target:
public final boolean mightBeRacilyClean(final int smudge_s, final int smudge_ns) { // If the index has a modification time then it came from disk // and was not generated from scratch in memory. In such cases // the entry is 'racily clean' if the entry's cached modification // time is equal to or later than the index modification time. In // such cases the work file is too close to the index to tell if // it is clean or not based on the modification time alone. // final int base = infoOffset + P_MTIME; final int mtime = NB.decodeInt32(info, base); if (smudge_s == mtime) return smudge_ns <= NB.decodeInt32(info, base + 4); return false; }
Source:
START private void init() { END if (mMediaPlayerList != null) { Log.wtfStack(TAG, "init: The service has already been initialized"); return; } mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); sDeviceMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); mMediaPlayerList = new MediaPlayerList(Looper.myLooper(), this); mNativeInterface = AvrcpNativeInterface.getInterface(); mNativeInterface.init(AvrcpTargetService.this); } Since init() is only called once, could we move it to start() so that start() and stop() become symmetrical?

Target:
private void init() { }
Source:
public void testByteBuf2BytesEmptyByteBuf() { ByteBuf buf = Unpooled.buffer(); ArrayAsserts.assertArrayEquals(new byte[]{}, ByteBufUtils.byteBuf2Bytes(buf)); START buf.release(); END } nit: could you please perform the release calls in a finally block so the ByteBufs get released even if the assert fails?

Target:
public void testByteBuf2BytesEmptyByteBuf() { ByteBuf buf = Unpooled.buffer(); try { ArrayAsserts.assertArrayEquals(new byte[]{}, ByteBufUtils.byteBuf2Bytes(buf)); } finally { buf.release(); } }
Source:
public String getPagingData() { START if(getPagination() == null) END return ""; return getPagination().getTag(); } Please add braces around the if expression and reformat

Target:
public String getPagingData() { if (getPagination() == null) { return ""; } return getPagination().getTag(); }
Source:
private static boolean isBalloonEnabled(VmManagementParametersBase params) { Boolean balloonEnabled = params.isBalloonEnabled(); return balloonEnabled != null ? balloonEnabled : START VmDeviceUtils.isBalloonEnabled(params.getVmStaticData().getId()); END } As you are calling a method in the same class you may want to drop the "VmDeviceUtils." prefix.

Target:
private static boolean isBalloonEnabled(VmManagementParametersBase params) { Boolean balloonEnabled = params.isBalloonEnabled(); return (balloonEnabled != null) ? balloonEnabled : isBalloonEnabled(params.getVmStaticData().getId()); }
Source:
private int distanceUntilTurn() { final GeoPoint whereIam = whereIAm(); final int fromEnd; if (whereIam == null) { START fromEnd = Integer.MAX_VALUE;} END else { // Get distance to end of active segment final Segment activeSeg = Route.journey().activeSegment(); fromEnd = activeSeg.distanceFromEnd(whereIam); } return fromEnd; } Three things here: 1. Why are you using `Integer.MAX_VALUE` as a magic number, instead of the (arguably more logical) `null` value to indicate a lack of location fix? (You would obviously need to change the return type to be an `Integer` object rather than an `int` primitive.) 2. Formatting. Yuck! 3. Why not just return from the if branch; do away with the else branch, and return inline instead of having a `fromEnd` variable?

Target:
private Integer distanceUntilTurn() { final GeoPoint whereIam = whereIAm(); if (whereIam != null) { // Get distance to end of active segment final Segment activeSeg = Route.journey().activeSegment(); return activeSeg.distanceFromEnd(whereIam); } return null; }
Source:
public void transformSlope(){ final ITmfTimestampTransform slope = TimestampTransformFactory.create(10, 0); assertEquals(t1e3, slope.transform(t1e2)); assertEquals(tn100, slope.transform(new TmfNanoTimestamp(10))); assertEquals(tn100, slope.transform(slope.transform(tn1))); START assertEquals(tn100, slope.transform(slope.transform(tn1))); END assertEquals(tn100, slope.composeWith(slope).transform(tn1)); } yes, we already knew that

Target:
public void transformSlope(){ final ITmfTimestampTransform slope = TimestampTransformFactory.create(10, 0); assertEquals(t1e3, slope.transform(t1e2)); assertEquals(tn100, slope.transform(new TmfNanoTimestamp(10))); assertEquals(tn100, slope.transform(slope.transform(tn1))); assertEquals(tn100, slope.composeWith(slope).transform(tn1)); }
Source:
boolean isBitrateImproving(int newBitrateBps) { synchronized (critSect) { boolean initialProbe = !remoteRate.isValidEstimate() && newBitrateBps > 0; boolean bitrateAboveEstimate = remoteRate.isValidEstimate() && newBitrateBps > (int) (remoteRate .getLatestEstimate()); START return initialProbe || bitrateAboveEstimate; END } } Looks like the worst that could happen is that the values in the log message are not precise

Target:
private boolean isBitrateImproving(int newBitrateBps) { synchronized (critSect) { boolean initialProbe = !remoteRate.isValidEstimate() && newBitrateBps > 0; boolean bitrateAboveEstimate = remoteRate.isValidEstimate() && newBitrateBps > (int) (remoteRate .getLatestEstimate()); return initialProbe || bitrateAboveEstimate; } }
Source:
public COL get() { // load upon the first use if (parsed==null) { synchronized (this) { if (parsed==null) { try { load(); } catch (IOException e) { START throw new RuntimeException(e); END } } } } return parsed; } It would be rather preferable to create a new method with error propagation

Target:
public COL get() { // load upon the first use if (parsed==null) { synchronized (this) { if (parsed==null) { load(); } } } return parsed; }
Source:
START protected List<MPartStack> findDirectStacks(MPartSashContainer root) { END List<MPartStack> result = new ArrayList<>(); for (MPartSashContainerElement e : root.getChildren()) { if (e instanceof MPartStack) { result.add((MPartStack) e); } else if (e instanceof MPartSashContainer) { result.addAll(findDirectStacks((MPartSashContainer) e)); } } return result; } why not private? it is only used by the private method synchCTFState. I would place the new method below synchCTFState. I don't get really why the findElements() method does not what you need here. Both do a recursive search for MPartStack in areaModel. Maybe EModelServiceFindTest could be extended to check your use case?

Target:
private List<MPartStack> findDirectStacks(MPartSashContainer root) { List<MPartStack> result = new ArrayList<>(); for (MPartSashContainerElement e : root.getChildren()) { if (e instanceof MPartStack) { result.add((MPartStack) e); } else if (e instanceof MPartSashContainer) { result.addAll(findDirectStacks((MPartSashContainer) e)); } } return result; }
Source:
public boolean isAutomaticProvisioningEnabled () { START return AutomaticProvisioningStatus.ENABLED.equals(getAutomaticProvisioning()) ? true : false; END } Can be simplified to `AutomaticProvisioningStatus.ENABLED.equals(getAutomaticProvisioning());`

Target:
public boolean isAutomaticProvisioningEnabled () { return AutomaticProvisioningStatus.ENABLED.equals(getAutomaticProvisioning()); }
Source:
public Object poll() { Object value = queue.poll(); START if (capacity != null) { END capacity.incrementAndGet(); } return value; } Sorry that I missed a case. If we poll `null`, we should not increment `capacity`.

Target:
public Object poll() { Object value = queue.poll(); if (capacity != null && value != null) { capacity.incrementAndGet(); } return value; }
Source:
START public String query() { END if (query == null) { synchronized (conn) { if (query == null) { query = path() == uri || queryStart == -1 ? null : queryStart > 0 && uri.length() > queryStart ? uri.substring(queryStart + 1) : HttpUtils.parseQuery(uri); } } } return query; } This becomes unreadable with so many chain of logic operations and ternary blocks. I believe proper if statements would be preferred and more readable

Target:
public String query() { if (query == null && uri != null) { query = path() == uri || queryStart == -1 ? null : queryStart > 0 && uri.length() > queryStart ? uri.substring(queryStart + 1) : HttpUtils.parseQuery(uri); } return query; }
Source:
public PropertyValue getValue(ClassPropertyReference propertyReference, Object rawValue) throws XWikiRestException { String reference = ""; if (rawValue != null) { reference = rawValue.toString(); } if (StringUtils.isEmpty(reference)) { return null; } DocumentReference documentReference = documentReferenceResolver.resolve(reference, EntityType.DOCUMENT); PropertyValue propertyValue = START this.getValueFromQueryResult(documentReference, getPropertyDefinition(propertyReference)); END if (propertyValue != null) { propertyValue.setValue(reference); } return propertyValue; } You could also do: PropertyValue propertyValue = super.getValue(propertyReference, documentReference); just to be sure we don't miss something from the base class. It also makes it more clear that the reason we overwrite the implementation from the base class is because we want to change the input raw value and we want to add more information to the returned property value.

Target:
public PropertyValue getValue(ClassPropertyReference propertyReference, Object rawValue) throws XWikiRestException { String reference = ""; if (rawValue != null) { reference = rawValue.toString(); } if (StringUtils.isEmpty(reference)) { return null; } DocumentReference documentReference = documentReferenceResolver.resolve(reference, EntityType.DOCUMENT); PropertyValue propertyValue = super.getValue(propertyReference, documentReference); if (propertyValue != null) { propertyValue.setValue(reference); } return propertyValue; }
Source:
public boolean performPaste(Object target, ISelection selection) { if (target instanceof IBreakpointContainer && selection instanceof IStructuredSelection) { IBreakpointContainer container = (IBreakpointContainer) target; for (Object object : START ((IStructuredSelection)selection)) END { IBreakpoint breakpoint = (IBreakpoint)DebugPlugin.getAdapter(object, IBreakpoint.class); if (breakpoint != null) { container.getOrganizer().addBreakpoint(breakpoint, container.getCategory()); } } return true; } return false; } double parantheses should be obsolete here

Target:
public boolean performPaste(Object target, ISelection selection) { if (target instanceof IBreakpointContainer && selection instanceof IStructuredSelection) { IBreakpointContainer container = (IBreakpointContainer) target; for (Object object : (IStructuredSelection) selection) { IBreakpoint breakpoint = (IBreakpoint)DebugPlugin.getAdapter(object, IBreakpoint.class); if (breakpoint != null) { container.getOrganizer().addBreakpoint(breakpoint, container.getCategory()); } } return true; } return false; }
Source:
public static Node createInvalidType(Node node, NodeType type) { StringBuilder message = new StringBuilder("Invalid type " + node.getType() + ", expected " + type); if (node.getParent() != null && node.getParent() instanceof KeyValueNode) { START message.append(" (key: \"" + ((KeyValueNode) node.getParent()).getKey() + "\")"); END } return new ErrorNode(message.toString()); } Why are we only adding this to this error message only?

Target:
public static Node createInvalidType(Node node, NodeType type) { return new ErrorNode("Invalid type " + node.getType() + ", expected " + type); }
Source:
public static File getHadoopTokens(HadoopSecurityManager hadoopSecurityManager, Props props, Logger log) throws HadoopSecurityManagerException { File tokenFile = null; try { tokenFile = File.createTempFile("mr-azkaban", ".token"); } catch (Exception e) { START e.printStackTrace(); END throw new HadoopSecurityManagerException("Failed to create the token file.", e); } hadoopSecurityManager.prefetchToken(tokenFile, props, log); return tokenFile; } printing out stack trace is not needed

Target:
public static File getHadoopTokens(HadoopSecurityManager hadoopSecurityManager, Props props, Logger log) throws HadoopSecurityManagerException { File tokenFile = null; try { tokenFile = File.createTempFile("mr-azkaban", ".token"); } catch (Exception e) { throw new HadoopSecurityManagerException("Failed to create the token file.", e); } hadoopSecurityManager.prefetchToken(tokenFile, props, log); return tokenFile; }
Source:
public void tearDown() throws Exception { START super.tearDown(); lfuJedis.disconnect(); END } Reverse order.

Target:
public void tearDown() throws Exception { lfuJedis.disconnect(); super.tearDown(); }
Source:
protected AbstractProcessor(final String[] sourceExtensions, final String[] headerExtensions) { this.sourceExtensions = sourceExtensions.clone(); START if(headerExtensions != null) END { this.headerExtensions = (String[]) headerExtensions.clone(); } else { this.headerExtensions = null; } } Rather than changing the contract that all other compilers match, perhaps follow existing pattern and pass `new String[] {}`

Target:
protected AbstractProcessor(final String[] sourceExtensions, final String[] headerExtensions) { this.sourceExtensions = sourceExtensions.clone(); this.headerExtensions = headerExtensions.clone(); }
Source:
public void init(EmptyAssetsScreen presenter) { this.presenter = presenter; START if (!this.presenter.canUpdateProject()) { END this.addAsset.disabled = true; } } IMO this should move to the presenter in the first place.. i.e. where you call ```view.init( this )``` add the next line that calls ```if(this.canUpdateProject()) { view.enableAddAssetButton( false ); }```

Target:
public void init(EmptyAssetsScreen presenter) { this.presenter = presenter; }
Source:
public static void configureSentry(ApplicationContext context) { FileSettings settings = context.getBean(FileSettings.class); START String sentryDsn = ofNullable(settings.getString("sentry.dsn")).orElse("none"); END if (!sentryDsn.equals("none")) { Sentry.init(sentryDsn); } } можно просто не указывать настройку sentry.dsn либо явно указать протокол noop:// (https://github.com/getsentry/sentry-java/blob/master/sentry/src/main/java/io/sentry/dsn/Dsn.java#L21) — он используется по умолчанию думаю, не стоит поверх этого наворачивать ещё какую-то нашу собственную логику даже без явного вызова Sentry.init сентри все равно будет автоматически инициализировать клиент (и искать dsn в параметрах jvm или энв-переменных), поэтому доп. логика с none может привести к странному поведению

Target:
public static void configureSentry(ApplicationContext context) { FileSettings settings = context.getBean(FileSettings.class); Sentry.init(settings.getString("sentry.dsn")); }
Source:
public RequestMatcher value(String parameter, String... expectedValues) { List<Matcher<? super String>> matcherList = Arrays.stream(expectedValues) .map(Matchers::equalTo) .collect(Collectors.toList()); START return this.value(parameter, matcherList); END } We don't use `this" for methods.

Target:
public RequestMatcher value(String parameter, String... expectedValues) { List<Matcher<? super String>> matcherList = Arrays.stream(expectedValues) .map(Matchers::equalTo) .collect(Collectors.toList()); return value(parameter, matcherList); }
Source:
private ObjCClass(long handle, Class<? extends ObjCObject> type, String name, boolean custom) { super(handle, false); this.type = type; this.name = name; this.custom = custom; if (custom) { START ObjCObject.ObjectOwnershipHelper.registerClass(this); END } } I think it would be better to have this call at the end of the `ObjCClass.register()` method. Just after the `ObjCClass` instance is created.

Target:
private ObjCClass(long handle, Class<? extends ObjCObject> type, String name, boolean custom) { super(handle, false); this.type = type; this.name = name; this.custom = custom; }
Source:
private static boolean inSameSubtree(long bitsA, long bitsB, int level) { START return (bitsA >>> level) == (bitsB >>> level) || level == MAX_BITS; END } why flip the `||`?

Target:
private static boolean inSameSubtree(long bitsA, long bitsB, int level) { return level == MAX_BITS || (bitsA >>> level) == (bitsB >>> level); }
Source:
START private ReplicationFactor(int allReplicas, int transientReplicas) { END this.allReplicas = allReplicas; this.fullReplicas = allReplicas - transientReplicas; } nit: `allReplicas` and `totalReplicas` names are used for the same thing, maybe we should normalize it?

Target:
public ReplicationFactor(int allReplicas, int transientReplicas) { this.allReplicas = allReplicas; this.transientReplicas = transientReplicas; this.fullReplicas = allReplicas - transientReplicas; }
Source:
protected static void assertAttAuthzStatements(final Assertion assertion) throws WSSecurityException { if (CollectionUtils.isEmpty(assertion.getAttributeStatements()) START && (assertion.getAuthnStatements() == null || assertion.getAuthnStatements().isEmpty())) { END assertAuthzDecisionStatements(assertion); } } consider to use CollectionUtils

Target:
protected static void assertAttAuthzStatements(final Assertion assertion) throws WSSecurityException { if (CollectionUtils.isEmpty(assertion.getAttributeStatements()) && CollectionUtils.isEmpty(assertion.getAuthnStatements())) { assertAuthzDecisionStatements(assertion); } }
Source:
private void newTestSubject(int cachedEvents, long fetchDelay, long cleanupDelay) { Optional.ofNullable(testSubject).ifPresent(EmbeddedEventStore::shutDown); testSubject = new EmbeddedEventStore(storageEngine, NoOpMessageMonitor.INSTANCE, cachedEvents, fetchDelay, START cleanupDelay, MILLISECONDS, SnapshotResolver.lastSnapshotResolver()); END } This stuff would benefit..from a Builder maybe, with defaults in it. What do you think? ;p

Target:
private void newTestSubject(int cachedEvents, long fetchDelay, long cleanupDelay) { Optional.ofNullable(testSubject).ifPresent(EmbeddedEventStore::shutDown); testSubject = new EmbeddedEventStore(storageEngine, NoOpMessageMonitor.INSTANCE, cachedEvents, fetchDelay, cleanupDelay, MILLISECONDS); }
Source:
private MavenProject getSiblingModule(Artifact artifact) { @SuppressWarnings("unchecked") START List<MavenProject> modules = (List<MavenProject>)project.getParent().getModules(); END for (MavenProject module : modules) { if (module.getId().equals(artifact.getId())) { return module; } } return null; } can project.getParent() be null?

Target:
private MavenProject getSiblingModule(Artifact artifact) { if (project.getParent() == null) { return null; } @SuppressWarnings("unchecked") List<MavenProject> modules = (List<MavenProject>)project.getParent().getModules(); for (MavenProject module : modules) { if (module.getId().equals(artifact.getId())) { return module; } } return null; }
Source:
private ASTArgumentList getArgumentList(ASTArguments args) { if (args != null) { START super.visit(args, null); END return args.getFirstChildOfType(ASTArgumentList.class); } return null; } it doesn't seem right to do this here.... why a getter triggers node visitation? Aren't we visiting twice these nodes by doing this?

Target:
private ASTArgumentList getArgumentList(ASTArguments args) { if (args != null) { return args.getFirstChildOfType(ASTArgumentList.class); } return null; }
Source:
public Object getNextValue() { double value = (double) getValue(); double stepSize = MAX_VALUE; while (stepSize >= MIN_VALUE) { if (value >= stepSize) { break; } else { stepSize = stepSize / 10; } } if( value >= MAX_VALUE) { START return 0; END } return value + stepSize; } This should probably be `return MAX_VALUE`, to prevent cycling the step size back to zero. And below should be `return MIN_VALUE`

Target:
public Object getNextValue() { double value = (double) getValue(); double stepSize = MAX_VALUE; while (stepSize >= MIN_VALUE) { if (value >= stepSize) { break; } else { stepSize = stepSize / 10; } } if( value >= MAX_VALUE) { return null; } return value + stepSize; }
Source:
START protected Object computeParameterValue(JpaParameter parameter, Object value, Object[] values) { END return value; } I don't think we need that if we drop the support for expression parameters as repository method parameters, right?

Target:
private Object computeParameterValue(JpaParameter parameter, Object value, Object[] values) { return value; }
Source:
public AbstractRepositoryRestController(PagedResourcesAssembler<Object> assembler, PersistentEntityResourceAssembler<Object> entityResourceAssembler) { START System.out.println("Registering " + this.getClass() + " controller..."); END this.assembler = assembler; this.perAssembler = entityResourceAssembler; } Remove that on before merging.

Target:
public AbstractRepositoryRestController(PagedResourcesAssembler<Object> assembler, PersistentEntityResourceAssembler<Object> entityResourceAssembler) { this.assembler = assembler; this.perAssembler = entityResourceAssembler; }
Source:
private Optional<Map<String, VariableDefinition>> getVariableDefinitionMap(String processDefinitionId) { ProcessExtensionModel processExtensionModel = processDefinitionId != null ? processExtensionService.getExtensionsForId(processDefinitionId) : null; return Optional.ofNullable(processExtensionModel) START .map(p -> p.getExtensionsByProcessDefinitionId(processDefinitionId)) END .map(Extension::getProperties); } I thought we did not have the processDefinitionId in the extensions json I thought we had only the process definition key in the extensions json And that's why yesterday in this class we tried to look up by key(and not by id like in the past) What am i missing?

Target:
private Optional<Map<String, VariableDefinition>> getVariableDefinitionMap(String processDefinitionId) { Extension processExtensionModel = processDefinitionId != null ? processExtensionService.getExtensionsForId(processDefinitionId) : null; return Optional.ofNullable(processExtensionModel) .map(Extension::getProperties); }
Source:
START protected void checkStarted() throws StoreException { END if (!started) { throw new StoreException("Store not started", StoreErrorCodes.Store_Not_Started); } } is this necessary?

Target:
private void checkStarted() throws StoreException { if (!started) { throw new StoreException("Store not started", StoreErrorCodes.Store_Not_Started); } }
Source:
public void close() throws SQLException { if (hpccConnection != null) { START hpccConnection.close(); END hpccConnection = null; } if (result != null) { result.close(); result = null; } sqlQuery = ""; dbMetadata = null; closed = true; parameters = null; parser = null; eclQuery = null; } Should you be closing the connection as well? What happens if the caller attempts to execute query after closing the prepstmt

Target:
public void close() throws SQLException { if (!closed) { closed = true; hpccConnection = null; result = null; sqlQuery = null; dbMetadata = null; parameters = null; parser = null; eclQuery = null; } }
Source:
public String getExpression() { // The escaped CSS content has to be escaped to be a valid Java literal START return "\"" + Generator.escape(toCss()) + "\""; END } toCss() already escape the String, no need to escape it again.

Target:
public String getExpression() { // The escaped CSS content has to be escaped to be a valid Java literal return "\"" + toCss() + "\""; }
Source:
public List<? extends Module> getJacksonModules() { return Arrays.<Module>asList( new SimpleModule("FirehoseModule") .registerSubtypes( new NamedType(ClippedFirehoseFactory.class, "clipped"), new NamedType(TimedShutoffFirehoseFactory.class, "timed"), new NamedType(IrcFirehoseFactory.class, "irc"), new NamedType(LocalFirehoseFactory.class, "local"), new NamedType(ProtoBufInputRowParser.class, "protobuf"), START new NamedType(EventReceiverFirehoseFactory.class, "receiver") END ) ); } there is another class named IndexingServiceFirehoseModule, wondering if we can just delete that class and use FireshoseModule in indexing service also.

Target:
public List<? extends Module> getJacksonModules() { return Arrays.<Module>asList( new SimpleModule("FirehoseModule") .registerSubtypes( new NamedType(ClippedFirehoseFactory.class, "clipped"), new NamedType(TimedShutoffFirehoseFactory.class, "timed"), new NamedType(IrcFirehoseFactory.class, "irc"), new NamedType(LocalFirehoseFactory.class, "local"), new NamedType(EventReceiverFirehoseFactory.class, "receiver") ) ); }
Source:
protected void handleDemandLoadException(Resource resource, IOException exception) { try { super.handleDemandLoadException(resource, exception); // CHECKSTYLE:OFF START } catch (Exception e) { END // CHECKSTYLE:ON // do nothing. The errors are added to the Resource#getErrors() in super(). } } Same question here

Target:
protected void handleDemandLoadException(Resource resource, IOException exception) { try { super.handleDemandLoadException(resource, exception); // CHECKSTYLE:OFF } catch (RuntimeException e) { // CHECKSTYLE:ON // do nothing. The errors are added to the Resource#getErrors() in super(). } }
Source:
public final Type getType() { if (beginA == endA && beginB < endB) return Type.INSERT; if (beginA < endA && beginB == endB) return Type.DELETE; START if (isEmpty()) END return Type.EMPTY; return Type.REPLACE; } Surprising to me you suggest this. I guess you spent this method call because you know for sure the call comes for free because of inlining. Right?

Target:
public final Type getType() { if (beginA == endA && beginB < endB) return Type.INSERT; if (beginA < endA && beginB == endB) return Type.DELETE; if (beginA == endA && beginB == endB) return Type.EMPTY; return Type.REPLACE; }
Source:
private String getHumanReadableSize(long bytes) { int unit = 1000; if (bytes < unit) START return bytes + " B"; END int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = "" + "KMGTPE".charAt(exp - 1); return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); } Cosmetic: Please, always use braces around conditions and loops. Thanks! :)

Target:
private String getHumanReadableSize(long bytes) { int unit = 1000; if (bytes < unit) { return bytes + " B"; } int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = "" + "KMGTPE".charAt(exp - 1); return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); }
Source:
private KieBuilderImpl kieBuilderClone( final KieFileSystem kieFileSystemClone ) { KieBuilderImpl kieBuilder = null; if ( this.kieBuilder != null ) { START kieBuilder = (KieBuilderImpl) createKieBuilder( kieFileSystemClone ); END kieBuilder.setkModule( ( (KieBuilderImpl) this.kieBuilder ).getkModule() ); kieBuilder.setTrgMfs( ( (KieFileSystemImpl) kieFileSystemClone ).getMfs() ); } return kieBuilder; } It is OK to make the `createKieBuilder` return KieBuilderImpl. Less likely to break in the future in case we support more implementations.

Target:
private KieBuilderImpl kieBuilderClone( final KieFileSystem kieFileSystemClone ) { KieBuilderImpl kieBuilder = null; if ( this.kieBuilder != null ) { kieBuilder = createKieBuilder( kieFileSystemClone ); kieBuilder.setkModule( ( (KieBuilderImpl) this.kieBuilder ).getkModule() ); kieBuilder.setTrgMfs( ( (KieFileSystemImpl) kieFileSystemClone ).getMfs() ); } return kieBuilder; }
Source:
START public void setUp() throws MalformedURLException { END base = new URL("http://localhost:" + port); } Generally, it's a good idea to have `throws Exception` rather than a more specific one in the signature of test methods.

Target:
public void setUp() throws Exception { base = new URL("http://localhost:" + port); }
Source:
public ProcessInstance getProcessInstance(String instanceId) throws WorkflowException { START ProcessInstanceImpl instance = repository.getById(instanceId); END return instance; } ![MINOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-minor.png 'Severity: MINOR') Immediately return this expression instead of assigning it to the temporary variable "instance". [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](http://integration.silverpeas.org/sonar/coding_rules#rule_key=squid%3AS1488)

Target:
public ProcessInstance getProcessInstance(String instanceId) throws WorkflowException { return repository.getById(instanceId); }
Source:
protected int[] makeDimValSelector(PooledTopNParams params, int numProcessed, int numToProcess) { final TopNMetricSpecBuilder<int[]> arrayProvider = params.getArrayProvider(); START if (query.getDimensionSpec().preservesOrdering()) { END return arrayProvider.build(); } arrayProvider.ignoreFirstN(numProcessed); arrayProvider.keepOnlyN(numToProcess); return query.getTopNMetricSpec().configureOptimizer(arrayProvider).build(); } same, needs to be negated

Target:
protected int[] makeDimValSelector(PooledTopNParams params, int numProcessed, int numToProcess) { final TopNMetricSpecBuilder<int[]> arrayProvider = params.getArrayProvider(); if (!query.getDimensionSpec().preservesOrdering()) { return arrayProvider.build(); } arrayProvider.ignoreFirstN(numProcessed); arrayProvider.keepOnlyN(numToProcess); return query.getTopNMetricSpec().configureOptimizer(arrayProvider).build(); }
Source:
protected void bindWidgetToSetting(UIWidget widget) { UISlider slider = widget.find("slider", UISlider.class); assert slider != null; updateSliderIfInteger(slider); setSliderRange(slider); slider.bindValue(new Binding<Float>() { @Override public Float get() { return getSetting().getValue().floatValue(); } @Override public void set(Float value) { START setSettingValue(value); END } }); } Don't need to have this in a separate function if it's just a oneliner, IMO.

Target:
protected void bindWidgetToSetting(UIWidget widget) { UISlider slider = widget.find("slider", UISlider.class); assert slider != null; updateSliderIfInteger(slider); setSliderRange(slider); slider.bindValue(new Binding<Float>() { @Override public Float get() { return getSetting().get().floatValue(); } @Override public void set(Float value) { setSettingValue(value); } }); }
Source:
public static void sendResponse(ChannelHandlerContext channel, HttpRequest request, String messageBody, HttpResponseStatus status) { sendResponse(channel, request, messageBody, null); START } END NIT: spacing (need new line). But wait and see if there's other changes you'll need to make from the other reviewers.

Target:
public static void sendResponse(ChannelHandlerContext channel, HttpRequest request, String messageBody, HttpResponseStatus status) { sendResponse(channel, request, messageBody, status, null); }
Source:
START public void clearSwapDir() throws IOException { END if (! m_blockPathMap.isEmpty()) { throw new IllegalStateException("Attempt to clear swap directory when " + "there are still managed blocks; use releaseAllBlocks() instead"); } try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(m_largeQuerySwapPath)) { Iterator<Path> it = dirStream.iterator(); while (it.hasNext()) { Path path = it.next(); VoltFile.recursivelyDelete(path.toFile()); } } } If its needed to be cleared in init --force please do cleanup there too.

Target:
private void clearSwapDir() throws IOException { if (! m_blockPathMap.isEmpty()) { throw new IllegalStateException("Attempt to clear swap directory when " + "there are still managed blocks; use releaseAllBlocks() instead"); } try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(m_largeQuerySwapPath)) { Iterator<Path> it = dirStream.iterator(); while (it.hasNext()) { Path path = it.next(); VoltFile.recursivelyDelete(path.toFile()); } } }
Source:
public void authenticateWithWrongAuthentication() throws SecurityException, SecurityProviderNotFoundException { when(provider.authenticate(authentication)).thenThrow(UnauthorisedException.class); manager.addProvider(provider); expected.expect(UnauthorisedException.class); START manager.authenticate(authentication); END verify(provider).authenticate(authentication); } wrap this in a `try`...

Target:
public void authenticateWithWrongAuthentication() throws SecurityException, SecurityProviderNotFoundException { when(provider.authenticate(authentication)).thenThrow(UnauthorisedException.class); manager.addProvider(provider); expected.expect(UnauthorisedException.class); try { manager.authenticate(authentication); } finally { verify(provider).authenticate(authentication); } }
Source:
START public ArrayList<CapraOfficeObject> getSelection() { END return this.selection; } Should return the interface (List), not the class.

Target:
public List<CapraOfficeObject> getSelection() { return this.selection; }
Source:
private static ArrayList<Artifact> asArtifacts(Collection<Change> changes) { ArrayList<Artifact> arts = new ArrayList<>(); for (Change artifactChange : changes) { Artifact changeArtifact = artifactChange.getChangeArtifact(); if (changeArtifact.isValid()) { START arts.add(artifactChange.getChangeArtifact()); END } } return arts; } use local variable "changeArtifact" here

Target:
private static ArrayList<Artifact> asArtifacts(Collection<Change> changes) { ArrayList<Artifact> arts = new ArrayList<>(); for (Change artifactChange : changes) { Artifact changeArtifact = artifactChange.getChangeArtifact(); if (changeArtifact.isValid()) { arts.add(changeArtifact); } } return arts; }
Source:
private LanguageMapping computeInheritedMapping(IProject project, IFile file, ICConfigurationDescription configuration) throws CoreException { LanguageMapping mappings[] = LanguageMappingResolver.computeLanguage(project, file.getProjectRelativePath().toPortableString(), configuration, fContentType.getId(), true); LanguageMapping inheritedMapping = mappings[0]; // Skip over the file mapping because we want to know what mapping the file // mapping overrides. int index = 1; while (inheritedMapping.inheritedFrom == LanguageMappingResolver.FILE_MAPPING) { START inheritedMapping = mappings[index++]; END } return inheritedMapping; } Where is the index guard? Would be much cleaner if you do standard for loop for (int i=0; i<mappinsg.length;i++) { if (mappings[i].inheritedFrom!=LanguageMappingResolver.FILE_MAPPING) return mappinsg[i]; } // not sure what we do here

Target:
private LanguageMapping computeInheritedMapping(IProject project, IFile file, ICConfigurationDescription configuration) throws CoreException { LanguageMapping mappings[] = LanguageMappingResolver.computeLanguage(project, file.getProjectRelativePath().toPortableString(), configuration, fContentType.getId(), true); // Skip over the file mapping because we want to know what mapping the file // mapping overrides. for (int i = 0; i < mappings.length; i++) { if (mappings[i].inheritedFrom != LanguageMappingResolver.FILE_MAPPING) { return mappings[i]; } } return null; }
Source:
public static DBI create(ConnectionFactory connectionFactory) { DBI dbi = new DBI(connectionFactory); START dbi.installPlugins(); END return dbi; } This is the only thing I object to. I'm not a fan of Spring-style magic--by which I mean stuff just happens because a JAR is on the classpath (or sometime next year, in the Java 9 module graph). JDBI has thus far done a great job of keeping the magic "visible." I would rather force users to make a single call to `DBI.installPlugins()` so that the ServiceLoader stuff is truly opt-in.

Target:
public static DBI create(ConnectionFactory connectionFactory) { return new DBI(connectionFactory); }
Source:
public TransactionTemplate retries( int retries ) { if ( retries < 1 ) { throw new IllegalArgumentException( "Number of retries must be greater than or equal to 1" ); START } END return new TransactionTemplate( gds, monitor, retries, backoff, retryPredicate ); } Oh, so the number of retries actually includes the first try as well.

Target:
public TransactionTemplate retries( int retries ) { return new TransactionTemplate( gds, monitor, retries, backoff, retryPredicate ); }
Source:
public String toString() { START return "InternalSinkRecord{" + "consumerRecord=" + originalRecord.toString() + "} " + super.toString(); END } Hmm, let's just have this delegate to the super method. It's internal, so we need not include the original record details. ```suggestion return super.toString(); ```

Target:
public String toString() { return super.toString(); }
Source:
public ZKConfig(File configFile) throws ConfigException { START init(); END addConfiguration(configFile); } Instead of calling `init` explicitly here, you could just call `this()` to call the default constructor `ZKConfig`.

Target:
public ZKConfig(File configFile) throws ConfigException { this(); addConfiguration(configFile); }
Source:
public String getServerVersion() START throws SecurityException, TransactionException, TException { END return Version.getVersion(ConcourseServer.class).toString(); } why does this need to declare that it throws these exceptions, now?

Target:
public String getServerVersion() { return Version.getVersion(ConcourseServer.class).toString(); }
Source:
public void registerCache(String name) { CacheDescriptor defaultDescriptor = getCacheDescriptor(DEFAULT_CACHE_ID); if (defaultDescriptor == null) { defaultDescriptor = new CacheDescriptor(); START defaultDescriptor.options.put(CacheDescriptor.OPTION_MAX_SIZE, END String.valueOf(CacheDescriptor.DEFAULT_MAX_SIZE)); register(XP_CACHES, defaultDescriptor); } CacheDescriptor newDescriptor = (CacheDescriptor) new CacheDescriptor().merge(defaultDescriptor); newDescriptor.name = name; // add to registry (merging if needed) register(XP_CACHES, newDescriptor); // start if needed maybeStart(name); } Don't forget to re-add default TTL here probably.

Target:
public void registerCache(String name) { CacheDescriptor defaultDescriptor = getCacheDescriptor(DEFAULT_CACHE_ID); if (defaultDescriptor == null) { defaultDescriptor = new CacheDescriptor(); defaultDescriptor.options.put(OPTION_MAX_SIZE, String.valueOf(DEFAULT_MAX_SIZE)); register(XP_CACHES, defaultDescriptor); } CacheDescriptor newDescriptor = (CacheDescriptor) new CacheDescriptor().merge(defaultDescriptor); newDescriptor.name = name; // add to registry (merging if needed) register(XP_CACHES, newDescriptor); // start if needed maybeStart(name); }
Source:
private Consumer<Future<String>> assertAllLocksAcquiredCorrectly() { return result -> { try { String assertionError = result.get( SECONDS_TO_RUN * 100, TimeUnit.SECONDS ); if ( assertionError != null ) { fail( assertionError ); } } catch ( InterruptedException | ExecutionException | TimeoutException e ) { START throw Exceptions.launderedException( e ); END } }; } `Exceptions.launderedException` is being removed, so avoid calling it here. Just wrap and throw `RuntimeException`.

Target:
private Consumer<Future<String>> assertAllLocksAcquiredCorrectly() { return result -> { try { String assertionError = result.get( SECONDS_TO_RUN * 100, TimeUnit.SECONDS ); if ( assertionError != null ) { fail( assertionError ); } } catch ( InterruptedException | ExecutionException | TimeoutException e ) { throw new RuntimeException( e ); } }; }
Source:
private void storeCredentials(AddRemotePage remotePage) { if (remotePage.getStoreInSecureStore()) { URIish uri = remotePage.getSelection().getURI(); START if (uri != null) END SecureStoreUtils.storeCredentials(remotePage.getCredentials(), uri); } } style nit: missing braces

Target:
private void storeCredentials(AddRemotePage remotePage) { if (remotePage.getStoreInSecureStore()) { URIish uri = remotePage.getSelection().getURI(); if (uri != null) { SecureStoreUtils.storeCredentials(remotePage.getCredentials(), uri); } } }
Source:
public Indexer(Config config, Deduper deduper) { this.config = config; this.deduper = deduper; this.localDatabase = new SqlDatabase(config); try { START localDatabase.getConnection().setReadOnly(true); END } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.eventBus = LocalEventBus.getInstance(); } try/catch block in a constructor with `e.printStackTrace()`? Shouldn't this be something like `SqlDatabase.createReadOnly(config);` or something?

Target:
public Indexer(Config config, Deduper deduper) { this.config = config; this.deduper = deduper; this.localDatabase = new SqlDatabase(config, true); this.eventBus = LocalEventBus.getInstance(); }
Source:
void setLocalPartitionCount(int partitionCount) { // this method should be invoked before participation, so the initial value is expected to be 0. if (!offlineCount.compareAndSet(0, partitionCount)) { START logger.warn("Number of OFFLINE partitions has changed before initializing participant metrics"); END } } Should this throw IllegalStateException? Seems like bug case.

Target:
void setLocalPartitionCount(int partitionCount) { // this method should be invoked before participation, so the initial value is expected to be 0. if (!offlineCount.compareAndSet(0, partitionCount)) { throw new IllegalStateException( "Number of OFFLINE partitions has changed before initializing participant metrics"); } }
Source:
START private void log(ITestNGMethod method, String prefix) { END if (method.getInstance() != null) { messages.add(prefix + method.getInstance().getClass().getName() + "." + method.getMethodName()); } else { messages.add(prefix + method.getMethodName()); } } could be static

Target:
private static void log(ITestNGMethod method, String prefix) { if (method.getInstance() != null) { messages.add(prefix + method.getInstance().getClass().getName() + "." + method.getMethodName()); } else { messages.add(prefix + method.getMethodName()); } }
Source:
public Void visitAggregation(AggregationNode node, ImmutableList.Builder<Expression> context) { node.getAggregations().values() .forEach(aggregation -> context.add(aggregation.getCall())); node.getGroupingSets().forEach(groupingSet -> groupingSet START .forEach(symbol -> context.add(symbol.toSymbolReference()))); END return super.visitAggregation(node, context); } It is wrong. Symbols are not expressions.

Target:
public Void visitAggregation(AggregationNode node, ImmutableList.Builder<Expression> context) { node.getAggregations().values() .forEach(aggregation -> context.add(aggregation.getCall())); return super.visitAggregation(node, context); }
Source:
public SslConnection accept(StreamConnection tcpConnection, SSLEngine engine) { SslConnection connection = new JsseSslStreamConnection(tcpConnection, engine, socketBufferPool, applicationBufferPool, startTls); if(sslEngineCallback != null) { sslEngineCallback.acceptCallback(connection, engine); } START return connection; END } What is the purpose of this mechanism?

Target:
public SslConnection accept(StreamConnection tcpConnection, SSLEngine engine) { return new JsseSslStreamConnection(tcpConnection, engine, socketBufferPool, applicationBufferPool, startTls); }
Source:
private static String remoteUrl(final Context context) { String customURL = context.get(Download.INSTANCE); if(customURL != null && !customURL.isEmpty()) { START return context.get(Download.INSTANCE); END } else { return DEFAULT_REMOTE_URL; } } Let's try sticking to the current style add final and use it as return value

Target:
private static String remoteUrl(final Context context) { final String customURL = context.get(Download.INSTANCE); if(customURL != null && !customURL.isEmpty()) { return customURL; } else { return DEFAULT_REMOTE_URL; } }
Source:
private void mapLinesToOffsets() throws IOException { START try (Scanner scanner = new Scanner(Paths.get(filePath))) { END int currentGlobalOffset = 0; while (scanner.hasNextLine()) { lineToOffset.add(currentGlobalOffset); currentGlobalOffset += getLineLengthWithLineSeparator(scanner); } } } why not have `filePath` be a `Path` directly?

Target:
private void mapLinesToOffsets() throws IOException { try (Scanner scanner = new Scanner(filePath)) { int currentGlobalOffset = 0; while (scanner.hasNextLine()) { lineToOffset.add(currentGlobalOffset); currentGlobalOffset += getLineLengthWithLineSeparator(scanner); } } }
Source:
public boolean handlesEvent(CellPreviewEvent<EntityModel> event) START { END NativeEvent nativeEvent = event.getNativeEvent(); if (!BrowserEvents.CLICK.equals(nativeEvent.getType())) { return false; } return true; } this can be simply "return BrowserEvents.CLICK.equals( event.getNativeEvent().getType())"

Target:
public boolean handlesEvent(CellPreviewEvent<EntityModel> event) { return BrowserEvents.CLICK.equals(event.getNativeEvent().getType()); }
Source:
START public Optional<Iterable<String>> getFlags(String field) { END Optional<String> value = delegate.getValue(SECTION_NAME, field); return value.map(input -> Splitter.on(" ").split(input.trim())); } We should mark this as `private`.

Target:
private Optional<Iterable<String>> getFlags(String field) { Optional<String> value = delegate.getValue(SECTION_NAME, field); return value.map(input -> Splitter.on(" ").split(input.trim())); }
Source:
private void storeNetwork() throws UnsupportedEncodingException { START if (sourceProtocol.equals(NetConfigSourceProtocol.OPENSTACK_METADATA)) { END networkData = new VmInitToOpenStackMetadata(vmInit).asMap(); } else { storeNetworkAsEni(); } } we typically compare enum values using '==' instead of 'equals'

Target:
private void storeNetwork() throws UnsupportedEncodingException { if (sourceProtocol == NetConfigSourceProtocol.OPENSTACK_METADATA) { networkData = new VmInitToOpenStackMetadata(vmInit).asMap(); } else { storeNetworkAsEni(); } }
Source:
public Object execute(ExecutionEvent aEvent) throws ExecutionException { GerritTableView reviewTableView = GerritTableView.getActiveView(); // see http://gerrit-documentation.googlecode.com/svn/Documentation/2.5.2/user-search.html //for All > AbandonedOpen--> status:abandoned START GerritUi.Ftracer.traceInfo(NLS.bind(Messages.AllReviewsHandler_executeCommand, END GerritQuery.QUERY_ALL_ABANDONED_CHANGES)); reviewTableView.processCommands(GerritQuery.QUERY_ALL_ABANDONED_CHANGES); return null; } Strings that aren't being displayed to users should not be internationalized.

Target:
public Object execute(ExecutionEvent aEvent) throws ExecutionException { GerritTableView reviewTableView = GerritTableView.getActiveView(); // see http://gerrit-documentation.googlecode.com/svn/Documentation/2.5.2/user-search.html //for All > AbandonedOpen--> status:abandoned reviewTableView.processCommands(GerritQuery.QUERY_ALL_ABANDONED_CHANGES); return null; }
Source:
protected boolean canDoAction() { START END setGlusterVolumeId(getParameters().getVolumeId() == null ? getGeoRepSession().getMasterVolumeId() : getParameters().getVolumeId()); if (!super.canDoAction()) { return false; } if (getGeoRepSession().getStatus().equals(GeoRepSessionStatus.ACTIVE)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GEOREP_SESSION_ALREADY_STARTED); } return true; } I think this change does not belong in this patch

Target:
protected boolean canDoAction() { setGlusterVolumeId(getGeoRepSession().getMasterVolumeId()); if (!super.canDoAction()) { return false; } if (getGeoRepSession().getStatus().equals(GeoRepSessionStatus.ACTIVE)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GEOREP_SESSION_ALREADY_STARTED); } return true; }