auphong2707/dl4se-code-review-dataset huggingface dataset:
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); START assertTrue(ifaced.getName().equals(iface.getName()) && ifaced.getQos().equals(iface.getQos())); END } 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)

Target:
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); assertEquals(iface.getName(), ifaced.getName()); assertEquals(iface.getQos(), ifaced.getQos()); }
Source:
public PatientProgram savePatientProgram(PatientProgram patientProgram) throws DAOException { if (patientProgram.getPatientProgramId() == null) { sessionFactory.getCurrentSession().save(patientProgram); } else { sessionFactory.getCurrentSession().merge(patientProgram); } START CustomDatatypeUtil.saveAttributesIfNecessary(patientProgram); END return patientProgram; } Shouldn't this be done before the patientProgram is saved, instead of after?

Target:
public PatientProgram savePatientProgram(PatientProgram patientProgram) throws DAOException { CustomDatatypeUtil.saveAttributesIfNecessary(patientProgram); if (patientProgram.getPatientProgramId() == null) { sessionFactory.getCurrentSession().save(patientProgram); } else { sessionFactory.getCurrentSession().merge(patientProgram); } return patientProgram; }
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(); START rackspace = context.unwrap(CloudFilesApiMetadata.CONTEXT_TOKEN).getApi(); END } Does `unwrapApi` not work for some reason? Just curious...it would make a nice example of the new call, that's why I ask...

Target:
public UploadDirectoryToCDN(String username, String apiKey) { BlobStoreContext context = ContextBuilder.newBuilder(PROVIDER) .credentials(username, apiKey) .buildView(BlobStoreContext.class); storage = context.getBlobStore(); rackspace = context.unwrap(CloudFilesApiMetadata.CONTEXT_TOKEN).getApi(); // can use unwrapApi() in jclouds 1.7.0 }
Source:
public SslContextBuilder keyManager(KeyManager keyManager) { START if (forServer) { END checkNotNull(keyManager, "keyManager required for servers"); } this.keyManagerFactory = new KeyManagerFactoryWrapper(keyManager); keyCertChain = null; key = null; keyPassword = null; return this; } 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).

Target:
public SslContextBuilder keyManager(KeyManager keyManager) { if (forServer) { checkNotNull(keyManager, "keyManager required for servers"); } if (keyManager != null) { this.keyManagerFactory = new KeyManagerFactoryWrapper(keyManager); } else { this.keyManagerFactory = null; } keyCertChain = null; key = null; keyPassword = null; return this; }
Source:
START public boolean isTypeSupported(Class<T> clazz) { END // TODO: Add other types? Float, etc if (String.class.isAssignableFrom(clazz) || Integer.class.isAssignableFrom(clazz) || Boolean.class.isAssignableFrom(clazz)) { return true; } return false; } Should this be protected, or do we really want to allow to call it outside this class?

Target:
protected 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; }
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", START "Boris_Bokowski@ca.ibm.com")); END elements.add(new Person("Tod", "Creasey", "Tod_Creasey@ca.ibm.com")); elements.add(new Person("Wayne", "Beaton", "wayne@eclipse.org")); return elements; } Replace Boris?

Target:
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("Tod", "Creasey", "Tod_Creasey@ca.ibm.com")); elements.add(new Person("Wayne", "Beaton", "wayne@eclipse.org")); return elements; }
Source:
protected void updateIteration() { START refreshIteration = refreshIteration++ % NUMBER_VMS_REFRESHES_BEFORE_SAVE; END } maybe better to separate the incerement and then check

Target:
protected void updateIteration() { refreshIteration = (++refreshIteration) % NUMBER_VMS_REFRESHES_BEFORE_SAVE; }
Source:
public void add(E newInterval) { super.add(newInterval); START fListeners.stream().forEach(l -> l.elementAdded(this, newInterval)); END } you can do fListeners.forEach() directly on Collections

Target:
public void add(E newInterval) { super.add(newInterval); }
Source:
public RuleEvaluationWorker(Map<String, Set<String>> docsToCheckAndEvents) { this.docsToCheckAndEvents = docsToCheckAndEvents; START List<String> docs = new ArrayList<String>(); END docs.addAll(docsToCheckAndEvents.keySet()); setDocuments(Framework.getService(RepositoryManager.class).getDefaultRepositoryName(), docs); } `new ArrayList<String>();` -> `new ArrayList<>();`

Target:
public RuleEvaluationWorker(Map<String, Set<String>> docsToCheckAndEvents) { this.docsToCheckAndEvents = docsToCheckAndEvents; List<String> docs = new ArrayList<>(); docs.addAll(docsToCheckAndEvents.keySet()); setDocuments(Framework.getService(RepositoryManager.class).getDefaultRepositoryName(), docs); }
Source:
private static String getTestingAlias(GoImportSpec testingImportSpec) { String alias = GoConstants.TESTING_PATH; START if (testingImportSpec != null) { END alias = !testingImportSpec.isDot() ? StringUtil.notNullize(testingImportSpec.getAlias(), GoConstants.TESTING_PATH) : ""; } return alias; } alias variable is redundant

Target:
private static String getTestingAlias(GoImportSpec testingImportSpec) { return testingImportSpec == null ? GoConstants.TESTING_PATH : !testingImportSpec.isDot() ? StringUtil.notNullize(testingImportSpec.getAlias(), GoConstants.TESTING_PATH) : ""; }
Source:
public SystemPurposeComplianceStatusDTO(SystemPurposeComplianceStatusDTO source) { START this.populate(source); END } 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).

Target:
public SystemPurposeComplianceStatusDTO(SystemPurposeComplianceStatusDTO source) { super(source); }
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), START new PartitionAllEntriesEviction(logger, this) END }; } We create a new map-operation for every call, so moving `evictions` here doesn't make any difference.

Target:
public MapOperation() { }
Source:
private static Instant retrieveDeadlineTimestamp(JobDataMap jobDataMap) { Object timestamp = jobDataMap.get(MESSAGE_TIMESTAMP); START if (timestamp instanceof String) return Instant.parse(timestamp.toString()); END return Instant.ofEpochMilli((long) timestamp); } 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.

Target:
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); }
Source:
START public AggregatorFactory[] getMetrics() END { return metrics; } Do all of these getters need to be public ? I think except `getBytesInMemory()`, others can be default package access.

Target:
AggregatorFactory[] getMetrics() { return metrics; }
Source:
public void prepare() throws IOException { e = SQLExecutor.builder(clusterService) START .enableDefaultTables() END .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()); } ```suggestion ``` Please don't add tables that are not used. Wastes CPU cycles.

Target:
public void prepare() throws IOException { e = SQLExecutor.builder(clusterService) .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()); }
Source:
public void setUp() { START jUnitCore = new JUnitCore(); END testListener = new TestListener(); jUnitCore.addListener(testListener); } 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.

Target:
public void setUp() { jUnitCore.addListener(testListener); }
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; } START ChangeVmClusterValidator validator = Injector.injectMembers(new ChangeVmClusterValidator(this, END getParameters().getClusterId(), getParameters().getVmCustomCompatibilityVersion(), getVmDeviceUtils())); return validator.validate(); } 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

Target:
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 = ChangeVmClusterValidator.create(this, getParameters().getClusterId(), getParameters().getVmCustomCompatibilityVersion()); return validator.validate(); }
Source:
public TrustManagerFactory getTrustMgr(String serverName) { try { START KeyStore trustStore = trustMgrMap.get(serverName); END if (trustStore != null) { TrustManagerFactory fact = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); fact.init(trustStore); return fact; } return null; } catch (NoSuchAlgorithmException | KeyStoreException e) { throw new RuntimeException(e); } } 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.

Target:
public TrustManagerFactory getTrustMgr(String serverName) { return trustMgrMap.get(serverName); }
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); START this.isInModuleInfo = tmp; END return edit; } I suggest putting this into a finally block.

Target:
public TextEdit formatModuleInfoFile(int kind, String source, int offset, int length, int indentationLevel, String lineSeparator) { boolean tmp = this.isInModuleInfo; try { this.isInModuleInfo = true; return format(kind, source, new IRegion[] { new Region(offset, length) }, indentationLevel, lineSeparator); } finally { this.isInModuleInfo = tmp; } }
Source:
public <K, V> RemoteCache<K, V> getCache(String cacheName) { START RemoteCache<K,V> cache = hotrodClient.getCache( cacheName, TransactionMode.NONE ); END if ( cache == null ) { throw log.expectedCachesNotDefined( Collections.singleton( cacheName ) ); } return cache; } Should this become a property?

Target:
public <K, V> RemoteCache<K, V> getCache(String cacheName) { RemoteCache<K,V> cache = hotrodClient.getCache( cacheName ); if ( cache == null ) { throw log.expectedCachesNotDefined( Collections.singleton( cacheName ) ); } return cache; }
Source:
public static Object valueForStringWithType(String value, VoltType type) { START if (type == null || type == VoltType.NULL) { END 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; } 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.

Target:
public static Object valueForStringWithType(String value, VoltType type) { if (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; }
Source:
public void testContructor() throws IOException { String code = "S2020-04-04"; ReportingPeriod period = ReportingPeriod.from(code); assertEquals(period.getClass(), SinceX.class); START assertEquals(period.getClass(), SinceX.class); END } doppelt?

Target:
public void testContructor() throws IOException { String code = "S2020-04-04"; ReportingPeriod period = ReportingPeriod.from(code); assertEquals(period.getClass(), SinceX.class); }
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) { START assertTrue(conn.getstorage_type() == StorageType.NFS); END } } please user assertEquals

Target:
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) { assertEquals(StorageType.NFS, conn.getstorage_type()); } }
Source:
public static void setOverrideFileName(String... path) { fOverridePath = START (path == null) ? null : path; END fOverride = true; } path

Target:
public static void setOverrideFileName(String... path) { fOverridePath = path; fOverride = true; }
Source:
void addChanges(Collection<String> filesToUpdate, Collection<IResource> resourcesToUpdate) { synchronized (lock) { files.addAll(filesToUpdate); resources.addAll(resourcesToUpdate); } START if (!filesToUpdate.isEmpty()) { END schedule(defaultDelay); } } Small style nit: We don't use braces around simple statements.

Target:
void addChanges(Collection<String> filesToUpdate, Collection<IResource> resourcesToUpdate) { synchronized (lock) { files.addAll(filesToUpdate); resources.addAll(resourcesToUpdate); } if (!filesToUpdate.isEmpty()) schedule(defaultDelay); }
Source:
public static synchronized String getEncryptionKey(String name) { START final String keyString = getUniqueId(name); END if (CACHED_ENCRYPTION_KEYS.get(keyString) == null) { generateEncryptionKey(keyString); } return CACHED_ENCRYPTION_KEYS.get(keyString); } Why not use name as the key in CACHED_ENCRYPTION_KEYS?

Target:
public static synchronized String getEncryptionKey(String name) { if (CACHED_ENCRYPTION_KEYS.get(name) == null) { generateEncryptionKey(name); } return CACHED_ENCRYPTION_KEYS.get(name); }
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) { START throw new RuntimeException(e); END } } } That would case the page loading to fail. The exception should be removed from GerritUtil.toReview() instead.

Target:
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(); review = GerritUtil.toReview(detail); } }
Source:
public ISnapshotInfo getSnapshotInfo(String sessionName, IProgressMonitor monitor) throws ExecutionException { START return new SnapshotInfo(EMPTY_STRING); END } 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).

Target:
public ISnapshotInfo getSnapshotInfo(String sessionName, IProgressMonitor monitor) throws ExecutionException { return null; }
Source:
public long getEntryLastModified() { if (modTimes == null) return 0; Long cutOff = Long.valueOf(super.getEntryLastModified()); START SortedSet<Long> head = modTimes.headSet(cutOff, true); END return head.isEmpty() ? 0 : head.last().longValue(); } headSet(Object,boolean) is a Java 6 API. We need to define cutOff as super.getEntryLastModified() - 1 instead.

Target:
public long getEntryLastModified() { if (modTimes == null) return 0; Long cutOff = Long.valueOf(super.getEntryLastModified() + 1); SortedSet<Long> head = modTimes.headSet(cutOff); return head.isEmpty() ? 0 : head.last().longValue(); }
Source:
public ParameterizedSqlFactory(String initialSql) { sqlStringBuilder = new StringBuilder(initialSql); START parameters = new ArrayList(); END } 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.

Target:
public ParameterizedSqlFactory(String initialSql) { sqlStringBuilder = new StringBuilder(initialSql); parameters = new ArrayList<>(); }
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; START } catch (NumberFormatException e) { END 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); } } Is this needed? What throws NumberFormatException?

Target:
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 (IOException e) { throw new DatasetIOException("Could not access signal path: " + signalPath, e); } }
Source:
private boolean hostHasPpcArchitecture() { Cluster cluster = getModel().getSelectedCluster(); if (cluster == null) { return false; } ArchitectureType archType = cluster.getArchitecture(); return START (archType == ArchitectureType.ppc64) || END (archType == ArchitectureType.ppc64le) || (archType == ArchitectureType.ppcle); } Use equals instead of '==' as follows (And do the same for the 2 other conditions): ArchitectureType.ppc64.equals(archType);

Target:
private boolean hostHasPpcArchitecture() { Cluster cluster = getModel().getSelectedCluster(); if (cluster == null) { return false; } ArchitectureType archType = cluster.getArchitecture(); return ArchitectureType.ppc64.equals(archType) || ArchitectureType.ppc64le.equals(archType) || ArchitectureType.ppcle.equals(archType); }
Source:
private static String getExtension(String name) { int ext = name.lastIndexOf('.'); return 0 < ext ? START name.substring(ext, name.length()) : END ""; } name.substring(ext) is equivalent and shorter to write.

Target:
private static String getExtension(String name) { int ext = name.lastIndexOf('.'); return 0 < ext ? name.substring(ext) : ""; }
Source:
public void checkpoint() { START throw new UnsupportedOperationException("Checkpoint is not supported in NoopJournalSystem"); END } more consistent to make this a no-op like other methods

Target:
public void checkpoint()
Source:
private void recalculateMacsCount() { if (!validate()) { setAvailableMacsCount(-1); return; } if (macRange.getMacPoolId() == null) { String from = getLeftBound().getEntity(); String to = getRightBound().getEntity(); START Long count END = MacRangeValidation.macToLong(to) - MacRangeValidation.macToLong(from) + 1; setAvailableMacsCount(count.intValue()); } } macToLong returns 'long'

Target:
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((int) count); } }
Source:
public void setup() { START buffer = (DiskBuffer) new DiskBuffer(BUFFER_DIR, maxEvents); END } Is this cast necessary?

Target:
public void setup() { buffer = new DiskBuffer(BUFFER_DIR, maxEvents); }
Source:
private boolean filterInvalid(Position position) { START return filterInvalid && !position.getValid() || position.getLatitude() > 90 || position.getLongitude() > 180; END } It would make sense to check minimum values as well.

Target:
private boolean filterInvalid(Position position) { if (filterInvalid == true) { return !position.getValid() || position.getLatitude() > 90 || position.getLongitude() > 180 || position.getLatitude() < -90 || position.getLongitude() < -180; } return false; }
Source:
public 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)); START return allowedLocations; END } 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));

Target:
public Set<Location> getAllowedLocations() { return new HashSet<Location>(asList(CONSTRUCTOR, METHOD, FIELD, OVERVIEW, PACKAGE, TYPE)); }
Source:
public String getTasksJsonString(long taskId) throws JSONException { TaskObject task = TaskObject.get(taskId); START return new ConvertSprintBacklog().getTaskJsonString(task); END } getTaskJsonString() 是否可以改成 static method

Target:
public String getTasksJsonString(long taskId) throws JSONException { TaskObject task = TaskObject.get(taskId); return ConvertSprintBacklog.getTaskJsonString(task); }
Source:
START private void addVolumeToDb(final GlusterVolumeEntity createdVolume) { END 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; } }); } no need explicitly open transaction, only one save to DB, transaction will be open automaticly

Target:
private void addVolumeToDb(final GlusterVolumeEntity createdVolume) { // volume fetched from VDSM doesn't contain cluster id GlusterFS // is not aware of multiple clusters createdVolume.setClusterId(getVdsGroupId()); DbFacade.getInstance().getGlusterVolumeDao().save(createdVolume); }
Source:
public Sheet getDataSheet(File file) { stream = new PushbackInputStream(new FileInputStream(file)); Workbook wb = null; try { wb = WorkbookFactory.create(stream); } catch (Exception e) { START Log.error("Workbook creation exception:" + e); END } return wb.getSheetAt(0); } 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?

Target:
public Sheet getDataSheet(File file) { Workbook wb = null; try { stream = new PushbackInputStream(new FileInputStream(file)); wb = WorkbookFactory.create(stream); } catch (Exception e) { log.error("Workbook creation exception:" + e); } return wb.getSheetAt(0); }
Source:
public void updateAttributes() { OperatingSystem operatingSystem = getCurrentOperatingSystem(); if (operatingSystem != null) { OSProcess process = operatingSystem.getProcess(this.processID); if (process != null) { copyValuesToThisProcess(process); } else { START LOG.error("No process found: {}", this.processID); END } } else { LOG.error("Unsupported platform. No update performed."); } } 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!

Target:
public boolean updateAttributes() { OSProcess process = operatingSystem.getProcess(this.processID); if (process == null) { LOG.debug("No process found: {}", this.processID); return false; } copyValuesToThisProcess(process); return true; }
Source:
public boolean isMissingHookConflict() { START return (this.conflictStatus & MISSING_HOOK.getValue()) == MISSING_HOOK.getValue(); END } avoid using this in these cases.

Target:
public boolean isMissingHookConflict() { return (conflictStatus & MISSING_HOOK.getValue()) == MISSING_HOOK.getValue(); }
Source:
public Map<AccountGroup.UUID, GroupMembersList> getUnresolvedGroups( final boolean recursive) { if (!recursive) { if (isResolved()) { return Collections.emptyMap(); START } else { END return Collections.singletonMap(getGroup().getGroupUUID(), this); } } else { return getAllUnresolvedGroups(new HashSet<AccountGroup.Id>()); } } Nit: My pref would be to eliminate the unneeded elses (117,120) since there are returns.

Target:
public Map<AccountGroup.UUID, GroupMembersList> getUnresolvedGroups( final boolean recursive) { if (!recursive) { if (isResolved()) { return Collections.emptyMap(); } return Collections.singletonMap(getGroup().getGroupUUID(), this); } return getAllUnresolvedGroups(new HashSet<AccountGroup.Id>()); }
Source:
public boolean nextBoolean() throws IOException { requirePeek(); boolean value; try { START value = parser.getBooleanValue(); END } catch (JsonParseException e) { value = Boolean.parseBoolean(parser.getValueAsString()); } clearPeek(); return value; } Can you use `parser.getCurrentToken()` to detect JSON type ?

Target:
public boolean nextBoolean() throws IOException { requirePeek(); boolean value = parser.getBooleanValue(); clearPeek(); return value; }
Source:
START boolean closeOnProtocolViolation() { END return closeOnProtocolViolation; } why are all methods public except this one ?

Target:
public boolean closeOnProtocolViolation() { return closeOnProtocolViolation; }
Source:
START public String getSelinuxEnforceMode() { END 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(); } This should be done using the EnumTranslator. For example, see VmGeneralModel - > updateProperties(). In addition, add the appropriate values to LocalizedEnums.java an LocalizedEnums.properties.

Target:
public String getSelinuxEnforceMode() { return selinuxEnforceMode; }
Source:
public void startThreads() { START if (!this.threadStarted) { END synchronized (this) { if (!this.threadStarted) { int nbThreads = this.configuration.getProperty("mentions.poolSize", 1); for (int i = 0; i < nbThreads; i++) { startConsumer(); } this.threadStarted = true; } } } } Sounds like you forgot to remove this one

Target:
public void startThreads() { synchronized (this) { if (!this.threadStarted) { int nbThreads = this.configuration.getProperty("mentions.poolSize", 1); for (int i = 0; i < nbThreads; i++) { startConsumer(); } this.threadStarted = true; } } }
Source:
public void init(EObject original, EditingDomain editingDomain) { List<EStructuralFeature> features = featuresProvider .getFeatures(original); initControlFactory(editingDomain, original); for (final EStructuralFeature feature : features) { START if(!featuresProvider.getClass().equals(FeaturesProvider.class) || isToBeRendered(feature) ){ END createControlForFeature(feature); } } // toolkit.paintBordersFor(main); this.layout(); } 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...

Target:
public void init(EObject original, EditingDomain editingDomain) { List<EStructuralFeature> features = featuresProvider .getFeatures(original); initControlFactory(editingDomain, original); for (final EStructuralFeature feature : features) { createControlForFeature(feature); } // toolkit.paintBordersFor(main); this.layout(); }
Source:
public List<Annotation> getQualifiers() { return new ArrayList<Annotation>( START Arrays.asList(new org.jboss.arquillian.warp.servlet.AfterServlet() { END @Override public Class<? extends Annotation> annotationType () { return org.jboss.arquillian.warp.servlet.AfterServlet.class; } } ) ); } I think you can return Arrays.asList(...) directly, no need to create wrap that in ArrayList.

Target:
public List<Annotation> getQualifiers() { return Arrays.asList((Annotation) new org.jboss.arquillian.warp.servlet.AfterServlet() { @Override public Class<? extends Annotation> annotationType () { return org.jboss.arquillian.warp.servlet.AfterServlet.class; } } ); }
Source:
protected void initialize(Subject subj) throws PrivilegedActionException { final Configuration config = getRemoteCacheManagerConfig(subj); START Subject.doAs(subj, new PrivilegedExceptionAction<Void>() { END public Void run() throws Exception { remoteCacheManager = new RemoteCacheManager(config, true); return null; } }); remoteCache = remoteCacheManager.getCache(TEST_CACHE_NAME); } 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

Target:
protected void initialize(Subject subj) throws PrivilegedActionException { final Configuration config = getRemoteCacheManagerConfig(subj); remoteCacheManager = new RemoteCacheManager(config, true); remoteCache = remoteCacheManager.getCache(TEST_CACHE_NAME); }
Source:
START LauncherDiscoveryRequest buildRequest(Bundle bundle) { END List<DiscoverySelector> selectors = new ArrayList<>(baseSelectors.size() + 1); selectors.add(BundleSelector.selectBundle(bundle)); return LauncherDiscoveryRequestBuilder.request() .configurationParameter(BundleEngine.CHECK_UNRESOLVED, unresolved) .selectors(selectors) .build(); } 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.

Target:
LauncherDiscoveryRequest buildRequest(Bundle bundle) { List<DiscoverySelector> selectors = new ArrayList<>(baseSelectors.size() + 1); selectors.addAll(baseSelectors); selectors.add(BundleSelector.selectBundle(bundle)); return LauncherDiscoveryRequestBuilder.request() .configurationParameter(BundleEngine.CHECK_UNRESOLVED, unresolved) .selectors(selectors) .build(); }
Source:
protected void statementExecuteUpdateBefore(StatementProxy statement, String sql) { super.statementExecuteUpdateBefore(statement,sql); START try { END Before(statement,sql); }catch (Exception e){ } } 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.

Target:
protected void statementExecuteUpdateBefore(StatementProxy statement, String sql) { super.statementExecuteUpdateBefore(statement,sql); Before(statement,sql); }
Source:
public static DecoderResult failure(Throwable cause) { ObjectUtil.checkNotNull(cause, "cause"); START return new DecoderResult(cause); END } nit: merge lines

Target:
public static DecoderResult failure(Throwable cause) { return new DecoderResult(ObjectUtil.checkNotNull(cause, "cause")); }
Source:
private void writeObject(Schema schema, GenericRecord datum) throws Exception { START BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(new ByteArrayOutputStream(5), null); END GenericDatumWriter<GenericData.Record> writter = new GenericDatumWriter<GenericData.Record>(schema); writter.write(schema, datum, encoder); } Why 5? Just use the default unless there's a good reason not to.

Target:
private void writeObject(Schema schema, GenericRecord datum) throws Exception { BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(new ByteArrayOutputStream(), null); GenericDatumWriter<GenericData.Record> writer = new GenericDatumWriter<GenericData.Record>(schema); writer.write(schema, datum, encoder); }
Source:
public Collection<String> getNames() { if (names == null) { START names = new HashSet<>(named.keySet()); END namedArgumentFinder.forEach(args -> names.addAll(args.getNames())); } return Collections.unmodifiableSet(names); } 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.

Target:
public Collection<String> getNames() { final Set<String> names = new HashSet<>(named.keySet()); namedArgumentFinder.forEach(args -> names.addAll(args.getNames())); return Collections.unmodifiableSet(names); }
Source:
public FBOConfig getFboConfig(ResourceUrn fboName) { FBOConfig fboConfig = fboConfigs.get(fboName); if (fboConfig == null) { START logger.error("Failed to retrieve FBOConfig '" + fboName + "'!"); END } return fboConfig; } 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.

Target:
public FBOConfig getFboConfig(ResourceUrn fboName) { FBOConfig fboConfig = fboConfigs.get(fboName); if (fboConfig == null) { logger.warn("Failed to retrieve FBOConfig '" + fboName + "'!"); } return fboConfig; }
Source:
START void setKey(Input newInput, char newKeyChar) { END this.input = newInput; this.keyChar = newKeyChar; } 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)

Target:
protected void setKey(Input newInput, char newKeyChar) { this.input = newInput; this.keyChar = newKeyChar; }
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()); START } END return this; } 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.

Target:
public Builder<EvictionConfiguration> configure(OperationContext context, ModelNode model) throws OperationFailedException { EvictionStrategy strategy = ModelNodes.asEnum(STRATEGY.getDefinition().resolveModelAttribute(context, model), EvictionStrategy.class); this.builder.strategy(strategy); if (strategy.isEnabled()) { this.builder.type(EvictionType.COUNT).size(MAX_ENTRIES.getDefinition().resolveModelAttribute(context, model).asLong()); } return this; }
Source:
public void closed( BoltConnection connection ) { String id = connection.id(); try { START CompletableFuture currentFuture = activeWorkItems.remove( id ); END if ( currentFuture != null ) { currentFuture.cancel( true ); } } finally { activeConnections.remove( id ); } } `CompletableFuture<Boolean>` to avoid raw types

Target:
public void closed( BoltConnection connection ) { String id = connection.id(); try { CompletableFuture<Boolean> currentFuture = activeWorkItems.remove( id ); if ( currentFuture != null ) { currentFuture.cancel( true ); } } finally { activeConnections.remove( id ); } }
Source:
public void testIsExternalVM() throws IOException { try { XmlDocument xmlDocument = new XmlDocument(getXmlOvfData()); assertFalse("VM should not be external VM", OvfUtils.isExternalVM(xmlDocument)); START } catch (Exception e) { e.printStackTrace(); } END } 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.

Target:
public void testIsExternalVM() throws Exception { XmlDocument xmlDocument = new XmlDocument(getXmlOvfData()); assertFalse("VM should not be external VM", OvfUtils.isExternalVM(xmlDocument)); }
Source:
public static boolean folderContains(File folder, String filename) { if (folder == null) { return false; } if (!folder.isDirectory()) { return false; } START File[] fileList = folder.listFiles(); END if (fileList == null) { return false; } for (File f : fileList) { if (f.getName().equals(filename)) { return true; } } return false; } 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

Target:
public static boolean folderContains(File folder, String filename) { if (folder == null) { return false; } File[] fileList = folder.listFiles(); if (fileList == null) { return false; } for (File f : fileList) { if (f.getName().equals(filename)) { return true; } } return false; }
Source:
public void addWhiteListPatterns(String... patterns) { START this.whiteListPatterns.addAll(Arrays.asList(patterns)); END } `Collections.addAll(whiteListPatterns, patterns)` can be used here.

Target:
public void addWhiteListPatterns(String... patterns) { Collections.addAll(this.whiteListPatterns, patterns); }
Source:
private Long getRegistrationMillis(String playerName) { START if (!isRegistered(playerName.toLowerCase())) { END return null; } PlayerAuth auth = playerCache.getAuth(playerName); if (auth == null) { auth = dataSource.getAuth(playerName); } if (auth != null) { return auth.getRegistrationDate(); } return null; } I think that this check can be avoided as we already check if auth != null below

Target:
private Long getRegistrationMillis(String playerName) { PlayerAuth auth = playerCache.getAuth(playerName); if (auth == null) { auth = dataSource.getAuth(playerName); } if (auth != null) { return auth.getRegistrationDate(); } return null; }
Source:
public HashConfigurationBuilder capacityFactor(float capacityFactor) { START if (numSegments < 0) throw new IllegalArgumentException("capacityFactor must be positive"); END this.capacityFactor = capacityFactor; return this; } typo: capacityFactor instead of numSegments

Target:
public HashConfigurationBuilder capacityFactor(float capacityFactor) { if (capacityFactor < 0) throw new IllegalArgumentException("capacityFactor must be positive"); this.capacityFactor = capacityFactor; return this; }
Source:
public synchronized void onHeaders(Response response) { long length = response.getHeaders().getLongField(HttpHeader.CONTENT_LENGTH.asString()); if (length > maxLength) { response.abort(new ResponseTooLargeException()); } START allocateCurrentArray(); END } This is not needed here

Target:
public synchronized void onHeaders(Response response) { long length = response.getHeaders().getLongField(HttpHeader.CONTENT_LENGTH.asString()); if (length > maxLength) { response.abort(new ResponseTooLargeException()); } }
Source:
public WorkspaceItem build() { try { return workspaceItem; START } catch (Exception e) { END return handleException(e); } } The return statement can never throw an exception here. So please remove the try-catch block.

Target:
public WorkspaceItem build() { return workspaceItem; }
Source:
START public static SortedMap<String, Charset> requiredCharsets() { END return Collections.unmodifiableSortedMap(REQUIRED_CHARSETS); } Why sorted map? TreeMap is sorted already?!

Target:
public static SortedMap<String, Charset> requiredCharsets() { return REQUIRED_CHARSETS; }
Source:
protected void checkProject(Project project) { assertNotNull(project.getId()); assertEquals(project.toString(), client.getProjectApi().getProject(project.getId()).toString()); START assertTrue(project.getState() != null && project.getState() != Project.State.UNRECOGNIZED); END } [minor] Split into two asserts or add a message showing what the offending value actually is?

Target:
protected void checkProject(Project project) { assertNotNull(project.getId()); assertEquals(project.toString(), client.getProjectApi().getProject(project.getId()).toString()); assertTrue(project.getState() != null); assertTrue(project.getState() != Project.State.UNRECOGNIZED); }
Source:
public AtsProgramArtifactToken(Long id, String name, ArtifactTypeToken artifactType) { START super(id, GUID.create(), name, CoreBranches.COMMON, artifactType); END } Please call ArtifactToken constructors without guid.

Target:
public AtsProgramArtifactToken(Long id, String name, ArtifactTypeToken artifactType) { super(id, name, CoreBranches.COMMON, artifactType); }
Source:
public void setUseBulkWriteOperations(final boolean useBulkWriteOperations) { START LOG.warning("Setting useBulkWriteOperations has no value functionally or performance-wise."); END } I think the deprecate is sufficient. Why also log a warning?

Target:
public void setUseBulkWriteOperations(final boolean useBulkWriteOperations) { }
Source:
public void setActionConfirmationMessage(String message) { boolean isNonEmptyMessage = message != null; if START (isNonEmptyMessage) { END actionConfirmationMessage.setText(message); } actionConfirmationMessage.setVisible(isNonEmptyMessage); } When will this be false?

Target:
public void setActionConfirmationMessage(String message) { boolean isNonEmptyMessage = message != null; if (isNonEmptyMessage) { actionConfirmationMessage.setText(message); } }
Source:
public void close() throws InterruptedException { START close(false, false); END } the second parameter can be removed

Target:
public void close() throws InterruptedException { close(false); }
Source:
protected void recursivelyPrint(AbstractPlanNode node, StringBuilder sb) { for (int i = 0; i < indent; i++) { sb.append("\t"); } sb.append(node.toJSONString() + "\n"); indent++; if (node.getChildCount() > 0) { recursivelyPrint(node.getChild(0), sb); } START } END This class has a member variable called `indent` which will incur a data race in `recursivelyPrint`. This is easily fixable though by just making `indent` a parameter to `recursivelyPrint`. I realize it's debug-only code.

Target:
protected void recursivelyPrint(AbstractPlanNode node, StringBuilder sb) { recursivelyPrint(node, sb, 0); }
Source:
public void update(int inputIndex) { status.setTargetOutputRowCount(super.update(inputIndex, status.getOutPosition())); START if (logger.isDebugEnabled()) { END logger.debug("BATCH_STATS, incoming {}: {}", inputIndex == 0 ? "left" : "right", getRecordBatchSizer(inputIndex)); } } if condition not needed.

Target:
public void update(int inputIndex) { status.setTargetOutputRowCount(super.update(inputIndex, status.getOutPosition())); logger.debug("BATCH_STATS, incoming {}: {}", inputIndex == 0 ? "left" : "right", getRecordBatchSizer(inputIndex)); }
Source:
private int getNextPosition() throws CoreException { START if (nextMemberPosition == -1) { END nextMemberPosition = 0; while (nextMemberPosition < MAX_MEMBER_COUNT && getMemberRecord(nextMemberPosition) != 0) { nextMemberPosition++; } } return nextMemberPosition; } Better: nextMemberPosition < 0

Target:
private int getNextPosition() throws CoreException { if (nextMemberPosition < 0) { nextMemberPosition = 0; while (nextMemberPosition < MAX_MEMBER_COUNT && getMemberRecord(nextMemberPosition) != 0) { nextMemberPosition++; } } return nextMemberPosition; }
Source:
public BulkResponse executeRequest() { if (bulkRequest.numberOfActions() == 0) { return null; } START logger.trace("[{}] ES API CALL: bulk request with actions", jobId, bulkRequest.numberOfActions()); END BulkResponse bulkResponse = resultsPersisterService.bulkIndexWithRetry( bulkRequest, jobId, shouldRetry, msg -> auditor.warning(jobId, "Bulk indexing of annotations failed " + msg)); bulkRequest = new BulkRequest(AnnotationIndex.WRITE_ALIAS_NAME); return bulkResponse; } nit: make `bulkRequest.numberOfActions()` a Supplier so it is only called if trace logging is enabled. ```suggestion logger.trace("[{}] ES API CALL: bulk request with actions", () -> jobId, () -> bulkRequest.numberOfActions()); ```

Target:
public BulkResponse executeRequest() { if (bulkRequest.numberOfActions() == 0) { return null; } logger.trace("[{}] ES API CALL: bulk request with actions", () -> jobId, () -> bulkRequest.numberOfActions()); BulkResponse bulkResponse = resultsPersisterService.bulkIndexWithRetry( bulkRequest, jobId, shouldRetry, msg -> auditor.warning(jobId, "Bulk indexing of annotations failed " + msg)); bulkRequest = new BulkRequest(AnnotationIndex.WRITE_ALIAS_NAME); return bulkResponse; }
Source:
public int size() { int size = 0; // We have to loop through to make sure to remove expired entries for (Iterator<InternalCacheEntry<K, V>> iter = iterator(); iter.hasNext(); ) { START if (iter.next().getValue() == null) continue; END if (++size == Integer.MAX_VALUE) return Integer.MAX_VALUE; } return size; } isn't the iterator() excluding the expired and Tombstones?

Target:
public int size() { int size = 0; // We have to loop through to make sure to remove expired entries for (Iterator<InternalCacheEntry<K, V>> iter = iterator(); iter.hasNext(); ) { iter.next(); if (++size == Integer.MAX_VALUE) return Integer.MAX_VALUE; } return size; }