auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static Set<String> getRootQualifiers(ResourceTypes resourceTypes) { return resourceTypes.getRoots().stream() .map(ResourceType::getQualifier) .filter(q -> !DEPRECATED_QUALIFIERS.contains(q)) .collect(Collectors.toCollection(TreeSet::new)); }

Target:
I think LIBRARY are no more used
Source:
public RuntimeFilterManager(QueryWorkUnit workUnit, DrillbitContext drillbitContext) { this.rootWrapper = workUnit.getRootWrapper(); this.drillbitContext = drillbitContext; lineSeparator = java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("line.separator")); }

Target:
Consider using `System.lineSeparator()` instead.
Source:
private void activateMarkers() { if (!fGerritClient.getRepository().getServerInfo().isAnonymous()) { String value = NLS.bind(Messages.ChangeDetailEditor_EGerriTipValue, fChangeInfo.getUserSelectedRevision().get_number()); UIUtils.showDialogTip(MARKERS_KEY, headerSection.getShell(), Messages.EGerriTip, value); } }

Target:
ChangeDetailEditor_EGerriTipValue has no more arguments, should we just use it directly , no need to set the arguments ?
Source:
public void testCreate() throws StripeException { Map<String, Object> params = new HashMap<String, Object>(); params.put("currency", "usd"); final Order order = Order.create(params); assertNotNull(order); verifyRequest( APIResource.RequestMethod.POST, "/v1/orders", params ); }

Target:
should be called `resource`
Source:
private FirewallRule findById(List<FirewallRule> collection, String id) { FirewallRule result = null; for (FirewallRule rule : collection) { if (rule.id().equals(id)) { result = rule; } } return result; }

Target:
Just `return rule`.
Source:
public void addDownload(String download){ if(!downloads.contains(download)) { downloads.add(download); } }

Target:
Should probably use a Set<String> instead of a List<String> so that the intention of the code is clear by first glance.
Source:
public void copyDetailsFromOtherCuObjectCodeActivationGlobal(CuObjectCodeActivationGlobal oldGlobal) { for (CuObjectCodeGlobalDetail oldDetail : oldGlobal.getObjectCodeGlobalDetails()) { CuObjectCodeGlobalDetail newDetail = (CuObjectCodeGlobalDetail) ObjectUtils.deepCopy(oldDetail); newDetail.setObjectId(null); newDetail.setDocumentNumber(getDocumentNumber()); newDetail.setVersionNumber(new Long(0)); getObjectCodeGlobalDetails().add(newDetail); } }

Target:
Should this be 1 or null instead of 0?
Source:
private void loadVncData(HasConsoleModel model, KeyMaker keyMaker) { if (!(model.getDefaultConsoleModel() instanceof VncConsoleModel)) { return; } model.setSelectedProtocol(ConsoleProtocol.VNC); asVncConsoleModel(model).setVncImplementation(VncConsoleModel.ClientConsoleMode .valueOf(clientStorage.getLocalItem(keyMaker.make(VNC_CLIENT_MODE)))); }

Target:
You can not be sure that the value is present in the local storage (see the storeVncData). Please wrap the ...valueOf(...) by try-catch
Source:
private RuleApplication applyRule() { SymbolAllocator symbolAllocator = new SymbolAllocator(symbols); Memo memo = new Memo(idAllocator, plan); Lookup lookup = Lookup.from(memo::resolve); Optional<PlanNode> result = inTransaction(session -> rule.apply(memo.getNode(memo.getRootGroup()), lookup, idAllocator, symbolAllocator, session)); return new RuleApplication( memo, lookup, symbolAllocator.getTypes(), result); }

Target:
These arguments can all go on the same line
Source:
public void testPushDownArray() throws Exception { testParquetFilterPushDown("t.`user`.hobby_ids[0] = 1", 3, 2); testParquetFilterPushDown("t.`user`.hobby_ids[0] = 100", 0, 1); testParquetFilterPushDown("t.`user`.hobby_ids[0] <> 1", 8, 7); testParquetFilterPushDown("t.`user`.hobby_ids[2] > 20", 5, 4); testParquetFilterPushDown("t.`user`.hobby_ids[0] between 10 and 20", 5, 5); testParquetFilterPushDown("t.`user`.hobby_ids[4] = 15", 1, 3); testParquetFilterPushDown("t.`user`.hobby_ids[2] is not null", 11, 6); testParquetFilterPushDown("t.`user`.hobby_ids[3] is null", 11, 7); }

Target:
Why the expected output was changed?
Source:
default Direction getBubbleElevatorDirection() { Block block = this.getBlockState().getBlock(); if (block == Blocks.BUBBLE_COLUMN) { return this.getBlockState().get(BubbleColumnBlock.DRAG) ? Direction.DOWN : Direction.UP; } else { return block.getBubbleElevatorDirection(this.getBlockState()); } }

Target:
This logic should be in the default implementation.
Source:
public void testSystemPropertiesOverrideConfigurationValues() { final String keyName = CoreConfig.MAX_CASSANDRA_CONNECTIONS.toString(); Configuration config = Configuration.getInstance(); try { Assert.assertEquals("75", config.getStringProperty(CoreConfig.MAX_CASSANDRA_CONNECTIONS)); System.setProperty(keyName, "something else"); Assert.assertEquals("something else", config.getStringProperty(CoreConfig.MAX_CASSANDRA_CONNECTIONS)); } finally { System.clearProperty(keyName); Configuration.clearProperty(keyName); } }

Target:
Why access this method staticly?
Source:
public void onSubscribe(Subscription inner) { SubscriptionHelper.setOnce(this, inner); o.onSubscribe(this); inner.request(Long.MAX_VALUE); }

Target:
You can set it on a plain field, no need for atomics: ``` java this.inner = inner; o.onSubscribe(this); inner.request(Long.MAX_VALUE); ```
Source:
public WebElement forElementPresent(By by) { changeImplicitWait(250, TimeUnit.MILLISECONDS); try { return wait.until(ExpectedConditions.presenceOfElementLocated(by)); } catch(TimeoutException e) { PageObjectLogging.log( ELEMENT_PRESENT_MESSAGE, String.format(ELEMENT_PRESENT_ERROR_FORMAT, by.toString()), true ); throw e; } finally { restoreDeaultImplicitWait(); } }

Target:
`true` -> `false` ?
Source:
public boolean accept(Issue issue) { if (issueShouldNotBeReported(issue, excludedLinesByRule())) { return false; } return true; }

Target:
could be simplified.
Source:
public HashMap<String, ArrayList<Order>> getBuyOrders() { return buyOrders; }

Target:
this method should be changed to private
Source:
public static Color getSystemForegroundColor(Display display) { ColorRegistry colorRegistry = JFaceResources.getColorRegistry(); Color foreground = colorRegistry.get(JFacePreferences.INFORMATION_FOREGROUND_COLOR); if (foreground == null) { return JFaceColors.getInformationViewerForegroundColor(display); } return foreground; }

Target:
There's no need to make these public, even if the package is internal.
Source:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } SwitchStatementTree switchStatementTree = (SwitchStatementTree) tree; Optional<CaseLabelTree> defaultLabel = getDefaultLabel(switchStatementTree); if (!defaultLabel.isPresent()) { if (!isSwitchOnEnum(switchStatementTree)) { reportIssue(switchStatementTree.switchKeyword(), "Add a default case to this switch."); } else if (missingCasesOfEnum(switchStatementTree)) { reportIssue(switchStatementTree.switchKeyword(), "Complete cases by adding the missing enum constants or add a default case to this switch."); } } }

Target:
You should go one step more in simplifying the rule: Change this method to return a boolean: `hasNoDefault(switchStatementTree)` ``` return allLabels(switchStatementTree).noneMatch(SwitchLastCaseIsDefaultCheck::isDefault); ```
Source:
public String getAttribute() { if (fAttribute.equals(NOT_SET)) { setAttribute(); } return fAttribute; }

Target:
This method should be synchronized, otherwise, chances are eventually there might be a race condition for setting fAttribute.
Source:
public DotRunnableThread(final List<DotRunnable> allListeners) { this.listeners = getListeners(allListeners); this.flushers = getFlushers(allListeners); this.networkCacheFlushThread.start(); }

Target:
![BLOCKER](https://sonarsource.github.io/sonar-github/severity-blocker.png 'Severity: BLOCKER') Move this "start" call to another method. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3AS2693)
Source:
private void createIndex() { lastFoundElementPosition = 0; filteredPlan.clear(); for (PlanElement element : plan.getList()) { if (!element.isComment()) { filteredPlan.add(element); } } }

Target:
style nit: no braces around single line blocks
Source:
public Collection<Map.Entry<K, V>> scanAndFilterByEntry( Predicate<? super Map.Entry<K, V>> entryPredicate) { return mainMap.entryStream().parallel() .filter(entryPredicate) .collect(Collectors.toCollection(ArrayList::new)); }

Target:
is there a difference between parallelStream() and entryStream().parallel() ?
Source:
protected boolean isValidChar(final char c) { return isValidChar(regExp, c); }

Target:
can be `private`? or at least package protected access?
Source:
public boolean verifyEventIdentifier(AbstractPlaceEvent event) { boolean equals = Objects.equals(getEditorIdentifier(), event.getPlace().getIdentifier()); boolean equals1 = Objects.equals(editorPlaceRequest, event.getPlace()); return (equals && equals1); }

Target:
Toni, could we please choose better variable names here? `equals` and `equals1` do not say much for newcomer to the codebase. Or we could avoid storing partial results by: ```java if(!Objects.equals(editorPlaceRequest, event.getPlace())) { return false; } if (!Objects.equals(getEditorIdentifier(), event.getPlace().getIdentifier())) { return false; } return true; ``` Please let me know what do you think.
Source:
public void star() throws IOException { this.entry.uri() .path(RtGist.PATH_ELEMENT_STAR).back().method("PUT") .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_NO_CONTENT); }

Target:
It's an obvious code duplication. We can save this new request with a modified URI into `this.request`, and use it in all methods. This is how it works in other classes, take a look
Source:
public IssueOutputView(Issue issue) { this(issue, null, null); }

Target:
What is the need to make `issueArticles` nullable? It would be easier to understand this view class if we required it. If that's totally impractical, we should consider having a separate view class to capture the difference.
Source:
public ProcessEngineConfiguration setDefaultNumberOfRetries(int defaultNumberOfRetries) { this.defaultNumberOfRetries = defaultNumberOfRetries; return this; }

Target:
not 100% sure, but this breaks binary compatibility, right?
Source:
public void testSequenceFlowSupplier() throws Exception { final CaseManagementSetChildNodeGraphCommand command = new CaseManagementSetChildNodeGraphCommand(parent, candidate, index, originalParent, originalIndex); final Supplier<ViewConnector<SequenceFlow>> supplier = command.sequenceFlowSupplier(); final ViewConnector<SequenceFlow> viewConnector = supplier.get(); assertNotNull(viewConnector); assertNotNull(viewConnector.getSourceConnection()); assertNotNull(viewConnector.getTargetConnection()); assertNotNull(viewConnector.getBounds()); assertNotNull(viewConnector.getDefinition()); }

Target:
The Exception is never thrown.
Source:
public long getSessionSeqId() { if (sessionSeqId == null) { sessionSeqId = -1L; String sessionId = getContext().getEngineContext().getSessionId(); // The session may not exists for quartz jobs if (getSessionDataContainer().isSessionExists(sessionId)) { sessionSeqId = getSessionDataContainer().getEngineSessionSeqId(sessionId); } } return sessionSeqId; }

Target:
instead of an early assignment which might be overridden in line 2355, it can be set as the 'else' part of the if statement below (line 2356).
Source:
private boolean isTxnRelatedEvent(final NotificationEvent event) { return ((event.getEventType().equals(MessageFactory.OPEN_TXN_EVENT)) || (event.getEventType().equals(MessageFactory.COMMIT_TXN_EVENT)) || (event.getEventType().equals(MessageFactory.ABORT_TXN_EVENT)) || (event.getEventType().equals(MessageFactory.ALLOC_WRITE_ID_EVENT)) ); }

Target:
Allocate write ID is a DB/table related event and should be ignored if not lookup on this DB/table.
Source:
public static void setBackground(boolean async) { background = async; }

Target:
Can't we have this static flag on FS instead? Then we wouldn't need to make FileStoreAttributeCache public.
Source:
public V put(@NonNull K key, @NonNull V value) { map.put(key, new Entry<>(key, value, ++time)); if (map.size() >= maximumSize) { purge(); } return value; }

Target:
For a small maximuSize, like 1, it may be more reasonable to check for: map.size() > maximumSize
Source:
private static void setIfNotNullOrEmpty( MongoProperties.Builder builder, MongoProp prop, String value ) { if ( value != null && value.trim().length() > 0 ) { boolean isPassword = MongoProp.PASSWORD.equals( prop ); boolean isEncrypted = value.startsWith( Encr.PASSWORD_ENCRYPTED_PREFIX ); if ( isPassword && isEncrypted ) { value = Encr.decryptPasswordOptionallyEncrypted( value ); } builder.set( prop, value ); } }

Target:
Shouldn't do this line - it's handled by the ...Optionally... bit in the Encr class. https://github.com/pentaho/pentaho-kettle/blob/master/core/src/org/pentaho/di/core/encryption/KettleTwoWayPasswordEncoder.java#L86-L91
Source:
public Mutation toMutation(K key) { V valueFromStorage = (V) valueDataConversion.fromStorage(value); return new Mutations.ReadWriteWithValue<>(valueFromStorage, f); }

Target:
One use/test case is, a non-serializable pojo (user type) that is encoded as a UTF-8 byte[ ] with some string representation of it.
Source:
public Entry(Map.Entry<String,String> e) { this(e.getKey(), e.getValue()); }

Target:
IMHO it does not need to be public
Source:
private String parsePath() throws URISyntaxException { String[] parts = uri.split("\\?")[0].split(":", 2); if (parts.length < 2 || parts[1].length() < 1) throw new URISyntaxException(uri, "invalid path"); else return parts[1]; }

Target:
parts[1].isEmpty
Source:
public void setItems(Collection value) { genVersionToBaseTemplate(value); final List<VmTemplate> sortedValues = sortTemplates(value); super.setItems(sortedValues); }

Target:
this will affect the sorting also on the webadmin - but on webadmin we support sortable columns. Please move this logic to UserPortalTemplateListModel.
Source:
public void edit(VolumeBrickModel object) { table.setRowData(new ArrayList<ListModel>()); table.edit(object.getBricks()); Driver.driver.edit(object); }

Target:
why you need this line? table.setRowData(new ArrayList<ListModel>());
Source:
public List<QuickFilter> getQuickFilters() { return this.quickFilters; }

Target:
`return quickFilters`
Source:
public void testBounds() { int low = fCondition.min(); assertEquals(LOW, low); int high = fCondition.max(); assertEquals(HIGH, high); }

Target:
why not directly assertEquals(LOW, fCondition.min()); ?
Source:
public String weather() { String result = this.restTemplate.getForObject("http://" + WEATHER_SERVICE + "/weather", String.class); return "Weather Service Response: " + result; }

Target:
`this` is redundant here.
Source:
public boolean isExtensionEnabled() { if (enablement != null) { try { return enablement.getExpression().evaluate(new EvaluationContext(null, new Object())) .equals(EvaluationResult.TRUE); } catch (CoreException e) { // TODO: handle exception } } return true; }

Target:
Let's move this into an EnablementTester.evaluate(...) method.
Source:
public ProviderNotificationManager createProviderNotificationManager(final DiagramEventBroker diagramEventBroker, final EObject view, final NotificationListener notificationListener) { if (manager != null) { return manager; } manager = new ProviderNotificationManager(diagramEventBroker, view, notificationListener) { @Override protected void registerListeners() { // TODO install listener on allocation(Abstraction) of the model. } }; return manager; }

Target:
'null' must be first operande
Source:
public void startSyncFolderOperation(OCFile folder) { long currentSyncTime = System.currentTimeMillis(); mSyncInProgress = true; // perform folder synchronization RemoteOperation synchFolderOp = new RefreshFolderOperation( folder, currentSyncTime, false, false, false, getStorageManager(), getAccount(), getApplicationContext() ); synchFolderOp.execute(getAccount(), this, null, null); }

Target:
This method can be`private`.
Source:
public static ProtobufMetadataManagerImpl getProtobufMetadataManager(EmbeddedCacheManager cacheManager) { if (cacheManager == null) { throw new IllegalArgumentException("cacheManager cannot be null"); } ProtobufMetadataManagerImpl metadataManager = (ProtobufMetadataManagerImpl) cacheManager.getGlobalComponentRegistry().getComponent(ProtobufMetadataManager.class); if (metadataManager == null) { throw new IllegalStateException("ProtobufMetadataManager not initialised yet!"); } return metadataManager; }

Target:
This can be private again.
Source:
public void onSessionKeyUpdate(SessionKey sessionKey) { log.info("Session key updated"); synchronized (DistributedHerder.this) { DistributedHerder.this.sessionKey = sessionKey.key(); if (isLeader() && keyRotationIntervalMs > 0) { DistributedHerder.this.keyExpiration = sessionKey.creationTimestamp() + keyRotationIntervalMs; } } }

Target:
Should this log message be before or after we actually do update the session key?
Source:
public String getAuthorizationUrl(OAuthConfig config) { System.out.print("Authorisation URL: "); // User must provide these 5 elements to the service builder String url = String.format(AUTHORIZE_URL, OAuthEncoder.encode(config.getApiKey()), OAuthEncoder.encode(config.getCallback()), OAuthEncoder.encode(config.getScope()), OAuthEncoder.encode(config.getState())); return url; }

Target:
forgotten line of code?
Source:
public Object getParameter(String name) { final HostThread currentHostThread = fCurrentHostThread; if (currentHostThread == null) { return null; } if (name.equals(CriticalPathModule.PARAM_WORKER)) { /* Try to find the worker for the critical path */ IAnalysisModule mod = getModule(); if ((mod != null) && (mod instanceof CriticalPathModule)) { LttngWorker worker = new LttngWorker(currentHostThread, "", 0); //$NON-NLS-1$ return worker; } return currentHostThread; } return null; }

Target:
This code here should be inside the if, because we don't need to do anything if the parameter request is not PARAM_WORKER
Source:
public static ExceptionThrowingSubTest expectThrowable(Runnable runnable) { return expectException( runnable.toString(), runnable ); }

Target:
Maybe `expectThrowable` for consistency?
Source:
protected CONNECTCXFClient(ServicePortDescriptor<T> portDescriptor, String url, AssertionType assertion, ServicePortBuilder<T> portBuilder) { serviceEndpoint = super.configureBasePort(portBuilder.createPort(), url, assertion != null ? assertion.getTransactionTimeout() : null); configCNCheck(); }

Target:
remove this
Source:
public <V> Setting<V> get(SimpleUri id, Class<V> valueType) { Setting setting = settings.get(id); Class settingValueClass = setting.getValueClass(); if (!settingValueClass.equals(valueType)) { throw new ClassCastException( "Expected a Setting of type " + valueType.getName() + ", found a Setting of type " + settingValueClass.getName() ); } return (Setting<V>) setting; }

Target:
Can we add the name of the setting in there somewhere as well?
Source:
public String getCustomField(String fieldName) { if(customFields == null) return null; for (CustomField f : customFields) { if (f.getName().equals(fieldName)) { return f.getValue(); } } return null; }

Target:
it's better to init customFields with an empty collection to avoid "==null"
Source:
private CommandCall duplicateCommandForDifferentElement(CommandCall commandCall, Element element) { String expression = commandCall.getExpression(); if (expression.equals("")) { expression = element.getText(); } return new CommandCall(null, commandCall.getCommand(), element, expression, commandCall.getResource()); }

Target:
Any way we can clean this up? It seems to only be needed for example commands, but hard to check what the command is here since it's wrapped in decorators.
Source:
public M fromBytes(byte[] messageBuffer) { if (deserializer == null) deserializer = new ThriftBinaryDeserializer(); try { M message = typeRef.safeNewInstance(); deserializer.deserialize(message, messageBuffer); return message; } catch (TException e) { logWarning("failed to deserialize", e); return null; } catch (Throwable e) { // Arbitrary bytes can cause a runtime exception in Thrift logWarning("failed to deserialize", e); return null; } }

Target:
TException is throwable, too, and treated the same -- combine the catch clauses?
Source:
public void showPage(Control page) { if (page.isDisposed() || page.getParent() != this) { return; } currentPage = page; // show new page page.setVisible(true); layout(true); // hide old (and all others) *after* new page has been made visible in // order to avoid flashing Control[] children = getChildren(); for (Control element : children) { Control child = element; if (child != page && !child.isDisposed()) { child.setVisible(false); } } }

Target:
remove
Source:
public void info(String message, Object... objects) { LOG.warn(message, objects); }

Target:
info vs warn
Source:
public String getLinkAt(int offset) { // Check if there is a link at the offset for (int i = 0; i < linkRanges.size(); i++) { if (linkRanges.get(i).isOffsetInRange(offset)) { return hrefs.get(i); } } return null; }

Target:
Let's avoid `null` and rework to empty string
Source:
public String toString() { readLock.lock(); try { return "FileListCacheValue{fileNames=" + getFileNames() + "}"; } finally { readLock.unlock(); } }

Target:
This change I requested was supposed to remove the need for a read lock
Source:
protected Control createControl(Composite parent) { // Configure table CTConfiguration config = new CTConfiguration(parent, CTConfiguration.STYLE_GRID); config.setHorizontalAlignment(SWT.CENTER); config.setCellSelectionEnabled(false); config.setColumnSelectionEnabled(false); config.setRowSelectionEnabled(false); config.setColumnHeaderLayout(CTConfiguration.COLUMN_HEADER_LAYOUT_FILL_EQUAL); config.setRowHeaderLayout(CTConfiguration.ROW_HEADER_LAYOUT_DEFAULT); this.table = new ComponentTable(parent, SWT.FULL_SELECTION, config); return this.table.getControl(); }

Target:
Please not here. This is not a standard SWT table.
Source:
public boolean isEnabled() { return getActiveTextEditor() != null; }

Target:
return 'true'
Source:
void verifyMetadata(MessageMetadata metadata) throws Exception { if (metadata.getMessageMetadataType() != MessageType.LOG_ENTRY_MESSAGE || metadata.getSnapshotTimestamp() != srcGlobalSnapshot) { log.error("Wrong message metadata {}, expecting type snapshot {}", metadata, MessageType.LOG_ENTRY_MESSAGE, srcGlobalSnapshot); throw new Exception("wrong type of message"); } }

Target:
maybe you need a specific Exception Type
Source:
public void setVmBackup(VmBackup value) { vmBackup = value; }

Target:
This is a bug, the setter does nothing, use 'this'
Source:
public void setPrice1(int price3) { if (price3 < 0 || price3 > 10000) { throw new IllegalArgumentException("Invalid price: " + price3); // Compliant } if (true) { assert price3 > 1000; // Noncompliant } }

Target:
what is this part for? you are not checking throw statements.
Source:
public String evaluate(TransactionContext txnCtx, Input<Object>[] args) { assert args.length == 2 : "repeat takes exactly two arguments"; var text = (String) args[0].value(); if (text == null) { return null; } var repetitions = (int) args[1].value(); if (repetitions <= 0) { return ""; } else { return text.repeat(repetitions); } }

Target:
This will fail on `null`
Source:
public void setActionBarNotificationBarColor(MaterialColor color) { getSupportActionBar().setBackgroundDrawable(new ColorDrawable(color.toActionBarColor(this))); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().setStatusBarColor(color.toStatusBarColor(this)); } }

Target:
why is this public?
Source:
public static ProjectBuildType getProjectType(IProject project) { // ------------ AUTOTOOLS // Autotools has an 'Autotools' nature by which we can identify it. if (isAutoTools(project)) return ProjectBuildType.AUTO_TOOLS; IConfiguration defaultConfiguration = helper_getActiveConfiguration(project); IBuilder builder = defaultConfiguration.getBuilder(); Boolean projIsManaged = builder.isManagedBuildOn(); if (projIsManaged) return ProjectBuildType.MANAGED_MAKEFILE; else return ProjectBuildType.OTHER; //E.g a manual makefile. }

Target:
Please use for every if/else/for/etc. block.
Source:
protected long download(T object, File outFile) throws IOException { try { openObjectFunction.open(object, outFile); } catch (IOException e) { throw new RuntimeException(e); } return outFile.length(); }

Target:
This isn't necessary.
Source:
private Collection<VCastResult> getResultFiles(VCastDataStore dataStore) { Collection<VCastResult> results = null; try { results = dataStore.getAllResults(); } catch (OseeCoreException ex) { throw new OseeCoreException(ex, "SQL error while reading results"); } return results; }

Target:
what's the point of catching and then throwing the same exception type?
Source:
public PinotQueryGeneratorContext visitFilter(FilterNode node, PinotQueryGeneratorContext context) { context = node.getSource().accept(this, context); requireNonNull(context, "context is null"); LinkedHashMap<VariableReferenceExpression, Selection> selections = context.getSelections(); String filter = node.getPredicate().accept(pinotFilterExpressionConverter, (var) -> selections.get(var)).getDefinition(); return context.withFilter(filter).withOutputColumns(node.getOutputVariables()); }

Target:
public
Source:
private Space(String enumeratedValue) { this.enumeratedValue = enumeratedValue; }

Target:
JavaDoc and method signature did not match. Please update the JavaDoc!
Source:
public Guid getStorageDomainIdForPoolByType(Guid pool, StorageDomainType type) { Guid returnValue = Guid.Empty; List<storage_domains> domains = getAllForStoragePool(pool); for (storage_domains domain : domains) { if (domain.getstorage_domain_type() == StorageDomainType.Master) { returnValue = domain.getId(); break; } } return returnValue; }

Target:
still requires fix: domain.getstorage_domain_type() == type
Source:
public void lock(T id) throws InterruptedException { threadsLocked.inc(); idsLocked.update(1); lockInternal(id); threadsLocked.dec(); }

Target:
For this it's better to do: ``` threadsLocked.inc(); try { // other stuff } finally { threadsLocked.dec(); } ``` This way if an exception is thrown we still decrement the threadsLocked counter.
Source:
public RunLengthEncodedBlock(Block value, int positionCount) { requireNonNull(value, "value is null"); if (value.getPositionCount() != 1) { throw new IllegalArgumentException(format("Expected value to contain a single position but has %s positions", value.getPositionCount())); } // value can not be a RunLengthEncodedBlock because this could cause stack overflow in some of the methods if (value instanceof RunLengthEncodedBlock) { throw new IllegalArgumentException(format("Value can not be an instance of a %s", getClass().getName())); } if (positionCount < 0) { throw new IllegalArgumentException("positionCount is negative"); } this.value = value this.positionCount = positionCount; }

Target:
looks like syntax typo (`Add position checks in RunLenghtEncodedBlock` commit)
Source:
public Message.Request request() { Message.Request request = callback.request(); if (retryConsistencyLevel != null && retryConsistencyLevel != request.consistency()) return request.copy(retryConsistencyLevel); else return request; }

Target:
Is the idea to always copy because the request could be used again in a Retry (independent of a speculative execution being executed?)
Source:
public void init(FilterConfig filterConfig) throws ServletException { dirAllowed = Context.getConfig().getBoolean("media.dirAllowed"); }

Target:
I would prefer to use full words. For example `directoryAllow`.
Source:
public ExtentBufferedCompositePattern(Extent extent, Pattern... patterns) { super(extent); checkArgument(patterns.length == 0, "patterns cannot be empty"); this.patterns = patterns; }

Target:
This is backwards, you want the expected condition to be here.
Source:
public boolean isValid(Object[] value, ConstraintValidatorContext context) { if ( value.length != 3 ) { throw new IllegalStateException( "Unexpected method signature" ); } // one or both limits are unbounded => always consistent if ( value[1] == null || value[2] == null ) { return true; } return ( (Date) value[1] ).before( (Date) value[2] ); }

Target:
It's tangential, but `IllegalArgumentException` seems more reasonable.
Source:
private static boolean monoNativeFailure(Either<Utils.CommandResult> result) { if (result == null || !result.isSuccess()) { return true; } else { Utils.CommandResult commandResult = result.get(); return monoNativeFailure(commandResult.output) || monoNativeFailure(commandResult.error); } }

Target:
maybe check for start of file or newline also?
Source:
private void removeAppBar() { DWORD dwABM = new DWORD(); APPBARDATA ABData = new APPBARDATA.ByReference(); ABData.cbSize.setValue( ABData.size() ); dwABM.setValue(ShellAPI.ABM_REMOVE); UINT_PTR result = Shell32.INSTANCE.SHAppBarMessage( dwABM, ABData); assertNotNull(result ); }

Target:
Another extra space, can you plese cleanup all these similar things? There're a few others, some functions have spaces in parameters, some don't like `queryPos( APPBARDATA ABData )` vs. `dwABM.setValue(ShellAPI.ABM_QUERYPOS);`. Sorry to be a pest, just looks messy and inconsistent.
Source:
public boolean couldMatch(ScriptPath path) { return (path.eventLower.startsWith("mythicmob") && (path.eventArgLowerAt(2).equals("spawns"))); }

Target:
stray parens Also, use the standard couldMatch format used through Denizen, not this weird inline thing.
Source:
void init() { controllerHomeDir = resolveControllerHomeDir(); this.initAccessOfDirectories(); this.initAccessOfHosts(); }

Target:
Why does it resolve controller home? is it better to name it with HomeDir? It's because this class not only called from controller but agent.
Source:
protected Sequence getServicesSequence(DsfSession session, ILaunch launch, IProgressMonitor rm) { if (launch instanceof GdbLaunch) { return new ServicesLaunchSequence(session, (GdbLaunch)launch, rm); } return null; }

Target:
It is always expected that launch would be an instance of GdbLaunch, I don't think the check is required.
Source:
public AdvanceResult advanceNursery(final AdvancingNursery advanceInfo, final Workbook workbook) throws RuleException, MiddlewareQueryException, FieldbookException { return this.namingConventionService.advanceNursery(advanceInfo, workbook); }

Target:
`MiddlewareQueryException` is now a run time exception so it is not required to be part of the method signature. Not invalid to have it in signature, but Sonar will report it as a _Major_ category violation.
Source:
public org.ovirt.engine.api.model.Cluster update(org.ovirt.engine.api.model.Cluster incoming) { //TODO MM: Dear code reviewer! I'm not sure if this is really cool. I'd assume mapping should happen in mappers, but their powers are limited. Please advise. MacPool macPool = incoming.getMacPool(); macPool.setId(MacPoolIdByIdOrName.get(macPool.getId(), macPool.getName(), this)); return performUpdate(incoming, new QueryIdResolver<>(VdcQueryType.GetClusterById, IdQueryParameters.class), VdcActionType.UpdateCluster, new UpdateParametersProvider()); }

Target:
Please make it non-static, similar to what is done with ManagementNetworkFinder
Source:
protected @NonNull TmfViewer createLeftChildViewer(@Nullable Composite parent) { String analysisId = NonNullUtils.nullToEmptyString(getViewSite().getSecondaryId()); return new AbstractSegmentStoreScatterChartTreeViewer(Objects.requireNonNull(parent)) { @Override protected @Nullable ISegmentStoreProvider getSegmentStoreProvider(ITmfTrace trace) { IAnalysisModule module = TmfTraceUtils.getAnalysisModuleOfClass(trace, IAnalysisModule.class, analysisId); if (module instanceof ISegmentStoreProvider) { return (ISegmentStoreProvider) module; } return null; } }; }

Target:
handle this with an error log and returning null instead of a viewer? as the view won't work with an incorrect id?
Source:
public void testReservedSkippableBeforeStreamIdentifier() throws Exception { ByteBuf in = Unpooled.wrappedBuffer(new byte[] { -0x7f, 0x06, 0x00, 0x00, 's', 'n', 'e', 't', 't', 'y' }); assertFalse(channel.writeInbound(in)); }

Target:
I think it makes more sense to omit this assert in the expected exception cases?
Source:
public void set(String name, Property property) throws PropertyNotFoundException { Field field = getType().getField(name); if (field == null) { Property removedProperty = computeRemovedProperty(name); if (removedProperty != null) { removedProperty.set(name, property); } return; } children.put(field.getName().getPrefixedName(), property); setIsModified(); }

Target:
In the `get` method which calls `getChild` we use `property.getName()` instead of `field.getName().getPrefixedName()` as the key in the `children` map. Can you make this consistent so that we're sure there's no discrepancy between prefixed/unprefixed?
Source:
public int andCardinality(Container x) { if (this.getCardinality() == 0) return 0; else if (x.getCardinality() ==0) return 0; else { if (x instanceof ArrayContainer) return and((ArrayContainer) x).getCardinality(); else if (x instanceof BitmapContainer) return and((BitmapContainer) x).getCardinality(); return and((RunContainer) x).getCardinality(); } }

Target:
`andCardinality(Container)` should be called here instead of `and(Container).getCardinality()`
Source:
public Set<WorkerNetAddress> getWorkerAddresses() throws UnavailableException { if (mSafeModeManager.isInSafeMode()) { throw new UnavailableException(ExceptionMessage.MASTER_IN_SAFEMODE.getMessage()); } Set<WorkerNetAddress> workerAddresses = new HashSet<>(); for (MasterWorkerInfo worker : mWorkers) { // worker net address is unmodifiable after initialization, no locking is needed workerAddresses.add(worker.getWorkerAddress()); } return workerAddresses; }

Target:
(nit) Initialize with initial capacity to be the number of workers.
Source:
public void setUp() { params.put("CallSid", "CA1234567890ABCDE"); params.put("Caller", "+14158675309"); params.put("Digits", "1234"); params.put("From", "+14158675309"); params.put("To", "+18005551212"); signature = "RSOYDt4T1cUTdK1PDd93/VVr8B8="; }

Target:
move this to where `signature` is declared, since it never changes?
Source:
public String getAttributeValue(@Nullable String name) { return name; }

Target:
public @Nullable String...
Source:
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { for (Object cookie : cookiesToClear) { Cookie realCookie = null; if (cookie instanceof String) { realCookie = new Cookie((String) cookie, null); String cookiePath = request.getContextPath() + "/"; realCookie.setPath(cookiePath); realCookie.setMaxAge(0); }else if (cookie instanceof Cookie){ realCookie = (Cookie) cookie; } response.addCookie(realCookie); } }

Target:
This logic will obviously need updated once we change `this.cookiesToClear`.
Source:
private MethodHandles.Lookup getMethodHandleLookup(Class<?> endpointClass) throws InvalidWebSocketException { return MethodHandles.publicLookup().in(endpointClass); }

Target:
Can remove the throws `InvalidWebSocketException` now.
Source:
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { if (maxConnections > 0) { if (numConnections.incrementAndGet() > maxConnections) { ctx.getChannel().close(); numConnections.decrementAndGet(); log.info("Accepted connection above limit ({}). Dropping.", maxConnections); } } super.channelOpen(ctx, e); }

Target:
won't this be a double-decrement?
Source:
public Builder from(int ... nums) { this.matchers.add((from, to, msg) -> Arrays.binarySearch(nums, from) >= 0); return this; }

Target:
this assumes the input is sorted, but the test case is what calls this; its very possible that the test defined them in non-sorted order
Source:
public B channel(Class<? extends C> channelClass) { ObjectUtil.checkNotNull(channelClass, "channelClass"); return channelFactory(new ReflectiveChannelFactory<C>(channelClass)); }

Target:
@qeesung: nit you can merge the above 2 lines as `checkNotNull` returns `channelClass`.
Source:
public void getActiveConditions_shouldGetActiveConditions() { List<Condition> activeConditions = conditionService.getActiveConditions(patientService.getPatient(2)); Condition firstActiveCondition = activeConditions.get(0); Condition secondActiveCondition = activeConditions.get(1); String firstUUID = "2cc6880e-2c46-11e4-9138-a6c5e4d20fb7"; String secondUUID = "2cc6880e-2c46-15e4-9038-a6c5e4d22fb7"; Assert.assertTrue(activeConditions.size() == 2); Assert.assertEquals(firstUUID,firstActiveCondition.getUuid()); Assert.assertEquals(secondUUID, secondActiveCondition.getUuid()); }

Target:
For variables which you are using in one place, remove them and just use the actual value in that one place.
Source:
public synchronized Inode<?> getInodeOrNull() { if (!fullPathExists()) { return null; } List<Inode<?>> inodeList = Lists.newArrayList(mLockList.getInodes()); return inodeList.get(inodeList.size() - 1); }

Target:
why is there a `newArrayList`?
Source:
private static <T> Set<T> findDuplicates(Collection<T> list) { Set<T> duplicates = new HashSet<>(); Set<T> uniques = new HashSet<>(); for(T t : list) { if(!uniques.add(t)) { duplicates.add(t); } } return duplicates; }

Target:
why not `list.stream().forEach`?
Source:
public boolean next() throws IOException { for (;;) { LogQueueEntry t = queue.poll(); if (t == null) { return false; } refName = t.lc.getRefName(); updateIndex = t.lc.getUpdateIndex(); entry = t.lc.getReflogEntry(); boolean include = includeDeletes || entry != null; skipShadowed(refName, updateIndex); add(t); if (include) { return true; } return true; } }

Target:
This isn't right.
Source:
void remove(MessageGroup group) { Object correlationKey = group.getGroupId(); if (this.groupIds.contains(correlationKey)) { this.messageStore.removeMessageGroup(correlationKey); this.groupIds.remove(correlationKey); } }

Target:
That's not logic for this method. If we are here, we have to be already sure that it is our own group. The real problem is definitely in the `ForceReleaseMessageGroupProcessor` implementation. We have to check for its presence there. All other logic should not be affected. Please, make this `remove()` method `protected`.
Source:
public void sendOffsetsToTransaction(Map<TopicPartition, OffsetAndMetadata> offsets, String consumerGroupId) throws ProducerFencedException { if (!cachedGroupMetadata.groupId().equals(consumerGroupId)) { // Generally this logic should only be triggered once during first call. log.warn("Cached consumer groupId changed from to {}. If the old group id is not empty, this indicates an abuse of this API", cachedGroupMetadata.groupId(), consumerGroupId); cachedGroupMetadata = new ConsumerGroupMetadata(consumerGroupId, JoinGroupRequest.UNKNOWN_GENERATION_ID, JoinGroupRequest.UNKNOWN_MEMBER_ID, Optional.empty()); } sendOffsetsToTransactionInternal(offsets, cachedGroupMetadata, false); }

Target:
Hmm, this feels like premature optimization. The offsets map is more likely to be a problem. Also, I'm not sure we should restrict the usage. It is possible today to send offsets for multiple groups. Is there a good reason to restrict this even if it doesn't make sense in streams?
Source:
public boolean cancel(final Exception rootReason) { if (transitionCancel(rootReason)) { final Exception reason = new CancellationException(rootReason); try { traceFailure(reason); } catch (Throwable ex) { LOGGER.warn("Exception thrown in logging trace for failure!", ex); } getSettableDelegate().fail(reason); return true; } return false; }

Target:
The issue we found was when the original `reason` could not be logged due to an error in its `toString`. Do we have any concern that logging the _new_ error might have the same issue? Would it be better to have two stages to this? 1. Catch the logging error, then try to log that error. 2. Catch _that_ error if it happens, and log a generic, static message.
Source:
int allVersionsCombined() { return formatIdentifier >>> SHIFT_FORMAT_IDENTIFIER | formatVersion >>> SHIFT_FORMAT_VERSION; }

Target:
Can be private
Source:
protected void writeJDBCStoreConnection(XMLExtendedStreamWriter writer, SimpleConnectionFactoryConfiguration configuration) throws XMLStreamException { writer.writeStartElement(Element.SIMPLE_CONNECTION); writeOptional(writer, Attribute.CONNECTION_URL, configuration.connectionUrl()); writeOptional(writer, Attribute.DRIVER_CLASS, configuration.driverClass()); writeOptional(writer, Attribute.USERNAME, configuration.username()); writeOptional(writer, Attribute.PASSWORD, configuration.password()); writer.writeEndElement(); }

Target:
the connection configuration is never serialized.
Source:
static ByteBuf copyData(ByteBufList list) { ByteBuf buf = Unpooled.buffer(list.readableBytes()); for (int i = 0; i < list.size(); i++) { buf.writeBytes(list.getBuffer(i).slice()); } return buf; }

Target:
"public" or "private" ?
Source:
private String getXMI_ID(final EObject eobject) { if (eobject.eResource() instanceof XMIResource) { return ((XMIResource) eobject.eResource()).getID(eobject); } ; return null; }

Target:
Useless
Source:
@Override public float getPressure () { return 0; }

Target:
Can you format these overrides?
Source:
private boolean checkForJournalFlush() { // System.err.printf("checkForJournalFlush: queue size=%d; journal size = %d\n", queue.size(), journal.size()) ; // System.err.printf("checkForJournalFlush: QueueBatchSize=%d; MaxQueueThreshold=%d; JournalThresholdSize=%d\n", // QueueBatchSize, MaxQueueThreshold, JournalThresholdSize) ; if ( QueueBatchSize == 0 ) return true ; if ( queue.size() >= QueueBatchSize ) // Based on number of queued commits // The MaxQueueThreshold is handled in processDelayedReplayQueue. return true ; boolean journalSizeFlush = (JournalThresholdSize > 0 && journal.size() > JournalThresholdSize ) ; if ( journalSizeFlush ) // JENA-1222 // Based on Journal file growing large in terms of bytes return true ; // No test for excessive queue length (MaxQueueThreshold). // That happens in notifyCommit (writer exit). return false ; }

Target:
I'm probably missing something, but it seems like this is part of the next case (isn't `queue.size() >= 0` an invariant?). Is this called out just to emphasize that setting `0` => "no queuing"?
Source:
private ProjectState newProjectState(ProjectConfig local) { PrologEnvironment.Factory envFactory = null; GitRepositoryManager gitMgr = null; ProjectControl.AssistedFactory projectControlFactory = null; RulesCache rulesCache = null; SitePaths sitePaths = null; List<CommentLinkInfo> commentLinks = null; all.put(local.getProject().getNameKey(), new ProjectState(sitePaths, projectCache, allProjectsName, projectControlFactory, envFactory, gitMgr, rulesCache, commentLinks, local)); return all.get(local.getProject().getNameKey()); }

Target:
Use add(ProjectConfig) method here instead of repeating the same code?
Source:
public static Collection<PersonaAccount> getPersonaAccountsForAccount(long accountId) throws CentralRepoException { String queryClause = PERSONA_ACCOUNTS_QUERY_CALUSE + " WHERE persona_accounts.account_id = " + accountId + "AND p.status_id != " + Persona.PersonaStatus.DELETED.getStatusId(); CentralRepository cr = CentralRepository.getInstance(); if (cr != null) { String queryClause = PERSONA_ACCOUNTS_QUERY_CALUSE + " WHERE persona_accounts.account_id = " + accountId; PersonaAccountsQueryCallback queryCallback = new PersonaAccountsQueryCallback(); cr.executeSelectSQL(queryClause, queryCallback); return queryCallback.getPersonaAccountsList(); } return new ArrayList<>(); }

Target:
There's a re-declaration error here, that got fixed on the parent branch. That needs to get merged in here.
Source:
public boolean hasMultipleValues(final String dimension) { if (isVirtualColumn(dimension)) { return virtualColumns.getVirtualColumn(dimension).capabilities(dimension).hasMultipleValues(); } final Column column = index.getColumn(dimension); if (column == null || !columnSupportsFiltering(column)) { return false; } else { return column.getCapabilities().hasMultipleValues(); } }

Target:
The same question, how "column supports filtering" relates to "has multiple values"?
Source:
public void resumeNode(String id) { waitServerUntilAvailable.apply(getNode(id)); api.serverApi().updateStatus(id, Server.UpdateStatus.create(Types.ServerAction.POWER_ON, Types.ServerActionMethod.HARDWARE)); }

Target:
This won't work? You wait until the node is powered on when you want to resume it. This will take forever.
Source:
public IStyledLabelProvider[] getLabelProviders() { if (fLabelProviders == null) { fLabelProviders = CHEProviderSettings.getCCallHierarchyLabelProviders(); } return fLabelProviders; }

Target:
either make this a get method that returns the result, or have it be a "load" method. Having it do both is unexpected (same for above method)
Source:
public void registerOperations(ManagementResourceRegistration resourceRegistration) { if (showResources) { resourceRegistration.registerOperationHandler(ShowJaxrsResourcesHandler.DEFINITION, new ShowJaxrsResourcesHandler()); } else { resourceRegistration.registerOperationHandler(ADD_DEFINITION, JaxrsSubsystemAdd.INSTANCE); resourceRegistration.registerOperationHandler(REMOVE_DEFINITION, ReloadRequiredRemoveStepHandler.INSTANCE); } }

Target:
Why are these registered at all? What invokes them?
Source:
public int hashCode() { int result = processId.hashCode(); result = 31 * result + taskId.hashCode(); result = 31 * result + taskName.hashCode(); result = 31 * result + formName.hashCode(); return result; }

Target:
And one for luck ;-)
Source:
public synchronized void stop(final String reason) { new Thread( "Shutdown Thread" ) { @Override public void run() { independentThreadStop( reason, true ); } }.start(); }

Target:
Can probably remove synchronized now?
Source:
public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> e = (Map.Entry<?,?>)o; return ((key == null ? e.getKey() == null : key.equals(e.getKey())) && (value == null ? e.getValue() == null : value.equals(e.getValue()))); }

Target:
braces
Source:
public PostgreSqlEngine(final PdbProperties properties, final String driver) throws DatabaseEngineException { super(driver, properties, Dialect.POSTGRESQL); }

Target:
protected ?
Source:
public void dispose() { clearCachedSwingEditor(); }

Target:
make dispose synchronized, then we could remove the volatile keyword in the class member.
Source:
public void run() { if(thread == null || !Thread.currentThread().equals(thread)) { thread = new Thread(this); thread.start(); } else { try { if (logger.isInfoEnabled()) logger.info("Start reconnecting " + provider); provider.register( getUIService().getDefaultSecurityAuthority(provider)); } catch (OperationFailedException ex) { logger.error("cannot re-register provider will keep going", ex); } } }

Target:
I'm thinking that new thread is not needed for the reconnect task. This thread should be dead already by the time a new reconnect is needed and I see `Timer` instance serving the purpose of this thread. What do you think?
Source:
public void checkProperties(Properties properties) { properties.setProperty("log4j.shutdownCallbackRegistry", "io.druid.common.config.Log4jShutdown"); properties.setProperty("log4j.shutdownHookEnabled", "true"); }

Target:
Couldn't this actually depend on the class and generate the name from that?
Source:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartTimerEvent emptyTop = getStartNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, StartTimerEvent.class); assertGeneralSet(emptyTop.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertTimerEventEmpty(emptyTop.getExecutionSet(), NON_INTERRUPTING, ""); // Know issue. Should be uncommented after https://issues.jboss.org/browse/JBPM-7038 will be fixed //assertDataIOSet(emptySubprocess.getDataIOSet(), EMPTY_VALUE); }

Target:
```suggestion assertTimerEventEmpty(emptyTop.getExecutionSet(), NON_INTERRUPTING, EMPTY_VALUE); ```
Source:
private EmbeddedExpirableMetadata( long lifespan, TimeUnit lifespanUnit, long maxIdle, TimeUnit maxIdleUnit, EntryVersion version) { super(version); this.lifespan = lifespan < 0 ? lifespan : lifespanUnit.toMillis(lifespan); this.maxIdle = maxIdleUnit.toMillis(maxIdle); }

Target:
We should handle maxIdle as well