auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void updateDetailsAvailability() { super.updateDetailsAvailability(); START NetworkView network = (NetworkView) getSelectedItem(); END networkExternalSubnetListModel.setIsAvailable(network.isExternal()); } I think this might return null.

Target:
protected void updateDetailsAvailability() { super.updateDetailsAvailability(); NetworkView network = (NetworkView) getSelectedItem(); networkExternalSubnetListModel.setIsAvailable(network != null && network.isExternal()); }
Source:
public Object getResponse() { START return true; END } seems `false` is also a valid response.

Target:
public Object getResponse() { return response; }
Source:
public InputContent parseInputStream( InputStream inputStream, Boolean strict ) throws IOException, START ReadException { END Description description = deserialize(new InputStreamReader(inputStream), strict); Content content = complexify(description); return new InputContent(content, description.getType()); } this doesnt need to be on a different line

Target:
public InputContent parseInputStream( InputStream inputStream, Boolean strict ) throws IOException, ReadException { Description description = deserialize(new InputStreamReader(inputStream), strict); Content content = complexify(description); return InputContent.create(content, description.getType()); }
Source:
private void setUpAccessBaseAgingExpectations() { ReferenceQueue<Integer> queue = mock(ReferenceQueue.class); map = new ReapedMap<String, Integer>(1000, true, queue); START when(queue.poll()).thenReturn(null); END } Why is this necessary? This is the default behaviour for mocked Object returning methods.

Target:
private void setUpAccessBaseAgingExpectations() { ReferenceQueue<Integer> queue = mock(ReferenceQueue.class); map = new ReapedMap<String, Integer>(1000, true, queue); }
Source:
protected RollCycle decodeRollCycle(String retentionDuration) { if (retentionDuration == null || retentionDuration.isEmpty()) { return DAILY; } String rollingPeriod = retentionDuration.substring(retentionDuration.length() - 1); switch (rollingPeriod) { case SECOND_ROLLING_PERIOD: START return RollCycles.TEST_SECONDLY; END case MINUTE_ROLLING_PERIOD: return MINUTELY; case HOUR_ROLLING_PERIOD: return HOURLY; case DAY_ROLLING_PERIOD: return DAILY; default: throw new IllegalArgumentException("Unknown rolling period: " + rollingPeriod); } } Can use the static import too. And I assume you can then remove the `RollCycles` import.

Target:
protected RollCycle decodeRollCycle(String retentionDuration) { if (retentionDuration == null || retentionDuration.isEmpty()) { return DAILY; } String rollingPeriod = retentionDuration.substring(retentionDuration.length() - 1); switch (rollingPeriod) { case SECOND_ROLLING_PERIOD: return TEST_SECONDLY; case MINUTE_ROLLING_PERIOD: return MINUTELY; case HOUR_ROLLING_PERIOD: return HOURLY; case DAY_ROLLING_PERIOD: return DAILY; default: throw new IllegalArgumentException("Unknown rolling period: " + rollingPeriod); } }
Source:
void process(BitVector changedBits, BitVector deletedBits) { toEntityIntBags(changedBits, deletedBits); // note: processAll != process subscriptions.get(0).processAll(changed, deleted); START for (int i = 0, s = subscriptions.size(); s > i; i++) { END subscriptions.get(i).process(changed, deleted); } } `i` should start at 1, as it's already processed by the preceding LOC.

Target:
void process(BitVector changedBits, BitVector deletedBits) { toEntityIntBags(changedBits, deletedBits); // note: processAll != process subscriptions.get(0).processAll(changed, deleted); for (int i = 1, s = subscriptions.size(); s > i; i++) { subscriptions.get(i).process(changed, deleted); } }
Source:
START void setMinMax(double min, double max) END { this.min = min; this.max = max; } private?

Target:
private void setMinMax(double min, double max) { this.min = min; this.max = max; }
Source:
private void checkTableNotExists(SchemaTableName tableName) { if (tables.values().stream() .map(MemoryTableHandle::toSchemaTableName) .anyMatch(tableName::equals)) { throw new PrestoException(ALREADY_EXISTS, format("Table [%s] already exists", tableName.toString())); } START if (views.keySet().stream() END .anyMatch(tableName::equals)) { throw new PrestoException(ALREADY_EXISTS, format("View [%s] already exists", tableName.toString())); } } Nit: I wouldn't wrap here, since it's short and there's only one item, so wrapping makes it harder to read

Target:
private void checkTableNotExists(SchemaTableName tableName) { if (tables.values().stream() .map(MemoryTableHandle::toSchemaTableName) .anyMatch(tableName::equals)) { throw new PrestoException(ALREADY_EXISTS, format("Table [%s] already exists", tableName.toString())); } if (views.keySet().contains(tableName)) { throw new PrestoException(ALREADY_EXISTS, format("View [%s] already exists", tableName.toString())); } }
Source:
START private static void addCaseFileVariableToResult(Collection<Pair<Object, String>> result, String element) { END if (element.length() > 0) { List<String> list = Arrays.asList(element.split(",")); list.forEach(s1 -> { String value = CaseFileVariables.CASE_FILE_PREFIX + s1.split(":")[0]; result.add(new Pair<>(value, value)); }); } } same, I think this method has no need to be `static`

Target:
private void addCaseFileVariableToResult(Collection<Pair<Object, String>> result, String element) { if (element.length() > 0) { List<String> list = Arrays.asList(element.split(",")); list.forEach(s1 -> { String value = CaseFileVariables.CASE_FILE_PREFIX + s1.split(":")[0]; result.add(new Pair<>(value, value)); }); } }
Source:
public SessionPresenterView showError(final String message) { Notify.hideAll(); getSettings().setType(kieNotificationCssClass(NotifyType.DANGER)); START showNotification(translate(SessionPresenterView_Error), END translate(SessionPresenterView_Notifications), IconType.EXCLAMATION_CIRCLE); return this; } This causes the `message` argument to be unsued.... IMO is confusing, as the Alerts panel could be not present (standalone/submarine)...

Target:
public SessionPresenterView showError(final String message) { getSettings().setType(kieNotificationCssClass(NotifyType.DANGER)); showNotification(translate(SessionPresenterView_Error), message, IconType.EXCLAMATION_CIRCLE); return this; }
Source:
private void encodeDistribution(DBObject dbObject, Described entity) { TranslatorUtils.fromIterable(dbObject, DISTRIBUTION_KEY, entity.getDistributions(), START new Function<Distribution, DBObject>() { END @Override public DBObject apply(Distribution distribution) { return distributionTranslator.toDBObject(new BasicDBObject(), distribution); } }); } lambda

Target:
private void encodeDistribution(DBObject dbObject, Described entity) { TranslatorUtils.fromIterable(dbObject, DISTRIBUTION_KEY, entity.getDistributions(), distribution -> distributionTranslator.toDBObject( new BasicDBObject(), distribution) ); }
Source:
private boolean checkJoinGroupNode(StaticAnalysis sa, JoinGroupNode node, Set<IVariable<?>> projectedVars) { AtomicBoolean res = new AtomicBoolean(); START node.forEach(child -> { END res.compareAndSet(false, checkIfNodeProducesVars(sa, child, projectedVars)); }); return res.get(); } Why we aren't using foreach here like in checkServiceNode()? Wouldn't it do extra work if the first child already contains the variable but there many more children?

Target:
private boolean checkJoinGroupNode(StaticAnalysis sa, JoinGroupNode node, Set<IVariable<?>> projectedVars) { AtomicBoolean res = new AtomicBoolean(); node.forEach(child -> res.compareAndSet(false, checkIfNodeProducesVars(sa, child, projectedVars))); return res.get(); }
Source:
START public HashMap<String, ObjectId> getUpdated() { END return updated; } Style-nit: Our public API should return Map, Set, List and not a concrete implementation type. Sorry I missed this during earlier review iterations.

Target:
public Map<String, ObjectId> getUpdated() { return updated; }
Source:
public void timeUnitNullFail() throws Exception { START Timed<Integer> t1 = new Timed<Integer>(1, 5, null); END } `t1` shows up as unused variable, please remove the assignment.

Target:
public void timeUnitNullFail() throws Exception { new Timed<Integer>(1, 5, null); }
Source:
public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) { START View root = inflater.inflate(R.layout.fragment_for_leads, null); END return root; } ``` View root = inflater.inflate(R.layout.fragment_for_leads, container, false); ``` should be used instead

Target:
public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_for_leads, container, false); return root; }
Source:
START public Map<String,Integer> listLanguages() throws IOException { END return root.retrieve().to(getApiTailUrl("languages"), HashMap.class); } Size in bytes, max Integer will be 2Gb, i think some crazy repo may have such number. Long looks better.

Target:
public Map<String,Long> listLanguages() throws IOException { return root.retrieve().to(getApiTailUrl("languages"), HashMap.class); }
Source:
public static Win32VK fromValue(final int code) { START if (code < 0 || code > 0xFF) { END throw new IllegalArgumentException(String.format("No mapping for %02x", code)); } for (Win32VK vk : Win32VK.values()) { if (vk.code == code) { return vk; } } // We shall not reach here. throw new IllegalArgumentException(String.format("No mapping for %02x", code)); } Any reason to special case this? The fall through to line 300 should catch it.

Target:
public static Win32VK fromValue(final int code) { for (Win32VK vk : Win32VK.values()) { if (vk.code == code) { return vk; } } throw new IllegalArgumentException(String.format("No mapping for %02x", code)); }
Source:
public <R> R execute(ResultProducer<R> producer) { START if (bindings.isEmpty()) { END throw new IllegalStateException("No batch parts to execute"); } try { return producer.produce(() -> internalBatchExecute().stmt, getContext()); } catch (SQLException e) { throw new UnableToProduceResultException("Exception producing batch result", e, getContext()); } } It might be good to add a sanity check to validate that `getBinding()` is empty, to catch users who forget to call `add()`. Mockito does something similar e.g. if you call `verify(mock)` without chaining a method call on the mock.

Target:
public <R> R execute(ResultProducer<R> producer) { try { return producer.produce(() -> internalBatchExecute().stmt, getContext()); } catch (SQLException e) { throw new UnableToProduceResultException("Exception producing batch result", e, getContext()); } }
Source:
private void print() { if (canceled) { out.print("[CANCELED] "); } else if (total == IProgressMonitor.UNKNOWN) { out.print(animationFrames[animationFrameId]); START animationFrame = (animationFrame + 1) % animationFrames.length; END } else { out.printf("[%2d%%] ", worked / total); } out.print(task); if (subTask != null) { out.printf(" - %s", subTask); } out.print('\r'); } Has to be animationFrameId = (animationFrameId + 1) ...

Target:
private void print() { if (canceled) { out.print("[CANCELED] "); } else if (total == IProgressMonitor.UNKNOWN) { out.print(animationFrames[animationFrameId]); animationFrameId = (animationFrameId + 1) % animationFrames.length; } else { out.printf("[%2d%%] ", worked / total); } out.print(task); if (subTask != null) { out.printf(" - %s", subTask); } out.print('\r'); }
Source:
default ListenableFuture<Resolved<I>> resolveIds(Iterable<Id> ids, Boolean refreshCache) { START throw new UnsupportedOperationException(); END } should this just proxy to the plain resolveIds method?

Target:
default ListenableFuture<Resolved<I>> resolveIds(Iterable<Id> ids, Boolean refreshCache) { return resolveIds(ids); }
Source:
public URI createAdminUnit(URI path, Model model) { // Add types to the object being created model = populateModelTypes(path, model, START Arrays.asList(Cdr.AdminUnit, PcdmModels.Object)); END return createContentContainerObject(path, model); } Should be PcdmModels.Collection to agree with the rest of the code

Target:
public URI createAdminUnit(URI path, Model model) { // Add types to the object being created model = populateModelTypes(path, model, Arrays.asList(Cdr.AdminUnit, PcdmModels.Collection)); return createContentContainerObject(path, model); }
Source:
public final String readUTF() throws IOException { int numberOfBytes = readInt(); if (numberOfBytes == NULL_ARRAY_LENGTH) { return null; } START checkAvailable(pos, numberOfBytes); END String result = new String(data, pos, numberOfBytes, UTF_8); pos += numberOfBytes; return result; } It looks like the bounds check is also done by String constructor. Can you check if this line is still necessary ?

Target:
public final String readUTF() throws IOException { int numberOfBytes = readInt(); if (numberOfBytes == NULL_ARRAY_LENGTH) { return null; } String result = new String(data, pos, numberOfBytes, UTF_8); pos += numberOfBytes; return result; }
Source:
private S3StorageProvider getS3StorageProvider() { if (!storageAccountManager.isInitialized()) { throw new DuraCloudRuntimeException("storageAccountManager is not initialized!!!"); } StorageAccount account = storageAccountManager.getPrimaryStorageAccount(); StorageProviderType type = account.getType(); START if (!type.equals(StorageProviderType.AMAZON_S3)) { END throw new DuraCloudRuntimeException( "The type of primary storage provider on " + storageAccountManager.getAccountName() + " must be " + StorageProviderType.AMAZON_S3); } return new S3StorageProvider(account.getUsername(), account.getPassword(), account.getOptions()); } This type check should be removed. There are storage provider types build on top of the AMAZON_S3 implementation which would have a different type, but would still work just as well for streaming. For example, using the CHRONOPOLIS provider but where some spaces are not used for snapshots (left in S3) could support this. Also, the 4Science-proposed AMAZON_ONE type would fit this category.

Target:
private S3StorageProvider getS3StorageProvider() { if (!storageAccountManager.isInitialized()) { throw new DuraCloudRuntimeException("storageAccountManager is not initialized!!!"); } StorageAccount account = storageAccountManager.getPrimaryStorageAccount(); StorageProviderType type = account.getType(); return new S3StorageProvider(account.getUsername(), account.getPassword(), account.getOptions()); }
Source:
private static void closeSettingsChangedShell() { new WaitUntil(new ShellIsAvailable("Validator Settings Changed"), TimePeriod.LONG); DefaultShell shell = new DefaultShell("Validator Settings Changed"); String shellText = shell.getText(); new PushButton("Yes").click(); START new WaitWhile(new ShellIsActive(shellText), TimePeriod.LONG); END } ShellIsAvailable

Target:
private static void closeSettingsChangedShell() { new WaitUntil(new ShellIsAvailable("Validator Settings Changed"), TimePeriod.LONG); DefaultShell shell = new DefaultShell("Validator Settings Changed"); String shellText = shell.getText(); new PushButton("Yes").click(); new WaitWhile(new ShellIsAvailable(shellText), TimePeriod.LONG); }
Source:
public void setUp() START throws Exception { END User.disableStorage(); // don't change the app login from this test } Can this throw an Exception?

Target:
public void setUp() { User.disableStorage(); // don't change the app login from this test }
Source:
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { if (delegate instanceof X509ExtendedTrustManager) { START ((X509ExtendedTrustManager)delegate).checkClientTrusted(chain, authType, socket); END } else { throw new UnsupportedOperationException(); } verifier.checkChain(chain); } IMHO copy-paste bug - should be `checkServerTrusted` instead.

Target:
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { if (delegate instanceof X509ExtendedTrustManager) { ((X509ExtendedTrustManager)delegate).checkServerTrusted(chain, authType, socket); } else { throw new UnsupportedOperationException(); } verifier.checkChain(chain); }
Source:
private boolean isEmailValid(String email) { START EmailValidator emailValidator = EmailValidator.getInstance(); END return emailValidator.isValid(email); } Can you combine these 2 lines into 1

Target:
private boolean isEmailValid(String email) { return EmailValidator.getInstance().isValid(email); }
Source:
public void evict(WrappedBytes key) { Lock lock = locks.getLock(key).writeLock(); lock.lock(); try { checkDeallocation(); long address = memoryLookup.getMemoryAddress(key); if (address != 0) { // TODO: this could be more efficient InternalCacheEntry<WrappedBytes, WrappedBytes> ice = performGet(address, key); START passivator.passivate(ice); END performRemove(address, key); } } finally { lock.unlock(); } } We should add an if check here for ice and only do this line and the next if it is not null. Prevents another possible loop through the linked list if it exists.

Target:
public void evict(WrappedBytes key) { Lock lock = locks.getLock(key).writeLock(); lock.lock(); try { checkDeallocation(); long address = memoryLookup.getMemoryAddress(key); if (address != 0) { // TODO: this could be more efficient InternalCacheEntry<WrappedBytes, WrappedBytes> ice = performGet(address, key); if (ice != null) { passivator.passivate(ice); performRemove(address, key); } } } finally { lock.unlock(); } }
Source:
START public static Put getHadoopVersionPut(int historyFileVersion, byte[] jobKeyBytes) { END Put pVersion = new Put(jobKeyBytes); byte[] valueBytes = null; valueBytes = Bytes.toBytes(Integer.toString(historyFileVersion)); byte[] qualifier = Bytes.toBytes(JobHistoryKeys.hadoopversion.toString().toLowerCase()); pVersion.add(Constants.INFO_FAM_BYTES, qualifier, valueBytes); return pVersion; } If having subclasses inherit a common implementation is the goal, using an instance method is preferred (i.e. non-static). Using static methods for inheritance purposes is bit of an anti-pattern.

Target:
public Put getHadoopVersionPut(int historyFileVersion, byte[] jobKeyBytes) { Put pVersion = new Put(jobKeyBytes); byte[] valueBytes = null; valueBytes = Bytes.toBytes(Integer.toString(historyFileVersion)); byte[] qualifier = Bytes.toBytes(JobHistoryKeys.hadoopversion.toString().toLowerCase()); pVersion.add(Constants.INFO_FAM_BYTES, qualifier, valueBytes); return pVersion; }
Source:
START public Map<String, Object> getMetadata() { END return this.metadata; } +1 to future proofing the name Have a look at one of the Adapters in [NovaParserModule.java](https://github.com/jclouds/jclouds/blob/master/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/config/NovaParserModule.java). You'll want to do something like that for the Image class. Don't forget to add it to the [provideCustomAdapterBindings()](https://github.com/jclouds/jclouds/blob/master/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/config/NovaParserModule.java#L57) method.

Target:
public Map<String, String> getMetadata() { return this.metadata; }
Source:
protected Node[] createNodes(AbstractFile t) { Node[] node = new Node[1]; START if(t.isDir()){ END //TODO log an error ??? return node; } else { //replace FileNode with our own subclass of its base type or similar node[0] = new DataResultFilterNode(new FileNode(t, false), DirectoryTreeTopComponent.findInstance().getExplorerManager()); return node; } } This check is not necessary, we do not compute MD5 hashes for directories.

Target:
protected Node[] createNodes(AbstractFile t) { Node[] node = new Node[1]; //TODO replace FileNode with our own subclass of its base type or similar node[0] = new DataResultFilterNode(new FileNode(t, false), DirectoryTreeTopComponent.findInstance().getExplorerManager()); return node; }
Source:
public ByteBuffer newByteBuffer(byte[] b, int offset, int length) { START return b == null || b.length == 0 || length == 0 ? ByteBufferImpl.EMPTY_INSTANCE : new ByteBufferImpl(b, offset, length); END } Can be: ```java return ByteBufferImpl.create(b, offset, length);` ```

Target:
public ByteBuffer newByteBuffer(byte[] b, int offset, int length) { return ByteBufferImpl.create(b, offset, length); }
Source:
public List<ExtensionProxy> getExtensionsByService(String provides) { List<ExtensionProxy> results = new ArrayList<>(); for (ExtensionEntry entry : initializedEntries.values()) { START if (entry.initialized END && entry.extension.getContext().<List> get(Base.ContextKeys.PROVIDES).contains(provides)) { results.add(entry.extension); } } return results; } of course it is initialized if it is in the initialized entries... now?

Target:
public List<ExtensionProxy> getExtensionsByService(String provides) { List<ExtensionProxy> results = new ArrayList<>(); for (ExtensionEntry entry : initializedEntries.values()) { if (entry.extension.getContext().<List> get(Base.ContextKeys.PROVIDES).contains(provides)) { results.add(entry.extension); } } return results; }
Source:
private boolean isBrokerWithPRTSupport(final Intent intent) { if (intent == null) { throw new IllegalArgumentException("intent"); } // Only new broker with PRT support will send down the value and the version will be v2 final String brokerVersion = intent.getStringExtra(AuthenticationConstants.Broker.BROKER_VERSION); if (!StringExtensions.IsNullOrBlank(brokerVersion) START && AuthenticationConstants.Broker.BROKER_PROTOCOL_VERSION.equalsIgnoreCase(brokerVersion)) { END return true; } return false; } you can do return (!StringExtensions.IsNullOrBlank(brokerVersion) && AuthenticationConstants.Broker.BROKER_PROTOCOL_VERSION.equalsIgnoreCase(brokerVersion)); #Closed

Target:
private boolean isBrokerWithPRTSupport(final Intent intent) { if (intent == null) { throw new IllegalArgumentException("intent"); } // Only new broker with PRT support will send down the value and the version will be v2 final String brokerVersion = intent.getStringExtra(AuthenticationConstants.Broker.BROKER_VERSION); return AuthenticationConstants.Broker.BROKER_PROTOCOL_VERSION.equalsIgnoreCase(brokerVersion); }
Source:
public PluginClassLoader pluginClassLoader(String name) { if (PluginUtils.shouldLoadInIsolation(name)) { SortedMap<PluginDesc<?>, ClassLoader> inner = pluginLoaders.get(name); if (inner != null) { ClassLoader pluginLoader = inner.get(inner.lastKey()); START if (pluginLoader instanceof PluginClassLoader) { END return (PluginClassLoader) pluginLoader; } } } return null; } I believe the existing behavior may be intentional and have something to do with the parent of the `DelegatingClassLoader` being something other than the system class loader. However, I'm not familiar enough with this part of the code base to say for sure; we should probably err on the side of keeping the existing functionality as-is unless someone else (e.g., @kkonstantine or a committer) can vouch that the current changes here wouldn't break anything.

Target:
public PluginClassLoader pluginClassLoader(String name) { if (!PluginUtils.shouldLoadInIsolation(name)) { return null; } SortedMap<PluginDesc<?>, ClassLoader> inner = pluginLoaders.get(name); if (inner == null) { return null; } ClassLoader pluginLoader = inner.get(inner.lastKey()); return pluginLoader instanceof PluginClassLoader ? (PluginClassLoader) pluginLoader : null; }
Source:
private PyUDFExpression() { name = ""; //set default return type this is changed once pythonfunction is retrived. outputType = Type.BLOB_TYPE; START } END I don't understand how this is used, or why BLOB_TYPE is the default here. Can you give me an example of where you use it?

Target:
private PyUDFExpression()
Source:
public void removeInstance(Object instance) { START deployedCacheStores.put(instance.getClass().getName(), new CompletableFuture<>()); END } Why are we setting it to new a new empty CompletableFuture? Is removing not sufficient?

Target:
public void removeInstance(Object instance) { deployedCacheStores.remove(instance.getClass().getName()); }
Source:
protected String createRecordName(String objectType) { StringBuilder sb = new StringBuilder(); START Formatter formatter = new Formatter(sb, Locale.US); END formatter.format("ManagerTest_%s_%08d", objectType, System.currentTimeMillis()); return sb.toString(); } You don't need `Formatter`. You can replace these lines with a single `String.format(...)` statement.

Target:
protected String createRecordName(String objectType) { return String.format(Locale.US, "ManagerTest_%s_%08d", objectType, System.currentTimeMillis()); }
Source:
EagerQueryResult() { START fields = originalResult.columns().toArray( new String[originalResult.columns().size()] ); END } Change it to `new String[0]`, it's just shorter.

Target:
EagerQueryResult() { fields = originalResult.columns().toArray( new String[0] ); }
Source:
public ArtifactoryClientBuilder addInterceptorLast(HttpRequestInterceptor httpRequestInterceptor) { if (this.requestInterceptorList == null) { START this.requestInterceptorList = new ArrayList<>(); END } this.requestInterceptorList.add(httpRequestInterceptor); return this; } I suggest to add an initialization in the declaration, instead of this `if` and the `if` in line 148: private List<HttpRequestInterceptor> requestInterceptorLis = new ArrayList<>();

Target:
public ArtifactoryClientBuilder addInterceptorLast(HttpRequestInterceptor httpRequestInterceptor) { this.requestInterceptorList.add(httpRequestInterceptor); return this; }
Source:
public Stock(String symbol, String name, double price) { START super(); END this.symbol = symbol; this.name = name; this.price = price; } super() is not necessary

Target:
public Stock(String symbol, String name, double price) { //super(); this.symbol = symbol; this.name = name; this.price = price; }
Source:
public boolean removeAll(Collection<?> c) { boolean removedSomething = false; START for (Object removeMe : c) { END removedSomething |= remove(removeMe); } return removedSomething; } s/`removeMe`/`key`/ ?

Target:
public boolean removeAll(Collection<?> c) { boolean removedSomething = false; for (Object key : c) { removedSomething |= remove(key); } return removedSomething; }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DimFilterHavingSpec that = (DimFilterHavingSpec) o; START return dimFilter != null ? dimFilter.equals(that.dimFilter) : that.dimFilter == null; END } dimFilter is non-null, so could be simplified unless you want to stick to "as IntelliJ generated" form.

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DimFilterHavingSpec that = (DimFilterHavingSpec) o; return dimFilter.equals(that.dimFilter); }
Source:
START private Session openSession() { END final Session currentSession = (Session) this.emProvider.get().getDelegate(); final SessionFactory factory = currentSession.getSessionFactory(); return factory.openSession(); } Same question as above: why change the scope?

Target:
protected Session openSession() { final Session currentSession = (Session) this.emProvider.get().getDelegate(); final SessionFactory factory = currentSession.getSessionFactory(); return factory.openSession(); }
Source:
Pair<IAnnotationModel, List<ContributionAnnotation>> addNewEntry( final List<ContributionAnnotation> annotations) { if (queue.size() > maxHistoryLength) { throw new IllegalStateException( START "The queue already contains the allowed number of annotations."); END } Pair<IAnnotationModel, List<ContributionAnnotation>> removedEntry = removeEntryIfFull(); queue.add(annotations); return removedEntry; } Amend message as it no longer represent the correct error state? A full queue on call is now allowed (which you correctly test for by now using `>` instead of `>=`). The issue you are checking for now it that there already are too many entries before the addition, meaning the queue was already in an illegal state before the call.

Target:
Pair<IAnnotationModel, List<ContributionAnnotation>> addNewEntry( final List<ContributionAnnotation> annotations) { Pair<IAnnotationModel, List<ContributionAnnotation>> removedEntry = removeEntryIfFull(); queue.add(annotations); return removedEntry; }
Source:
START public Optional<Guid> END getUserIdIfExternal() { return isInternalExecution() ? Optional.empty() : Optional.ofNullable(getUserId()); } this can be reduced to protected.

Target:
protected Optional<Guid> getUserIdIfExternal() { return isInternalExecution() ? Optional.empty() : Optional.ofNullable(getUserId()); }
Source:
public Group removeAccount(Account account) { Assert.notNull(account, "account cannot be null"); GroupMembership groupMembership = null; for (GroupMembership accountGroupMembership : getAccountMemberships()) { START if (accountGroupMembership.getAccount().getHref().equalsIgnoreCase(account.getHref())) { END groupMembership = accountGroupMembership; break; } } if (groupMembership != null){ groupMembership.delete(); } else { throw new IllegalStateException("The specified account does not belong to this Group."); } return this; } `href`s are case sensitive. Please use `equals(String)` instead of `equalsIgnoreCase(String)`

Target:
public Group removeAccount(Account account) { Assert.notNull(account, "account cannot be null"); GroupMembership groupMembership = null; for (GroupMembership accountGroupMembership : getAccountMemberships()) { if (accountGroupMembership.getAccount().getHref().equals(account.getHref())) { groupMembership = accountGroupMembership; break; } } if (groupMembership != null){ groupMembership.delete(); } else { throw new IllegalStateException("The specified account does not belong to this Group."); } return this; }
Source:
private boolean canPasteAll(IJavaElement destination) { for (TypedSource START fSource : END fSources) { if (!canPaste(fSource.getType(), destination)) { return false; } } return true; } rename to source

Target:
private boolean canPasteAll(IJavaElement destination) { for (TypedSource source : fSources) { if (!canPaste(source.getType(), destination)) { return false; } } return true; }
Source:
public ObjectListingChunk getNextChunk() throws IOException { if (mResult.isTruncated()) { String nextMarker = mResult.getNextMarker(); START mRequest.setMarker(nextMarker); END ObjectListing nextResult = mClient.listObjects(mRequest); if (nextResult != null) { return new OSSObjectListingChunk(mRequest, nextResult); } } return null; } Could you inline the first call? `mRequest.setMarker(mResult.getNextMarker())`

Target:
public ObjectListingChunk getNextChunk() throws IOException { if (mResult.isTruncated()) { mRequest.setMarker(mResult.getNextMarker()); ObjectListing nextResult = mClient.listObjects(mRequest); if (nextResult != null) { return new OSSObjectListingChunk(mRequest, nextResult); } } return null; }
Source:
public boolean equals(final Object o) { if (this == o) { return true; } START if (o == null || getClass() != o.getClass()) { END return false; } final LoopDetectionCriteria that = (LoopDetectionCriteria) o; return seen.equals(that.seen); } Is there a particular reason why `getClass()` is used instead of `instanceof`. `instanceof` is less restrictive and may be the better choice.

Target:
public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof LoopDetectionCriteria)) { return false; } final LoopDetectionCriteria that = (LoopDetectionCriteria) o; return seen.equals(that.seen); }
Source:
public void testBool() { final Arbitrary<Boolean> arbBooleanR = arbitrary(arbBoolean.gen); final Property p = property(arbBooleanR, arbBooleanR, (m1, m2) -> bool(m1.equals(m2)) START .implies(new BoolTestClass(m1).getBoolean() == new BoolTestClass(m2).getBoolean())); END PropertyAssert.assertResult(p); } What is the purpose of wrapping the Boolean in a class and getting the boolean back out, rather than a direct `m1 == m2` expression?

Target:
public void testBool() { final Arbitrary<Boolean> arbBooleanR = arbitrary(arbBoolean.gen); final Property p = property(arbBooleanR, arbBooleanR, (m1, m2) -> bool(m1.equals(m2)) .implies(m1 == m2)); PropertyAssert.assertResult(p); }
Source:
private void update() { // OK to ignore calls to update() if already busy updating if (busy.compareAndSet(false, true)) { try { PollingResponse response = reader.call(); if (response.hasData()) { current = response.getToAdd(); notifyConfigUpdated(this); } } catch (Exception e) { try { notifyError(e, this); } catch (Exception e2) { START LOG.warn("Failed to notify error observer"); END } } finally { busy.set(false); } } } Shouldn't this pass the exception to the logger so the user will know what the failure was?

Target:
private void update() { // OK to ignore calls to update() if already busy updating if (busy.compareAndSet(false, true)) { try { PollingResponse response = reader.call(); if (response.hasData()) { current = response.getToAdd(); notifyConfigUpdated(this); } } catch (Exception e) { try { notifyError(e, this); } catch (Exception e2) { LOG.warn("Failed to notify error observer", e2); } } finally { busy.set(false); } } }
Source:
START public javax.ws.rs.core.Response toResponse(InvalidValueException e) { END Fault fault = new Fault(); fault.setReason("Invalid Value"); fault.setDetail(e.getMessage()); return Response.status(Response.Status.BAD_REQUEST).entity(fault).build(); } Do you need the fully qualified class name here?

Target:
public Response toResponse(InvalidValueException e) { Fault fault = new Fault(); fault.setReason("Invalid Value"); fault.setDetail(e.getMessage()); return Response.status(Response.Status.BAD_REQUEST).entity(fault).build(); }
Source:
static long calculateDirSizeAndSave(final File dir) throws IOException { final Path path = Paths.get(dir.getPath(), FlowPreparer.PROJECT_DIR_SIZE_FILE_NAME); if (!Files.exists(path)) { final long sizeInByte = FileUtils.sizeOfDirectory(dir); FileIOUtils.dumpNumberToFile(path, sizeInByte); } START return FileIOUtils.readNumberFromFile(path); END } Return sizeInByte instead, if available.

Target:
static long calculateDirSizeAndSave(final File dir) throws IOException { final Path path = Paths.get(dir.getPath(), FlowPreparer.PROJECT_DIR_SIZE_FILE_NAME); if (!Files.exists(path)) { final long sizeInByte = FileUtils.sizeOfDirectory(dir); FileIOUtils.dumpNumberToFile(path, sizeInByte); return sizeInByte; } else { return FileIOUtils.readNumberFromFile(path); } }
Source:
public void initFromPage(int valueCount, ByteBufferInputStream inputStream) throws IOException { START int bitWidth = BytesUtils.readIntLittleEndianOnOneByte(inputStream); END decoder = new RunLengthBitPackingHybridDecoder(bitWidth, inputStream); } static import `readIntLittleEndianOnOneByte`.

Target:
public void initFromPage(int valueCount, ByteBufferInputStream inputStream) throws IOException { int bitWidth = readIntLittleEndianOnOneByte(inputStream); decoder = new RunLengthBitPackingHybridDecoder(bitWidth, inputStream); }
Source:
@Override public boolean onCreate() { START Picasso.setSingletonInstance(new Picasso.Builder(getContext()).build()); END return true; } if you want to override the singleton instance, then, you need to remove the ContentProvider from the manifest, right? or is there another way?

Target:
@Override public boolean onCreate() { context = getContext(); return true; }
Source:
public long getDelayBetweenSyncs(@NonNull TimeUnit unit) { START return TimeUnit.MILLISECONDS.convert(this.getDelayBetweenSyncs(), unit); END } No, this one was correct... 😈 We want to convert the internal delay (expressed in milliseconds) to whatever unit the client asked.

Target:
public long getDelayBetweenSyncs(@NonNull TimeUnit unit) { return unit.convert(this.getDelayBetweenSyncs(), TimeUnit.MILLISECONDS); }
Source:
public CompositeCodec(Map<Class<?>, Codec> delegates, Codec defaultCodec) { Assert.notNull(defaultCodec, "'defaultCodec' cannot be null"); this.defaultCodec = defaultCodec; START this.delegates = delegates; END } `new HashMap(delegates)` - don't keep a reference to the caller's map - he might change it.

Target:
public CompositeCodec(Map<Class<?>, Codec> delegates, Codec defaultCodec) { Assert.notNull(defaultCodec, "'defaultCodec' cannot be null"); this.defaultCodec = defaultCodec; this.delegates = new HashMap<Class<?>, Codec>(delegates); }
Source:
START public T get() { END return getOr(defaultValue); } final?

Target:
public final T get() { return getOr(defaultValue); }
Source:
private void updateNics(List<NetworkInterfaceModel> nics) { nicList.clear(); Collections.sort(nics); List<NetworkGroup> groups = new ArrayList<>(); for (NetworkInterfaceModel nic : nics) { groups.add(new NetworkGroup(nic, eventBus, style)); } nicList.addAll(groups, !rendered); START nicGroups = groups; END } if you are going to assign the local variable to the field, why not skip the local variable and use the field in the method?

Target:
private void updateNics(List<NetworkInterfaceModel> nics) { nicList.clear(); Collections.sort(nics); nicGroups = new ArrayList<>(); for (NetworkInterfaceModel nic : nics) { nicGroups.add(new NetworkGroup(nic, eventBus, style)); } nicList.addAll(nicGroups, !rendered); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RpcOptions options = (RpcOptions) o; if (timeout != options.timeout) return false; if (deliverOrder != options.deliverOrder) return false; START return unit == options.unit; END } nitpick: replace `if` with `&&` ```suggestion return timeout == options.timeout && deliverOrder == options.deliverOrder && unit == options.unit; ```

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RpcOptions options = (RpcOptions) o; return timeout == options.timeout && deliverOrder == options.deliverOrder && unit == options.unit; }
Source:
START protected abstract OutputStream getOutputStreamInternal(RepositoryPath repositoryPath) END throws IOException; protected final RepositoryOutputStream decorate(RepositoryPath repositoryPath, OutputStream os) throws IOException { if (os == null || os instanceof RepositoryOutputStream) { return (RepositoryOutputStream) os; } String path = RepositoryFiles.stringValue(repositoryPath); return RepositoryOutputStream.of(repositoryPath.getRepository(), path, os).with(this); } Why is it necessary to rename these methods?

Target:
protected abstract OutputStream getOutputStreamInternal(RepositoryPath repositoryPath) throws IOException; protected final RepositoryOutputStream decorate(RepositoryPath repositoryPath, OutputStream os) throws IOException { if (os == null || os instanceof RepositoryOutputStream) { return (RepositoryOutputStream) os; } return RepositoryOutputStream.of(repositoryPath, os).with(this); }
Source:
public MatchAttributeWithValue(String attributeName, String attributeRegex) { super("match attribute"); this.attributeName = attributeName; START this.attributeRegex = Pattern.compile(attributeRegex, DOTALL); END } Why DOTALL? As I know, it's needed to support multiline Strings, which hardly can happen to attribute values.

Target:
public MatchAttributeWithValue(String attributeName, String attributeRegex) { super("match attribute"); this.attributeName = attributeName; this.attributeRegex = Pattern.compile(attributeRegex); }
Source:
public void tearDown() throws Exception { if (executor != null) executor.shutdownNow(); if (app != null) Entities.destroyAll(app.getManagementContext()); START if (exampleEntity != null) Entities.destroyAll(exampleEntity.getApplication().getManagementContext()); END } saw NPE here - change to `if (exampleEntity != null && exampleEntity.getApplication() != null)` (happened when `ExampleAppInFile.groovy` was not on my classpath due to annoying Eclipse behaviour).

Target:
public void tearDown() throws Exception { if (executor != null) executor.shutdownNow(); if (app != null) Entities.destroyAll(app.getManagementContext()); if (exampleEntity != null && exampleEntity.getApplication() != null) Entities.destroyAll(exampleEntity.getApplication().getManagementContext()); }
Source:
public void refreshJobInfo(JobInfo info) { GroupInfo group = info.getGroupInfo(); if (group != null) { refreshGroup(group); } Object[] listenersArray = listeners.getListeners(); START for (Object element : listenersArray) { END IJobProgressManagerListener listener = (IJobProgressManagerListener) element; if (!isCurrentDisplaying(info.getJob(), listener.showsDebug())) { listener.refreshJobInfo(info); } } } inline listeners.getListeners()

Target:
public void refreshJobInfo(JobInfo info) { GroupInfo group = info.getGroupInfo(); if (group != null) { refreshGroup(group); } for (Object element : listeners.getListeners()) { IJobProgressManagerListener listener = (IJobProgressManagerListener) element; if (!isCurrentDisplaying(info.getJob(), listener.showsDebug())) { listener.refreshJobInfo(info); } } }
Source:
START public ConnectorHandle(ConnectorLocator locator, END Class<? extends StoragePluginConfig> configClass) { this.locator = locator; this.configClass = configClass; this.isIntrinsic = false; } Is it obvious if we pass config class so it is not intrinsic but if StoragePlugin instance it is? Maybe it's better to have this done using static methods for better readability? For example: We'll have only one constructor and two static methods: ``` private ConnectorHandle(ConnectorLocator locator, Class<? extends StoragePluginConfig> configClass, boolean isIntrinsic) { this.locator = locator; this.configClass = configClass; this.isIntrinsic = isIntrinsic; } public static ConnectorHandle initIntrinsic(ConnectorLocator locator, Class<? extends StoragePluginConfig> configClass) { return new ConnectorHandle(...); } public static ConnectorHandle initNonIntrinsic(ConnectorLocator locator, Class<? extends StoragePluginConfig> configClass) { return new ConnectorHandle(...); } ```

Target:
private ConnectorHandle(ConnectorLocator locator, Class<? extends StoragePluginConfig> configClass) { this.locator = locator; this.configClass = configClass; this.isIntrinsic = false; }
Source:
public void testReconfigureServer() { api().reconfigureServer(serverId, 4, CpuSpeed.HIGHPERFORMANCE.name(), 1); START waitForServerState(api(), serverId, State.PENDING_CHANGE, 30 * 60 * 1000, "Error"); END waitForServerState(api(), serverId, State.NORMAL, 30 * 60 * 1000, "Error"); } Is it possible that the reconfigure operation is fast enough that we don't actually see this state? Does it really make sense to wait for intermediate states?

Target:
public void testReconfigureServer() { api().reconfigureServer(serverId, 4, CpuSpeed.HIGHPERFORMANCE.name(), 1); waitForServerState(api(), serverId, State.NORMAL, 30 * 60 * 1000, "Error"); }
Source:
public void run() { try { log.info("Running reporting task: " + getClass().getSimpleName()); START currentSession = sessionFactory.getHibernateSessionFactory().getCurrentSession(); END executeTask(); log.info("Completed reporting task: " + getClass().getSimpleName()); } catch (Exception e) { log.error("An error occurred while running reporting task: " + getClass(), e); } } Revert back to sessionFactory.getCurrentSession()

Target:
public void run() { try { log.info("Running reporting task: " + getClass().getSimpleName()); currentSession = sessionFactory.getCurrentSession(); executeTask(); log.info("Completed reporting task: " + getClass().getSimpleName()); } catch (Exception e) { log.error("An error occurred while running reporting task: " + getClass(), e); } }
Source:
public static final boolean isStorageWritable() { START return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED; END } This should imho be implemented with an equals since you are comparing Strings and to make it null safe I would suggest: `return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());`

Target:
public static final boolean isStorageWritable() { return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); }
Source:
public ModuleMetadataResource toResource(ModuleMetadata entity) { START return createResourceWithId(entity.getName(), entity); END } I foresee clashes here. Should at least use <type> + "/" + <name>

Target:
public ModuleMetadataResource toResource(ModuleMetadata entity) { return createResourceWithId(entity.getId(), entity); }
Source:
private void bindFrontendInfrastructure() { bind(Frontend.class).in(Singleton.class); requestStaticInjection(Frontend.InstanceHolder.class); START requestStaticInjection(AssetProvider.class); END bind(VdcOperationManager.class).in(Singleton.class); bind(OperationProcessor.class).in(Singleton.class); bind(CommunicationProvider.class).to(GWTRPCCommunicationProvider.class).in(Singleton.class); } Hm, this method was meant to contain GIN bindings for "frontend communication infra" classes, so I'd rather put AssetProvider binding elsewhere, e.g. at the end of bindCommonInfrastructure method?

Target:
private void bindFrontendInfrastructure() { bind(Frontend.class).in(Singleton.class); requestStaticInjection(Frontend.InstanceHolder.class); bind(VdcOperationManager.class).in(Singleton.class); bind(OperationProcessor.class).in(Singleton.class); bind(CommunicationProvider.class).to(GWTRPCCommunicationProvider.class).in(Singleton.class); }
Source:
public Subscriber<Observable<? extends T>> call(final Subscriber<? super T> child) { MergeSubscriber<T> subscriber = new MergeSubscriber<T>(child, delayErrors, maxConcurrent); MergeProducer<T> producer = new MergeProducer<T>(subscriber); subscriber.producer = producer; START producer.lazySet(0); // make sure subscriber.producer is visible END child.add(subscriber); child.setProducer(producer); return subscriber; } What is this lazySet about? What about visibility would not work if this wasn't done?

Target:
public Subscriber<Observable<? extends T>> call(final Subscriber<? super T> child) { MergeSubscriber<T> subscriber = new MergeSubscriber<T>(child, delayErrors, maxConcurrent); MergeProducer<T> producer = new MergeProducer<T>(subscriber); subscriber.producer = producer; child.add(subscriber); child.setProducer(producer); return subscriber; }
Source:
public void getRadiologyOrders_shouldReturnAllRadiologyOrdersForGivenUrgency() throws Exception { Patient patient = patientService.getPatient(PATIENT_ID_WITH_ONE_VOIDED_AND_TWO_NON_VOIDED_RADIOLOGY_ORDERS); RadiologyOrderSearchCriteria radiologyOrderSearchCriteria = START new RadiologyOrderSearchCriteria.Builder().withPatient(patient) END .withUrgency(Urgency.STAT) .build(); List<RadiologyOrder> radiologyOrders = radiologyOrderService.getRadiologyOrders(radiologyOrderSearchCriteria); assertThat(radiologyOrders.size(), is(2)); for (RadiologyOrder radiologyOrder : radiologyOrders) { assertThat(radiologyOrder.getUrgency(), is(Urgency.STAT)); } } @bgeVam why did you add patient ?

Target:
public void getRadiologyOrders_shouldReturnAllRadiologyOrdersForGivenUrgency() throws Exception { RadiologyOrderSearchCriteria radiologyOrderSearchCriteria = new RadiologyOrderSearchCriteria.Builder().withUrgency(Urgency.STAT) .build(); List<RadiologyOrder> radiologyOrders = radiologyOrderService.getRadiologyOrders(radiologyOrderSearchCriteria); assertThat(radiologyOrders.size(), is(5)); for (RadiologyOrder radiologyOrder : radiologyOrders) { assertThat(radiologyOrder.getUrgency(), is(Urgency.STAT)); } }
Source:
static FeignException errorReading(Request request, Response ignored, IOException cause) { return new FeignException( START format("%s reading %s %s", cause.getMessage(), request.httpMethod().name(), request.url()), END cause); } `format` should be able to deal with `Enum`s just fine. no need to call `name()`

Target:
static FeignException errorReading(Request request, Response ignored, IOException cause) { return new FeignException( format("%s reading %s %s", cause.getMessage(), request.httpMethod(), request.url()), cause); }
Source:
protected WrappedByteBuf(ByteBuf buf) { ObjectUtil.checkNotNull(buf, "buf"); START this.buf = buf; END } nit: you can merge both lines above as `checkNotNull` will return the given argument

Target:
protected WrappedByteBuf(ByteBuf buf) { this.buf = ObjectUtil.checkNotNull(buf, "buf"); }
Source:
public boolean isFull() { START return chunks.size() == chunks.get(0).getObject().getAtomicUpdateGroupSize(); END } Should this check that chunks.get(0) exists?

Target:
public boolean isFull() { return !isEmpty() && chunks.size() == chunks.get(0).getObject().getAtomicUpdateGroupSize(); }
Source:
START public String END me() { return "" + state + ME_SEPARATOR; } private

Target:
public String me() { return state + ME_SEPARATOR; }