auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
CompletableFuture<Void> getFailureOp(CommitData cd) { return CompletableFuture.supplyAsync(() -> { try { rollbackLocks(cd); } catch (Exception e) { throw new CompletionException(e); } return null; }, env.getSharedResources().getSyncCommitExecutor()); }

Target:
After `throws Exception` is dropped from rollbackLocks, seems like this code should be : ```java CompletableFuture<Void> getFailureOp(CommitData cd) { return rollbackLocks(cd); } ```
Source:
private boolean isGuavaPrecondition(Symbol.MethodSymbol symbol) { return symbol.owner().type().is("com.google.common.base.Preconditions") && ("checkNotNull".equals(symbol.name()) || "checkArgument".equals(symbol.name()) || "checkState".equals(symbol.name()) ); }

Target:
symbol.name() called 3 times? maybe worth a dedicated variable.
Source:
public void loadTrace(ITmfTrace trace) { cancelUpdate(); super.loadTrace(trace); initializeDataProvider(); }

Target:
We had that cancelUpdate() at the beginning of updateContent(). Now the UpdateThread doesn't get cancelled with TmfXYChartViewer.windowRangeUpdated() and TmfCommonXAxisChartViewer.setNbPoints().
Source:
public StringInputRowParser( @JsonProperty("parseSpec") ParseSpec parseSpec, @JsonProperty("encoding") String encoding ) { this.parseSpec = parseSpec; this.mapParser = new MapInputRowParser(parseSpec); this.parser = parseSpec.makeParser(); parser.startFileFromBeginning(); if (encoding != null) { this.charset = Charset.forName(encoding); } else { this.charset = DEFAULT_CHARSET; } }

Target:
StringInputRowParser is used by parser options that aren't file-oriented (you can use it on streams etc) so this isn't a good place to put this. imo, this should replace `reset()` and be called in places that `reset()` is currently called (like FileIteratingFirehose). With one addition: it needs to be called before the very first file too.
Source:
public Object getNegotiatedProperty(String propName) { assertComplete(); switch (propName) { case Sasl.QOP: return selectedQop.getName(); case Sasl.MAX_BUFFER: return Integer.toString(actualMaxReceiveBuffer != 0 ? actualMaxReceiveBuffer : configuredMaxReceiveBuffer); case Sasl.RAW_SEND_SIZE: return Integer.toString(maxBuffer); } return super.getNegotiatedProperty(propName); }

Target:
The superclass only repeats the assertComplete() call. I don't think this PR adds any value.
Source:
public static BooleanExpression asBoolean(boolean value) { return asBoolean(Expressions.constant(value)); }

Target:
this is inside Expressions, so maybe just `asBoolean(constant(value))`, the same with the others
Source:
public void startPolicyEnforcement() throws IOException { if (m_pbd.getUsageSpecificLog().isDebugEnabled()) { m_pbd.getUsageSpecificLog().debug("Starting time based retention policy enforcement with retainMillis=" + m_retainMillis + " for PBD " + m_pbd.getNonce()); } m_reader = m_pbd.openForRead(CURSOR_NAME); scheduleTaskFor(m_pbd.getNonce(), ()->deleteOldSegments(), 0); }

Target:
You can do `this::deleteOldSegments` for the callable. It is more efficient lambda form
Source:
public void afterRun() throws Exception { if (recordStore.isWanReplicationEnabled()) { CacheRecord record = recordStore.getRecord(key); if (record != null) { publishWanUpdate(key, record); } else { publishWanRemove(key); } } super.afterRun(); }

Target:
Do you need to guard against `null` here as well?
Source:
protected String getConfigRoot() { return ClientConfigSections.HAZELCAST_CLIENT.name.toLowerCase(); }

Target:
`toLowerCase`
Source:
public synchronized int getCapacity() { return capacity; }

Target:
Does this method have to be synchronized, considering that `capacity` is `final`?
Source:
private Set<IArtifactType> getAllArtTypes() { Set<IArtifactType> allArtTypes = new HashSet<>(); if (artifactTypes == null || !artifactTypes.isEmpty()) { allArtTypes.addAll(artifactTypes); } else { getArtifactTypesFromWorkItemTypes(); } return allArtTypes; }

Target:
why add 'null' to allArtTypes?
Source:
public void testContextListenerIsSet() throws Exception { try (WizardCommandController tester = testHarness.createWizardController(MyFirstWizard.class)) { tester.initialize(); Assert.assertTrue("Wizard is not on a valid state", tester.isValid()); Assert.assertTrue("Listener is not set", listener.isContextInitialized()); tester.execute(); Assert.assertFalse("Listener is still set", listener.isContextInitialized()); } }

Target:
This should be moved outside the try block
Source:
private Later(F0<A> producer) { this.memo = P.hardMemo(producer); }

Target:
package private
Source:
private boolean isRunningFromCommandLine() { boolean runningFromCommandLine = false; // first look up all OptionProcessors and see if running from command line option is set Collection<? extends OptionProcessor> optionProcessors = Lookup.getDefault().lookupAll(OptionProcessor.class); Iterator<? extends OptionProcessor> optionsIterator = optionProcessors.iterator(); while (optionsIterator.hasNext()) { // find CommandLineOptionProcessor OptionProcessor processor = optionsIterator.next(); if (!(processor instanceof CommandLineOptionProcessor)) { continue; } // check if we are running from command line runningFromCommandLine = ((CommandLineOptionProcessor) processor).isRunFromCommandLine(); return runningFromCommandLine; } return false; }

Target:
Codacy flagged this method for "Avoid using a branching statement as the last in a loop." I think that is a reasonable call by Codacy and the code would be easier to read if runningFromCommandLine was set to true in the loop, followed by a break, and a single method return of runningFromCommandLine on what is currently line 136. Alternatively, one could also do away with runningFromCommandLine and have a return true statement in the loop, but I think the first alternative may be a little easier to read and will make Codacy content.
Source:
public Boolean onReceivedHttpAuthRequest(CordovaWebView view, ICordovaHttpAuthHandler handler, String host, String realm) { for (CordovaPlugin plugin : this.pluginMap.values()) { if (plugin != null && plugin.onReceivedHttpAuthRequest(view, handler, host, realm)) { return true; } } return false; }

Target:
Unless you want this to be tri-state, then "Boolean" should be "boolean". I don't see the need for tristate, so go with "boolean"
Source:
private String createAndGetLockPath() throws InterruptedException, KeeperException { // Create locks if it does not exist if (zk.exists(lockPath.toString(), false) == null) { try { Util.mkdir(zk, lockPath.toString(), ZooDefs.Ids.OPEN_ACL_UNSAFE); } catch (CloudnameException e) { log.log( java.util.logging.Level.INFO, "CloudnameException while trying to get lock path " + absoluteLockPath, e); } } return lockPath + "/" + lockName; }

Target:
lockPath is already String
Source:
public Tuple getTuple(EntityKey key, TupleContext tupleContext) { Entity entity = getEntity( key, tupleContext.getOptionsContext() ); if ( entity != null ) { return new Tuple( new RedisTupleSnapshot( entity.getProperties() ) ); } else if ( isInTheQueue( key, tupleContext ) ) { // The key has not been inserted in the db but it is in the queue return new Tuple( new RedisTupleSnapshot( entity.getProperties() ) ); } else { return null; } }

Target:
What I mean is, your dialect does not implement `BatchableGridDialect`, so items will never be put in to the operations queue.
Source:
public void invoke(ClientEvent event) { try { method.invoke(listener, event); } catch (InvocationTargetException e) { log.errorInvokingListener(method, listener, e.getTargetException()); throw log.exceptionInvokingListener( e.getClass().getName(), method, listener, e.getTargetException()); } catch (Exception e) { throw log.exceptionInvokingListener( e.getClass().getName(), method, listener, e); } }

Target:
Isn't it enough to throw the logging exception instead of also logging locally ?
Source:
ConfigFileConfigProvider(@JsonProperty("configFile") String configFile){ this.configFile = configFile; loadProperties(); }

Target:
can you make loadProperties() take configFile location as an argument and remove the global variable configFile . It seems it is not really needed and reducing global state is good in general.
Source:
public void addDataSource(long dataSourceObjectId) throws IngestStreamClosedException { // Do nothing System.out.println("### DefaultAddImageTaskIngestStream - addDataSource " + dataSourceObjectId); }

Target:
No println's, please.
Source:
private void deleteEmptyStagingDirectories(List<DeclaredIntentionToWrite> declaredIntentionsToWrite) { for (DeclaredIntentionToWrite declaredIntentionToWrite : declaredIntentionsToWrite) { Path path = declaredIntentionToWrite.getRootPath(); if (declaredIntentionToWrite.isTemporaryTable()) { // for temporary table simply delete the entire directory deleteRecursivelyIfExists(declaredIntentionToWrite.getContext(), hdfsEnvironment, path); continue; } if (declaredIntentionToWrite.getMode() != WriteMode.STAGE_AND_MOVE_TO_TARGET_DIRECTORY) { continue; } recursiveDeleteFilesAndLog(declaredIntentionToWrite.getContext(), path, ImmutableList.of(), true, "staging directory cleanup"); } }

Target:
I don't know if they should be put inside this method or not. Should temp table be considered as staging directories?
Source:
public void edit() { if (getWindow() != null) { return; } EditDiskProfileModel model = new EditDiskProfileModel(this, getCompatibilityVersion(), (DiskProfile) getSelectedItem(), getEntity().getStoragePoolId()); setWindow(model); initProfileStorageDomains(model); }

Target:
format
Source:
public void setUp() throws Exception { super.setUp(); gitDir = new File(project.getProject() .getLocationURI().getPath(), Constants.DOT_GIT); testRepository = new TestRepository(gitDir); testRepository.connect(project.getProject()); testRepository.commit("initial commit"); }

Target:
Please remove that line. It changes the tests.
Source:
protected long getParentDid() { long deckID; deckID = getCol().getDecks().selected(); return deckID; }

Target:
should look like this but without the declaration above - they should be on one line ```suggestion long deckID = getCol().getDecks().selected(); ```
Source:
public static String getFileExtension(File file) throws Exception { return FilenameUtils.getExtension(file.getAbsolutePath()).toLowerCase(); }

Target:
Actually this part does not throw any Exception. Just remove `throws Exception` and we should be good. Beware of spaces vs tabs. Prefer using spaces for indentation please.
Source:
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()))); }

Target:
You do not need to call Integer.parseInt(getUuid()) more than once in a method.
Source:
private void loadPerspectiveAndCheckLoadingTime(String perspectiveID, boolean headerIncluded) { //long loadingStart = System.currentTimeMillis(); String standalonePerspectiveURL = getStandalonePerspectiveURL(perspectiveID, headerIncluded); driver.get(standalonePerspectiveURL); BusyPopup.waitForDisappearance(); ApplicationLoadingPopup.waitForDisappearance(PERSPECTIVE_LOADING_TIMEOUT); //double perspectiveLoadingTime = (System.currentTimeMillis() - loadingStart) / (double) 1000; //TODO: What is the acceptable loading time? Do we want to test this? //assertThat(perspectiveLoadingTime) // .as("It should take less than "+PERSPECTIVE_LOADING_TIMEOUT+" seconds to load the perspective " + perspectiveID + ".") // .isLessThan(PERSPECTIVE_LOADING_TIMEOUT); }

Target:
Any chance we could make this test `@Parameterized`? To test 35 different perspectives from within one test case seems evil. Alternatively (as I'm sniffing potential problems with the annotation and Arquillian.), can we at least make the looped code its own function and put some logging around it, so that we know when was it that the test actually failed? Of course, we could also have a different method for each of the perspectives - which would be the "cleanest" solution in this situation. But I sort of see how that would be overkill.
Source:
public default IVariableBinding[] getSyntheticOuterLocals() { return null; }

Target:
THis should return empty array
Source:
protected void executeCommand() { AuthenticationProfile profile = sessionDataContainer.getProfile(getParameters().getSessionId()); if (profile == null) { setSucceeded(false); } else { sessionId = getParameters().getSessionId(); sourceIp = sessionDataContainer.getSourceIp(getParameters().getSessionId()); sessionDataContainer.setSessionValid(getParameters().getSessionId(), false); setSucceeded(true); } }

Target:
Both should be initialized even for failures
Source:
public static void updateNotification(Context context, MasterSecret masterSecret, long threadId) { if (TextSecurePreferences.isNotificationsEnabled(context)) { if (visibleThread == threadId) { DatabaseFactory.getThreadDatabase(context).setRead(threadId); sendInThreadNotification(context); } else { updateNotification(context, masterSecret, true); } } updateBadge(context); }

Target:
Sure you shouldn't do this if the thread is visible? This way, the notification will not disappear when the thread is visible for some reason.
Source:
protected void fillOptions(Map<Enum, String> options) { options.put(EnumModel.VAL1, EnumModel.VAL1.toString()); options.put(EnumModel.VAL2, EnumModel.VAL2.toString()); options.put(EnumModel.VAL3, EnumModel.VAL3.toString()); options.put(EnumModel.VAL4, EnumModel.VAL4.toString()); }

Target:
not sure if makes sense, but instead of putting the `toString()` as values, I probably would use the Enum's `name() `method, as the `toString()` is usually been overridden...
Source:
public boolean removeQueues(Queue... queues) { removeQueues(Arrays.asList(queues) .stream() .map(Queue::getName)); return super.removeQueues(queues); }

Target:
The same `Arrays.stream()` can be applied here as well.
Source:
private static Object castIntegerToObect(int value, Type type) { if (type == INTEGER || type == TINYINT || type == BIGINT) { return (long) value; } if (type == VARCHAR) { return value + ""; } if (type == DOUBLE) { return (double) value; } throw new UnsupportedOperationException(); }

Target:
String.valueOf()
Source:
public void testXmlConfig() throws IOException { EmbeddedCacheManager cm = new DefaultCacheManager("jpa-config.xml"); Cache<String, KeyValueEntity> specificCache = cm.getCache("specificCache"); validateConfig(specificCache); KeyValueEntity entity = new KeyValueEntity("k", "v"); specificCache.put(entity.getK(), entity); cm.stop(); }

Target:
`stop()` should be in a finally block, or you could use `TestingUtil.withCacheManager()`.
Source:
public boolean equals(Object o) { boolean equals = this == o || o instanceof URIEditorInput && getURI().equals(((URIEditorInput) o).getURI()); if (equals && o instanceof SessionEditorInput) { EObject input = getInput(false); if (input != null) { SessionEditorInput otherSessionEditorInput = (SessionEditorInput) o; return input.equals(otherSessionEditorInput.getInput(false)); } } return equals; }

Target:
Shouldn't this be SessionEditorInput? Here equals() can return true for instances of different subclasses of URIEditorInput which point to the same URI. I have not checked, but maybe it happen could if have my aird opened at the same time inside a non-Sirius editor.
Source:
private void loadChildEntities(LibraryDilution dilution) throws IOException { if (dilution.getLibrary() != null) { dilution.setLibrary(libraryDao.get(dilution.getLibrary().getId())); } if (dilution.getTargetedSequencing() != null) { dilution.setTargetedSequencing(targetedSequencingDao.get(dilution.getTargetedSequencing().getId())); } dilution.setDilutionCreator(authorizationManager.getCurrentUsername()); }

Target:
This will cause creator to change on every update
Source:
GdkColor getContextColor () { long /*int*/ fontHandle = fontHandle (); long /*int*/ context = OS.gtk_widget_get_style_context (fontHandle); GdkRGBA rgba = new GdkRGBA (); if (OS.GTK_VERSION < OS.VERSION(3, 18, 0)) { rgba = display.styleContextGetColor (context, OS.GTK_STATE_FLAG_NORMAL, rgba); } else { int styleState = OS.gtk_widget_get_state_flags(handle); rgba = display.styleContextGetColor (context, styleState, rgba); } return display.toGdkColor (rgba); }

Target:
No need to have the styleState variable at all.
Source:
public Subquery parameter(String listId, Object... values) { if (values == null || values.length == 0 || values[0] == null) { return this; } where.setToNormal(); where.setToIntersection(); where.addParameter(listId, values); return this; }

Target:
These 2 can be called just once.
Source:
public int hashCode() { int result = (key ? 1 : 0); result = 31 * result + (path != null ? path.hashCode() : 0); return result; }

Target:
Minor : parentheses are not needed
Source:
public boolean doSynchronousPing() { MerlinLog.d("Pinging : " + hostAddress); try { int responseCode = responseCodeFetcher.from(hostAddress); MerlinLog.d("Got response : " + responseCode); } catch (RequestException e) { if (e.causedByIO()) { return false; } throw e; } return true; }

Target:
Is this only used for logging?
Source:
public T hasThisElement(final Object val) { Assert.parametersNotNull("val", val); return addCriteria(FilterOperator.ELEMENT_MATCH, val, not); }

Target:
Is that bug reported? If not, it should be so we can track that it's getting fixed. Also, ensure that the bug fix should be done in a separate commit from the new feature work for elemMatch (I didn't check).
Source:
public Builder setSSHDirectory(final File sshDirectory) { this.sshDirectory = sshDirectory; return this; }

Target:
Since this class overrides the ```equals``` method, it also needs to override the ```hashCode``` method. Let me know if you have any questions on this.
Source:
public List<Attribute> getRequiredAttributes(PerunSession sess, List<Service> services, Facility facility, Resource resource, User user, Member member) throws InternalErrorException, MemberResourceMismatchException { List<Attribute> attributes = new ArrayList<>(); for (Service service : services) { getRequiredAttributes(sess, service, facility, resource, user, member); } return attributes; }

Target:
I believe you want to add result into the ``attributes`` list. Also, what if required attributes of passed services overlap? We probably should gather them into the set before returning as list.
Source:
public void zrevrangeByScoreWithScores(final byte[] key, final double max, final double min, final int offset, final int count) { sendCommand(ZREVRANGEBYSCORE, key, toByteArray(min), toByteArray(max), LIMIT.raw, toByteArray(offset), toByteArray(count), WITHSCORES.raw); }

Target:
parameter sequence swapped: max, min is correct.
Source:
public void write(int b) throws IOException { mSingleCharWrite[0] = (byte) b; write(mSingleCharWrite, 0, 1); }

Target:
`write(mSingleCharWrite)`?
Source:
public void deallocateFlow(String flowId) throws FlowNotFoundException, ProvisionerException { try { String netId = getNetworkSelector().findNetworkForFlowId(flowId); getNclController().deallocateFlow(netId, flowId); } catch (Exception e) { throw new ProvisionerException(e); } }

Target:
this method expects flowId, netId as parameters. Be careful with the order!
Source:
private String _encode(String strVal) { try { return URLEncoder.encode(strVal, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { return e.getMessage(); } }

Target:
Perhaps in this case the best is to just rethrow the exception as a RuntimeException
Source:
public boolean contains(Object o) { boolean contains = super.contains(o); if (!contains && o != null) { MarshalledEntry<K, V> me = persistenceManager.loadFromAllStores(o, true); contains = me != null; } return contains; }

Target:
if o is null, should no we just return false ?
Source:
public boolean provides(IOperation operation) { if (!(operation instanceof CreateDecoratorsOperation)) { return false; } IDecoratorTarget decoratorTarget = ((CreateDecoratorsOperation) operation).getDecoratorTarget(); View view = decoratorTarget.getAdapter(View.class); return view != null && DDiagramEditPart.MODEL_ID.equals(SiriusVisualIDRegistry.getModelID(view)); }

Target:
The cast should not be removed to avoid compilation errors on Eclipse versions which do not have the generified getAdapter.
Source:
public void MercuryCuratedMainPageTest_006_CheckWrongCategoryAlert() { CuratedContentPageObject ccp = new CuratedContentPageObject(driver); wikiURL = urlBuilder.getUrlForWiki(MercuryWikis.MERCURY_CC); ccp.openMercuryArticleByNameWithNoCacheBuster(wikiURL, MercurySubpages.CC_MAIN_PAGE); MercuryAlertComponentObject mercuryAlert = new MercuryAlertComponentObject( driver, Mercury.AlertMessage.NOT_EXISTING_CATEGORY); String oldUrl = driver.getCurrentUrl(); ccp.clickOnCuratedContentElementByIndex(2); Assertion.assertTrue(mercuryAlert.isAlertMessageVisible()); ccp.waitForLoadingSpinnerToFinish(); Assertion.assertUrlEqualToCurrentUrl(driver, oldUrl); }

Target:
remove extra line
Source:
private void testUpdateInterface(Guid interface_id) { VdsNetworkInterface iface = dao.get(interface_id); iface.setName(iface.getName().toUpperCase()); iface.setQos(newQos); dao.updateInterfaceForVds(iface); VdsNetworkInterface ifaced = dao.get(interface_id); assertTrue(ifaced.getName().equals(iface.getName()) && ifaced.getQos().equals(iface.getQos())); }

Target:
I would use a couple of assert equals since they give better output in case of failure. (Remember that the expected value should be the first one)
Source:
public PatientProgram savePatientProgram(PatientProgram patientProgram) throws DAOException { if (patientProgram.getPatientProgramId() == null) { sessionFactory.getCurrentSession().save(patientProgram); } else { sessionFactory.getCurrentSession().merge(patientProgram); } CustomDatatypeUtil.saveAttributesIfNecessary(patientProgram); return patientProgram; }

Target:
Shouldn't this be done before the patientProgram is saved, instead of after?
Source:
public UploadDirectoryToCDN(String username, String apiKey) { Iterable<Module> modules = ImmutableSet.<Module> of(new SLF4JLoggingModule()); BlobStoreContext context = ContextBuilder.newBuilder(PROVIDER) .credentials(username, apiKey) .modules(modules) .buildView(BlobStoreContext.class); storage = context.getBlobStore(); rackspace = context.unwrap(CloudFilesApiMetadata.CONTEXT_TOKEN).getApi(); }

Target:
Does `unwrapApi` not work for some reason? Just curious...it would make a nice example of the new call, that's why I ask...
Source:
public SslContextBuilder keyManager(KeyManager keyManager) { if (forServer) { checkNotNull(keyManager, "keyManager required for servers"); } this.keyManagerFactory = new KeyManagerFactoryWrapper(keyManager); keyCertChain = null; key = null; keyPassword = null; return this; }

Target:
The `forServer == false` flow looks wrong. If `null` is passed, then `KeyManagerFactoryWrapper` will throw (and we probably want the `keyManagerFactory` to be `null` in that case).
Source:
public boolean isTypeSupported(Class<T> clazz) { // TODO: Add other types? Float, etc if (String.class.isAssignableFrom(clazz) || Integer.class.isAssignableFrom(clazz) || Boolean.class.isAssignableFrom(clazz)) { return true; } return false; }

Target:
Should this be protected, or do we really want to allow to call it outside this class?
Source:
private List<Person> createModel() { List<Person> elements = new ArrayList<Person>(4); elements.add(new Person("Tom", "Schindl", "tom.schindl@bestsolution.at")); elements.add(new Person("Boris", "Bokowski", "Boris_Bokowski@ca.ibm.com")); elements.add(new Person("Tod", "Creasey", "Tod_Creasey@ca.ibm.com")); elements.add(new Person("Wayne", "Beaton", "wayne@eclipse.org")); return elements; }

Target:
Replace Boris?
Source:
protected void updateIteration() { refreshIteration = refreshIteration++ % NUMBER_VMS_REFRESHES_BEFORE_SAVE; }

Target:
maybe better to separate the incerement and then check
Source:
public void add(E newInterval) { super.add(newInterval); fListeners.stream().forEach(l -> l.elementAdded(this, newInterval)); }

Target:
you can do fListeners.forEach() directly on Collections
Source:
public RuleEvaluationWorker(Map<String, Set<String>> docsToCheckAndEvents) { this.docsToCheckAndEvents = docsToCheckAndEvents; List<String> docs = new ArrayList<String>(); docs.addAll(docsToCheckAndEvents.keySet()); setDocuments(Framework.getService(RepositoryManager.class).getDefaultRepositoryName(), docs); }

Target:
`new ArrayList<String>();` -> `new ArrayList<>();`
Source:
private static String getTestingAlias(GoImportSpec testingImportSpec) { String alias = GoConstants.TESTING_PATH; if (testingImportSpec != null) { alias = !testingImportSpec.isDot() ? StringUtil.notNullize(testingImportSpec.getAlias(), GoConstants.TESTING_PATH) : ""; } return alias; }

Target:
alias variable is redundant
Source:
public SystemPurposeComplianceStatusDTO(SystemPurposeComplianceStatusDTO source) { this.populate(source); }

Target:
This should be using `super(source);` instead of the populate method (I know it was like this in `ComplianceStatusDTO`, and it is wrong there too).
Source:
public MapOperation() { final ILogger logger = this.logger(); final int forcedEvictionRetryCount = getRetryCount(); evictions = new Eviction[]{ new RecordStoreForcedEviction(forcedEvictionRetryCount, logger, this), new PartitionRecordStoreForcedEviction(forcedEvictionRetryCount, logger, this), new AllEntriesEviction(logger, this), new PartitionAllEntriesEviction(logger, this) }; }

Target:
We create a new map-operation for every call, so moving `evictions` here doesn't make any difference.
Source:
private static Instant retrieveDeadlineTimestamp(JobDataMap jobDataMap) { Object timestamp = jobDataMap.get(MESSAGE_TIMESTAMP); if (timestamp instanceof String) return Instant.parse(timestamp.toString()); return Instant.ofEpochMilli((long) timestamp); }

Target:
We do not use single line if-statements throughout the project. Yes it's a nitty point, but I'd prefer you change it to curly braces.
Source:
public AggregatorFactory[] getMetrics() { return metrics; }

Target:
Do all of these getters need to be public ? I think except `getBytesInMemory()`, others can be default package access.
Source:
public void prepare() throws IOException { e = SQLExecutor.builder(clusterService) .enableDefaultTables() .addTable("create table t (" + " id integer primary key," + " qty integer constraint check_qty_gt_zero check (qty > 0)," + " constraint check_id_ge_zero check (id >= 0)" + ")") .build(); plannerContext = e.getPlannerContext(clusterService.state()); }

Target:
```suggestion ``` Please don't add tables that are not used. Wastes CPU cycles.
Source:
public void setUp() { jUnitCore = new JUnitCore(); testListener = new TestListener(); jUnitCore.addListener(testListener); }

Target:
In JUnit4-style tests, you can assign variables where they are defined (and make them final if you want :-). JUnit4 won't create an instance of the class until just before it is run, and it will make it eligible for garbage collection right after it is run.
Source:
protected boolean validate() { if (!canRunActionOnNonManagedVm()) { return false; } if (!isInternalExecution() && !ObjectIdentityChecker.canUpdateField(getVm(), "clusterId", getVm().getStatus())) { addValidationMessage(EngineMessage.VM_STATUS_NOT_VALID_FOR_UPDATE); return false; } ChangeVmClusterValidator validator = Injector.injectMembers(new ChangeVmClusterValidator(this, getParameters().getClusterId(), getParameters().getVmCustomCompatibilityVersion(), getVmDeviceUtils())); return validator.validate(); }

Target:
I tend to agree. I mean the validator should not be used in other places, as its name indicates, but several times we extended the use of validators in the past so it may be the better approach to simplify its instantiation
Source:
public TrustManagerFactory getTrustMgr(String serverName) { try { KeyStore trustStore = trustMgrMap.get(serverName); if (trustStore != null) { TrustManagerFactory fact = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); fact.init(trustStore); return fact; } return null; } catch (NoSuchAlgorithmException | KeyStoreException e) { throw new RuntimeException(e); } }

Target:
I would prefer this code to be done in the `KeyStoreHelper` constructor and keep a `Map<String, TrustManagerFactory >` so can be detected at this moment and this is also like how we do for the SNI key manager mapping.
Source:
public TextEdit formatModuleInfoFile(int kind, String source, int offset, int length, int indentationLevel, String lineSeparator) { boolean tmp = this.isInModuleInfo; this.isInModuleInfo = true; TextEdit edit = format(kind, source, new IRegion[] { new Region(offset, length) }, indentationLevel, lineSeparator); this.isInModuleInfo = tmp; return edit; }

Target:
I suggest putting this into a finally block.
Source:
public <K, V> RemoteCache<K, V> getCache(String cacheName) { RemoteCache<K,V> cache = hotrodClient.getCache( cacheName, TransactionMode.NONE ); if ( cache == null ) { throw log.expectedCachesNotDefined( Collections.singleton( cacheName ) ); } return cache; }

Target:
Should this become a property?
Source:
public static Object valueForStringWithType(String value, VoltType type) { if (type == null || type == VoltType.NULL) { return null; } // leverage existing (rather heavyweight) code to convert param types Object retval = ParameterConverter.tryToMakeCompatible(type.classFromType(), value); // check the result type in an assert assert(ParameterConverter.verifyParameterConversion(retval, type.classFromType())); return retval; }

Target:
do we allow `type == null`? It doesn't make sense to me to take a value without type info. probably add a precondition check to forbid that.
Source:
public void testContructor() throws IOException { String code = "S2020-04-04"; ReportingPeriod period = ReportingPeriod.from(code); assertEquals(period.getClass(), SinceX.class); assertEquals(period.getClass(), SinceX.class); }

Target:
doppelt?
Source:
public void testGetConnectableFileStorageConnectionsByStorageType() { List<StorageServerConnections> conns = dao.getConnectableStorageConnectionsByStorageType(FixturesTool.STORAGE_POOL_NFS_2, StorageType.NFS); assertNotNull(conns); assertEquals(1, conns.size()); for (StorageServerConnections conn : conns) { assertTrue(conn.getstorage_type() == StorageType.NFS); } }

Target:
please user assertEquals
Source:
public static void setOverrideFileName(String... path) { fOverridePath = (path == null) ? null : path; fOverride = true; }

Target:
path
Source:
void addChanges(Collection<String> filesToUpdate, Collection<IResource> resourcesToUpdate) { synchronized (lock) { files.addAll(filesToUpdate); resources.addAll(resourcesToUpdate); } if (!filesToUpdate.isEmpty()) { schedule(defaultDelay); } }

Target:
Small style nit: We don't use braces around simple statements.
Source:
public static synchronized String getEncryptionKey(String name) { final String keyString = getUniqueId(name); if (CACHED_ENCRYPTION_KEYS.get(keyString) == null) { generateEncryptionKey(keyString); } return CACHED_ENCRYPTION_KEYS.get(keyString); }

Target:
Why not use name as the key in CACHED_ENCRYPTION_KEYS?
Source:
public void init(IEditorSite site, IEditorInput input) { super.init(site, input); TaskData taskData = getModel().getTaskData(); if (taskData != null) { GerritChange change = GerritUtil.getChange(taskData); final ChangeDetailX detail = change.getChangeDetail(); try { review = GerritUtil.toReview(detail); } catch (GerritException e) { throw new RuntimeException(e); } } }

Target:
That would case the page loading to fail. The exception should be removed from GerritUtil.toReview() instead.
Source:
public ISnapshotInfo getSnapshotInfo(String sessionName, IProgressMonitor monitor) throws ExecutionException { return new SnapshotInfo(EMPTY_STRING); }

Target:
This will create a new object every time the method is called. Is this wanted? If not it'd be better to store the object once and always return it (static field).
Source:
public long getEntryLastModified() { if (modTimes == null) return 0; Long cutOff = Long.valueOf(super.getEntryLastModified()); SortedSet<Long> head = modTimes.headSet(cutOff, true); return head.isEmpty() ? 0 : head.last().longValue(); }

Target:
headSet(Object,boolean) is a Java 6 API. We need to define cutOff as super.getEntryLastModified() - 1 instead.
Source:
public ParameterizedSqlFactory(String initialSql) { sqlStringBuilder = new StringBuilder(initialSql); parameters = new ArrayList(); }

Target:
Initialization of the list should use generics. For this case, you can specify an empty generic-type placeholder and the compiler should be able to auto-detect what type should be used.
Source:
public long getReadyTimestamp(Constraints viewConstraints) { String normalizedConstraints = getNormalizedConstraints(viewConstraints); Path signalPath = new Path(signalDirectory, normalizedConstraints); // check if the signal exists try { try { FileStatus signalStatus = rootFileSystem.getFileStatus(signalPath); return signalStatus.getModificationTime(); } catch (final FileNotFoundException ex) { // empty, will be thrown when the signal path doesn't exist } return -1; } catch (NumberFormatException e) { throw new DatasetException("Signal contents were modified to not be a number: " + signalPath, e); } catch (IOException e) { throw new DatasetIOException("Could not access signal path: " + signalPath, e); } }

Target:
Is this needed? What throws NumberFormatException?
Source:
private boolean hostHasPpcArchitecture() { Cluster cluster = getModel().getSelectedCluster(); if (cluster == null) { return false; } ArchitectureType archType = cluster.getArchitecture(); return (archType == ArchitectureType.ppc64) || (archType == ArchitectureType.ppc64le) || (archType == ArchitectureType.ppcle); }

Target:
Use equals instead of '==' as follows (And do the same for the 2 other conditions): ArchitectureType.ppc64.equals(archType);
Source:
private static String getExtension(String name) { int ext = name.lastIndexOf('.'); return 0 < ext ? name.substring(ext, name.length()) : ""; }

Target:
name.substring(ext) is equivalent and shorter to write.
Source:
public void checkpoint() { throw new UnsupportedOperationException("Checkpoint is not supported in NoopJournalSystem"); }

Target:
more consistent to make this a no-op like other methods
Source:
private void recalculateMacsCount() { if (!validate()) { setAvailableMacsCount(-1); return; } if (macRange.getMacPoolId() == null) { String from = getLeftBound().getEntity(); String to = getRightBound().getEntity(); Long count = MacRangeValidation.macToLong(to) - MacRangeValidation.macToLong(from) + 1; setAvailableMacsCount(count.intValue()); } }

Target:
macToLong returns 'long'
Source:
public void setup() { buffer = (DiskBuffer) new DiskBuffer(BUFFER_DIR, maxEvents); }

Target:
Is this cast necessary?
Source:
private boolean filterInvalid(Position position) { return filterInvalid && !position.getValid() || position.getLatitude() > 90 || position.getLongitude() > 180; }

Target:
It would make sense to check minimum values as well.
Source:
public Set<Location> getAllowedLocations() { Set<Location> allowedLocations = new HashSet<Location>(); allowedLocations.addAll(Arrays.asList(Location.CONSTRUCTOR, Location.METHOD, Location.FIELD, Location.OVERVIEW, Location.PACKAGE, Location.TYPE)); return allowedLocations; }

Target:
Understood. IntelliJ does however suggest this small change: return new HashSet<Location>( asList(Location.CONSTRUCTOR, Location.METHOD, Location.FIELD, Location.OVERVIEW, Location.PACKAGE, Location.TYPE));
Source:
public String getTasksJsonString(long taskId) throws JSONException { TaskObject task = TaskObject.get(taskId); return new ConvertSprintBacklog().getTaskJsonString(task); }

Target:
getTaskJsonString() 是否可以改成 static method
Source:
private void addVolumeToDb(final GlusterVolumeEntity createdVolume) { TransactionSupport.executeInNewTransaction( new TransactionMethod<Void>() { @Override public Void runInTransaction() { // volume fetched from VDSM doesn't contain cluster id GlusterFS // is not aware of multiple clusters createdVolume.setClusterId(getVdsGroupId()); DbFacade.getInstance().getGlusterVolumeDao().save(createdVolume); return null; } }); }

Target:
no need explicitly open transaction, only one save to DB, transaction will be open automaticly
Source:
public Sheet getDataSheet(File file) { stream = new PushbackInputStream(new FileInputStream(file)); Workbook wb = null; try { wb = WorkbookFactory.create(stream); } catch (Exception e) { Log.error("Workbook creation exception:" + e); } return wb.getSheetAt(0); }

Target:
It seems this have added a new import: org.jfree.util.Log, why not use the same log object as line 204? log.error("Workbook creation exception", e); ? Is there a reason behind using 2 different ways of logging errors?
Source:
public void updateAttributes() { OperatingSystem operatingSystem = getCurrentOperatingSystem(); if (operatingSystem != null) { OSProcess process = operatingSystem.getProcess(this.processID); if (process != null) { copyValuesToThisProcess(process); } else { LOG.error("No process found: {}", this.processID); } } else { LOG.error("Unsupported platform. No update performed."); } }

Target:
That's not much different than the current `getProcess(int processID)` except with an optional rather than null. (And the API for that is fixed so we can't change it.) That's not the problem I'm discussing... the problem is that someone writing `new OSProcess(1234)` will definitely get a Process object unless we throw an exception. We could throw an `InstantiationError`, for example, and require them to handle it. Or a `MissingResourceException`. Or return a class with the pid and essentially zero data. Perhaps I should have thought about this dilemma before suggesting the feature!
Source:
public boolean isMissingHookConflict() { return (this.conflictStatus & MISSING_HOOK.getValue()) == MISSING_HOOK.getValue(); }

Target:
avoid using this in these cases.
Source:
public Map<AccountGroup.UUID, GroupMembersList> getUnresolvedGroups( final boolean recursive) { if (!recursive) { if (isResolved()) { return Collections.emptyMap(); } else { return Collections.singletonMap(getGroup().getGroupUUID(), this); } } else { return getAllUnresolvedGroups(new HashSet<AccountGroup.Id>()); } }

Target:
Nit: My pref would be to eliminate the unneeded elses (117,120) since there are returns.
Source:
public boolean nextBoolean() throws IOException { requirePeek(); boolean value; try { value = parser.getBooleanValue(); } catch (JsonParseException e) { value = Boolean.parseBoolean(parser.getValueAsString()); } clearPeek(); return value; }

Target:
Can you use `parser.getCurrentToken()` to detect JSON type ?
Source:
boolean closeOnProtocolViolation() { return closeOnProtocolViolation; }

Target:
why are all methods public except this one ?
Source:
public String getSelinuxEnforceMode() { if (selinuxEnforceMode == null) { // Nothing } else if (selinuxEnforceMode.equals(SELinuxMode.DISABLED)) { return constants.disabled(); } else if (selinuxEnforceMode.equals(SELinuxMode.PERMISSIVE)) { return constants.permissive(); } else if (selinuxEnforceMode .equals(SELinuxMode.ENFORCING)) { return constants.enforcing(); } return constants.notAvailableLabel(); }

Target:
This should be done using the EnumTranslator. For example, see VmGeneralModel - > updateProperties(). In addition, add the appropriate values to LocalizedEnums.java an LocalizedEnums.properties.
Source:
public void startThreads() { if (!this.threadStarted) { synchronized (this) { if (!this.threadStarted) { int nbThreads = this.configuration.getProperty("mentions.poolSize", 1); for (int i = 0; i < nbThreads; i++) { startConsumer(); } this.threadStarted = true; } } } }

Target:
Sounds like you forgot to remove this one
Source:
public void init(EObject original, EditingDomain editingDomain) { List<EStructuralFeature> features = featuresProvider .getFeatures(original); initControlFactory(editingDomain, original); for (final EStructuralFeature feature : features) { if(!featuresProvider.getClass().equals(FeaturesProvider.class) || isToBeRendered(feature) ){ createControlForFeature(feature); } } // toolkit.paintBordersFor(main); this.layout(); }

Target:
Why do you perform this test on FeaturesProvider's class? This really looks strange and I do not see how this relates to the goal of this commit...
Source:
public List<Annotation> getQualifiers() { return new ArrayList<Annotation>( Arrays.asList(new org.jboss.arquillian.warp.servlet.AfterServlet() { @Override public Class<? extends Annotation> annotationType () { return org.jboss.arquillian.warp.servlet.AfterServlet.class; } } ) ); }

Target:
I think you can return Arrays.asList(...) directly, no need to create wrap that in ArrayList.
Source:
protected void initialize(Subject subj) throws PrivilegedActionException { final Configuration config = getRemoteCacheManagerConfig(subj); Subject.doAs(subj, new PrivilegedExceptionAction<Void>() { public Void run() throws Exception { remoteCacheManager = new RemoteCacheManager(config, true); return null; } }); remoteCache = remoteCacheManager.getCache(TEST_CACHE_NAME); }

Target:
It should not be necessary to crate the RemoteCacheManager in a PrivligedAction. Only the GSSAPI mech requires a Subject to initialize the SASL client, and that should be passed in by the configuration
Source:
LauncherDiscoveryRequest buildRequest(Bundle bundle) { List<DiscoverySelector> selectors = new ArrayList<>(baseSelectors.size() + 1); selectors.add(BundleSelector.selectBundle(bundle)); return LauncherDiscoveryRequestBuilder.request() .configurationParameter(BundleEngine.CHECK_UNRESOLVED, unresolved) .selectors(selectors) .build(); }

Target:
Shouldn't this copy in `baseSelectors`? I know it it currently empty, but the code implies you want to add another selector to the base selectors.
Source:
protected void statementExecuteUpdateBefore(StatementProxy statement, String sql) { super.statementExecuteUpdateBefore(statement,sql); try { Before(statement,sql); }catch (Exception e){ } }

Target:
there are some concerns in this file. I can see you are doing some defensive code, but possibly there are ways to do this in less code. for example, if your before and after blocks did the defense, the delegation methods would not need to.
Source:
public static DecoderResult failure(Throwable cause) { ObjectUtil.checkNotNull(cause, "cause"); return new DecoderResult(cause); }

Target:
nit: merge lines
Source:
private void writeObject(Schema schema, GenericRecord datum) throws Exception { BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(new ByteArrayOutputStream(5), null); GenericDatumWriter<GenericData.Record> writter = new GenericDatumWriter<GenericData.Record>(schema); writter.write(schema, datum, encoder); }

Target:
Why 5? Just use the default unless there's a good reason not to.
Source:
public Collection<String> getNames() { if (names == null) { names = new HashSet<>(named.keySet()); namedArgumentFinder.forEach(args -> names.addAll(args.getNames())); } return Collections.unmodifiableSet(names); }

Target:
Sorry--what I meant before was to just build and return the collection on _every_ invocation, rather than storing it in a field. There's only one place calling this method now, so the caching doesn't buy us anything.
Source:
public FBOConfig getFboConfig(ResourceUrn fboName) { FBOConfig fboConfig = fboConfigs.get(fboName); if (fboConfig == null) { logger.error("Failed to retrieve FBOConfig '" + fboName + "'!"); } return fboConfig; }

Target:
Hmmm. I'm thinking we might want to turn this into a logger.warning instead. I'd use the error only if the program cannot proceed, while in this case the consumer code is responsible for reacting to a null return: this particular piece of code can cope perfectly well with it.
Source:
void setKey(Input newInput, char newKeyChar) { this.input = newInput; this.keyChar = newKeyChar; }

Target:
This is technically an API violation, although I can't find any usages. Probably an IDE recommendation? I don't think it is needed so we could swap it back to remain in compliance (to clarify see the surrounding diff since this preview gets confused)
Source:
public Builder<EvictionConfiguration> configure(OperationContext context, ModelNode model) throws OperationFailedException { EvictionStrategy strategy = ModelNodes.asEnum(STRATEGY.getDefinition().resolveModelAttribute(context, model), EvictionStrategy.class); if (strategy.isEnabled()) { this.builder.type(EvictionType.COUNT).size(MAX_ENTRIES.getDefinition().resolveModelAttribute(context, model).asLong()); } return this; }

Target:
This doesn't seem right, the call to org.infinispan.configuration.cache.EvictionConfigurationBuilder#strategy(org.infinispan.eviction.EvictionStrategy) is missing completely, thus the default strategy will always be NONE.
Source:
public void closed( BoltConnection connection ) { String id = connection.id(); try { CompletableFuture currentFuture = activeWorkItems.remove( id ); if ( currentFuture != null ) { currentFuture.cancel( true ); } } finally { activeConnections.remove( id ); } }

Target:
`CompletableFuture<Boolean>` to avoid raw types
Source:
public void testIsExternalVM() throws IOException { try { XmlDocument xmlDocument = new XmlDocument(getXmlOvfData()); assertFalse("VM should not be external VM", OvfUtils.isExternalVM(xmlDocument)); } catch (Exception e) { e.printStackTrace(); } }

Target:
https://i0.wp.com/100happybirthdaymemes.com/wp-content/uploads/2016/06/grumpy-cat-no-4.jpg In other words: throw the exception upwards and fail the test if parsing the XML fails.
Source:
public static boolean folderContains(File folder, String filename) { if (folder == null) { return false; } if (!folder.isDirectory()) { return false; } File[] fileList = folder.listFiles(); if (fileList == null) { return false; } for (File f : fileList) { if (f.getName().equals(filename)) { return true; } } return false; }

Target:
Fix formatting. Run formatter phase in maven. fileList==null doesnt do anything here since folder.isDirectory is checked above and listFiles returns null only if the File is not a directory. It will return empty if the directory doesn't contain any files
Source:
public void addWhiteListPatterns(String... patterns) { this.whiteListPatterns.addAll(Arrays.asList(patterns)); }

Target:
`Collections.addAll(whiteListPatterns, patterns)` can be used here.
Source:
private Long getRegistrationMillis(String playerName) { if (!isRegistered(playerName.toLowerCase())) { return null; } PlayerAuth auth = playerCache.getAuth(playerName); if (auth == null) { auth = dataSource.getAuth(playerName); } if (auth != null) { return auth.getRegistrationDate(); } return null; }

Target:
I think that this check can be avoided as we already check if auth != null below
Source:
public HashConfigurationBuilder capacityFactor(float capacityFactor) { if (numSegments < 0) throw new IllegalArgumentException("capacityFactor must be positive"); this.capacityFactor = capacityFactor; return this; }

Target:
typo: capacityFactor instead of numSegments
Source:
public synchronized void onHeaders(Response response) { long length = response.getHeaders().getLongField(HttpHeader.CONTENT_LENGTH.asString()); if (length > maxLength) { response.abort(new ResponseTooLargeException()); } allocateCurrentArray(); }

Target:
This is not needed here
Source:
public WorkspaceItem build() { try { return workspaceItem; } catch (Exception e) { return handleException(e); } }

Target:
The return statement can never throw an exception here. So please remove the try-catch block.
Source:
public static SortedMap<String, Charset> requiredCharsets() { return Collections.unmodifiableSortedMap(REQUIRED_CHARSETS); }

Target:
Why sorted map? TreeMap is sorted already?!
Source:
protected void checkProject(Project project) { assertNotNull(project.getId()); assertEquals(project.toString(), client.getProjectApi().getProject(project.getId()).toString()); assertTrue(project.getState() != null && project.getState() != Project.State.UNRECOGNIZED); }

Target:
[minor] Split into two asserts or add a message showing what the offending value actually is?
Source:
public AtsProgramArtifactToken(Long id, String name, ArtifactTypeToken artifactType) { super(id, GUID.create(), name, CoreBranches.COMMON, artifactType); }

Target:
Please call ArtifactToken constructors without guid.
Source:
public void setUseBulkWriteOperations(final boolean useBulkWriteOperations) { LOG.warning("Setting useBulkWriteOperations has no value functionally or performance-wise."); }

Target:
I think the deprecate is sufficient. Why also log a warning?