auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitFunctionOrMethodDeclaration(@NotNull GoFunctionOrMethodDeclaration o) { // todo: extract common interface START super.visitFunctionOrMethodDeclaration(o); END check(o.getSignature(), o.getBlock(), holder); } @Override public void visitFunctionLit(@NotNull GoFunctionLit o) { super.visitFunctionLit(o); check(o.getSignature(), o.getBlock(), holder); } }; } `check` does checkCanceled

Target:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitFunctionOrMethodDeclaration(@NotNull GoFunctionOrMethodDeclaration o) { // todo: extract common interface check(o.getSignature(), o.getBlock(), holder); } @Override public void visitFunctionLit(@NotNull GoFunctionLit o) { check(o.getSignature(), o.getBlock(), holder); } }; }
Source:
public JwtAuthenticationToken(Jwt jwt) { super(jwt); START this.name = this.getToken().getSubject(); END } This make sense, since `getToken()` is `final`, but what would you think of just doing: ```suggestion this.name = jwt.getSubject(); ``` So that readers of this code have fewer methods to jump through to understand the code.

Target:
public JwtAuthenticationToken(Jwt jwt) { super(jwt); this.name = jwt.getSubject(); }
Source:
public void start() { cacheName = ByteString.fromString(cache.getName()); this.transactional = configuration.transaction().transactionMode().isTransactional(); this.totalOrderProtocol = configuration.transaction().transactionProtocol().isTotalOrder(); START this.distributedOrReplicated = configuration.clustering().cacheMode().isDistributed() || configuration.clustering().cacheMode().isReplicated(); END } no longer used as well.

Target:
public void start() { cacheName = ByteString.fromString(cache.getName()); this.transactional = configuration.transaction().transactionMode().isTransactional(); this.totalOrderProtocol = configuration.transaction().transactionProtocol().isTotalOrder(); }
Source:
private URL getUrl() { String urlString = null; URL url = null; try { urlString = oProxyHelper .getAdapterEndPointFromConnectionManager(DIRECT_CONFIG_SERVICE_NAME); } catch (ConnectionManagerException ex) { START LOG.error("Error reading directConfig Url cannot be found: {}", ex.getLocalizedMessage(), ex); END } try { url = new URL(urlString); } catch (MalformedURLException ex) { LOG.error("Error while converting urlString into Url format {}", ex.getMessage(), ex); } return url; } I am OK with just using ex.getErrorMessage() than getLocalizedMessage(), but I do agree that we should try to stick with one method in our code for loggers.

Target:
private URL getUrl() { String urlString = null; URL url = null; try { urlString = oProxyHelper .getAdapterEndPointFromConnectionManager(DIRECT_CONFIG_SERVICE_NAME); } catch (ConnectionManagerException ex) { LOG.error("Error reading directConfig Url cannot be found: {}", ex.getLocalizedMessage(), ex); } try { url = new URL(urlString); } catch (MalformedURLException ex) { LOG.error("Error while converting urlString into Url format {}", ex.getLocalizedMessage(), ex); } return url; }
Source:
public List<SpoonFolder> getSubFolders() { List<SpoonFolder> result = new ArrayList<>(); Set<SpoonFolder> distinctSet = new HashSet<>(); for (SpoonFile f : getAllFiles()) { START SpoonFolder folder = f.getParent(); END if (distinctSet.add(folder)) { result.add(folder); } } return Collections.unmodifiableList(result); } are your sure hashCode/equals of SpoonFolder are correct? I'm not sure they are well tested.

Target:
public List<SpoonFolder> getSubFolders() { List<SpoonFolder> result = new ArrayList<>(); for (SpoonFile f : getAllFiles()) { SpoonFolder folder = f.getParent(); if (!result.contains(folder)) { result.add(folder); } } return Collections.unmodifiableList(result); }
Source:
public MockHttpServletRequest newPutRequest(String requestURI, Object content) { MockHttpServletRequest request = request(RequestMethod.PUT, requestURI); try { String json = new ObjectMapper().writeValueAsString(content); START request.setContent(json.getBytes("UTF-8")); END } catch (Exception e) { throw new RuntimeException(e); } return request; } Instead of the line above, why don't you just call newPutRequest(requestURI, json)?

Target:
public MockHttpServletRequest newPutRequest(String requestURI, Object content) { try { String json = new ObjectMapper().writeValueAsString(content); return newPutRequest(requestURI, json); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
private int[] propertyIds() { START int props[] = new int[numberOfProps]; END for ( int i = 0; i < numberOfProps; i++ ) { props[i] = i; } return props; } `int[] props` would make everyone including the style checker much happier

Target:
private int[] propertyIds() { int[] props = new int[numberOfProps]; for ( int i = 0; i < numberOfProps; i++ ) { props[i] = i; } return props; }
Source:
public void shouldPurgeAnAutoGenerationOption() throws Exception { MockHttpServletRequest req = request(RequestMethod.DELETE, getURI() + "/" + getUuid()); req.addParameter("purge", ""); handle(req); START assertNull(identifierSourceService END .getAutoGenerationOption(Context.getPatientService().getPatientIdentifierTypeByUuid(getUuid()))); } How sure are you that it was not null before the purging?

Target:
public void shouldPurgeAnAutoGenerationOption() throws Exception { assertNotNull(identifierSourceService.getAutoGenerationOption(Integer.parseInt(getUuid()))); MockHttpServletRequest req = request(RequestMethod.DELETE, getURI() + "/" + getUuid()); req.addParameter("purge", ""); handle(req); assertNull(identifierSourceService.getAutoGenerationOption(Integer.parseInt(getUuid()))); }
Source:
public Page appendColumn(Block block) { requireNonNull(block, "block is null"); if (positionCount != block.getPositionCount()) { throw new IllegalArgumentException("Block does not have same position count"); } Block[] newBlocks = Arrays.copyOf(blocks, blocks.length + 1); START System.arraycopy(blocks, 0, newBlocks, 0, blocks.length); END newBlocks[blocks.length] = block; return new Page(newBlocks); } Why both Arrays.copyOf and System.arrayCopy?

Target:
public Page appendColumn(Block block) { requireNonNull(block, "block is null"); if (positionCount != block.getPositionCount()) { throw new IllegalArgumentException("Block does not have same position count"); } Block[] newBlocks = Arrays.copyOf(blocks, blocks.length + 1); newBlocks[blocks.length] = block; return new Page(newBlocks); }
Source:
public void close() { Closeables.closeQuietly(nettyConnectionPool); try { timer.stop(); } START finally { END // ignored } } empty finally block

Target:
public void close() { Closeables.closeQuietly(nettyConnectionPool); try { timer.stop(); } catch(Exception e) { // ignored } }
Source:
private void completeAllExceptionally(Throwable t) { List<Data> completed; synchronized (futures) { START completed = new ArrayList<>(futures.size()); END completed.addAll(futures.values()); } for (Data data : completed) { data.cancelFuture.cancel(false); data.completeExceptionally(t); } } why not use `new ArrayList<>(futures.values());`

Target:
private void completeAllExceptionally(Throwable t) { List<Data> completed; synchronized (futures) { completed = new ArrayList<>(futures.values()); } for (Data data : completed) { data.cancelFuture.cancel(false); data.completeExceptionally(t); } }
Source:
START public final int hashCode() { return (int) (w2 >>> 32); } END Why use only w2? Why the right shift? Likely it doesn't really matter.

Target:
public final int hashCode() { return (int) (w2); }
Source:
private void close() { try { closeExecutors(); START m_loader.close(); END if (m_client != null) { m_client.close(); m_client = null; } } catch (Exception ex) { // Ignore } } should loader also be checked if it's non-null so that if follows similar paradigm as client. This way can call close() from main()'s exception block -> case where initialize fails in initializing loader for some reason and the logic can thereby make sure the initialized client connection gets closed and is not leaked.

Target:
private void close() { try { closeExecutors(); if (m_loader != null) { m_loader.close(); m_loader = null; } if (m_client != null) { m_client.close(); m_client = null; } } catch (Exception ex) { // Ignore } }
Source:
private static void writeContents( FileSystemAbstraction fileSystemAbstraction, File file, String contents ) { byte[] bytes = contents.getBytes(); try ( StoreChannel storeChannel = fileSystemAbstraction.create( file ) ) { storeChannel.write( ByteBuffer.wrap( bytes ) ); START storeChannel.close(); END } catch ( IOException e ) { throw new RuntimeException( e ); } } The try-with-resources takes care of the closing, right?

Target:
private static void writeContents( FileSystemAbstraction fileSystemAbstraction, File file, String contents ) { byte[] bytes = contents.getBytes(); try ( StoreChannel storeChannel = fileSystemAbstraction.create( file ) ) { storeChannel.write( ByteBuffer.wrap( bytes ) ); } catch ( IOException e ) { throw new RuntimeException( e ); } }
Source:
public boolean getAllowUntrustedCertificate() { START return vsConnectionConfig != null && vsConnectionConfig.getAllowUntrustedCertificate(); END } This change seems unnecessary. Best keep this PR limited to _just_ what's necessary to achieve this PR's aims.

Target:
public boolean getAllowUntrustedCertificate() { return vsConnectionConfig != null ? vsConnectionConfig.getAllowUntrustedCertificate() : false; }
Source:
public StopVmCommandBase(T parameters) { super(parameters); START setStoragePoolId(getVm().getstorage_pool_id()); END } A DB call inside the constuctor - not a good practice.

Target:
public StopVmCommandBase(T parameters) { super(parameters); }
Source:
public String getSQL() { String left = getContextSQL(nodes[LEFT]); String right = getContextSQL(nodes[RIGHT]); StringBuffer sb = new StringBuffer(); START sb.append(left).append(' ').append(Tokens.T_STARTS).append(Tokens.T_WITH).append(' '); END sb.append(right); return sb.toString(); } No space between STARTS and WITH??

Target:
public String getSQL() { String left = getContextSQL(nodes[LEFT]); String right = getContextSQL(nodes[RIGHT]); StringBuffer sb = new StringBuffer(); sb.append(left).append(' ').append(Tokens.T_STARTS).append(' ').append(Tokens.T_WITH).append(' '); sb.append(right); return sb.toString(); }
Source:
public boolean isApplicable(UpgradeCheckRequest request) throws AmbariException { UpgradeType upgradeType = request.getUpgradeType(); UpgradeCheckInfo annotation = m_checkClass.getAnnotation(UpgradeCheckInfo.class); if (null == annotation) { return true; } // empty upgrade type or matching should return true UpgradeType[] upgradeTypes = annotation.required(); START if (ArrayUtils.isEmpty(upgradeTypes) || ArrayUtils.contains(upgradeTypes, upgradeType)) { END return true; } return false; } simplify: `return ...`

Target:
public boolean isApplicable(UpgradeCheckRequest request) throws AmbariException { UpgradeType upgradeType = request.getUpgradeType(); UpgradeCheckInfo annotation = m_checkClass.getAnnotation(UpgradeCheckInfo.class); if (null == annotation) { return true; } // empty upgrade type or matching should return true UpgradeType[] upgradeTypes = annotation.required(); return (ArrayUtils.isEmpty(upgradeTypes) || ArrayUtils.contains(upgradeTypes, upgradeType)); }
Source:
private boolean validateHostPort(String string) { // https://stackoverflow.com/questions/2345063/java-common-way-to-validate-and-convert-hostport-to-inetsocketaddress try { // WORKAROUND: add any scheme to make the resulting URI valid. URI uri = new URI("my://" + string); // may throw URISyntaxException if (uri.getHost() == null || uri.getPort() == -1) { START throw new URISyntaxException(uri.toString(), "URI must have host and port parts"); END } } catch (URISyntaxException ex) { // validation failed return false; } // validation succeeded return true; } maybe `return false` here at once would be better?

Target:
private boolean validateHostPort(String string) { // https://stackoverflow.com/questions/2345063/java-common-way-to-validate-and-convert-hostport-to-inetsocketaddress try { // WORKAROUND: add any scheme to make the resulting URI valid. URI uri = new URI("my://" + string); // may throw URISyntaxException if (uri.getHost() == null || uri.getPort() == -1) { return false; } } catch (URISyntaxException ex) { // validation failed return false; } // validation succeeded return true; }
Source:
private int nextCorrelationId() { START if (!isReserved(correlationId)) correlationId = MIN_RESERVED_CORRELATION_ID; END return correlationId++; } as before, this could be if-then-else without the increment below for the `if` case.

Target:
int nextCorrelationId() { if (!isReserved(correlationId)) correlationId = MIN_RESERVED_CORRELATION_ID; return correlationId++; }
Source:
public BoltConnectionQueueMonitorAggregate( BoltConnectionQueueMonitor... monitors ) { START this.monitors = new ArrayList<>( Arrays.asList( monitors ) ); END } Can this be just `this.monitors = Arrays.asList( monitors );`?

Target:
public BoltConnectionQueueMonitorAggregate( BoltConnectionQueueMonitor... monitors ) { this.monitors = Arrays.asList( monitors ); }
Source:
public void testElementAt() { int i = fullList.get(0); START assertTrue(i == 1); END try { fullList.get(fullList.size()); } catch (IndexOutOfBoundsException e) { return; } fail("Should raise an ArrayIndexOutOfBoundsException"); } Do you think we should use `assertEquals()` (with as useful message) instead of `assertTrue()` so you'll get a useful stack trace if this fails? Future users might look at this file as an example of how to write a good JUnit test.

Target:
public void testElementAt() { int i = fullList.get(0); assertEquals(1,i); try { fullList.get(fullList.size()); } catch (IndexOutOfBoundsException e) { return; } fail("Should raise an ArrayIndexOutOfBoundsException"); }
Source:
public String shell(PyObject[] args, String[] kws) { ArgParser ap = JythonUtils.createArgParser(args, kws); Preconditions.checkNotNull(ap); String cmd = ap.getString(0); START if(args.length == 2) END return impl.shell(cmd, ap.getInt(1)); else return impl.shell(cmd); } needs a space after the if and needs both here and with the else.

Target:
public String shell(PyObject[] args, String[] kws) { ArgParser ap = JythonUtils.createArgParser(args, kws); Preconditions.checkNotNull(ap); String cmd = ap.getString(0); if (args.length == 2) { return impl.shell(cmd, ap.getInt(1)); } else { return impl.shell(cmd); } }
Source:
START public synchronized static Set<Class<? extends PhysicalOperator>> getSubTypes(ScanResult classpathScan) { END final Set<Class<? extends PhysicalOperator>> ops = classpathScan.getImplementations(PhysicalOperator.class); logger.debug("Found physical operator classes: {}.", ops.size(), ops); return ops; } Remove synchronized.

Target:
public static Set<Class<? extends PhysicalOperator>> getSubTypes(ScanResult classpathScan) { final Set<Class<? extends PhysicalOperator>> ops = classpathScan.getImplementations(PhysicalOperator.class); logger.debug("Found physical operator classes: {}.", ops.size(), ops); return ops; }
Source:
protected Map<String, Object> subsetMap(String prefix) { Map<String, Object> subset = new TreeMap<String, Object>(); for (Map.Entry<String, Object> e : configMap.entrySet()) { START if (e.getKey() != null && e.getKey().startsWith(prefix)) { END subset.put(e.getKey(), e.getValue()); } } return subset; } Good catch on the null check. I forgot Maps can have `null` as a key.

Target:
protected Map<String, String> subsetMap(String prefix) { Map<String, String> subset = new TreeMap<String, String>(); for (Map.Entry<String, String> e : configMap.entrySet()) { if (e.getKey() != null && e.getKey().startsWith(prefix)) { subset.put(e.getKey(), e.getValue()); } } return subset; }
Source:
public DesiredCapabilities getCapability(String testName) { DesiredCapabilities capabilities = new DesiredCapabilities(); // add capabilities based on dynamic _config.properties variables capabilities = initCapabilities(capabilities); if (R.CONFIG.getBoolean(SpecialKeywords.FULL_RESET_BEFORE_SUITE) && !R.CONFIG.get(SpecialKeywords.FULL_RESET_BEFORE_SUITE).isEmpty()) { START LOGGER.info("Will be execute 'fullResetBeforeSuite'!"); END executeFullResetBeforeSuite(capabilities); } return capabilities; } Let's use debug level instead of info.

Target:
public DesiredCapabilities getCapability(String testName) { DesiredCapabilities capabilities = new DesiredCapabilities(); // add capabilities based on dynamic _config.properties variables capabilities = initCapabilities(capabilities); return capabilities; }
Source:
START public synchronized IConnection connect(String storm_id, String host, int port, AtomicBoolean[] remoteBpStatus) { END return new Client(topoConf, remoteBpStatus, clientChannelFactory, clientScheduleService, host, port, this); } This no longer needs to be synchronized. That was used to protect connections, and is no longer needed if all we do is create a new Client.

Target:
public IConnection connect(String storm_id, String host, int port, AtomicBoolean[] remoteBpStatus) { return new Client(topoConf, remoteBpStatus, clientChannelFactory, clientScheduleService, host, port); }
Source:
START public static ContentFilter get() { END return ExtensionList.lookupSingleton(ContentFilters.class).isEnabled() ? ALL : DISABLED; } It seems cleaner to me to get rid of the DISABLED filter and rewrite the code so that if `isEnabled` is false you never access the filters or create a `FilteredOutputStream` at all. I would also move the ALL filter to `ContentFilter.java` so that this file is just the anonymization config settings.

Target:
public static ContentFilters get() { return ExtensionList.lookupSingleton(ContentFilters.class); }
Source:
public AvailabilityType getAvailability() { ReadAttribute op = new ReadAttribute(getAddress(), "cache-status"); Result res = getASConnection().execute(op); if (res != null && res.isSuccess()) { START if (res.getResult().equals("RUNNING")) { END return AvailabilityType.UP; } } return AvailabilityType.DOWN; } Likewise (re string comparison)

Target:
public AvailabilityType getAvailability() { ReadAttribute op = new ReadAttribute(getAddress(), "cache-status"); Result res = getASConnection().execute(op); if (res != null && res.isSuccess()) { if ("RUNNING".equals(res.getResult())) { return AvailabilityType.UP; } } return AvailabilityType.DOWN; }
Source:
public boolean isEdgeWithRectilinearRoutingStyle() { boolean isEdgeRectilinearRoutingStyle = false; if START (Routing.RECTILINEAR_LITERAL.getLiteral().equals(getRoutingStyle())) END { isEdgeRectilinearRoutingStyle = true; } return isEdgeRectilinearRoutingStyle; } to remove with the remark below

Target:
public boolean isEdgeWithRectilinearRoutingStyle() { boolean isEdgeRectilinearRoutingStyle = false; if (Routing.RECTILINEAR_LITERAL.equals(getRoutingStyle())) { isEdgeRectilinearRoutingStyle = true; } return isEdgeRectilinearRoutingStyle; }
Source:
private void encodeEventData(ObjectOutput out, Object data) throws IOException { if(data != null) { START out.writeObject(data); END }else{ logger.warn("encodeEventData data is null"); } } would it be better to implement it like this? ```java @Deprecated protected Object decodeHeartbeatData(Channel channel, ObjectInput in) throws IOException { return Response.HEARTBEAT_EVENT; } ```

Target:
private void encodeEventData(ObjectOutput out, Object data) throws IOException { out.writeObject(data); }
Source:
public void engineIsRunningNotification() { try { log.debug("DWH Heart Beat - Start"); TransactionSupport.executeInScope(TransactionScopeOption.RequiresNew, () -> { heartBeatVar.setDateTime(new Date()); dwhHistoryTimekeepingDao.save(heartBeatVar); START log.debug("DWH Heart Beat - End"); END return null; }); } catch (Exception ex) { log.error("Error updating DWH Heart Beat: {}", ex.getMessage()); log.debug("Exception", ex); } } Is there a need to have log.debug within transaction scope?

Target:
public void engineIsRunningNotification() { try { log.debug("DWH Heart Beat - Start"); TransactionSupport.executeInScope(TransactionScopeOption.RequiresNew, () -> { heartBeatVar.setDateTime(new Date()); dwhHistoryTimekeepingDao.save(heartBeatVar); return null; }); log.debug("DWH Heart Beat - End"); } catch (Exception ex) { log.error("Error updating DWH Heart Beat: {}", ex.getMessage()); log.debug("Exception", ex); } }
Source:
public BaseCassandraBolt withOutputFields(Fields fields) { START Preconditions.checkNotNull("fields should not be null."); END this.outputsFields.put(Utils.DEFAULT_STREAM_ID, fields); return this; } Missing args, to -> `Preconditions.checkNotNull(fields, "fields should not be null.");`

Target:
public BaseCassandraBolt withOutputFields(Fields fields) { Preconditions.checkNotNull(fields, "fields should not be null."); this.outputsFields.put(Utils.DEFAULT_STREAM_ID, fields); return this; }
Source:
private boolean isRelevant(EntityRef entity, Vector3f position) { START return entity.isAlwaysRelevant() || worldProvider.isBlockRelevant(position); END } Have you considered what is the most likely case if any? Is it more likely that an entity is always relevant or is it more likely that the block at the given position is relevant? If the latter is more likely you'd gain a smidgen of performance by inverting the two expressions.

Target:
private boolean isRelevant(EntityRef entity, Vector3f position) { return worldProvider.isBlockRelevant(position) || entity.isAlwaysRelevant(); }
Source:
public String getClassificationValue(ClassificationScheme classification, ExtrinsicObjectType extrinsicObject) { RegistryObjectType registryObjectType = getClassification(classification, extrinsicObject); START ClassificationType classType = null; END if ((registryObjectType != null) && (registryObjectType instanceof ClassificationType)) { return ((ClassificationType) registryObjectType).getNodeRepresentation(); } return null; } Declared but unused.

Target:
public String getClassificationValue(ClassificationScheme classification, ExtrinsicObjectType extrinsicObject) { RegistryObjectType registryObjectType = getClassification(classification, extrinsicObject); if (registryObjectType != null && (registryObjectType instanceof ClassificationType)) { return ((ClassificationType) registryObjectType).getNodeRepresentation(); } return null; }
Source:
START @Override public String toString() END { return "MetaData{metadata=" + metadata + '}'; } Not following XWiki codestyle.

Target:
public String toString() { return "MetaData{metadata=" + metadata + '}'; }
Source:
public static FlowTrigger createTestFlowTrigger(final List<FlowTriggerDependency> deps, final Duration maxWaitDuration) { START final FlowTrigger flowTrigger = new FlowTrigger( END new CronSchedule("* * * * ? *"), deps, maxWaitDuration); return flowTrigger; } The two lines can be merged into one.

Target:
public static FlowTrigger createTestFlowTrigger(final List<FlowTriggerDependency> deps, final Duration maxWaitDuration) { return new FlowTrigger( new CronSchedule("* * * * ? *"), deps, maxWaitDuration); }
Source:
public synchronized void recover(TaskId taskId) throws TooManyTasksFailedException { checkState(groupedLifespanScheduler.isPresent(), "groupedLifespanScheduler is not present for recoverable grouped execution"); if (anySourceSchedulingFinished) { START throw new IllegalStateException("Recover after any source scheduling finished is not supported"); END } groupedLifespanScheduler.get().onTaskFailed(taskId.getId(), sourceSchedulers); } `new PrestoException(GENERIC_RECOVERY_ERROR)` ? Make sure that you rethrow it as is here: https://github.com/prestodb/presto/pull/12529/commits/1690f79d028246209297d0f9743bc0893773ec97#diff-e97f65103d2e8ce8ea2916e4ab25f522R539 (catch PrestoException specifically as a special case)

Target:
public synchronized void recover(TaskId taskId) { checkState(groupedLifespanScheduler.isPresent(), "groupedLifespanScheduler is not present for recoverable grouped execution"); if (anySourceSchedulingFinished) { throw new IllegalStateException("Recover after any source scheduling finished is not supported"); } groupedLifespanScheduler.get().onTaskFailed(taskId.getId(), sourceSchedulers); }
Source:
public Block[] getSequenceBlocks(int start, int length) { BlockBuilder blockBuilder = UNKNOWN.createBlockBuilder(new BlockBuilderStatus(), length); START for (int i = start; i < start + length; i++) { END blockBuilder.appendNull(); } return new Block[] {blockBuilder.build()}; } why not `[0..length)`

Target:
public Block[] getSequenceBlocks(int start, int length) { BlockBuilder blockBuilder = UNKNOWN.createBlockBuilder(new BlockBuilderStatus(), length); for (int i = 0; i < length; i++) { blockBuilder.appendNull(); } return new Block[] {blockBuilder.build()}; }
Source:
public List<ExchangeDownloadStatus> refreshExchangeManager() { START LOG.info("force the exchangeManager to refresh: {}"); END ExchangeManagerUtil exUtil = new ExchangeManagerUtil(); return exUtil.forceRefreshExchanges(); } I don't think we need to LOG.info any-more; we can used LOG.debug or removed.

Target:
public List<ExchangeDownloadStatus> refreshExchangeManager() { ExchangeManagerUtil exUtil = new ExchangeManagerUtil(); return exUtil.forceRefreshExchanges(); }
Source:
protected void postShutdown() { logger().debug("Shutting down the elasticsearch index provider '{0}' in repository '{1}'", getName(), getRepositoryName()); try { client.close(); esNode.stop(); } catch (Exception e) { START } END } shouldn't the exception be logged ?

Target:
protected void postShutdown() { logger().debug("Shutting down the elasticsearch index provider '{0}' in repository '{1}'", getName(), getRepositoryName()); }
Source:
private void layoutWikiDataDescription(String description) { // set the text of the description... pageDescriptionText.setText(description); // and wait for it to lay out, so that we know the height of the description text. pageDescriptionText.post(new Runnable() { @Override public void run() { if (!parentFragment.isAdded()) { return; } // only show the description if it's two lines or less if (pageDescriptionText.getLineCount() > 2) { START pageDescriptionText.setVisibility(View.GONE); END } else { pageDescriptionText.setVisibility(View.VISIBLE); } } }); } Also consider pageDescriptionText.setVisibility(pageDescriptionText.getLineCount() > 2 > View.VISIBLE : View.GONE); to emphasize that conditional effects function input and no other logic.

Target:
private void layoutWikiDataDescription(String description) { // set the text of the description... pageDescriptionText.setText(description); // and wait for it to lay out, so that we know the height of the description text. pageDescriptionText.post(new Runnable() { @Override public void run() { if (!parentFragment.isAdded()) { return; } // only show the description if it's two lines or less pageDescriptionText.setVisibility(pageDescriptionText.getLineCount() > 2 ? View.GONE : View.VISIBLE); } }); }
Source:
START AsyncSession getSession() { END return AsyncSession.this; } Is there a reason to not make it `protected` ?

Target:
protected AsyncSession getSession() { return AsyncSession.this; }
Source:
START public static String get() { return props.getOrDefault(VERSION_RELEASE_KEY, "unset"); } END `getOrDefault` is not available in Java 7.

Target:
public static String get() { return props.get(VERSION_RELEASE_KEY); }
Source:
START protected Composite createWidgets(Composite parent, CDKServer cdkServer, FormToolkit toolkit) { END Composite composite = initializeSectionWidget(parent, toolkit); createChooseCredentialsWidgets(composite, toolkit); createEnvironmentWidgets(composite, toolkit, cdkServer); addRegistrationWidgets(parent, cdkServer, toolkit); return composite; } ![MAJOR](https://sonarsource.github.io/sonar-github/severity-major.png 'Severity: MAJOR') Add the "@Override" annotation above this method signature [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3AS1161)

Target:
protected Composite createWidgets(Composite parent, CDKServer cdkServer, FormToolkit toolkit) { Composite composite = initializeSectionWidget(parent, toolkit); createChooseCredentialsWidgets(composite, toolkit); createEnvironmentWidgets(composite, toolkit, cdkServer); addRegistrationWidgets(composite, cdkServer, toolkit); return composite; }
Source:
private void drawTiles( Canvas canvas ) { if( mPreviouslyDrawnTiles.size() > 0 ) { drawTilesConsideringPreviouslyDrawnLevel( canvas ); } else { drawTilesWithoutConsideringPreviouslyDrawnLevel( canvas ); } START Log.d( getClass().getSimpleName(), "prevous tile count: " + mPreviouslyDrawnTiles.size() ); END } TODO : remove that log before release.

Target:
private void drawTiles( Canvas canvas ) { if( mPreviouslyDrawnTiles.size() > 0 ) { drawTilesConsideringPreviouslyDrawnLevel( canvas ); } else { drawTilesWithoutConsideringPreviouslyDrawnLevel( canvas ); } }
Source:
private static void cleanUpOldFiles(File dir) { long cutoffTimestamp = System.currentTimeMillis() - (MAX_FILE_AGE_HOURS * Constants.HOUR_MS); File[] files = dir.listFiles(); for (File file : files) { if (!FileUtils.isFileNewer(file, cutoffTimestamp)) { START delete(file); END } } } When do we decide to use `stream`?

Target:
private static void cleanUpOldFiles(File dir) { long cutoffTimestamp = System.currentTimeMillis() - (MAX_FILE_AGE_HOURS * Constants.HOUR_MS); Arrays.asList(dir.listFiles()).stream() .filter(file -> !FileUtils.isFileNewer(file, cutoffTimestamp)) .forEach(file -> delete(file)); }
Source:
boolean getAsBoolean() throws Exception; } /** Wait until {@code predicate} is satisfied, or fail, with a given timeout. */ public static void waitUntil( String message, START int timeoutSeconds, END BooleanSupplierWithThrow predicate) throws Exception { int sleep = 125; final long timeout = System.currentTimeMillis() + timeoutSeconds * 1000; while (System.currentTimeMillis() < timeout) { if (predicate.getAsBoolean()) { return; } RunUtil.getDefault().sleep(sleep); } fail(message); } nit: long ?

Target:
boolean getAsBoolean() throws Exception; } /** Wait until {@code predicate} is satisfied, or fail, with a given timeout. */ public static void waitUntil( String message, long timeoutSeconds, BooleanSupplierWithThrow predicate) throws Exception { int sleep = 125; final long timeout = System.currentTimeMillis() + timeoutSeconds * 1000; while (System.currentTimeMillis() < timeout) { if (predicate.getAsBoolean()) { return; } RunUtil.getDefault().sleep(sleep); } fail(message); }
Source:
protected void endVmCommand() { setCommandShouldBeLogged(false); if (getVm() == null) { log.warn("VM is null, not performing full endAction"); START setSucceeded(true); END } getVm().setStatus(VMStatus.Down); getSnapshotDao().removeMemoryFromActiveSnapshot(getVmId()); getVmDynamicDao().update(getVm().getDynamicData()); setSucceeded(true); } missing return here

Target:
protected void endVmCommand() { setCommandShouldBeLogged(false); if (getVm() == null) { log.warn("VM is null, not performing full endAction"); setSucceeded(true); return; } getVm().setStatus(VMStatus.Down); getSnapshotDao().removeMemoryFromActiveSnapshot(getVmId()); getVmDynamicDao().update(getVm().getDynamicData()); setSucceeded(true); }
Source:
protected LevelsClass getListClass() { LevelsClass element = new LevelsClass(); element.fromString(Joiner.on(getSeparator()).join(FluentIterable.from(Arrays.asList( START enumType.getEnumConstants())).transform(GET_ACCESS_LEVEL_ENUM_IDENTIFIERS))); END return element; } element.fromString only returns a BaseProperty, it doesn't change the LevelsClass. i guess the method should only returns a new LevelsClass?

Target:
protected LevelsClass getListClass() { return new LevelsClass(); }
Source:
public void onRefresh() { super.onRefresh(); if (mFile != null) { // Refresh mFile mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId()); listDirectory(mFile); ((FileDisplayActivity)mContainerActivity).startSyncFolderOperation(mFile); START Log_OC.d(TAG, "Parent etag= |" + mFile.getEtag() + "|"); END } } Remove this Log, please.

Target:
public void onRefresh() { super.onRefresh(); if (mFile != null) { // Refresh mFile mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId()); listDirectory(mFile); ((FileDisplayActivity)mContainerActivity).startSyncFolderOperation(mFile); } }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PlanNodeStatsEstimate that = (PlanNodeStatsEstimate) o; START return Double.compare(that.outputRowCount, outputRowCount) == 0 && END Double.compare(that.outputSizeInBytes, outputSizeInBytes) == 0 && Objects.equals(symbolStatistics, that.symbolStatistics); } Change from `Object.equals` to `Double.compare` should be part of previous commit.

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PlanNodeStatsEstimate that = (PlanNodeStatsEstimate) o; return Double.compare(outputRowCount, that.outputRowCount) == 0 && Objects.equals(symbolStatistics, that.symbolStatistics); }
Source:
public BasicAuthDBConfig( final PasswordProvider initialAdminPassword, final PasswordProvider initialInternalClientPassword, final String initialAdminUser, final String initialAdminRole, final String initialAdminGroupMapping, final boolean enableCacheNotifications, final long cacheNotificationTimeout, final int credentialIterations ) { this.initialAdminPassword = initialAdminPassword; this.initialInternalClientPassword = initialInternalClientPassword; this.initialAdminUser = initialAdminUser; this.initialAdminRole = initialAdminRole; this.initialAdminGroupMapping = initialAdminGroupMapping; this.enableCacheNotifications = enableCacheNotifications; this.cacheNotificationTimeout = cacheNotificationTimeout; START this.iterations = credentialIterations; END } nit: Suggest renaming `iterations` and its getter as well here

Target:
public BasicAuthDBConfig( final PasswordProvider initialAdminPassword, final PasswordProvider initialInternalClientPassword, final String initialAdminUser, final String initialAdminRole, final String initialAdminGroupMapping, final boolean enableCacheNotifications, final long cacheNotificationTimeout, final int credentialIterations ) { this.initialAdminPassword = initialAdminPassword; this.initialInternalClientPassword = initialInternalClientPassword; this.initialAdminUser = initialAdminUser; this.initialAdminRole = initialAdminRole; this.initialAdminGroupMapping = initialAdminGroupMapping; this.enableCacheNotifications = enableCacheNotifications; this.cacheNotificationTimeout = cacheNotificationTimeout; this.credentialIterations = credentialIterations; }
Source:
public void setWidth(String width, boolean isFixedLayout) { table.setWidth("100%", true); //$NON-NLS-1$ START tableHeader.setWidth("100%", true); //$NON-NLS-1$ END } Please pass 'isFixedLayout' to the 'setWidth' methods

Target:
public void setWidth(String width, boolean isFixedLayout) { table.setWidth("100%", isFixedLayout); //$NON-NLS-1$ tableHeader.setWidth("100%", isFixedLayout); //$NON-NLS-1$ }
Source:
private void setCustomServer(String s) { SharedPreferences userPreferences = AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance()); SharedPreferences.Editor e = userPreferences.edit(); e.putBoolean("useCustomSyncServer", true); e.putString("syncBaseUrl", s); START e.commit(); END } same commit vs apply question here, one answer answers both

Target:
private void setCustomServer(String s) { SharedPreferences userPreferences = AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance()); SharedPreferences.Editor e = userPreferences.edit(); e.putBoolean("useCustomSyncServer", true); e.putString("syncBaseUrl", s); e.apply(); }
Source:
default List<Pattern> getExcludedResponseHeaderPatterns() { START return emptyList(); END } Generally better to qualify than making static import; this makes me go look at where it's coming from (ie. did you implement your own for some reason?) I tend to use static imports for constants or in Unit tests where its very obvious what is not provided by custom code (ie. assertXXX(..), mock(..), etc.) ```suggestion return Collections.emptyList(); ```

Target:
default List<Pattern> getExcludedResponseHeaderPatterns() { return Collections.emptyList(); }
Source:
public HelixAccountServiceFactory(VerifiableProperties verifiableProperties, MetricRegistry metricRegistry) { storeConfig = new HelixPropertyStoreConfig(verifiableProperties); accountServiceConfig = new HelixAccountServiceConfig(verifiableProperties); accountServiceMetrics = new AccountServiceMetrics(metricRegistry); notifier = START accountServiceConfig.zkClientConnectString.equals(HelixAccountServiceConfig.INVALID_ZK_CLIENT_CONNECT_STRING) END ? null : new HelixNotifier(accountServiceConfig.zkClientConnectString, storeConfig); } I don't think the `if` case is required here since it is assumed that `accountServiceConfig.zkClientConnectString` is not invalid (it is used in `getAccountService()`). What do you think?

Target:
public HelixAccountServiceFactory(VerifiableProperties verifiableProperties, MetricRegistry metricRegistry) { this(new HelixPropertyStoreConfig(verifiableProperties), new HelixAccountServiceConfig(verifiableProperties), new AccountServiceMetrics(metricRegistry), new HelixNotifier(new HelixAccountServiceConfig(verifiableProperties).zkClientConnectString, new HelixPropertyStoreConfig(verifiableProperties))); }
Source:
private void logExceptionBeforeFailOver(Exception ex, MessageHandler handler, Message<?> message) { if (this.logger.isInfoEnabled()) { this.logger.info("An exception was thrown by '" + handler + "' while handling '" + message + "': " + ex.getMessage() + ". Failing over to the next subscriber."); } else if (this.logger.isDebugEnabled()) { this.logger.debug("An exception was thrown by '" + handler + "' while handling '" + message + START "'. Failing over to the next subscriber.", ex); END } } Debug has to be detected first otherwise we'll always take the INFO branch.

Target:
private void logExceptionBeforeFailOver(Exception ex, MessageHandler handler, Message<?> message) { if (this.logger.isDebugEnabled()) { this.logger.debug("An exception was thrown by '" + handler + "' while handling '" + message + "'. Failing over to the next subscriber.", ex); } else if (this.logger.isInfoEnabled()) { this.logger.info("An exception was thrown by '" + handler + "' while handling '" + message + "': " + ex.getMessage() + ". Failing over to the next subscriber."); } }
Source:
public void started() { IdgenTask.setEnabled(true); START createLocationPrefixAttributeType(); END log.info("Idgen Module Started..."); } You should not be creating Location Attributes on idgen module startup. This is not a core function of the idgen module and might have other implications. If an implementer wants to use the LocationBasedPrefixProvider, then can take responsibility over ensuring that the correct LocationAttributeType and LocationAttributes exist.

Target:
public void started() { IdgenTask.setEnabled(true); log.info("Idgen Module Started..."); }
Source:
private static List<RunOrderWithArguments> withEmptyArguments( RunOrder[] runOrders ) { START List<RunOrderWithArguments> orderWithArguments = new ArrayList<RunOrderWithArguments>(); END for ( RunOrder runOrder : runOrders ) { RunOrderArguments args = new RunOrderArguments( new ArrayList<String>() ); orderWithArguments.add( new RunOrderWithArguments( runOrder, args ) ); } return orderWithArguments; } pls use diamond `new ArrayList<>();`

Target:
private static List<RunOrderWithArguments> withEmptyArguments( RunOrder[] runOrders ) { List<RunOrderWithArguments> orderWithArguments = new ArrayList<>(); for ( RunOrder runOrder : runOrders ) { RunOrderArguments args = new RunOrderArguments( new ArrayList<String>() ); orderWithArguments.add( new RunOrderWithArguments( runOrder, args ) ); } return orderWithArguments; }
Source:
public String getResourceContent(String name) throws IOException { String output = ""; if (getEngineContext() != null) { try (InputStream is = getResourceAsStream(name)) { if (is == null) { // Resources should always be encoded as UTF-8, to reduce the dependency on the system encoding output = FileUtils.readFileToString(new File(name), DEFAULT_ENCODING); } START else output = IOUtils.toString(is, DEFAULT_ENCODING); END } } return output; } This does not follow XWiki codestyle (missing { and }).

Target:
public String getResourceContent(String name) throws IOException { if (getEngineContext() != null) { try (InputStream is = getResourceAsStream(name)) { if (is != null) { return IOUtils.toString(is, DEFAULT_ENCODING); } } } // Resources should always be encoded as UTF-8, to reduce the dependency on the system encoding return FileUtils.readFileToString(new File(name), DEFAULT_ENCODING); }
Source:
public void assertStartsWithCount(int eventsCount, String startsWith) { List<LogEntry> logs = auditBackend.queryLogs(new AuditQueryBuilder().predicates( Predicates.eq(LOG_EVENT_ID, ID_FOR_AUDIT_STORAGE_TESTS), START new Predicate(new Reference(LOG_DOC_PATH), Operator.STARTSWITH, Literals.toLiteral(startsWith)))); END assertEquals(eventsCount, logs.size()); } Why not adding this to `Predicates` ?

Target:
public void assertStartsWithCount(int eventsCount, String startsWith) { List<LogEntry> logs = auditBackend.queryLogs(new AuditQueryBuilder().predicates( Predicates.eq(LOG_EVENT_ID, ID_FOR_AUDIT_STORAGE_TESTS), Predicates.startsWith(LOG_DOC_PATH, startsWith))); assertEquals(eventsCount, logs.size()); }
Source:
public static boolean isInChain(Certificate cert, List<Certificate> chain) { String lookSKI = getCertKeyIdSubject(cert); START if (null == lookSKI) { END return false; } String foundSKI = null; for (Certificate link : chain) { foundSKI = getCertKeyIdSubject(link); if (lookSKI.equals(foundSKI)) { return true; } } return false; } Inverse this, and combine with following lines. Can get rid of an entire branch

Target:
public static boolean isInChain(Certificate cert, List<Certificate> chain) { String lookSKI = getCertKeyIdSubject(cert); if (null != lookSKI) { for (Certificate link : chain) { String foundSKI = getCertKeyIdSubject(link); if (lookSKI.equals(foundSKI)) { return true; } } } return false; }
Source:
public static Function<HttpPollValue, Double> latency() { return new Function<HttpPollValue, Double>() { @Override @Nullable public Double apply(HttpPollValue input) { if (input.getLatencyFullContent()==null) return null; START return input.getLatencyFullContent().doubleValue(); END } }; } Why convert this to a double, rather than leave it as the exact long value?

Target:
public static Function<HttpPollValue, Long> latency() { return new Function<HttpPollValue, Long>() { public Long apply(HttpPollValue input) { return input.getLatencyFullContent(); } }; }
Source:
public void sendRequest(NetworkRequest request) throws InterruptedException { DataInputStream stream = new DataInputStream(request.getInputStream()); try { // The first 8 bytes is size of the request. TCP implementation uses this size to allocate buffer. See {@link BoundedReceive} // Here we just need to consume it. stream.readLong(); } catch (IOException e) { START throw new InterruptedException("stream read error." + e); END } requestQueue.put(request); } nit: this isn't exactly a result of an interrupt, so I think throwing a RuntimeException like `IllegalStateException` would be a better fit here.

Target:
public void sendRequest(NetworkRequest request) throws InterruptedException { DataInputStream stream = new DataInputStream(request.getInputStream()); try { // The first 8 bytes is size of the request. TCP implementation uses this size to allocate buffer. See {@link BoundedReceive} // Here we just need to consume it. stream.readLong(); } catch (IOException e) { throw new IllegalStateException("stream read error." + e); } requestQueue.put(request); }
Source:
START public static final KeyValueStoreListener create() { END return new ClientKeyValueStoreListener(); } no need the final in static methods

Target:
public static KeyValueStoreListener create() { return new ClientKeyValueStoreListener(); }
Source:
public void rollback() { for (Path file : tempFiles) { try { if (fileSystem.exists(file) && !fileSystem.delete(file, false)) { throw new IOException("Delete failed"); } } catch (IOException e) { log.warn(e, "Failed to delete temporary file: " + file); } START } END outputWriter.rollback(); } If you did this in the reverse order, you would prevent races... so blindly delete and then check if it still exists.

Target:
public void rollback() { for (Path file : tempFiles) { try { fileSystem.delete(file, false); if (fileSystem.exists(file)) { throw new IOException("Delete failed"); } } catch (IOException e) { log.warn(e, "Failed to delete temporary file: " + file); } } outputWriter.rollback(); }
Source:
private void writePackedRefs(String content) throws IOException { File pr = new File(diskRepo.getDirectory(), "packed-refs"); write(pr, content); START final long now = SystemReader.getInstance().getCurrentTime(); END final int oneHourAgo = 3600 * 1000; pr.setLastModified(now - oneHourAgo); } shouldn't you use a simple System.currrentTimeMillis() instead of the SystemReader?

Target:
private void writePackedRefs(String content) throws IOException { File pr = new File(diskRepo.getDirectory(), "packed-refs"); write(pr, content); final long now = System.currentTimeMillis(); final int oneHourAgo = 3600 * 1000; pr.setLastModified(now - oneHourAgo); }
Source:
protected NuxeoPrincipal createAdministrator() { START return new UserPrincipal("Administrator", new ArrayList<>(), false, true); END } can be replaced by an unmodifiable version like `List.of()`

Target:
protected NuxeoPrincipal createAdministrator() { return new UserPrincipal("Administrator", List.of(), false, true); }
Source:
private void migrateDirectory(String path, String source, String destination) throws Exception { String newDir = computeTargetPath(path, source, destination); mFileSystem.createDirectory(new AlluxioURI(newDir), START FileSystemOptions.createDirectoryDefaults(ServerConfiguration.global())); END } Doesn't mFileSystem do the merging already?

Target:
private void migrateDirectory(String path, String source, String destination) throws Exception { String newDir = computeTargetPath(path, source, destination); mFileSystem.createDirectory(new AlluxioURI(newDir)); }
Source:
public Diff getPrimeRefining() { Diff main = null; START if (primeRefining != null) { END main = primeRefining; } else { for (Diff refBy : this.getRefinedBy()) { if (refBy instanceof ReferenceChange) { ReferenceChange rc = (ReferenceChange)refBy; if (rc.getReference().isContainment() && (this.getDiscriminant() == rc.getValue())) { main = rc; break; } } } } return main; } you should replace the test by (primeRefining == null) and execute statements from the else block. Then always return primeRefining field after the "if", the main local variable is not useful

Target:
public Diff getPrimeRefining() { if (primeRefining == null) { for (Diff refBy : this.getRefinedBy()) { if (refBy instanceof ReferenceChange) { ReferenceChange rc = (ReferenceChange)refBy; if (rc.getReference().isContainment() && (this.getDiscriminant() == rc.getValue())) { primeRefining = rc; break; } } } } return primeRefining; }
Source:
START StoreIndexDescriptor( StoreIndexDescriptor indexDescriptor ) END { super( indexDescriptor ); this.id = indexDescriptor.id; this.owningConstraintId = indexDescriptor.owningConstraintId; this.name = indexDescriptor.name; } This constructor should delegate to other constructor

Target:
protected StoreIndexDescriptor( StoreIndexDescriptor indexDescriptor ) { super( indexDescriptor ); this.id = indexDescriptor.id; this.owningConstraintId = indexDescriptor.owningConstraintId; this.name = indexDescriptor.name; }
Source:
START public Void delete(@PathParam(RestParameter.ID) Long id) { END ratingDao.delete(id); return null; } You should return void instead of Void, so you won't have to return null

Target:
public void delete(@PathParam(RestParameter.ID) Long id) { ratingDao.delete(id); }