auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START private List<String> getListOfIsoFiles(File directory, OVirtNodeInfo info) { END List<String> isoFileList = new ArrayList<String>(); File[] filterOvirtFiles = filterOvirtFiles(directory, getIsoPattern(info)); for (File file : filterOvirtFiles) { isoFileList.add(file.getName()); } return isoFileList; } but you removed the static from there as well.

Target:
private static List<String> getListOfIsoFiles(File directory, OVirtNodeInfo info) { List<String> isoFileList = new ArrayList<String>(); File[] filterOvirtFiles = filterOvirtFiles(directory, getIsoPattern(info)); for (File file : filterOvirtFiles) { isoFileList.add(file.getName()); } return isoFileList; }
Source:
EWAHCompressedBitmap getBitmap() { // Fast path to immediately return the expanded result. Object r = bitmapContainer; if (r instanceof EWAHCompressedBitmap) return (EWAHCompressedBitmap) r; // Expand the bitmap and cache the result. XorCompressedBitmap xb = (XorCompressedBitmap) r; EWAHCompressedBitmap out = xb.bitmap; START while (true) { END r = xb.xorBitmap.bitmapContainer; if (r instanceof EWAHCompressedBitmap) { bitmapContainer = out = out.xor((EWAHCompressedBitmap) r); return out; } xb = (XorCompressedBitmap) r; out = out.xor(xb.bitmap); } } nit: jgit spells this for (;;)

Target:
EWAHCompressedBitmap getBitmap() { // Fast path to immediately return the expanded result. Object r = bitmapContainer; if (r instanceof EWAHCompressedBitmap) return (EWAHCompressedBitmap) r; // Expand the bitmap and cache the result. XorCompressedBitmap xb = (XorCompressedBitmap) r; EWAHCompressedBitmap out = xb.bitmap; for (;;) { r = xb.xorBitmap.bitmapContainer; if (r instanceof EWAHCompressedBitmap) { out = out.xor((EWAHCompressedBitmap) r); bitmapContainer = out; return out; } xb = (XorCompressedBitmap) r; out = out.xor(xb.bitmap); } }
Source:
public AbstractCorrelatingMessageHandler(MessageGroupProcessor processor, MessageGroupStore store, CorrelationStrategy correlationStrategy, ReleaseStrategy releaseStrategy) { Assert.notNull(processor); Assert.notNull(store); setMessageStore(store); this.outputProcessor = processor; this.correlationStrategy = correlationStrategy == null ? new HeaderAttributeCorrelationStrategy(IntegrationMessageHeaderAccessor.CORRELATION_ID) : correlationStrategy; this.releaseStrategy = releaseStrategy == null ? new SequenceSizeReleaseStrategy() : releaseStrategy; START super.messagingTemplate.setSendTimeout(DEFAULT_SEND_TIMEOUT); END sequenceAware = this.releaseStrategy instanceof SequenceSizeReleaseStrategy; } ??? `this.` of course. That's why I said to revert those all changes for the `messagingTemplate` and PR is becoming clear

Target:
public AbstractCorrelatingMessageHandler(MessageGroupProcessor processor, MessageGroupStore store, CorrelationStrategy correlationStrategy, ReleaseStrategy releaseStrategy) { Assert.notNull(processor); Assert.notNull(store); setMessageStore(store); this.outputProcessor = processor; this.correlationStrategy = correlationStrategy == null ? new HeaderAttributeCorrelationStrategy(IntegrationMessageHeaderAccessor.CORRELATION_ID) : correlationStrategy; this.releaseStrategy = releaseStrategy == null ? new SequenceSizeReleaseStrategy() : releaseStrategy; this.messagingTemplate.setSendTimeout(DEFAULT_SEND_TIMEOUT); sequenceAware = this.releaseStrategy instanceof SequenceSizeReleaseStrategy; }
Source:
public Statement createBootstrapScriptForGroup(String group, @Nullable String nodeName) { START return groupToBootScript.apply(group, null); END } Hmmm this is wrong now? There should be two methods, one passing null and the other one passing the nodeName.

Target:
public Statement createBootstrapScriptForGroup(String group, @Nullable String nodeName) { return groupToBootScript.apply(group, nodeName); }
Source:
public boolean create(Personname personnameRecord) { LOG.trace("PersonnameDAO.create() - Begin"); START boolean result = true; END if (personnameRecord != null) { result = super.create(personnameRecord); } LOG.trace("PersonnameDAO.create() - End"); return result; } No need for result variable

Target:
public boolean create(Personname personnameRecord) { LOG.trace("PersonnameDAO.create() - Begin"); return personnameRecord != null ? super.create(personnameRecord) : true; }
Source:
public void handleInvocation(EJBClientInvocationContext context) throws Exception { START log.info("In the client interceptor handleInvocation : " + this.getClass().getName() + " " + context.getViewClass() + " " + context.getLocator()); END context.getContextData().put("ClientInterceptorInvoked", this.getClass().getName() + " " + context.getViewClass() + " " + context.getLocator()); // Must make this call context.sendRequest(); } Please only log at debug or trace

Target:
public void handleInvocation(EJBClientInvocationContext context) throws Exception { log.debug("In the client interceptor handleInvocation : " + this.getClass().getName() + " " + context.getViewClass() + " " + context.getLocator()); // Must make this call context.sendRequest(); }
Source:
public void edit(final NewExternalSubnetModel subnet) { driver.edit(subnet); START if (subnet.getNetwork().getEntity() != null){ END networkEditor.asValueBox().setValue(subnet.getNetwork().getEntity().getName()); } } If I'm not mistaken, it shouldn't be possible for subnet.getNetwork() to be null, so you can drop the check.

Target:
public void edit(final NewExternalSubnetModel subnet) { driver.edit(subnet); networkEditor.asValueBox().setValue(subnet.getNetwork().getEntity().getName()); }
Source:
protected AddVmFromTemplateCommand<AddVmParameters> createCommand() { initVM(); AddVmParameters START param = END new AddVmParameters(vm); return new AddVmFromTemplateCommand<>(param, null); } this is probably simple enough to be inlined...

Target:
protected AddVmFromTemplateCommand<AddVmParameters> createCommand() { initVM(); return new AddVmFromTemplateCommand<>(new AddVmParameters(vm), null); }
Source:
public void testGetNameFromPath() { START String path1 = "/group1"; END String path2 = "/group1/group2/group3"; String emptyPath = ""; String nullPath = null; String rootPath = "/"; assertEquals(HDF5Utils.getNameFromPath(path1), "group1"); assertEquals(HDF5Utils.getNameFromPath(path2), "group3"); assertEquals(HDF5Utils.getNameFromPath(emptyPath), ""); assertNull(HDF5Utils.getNameFromPath(nullPath)); assertEquals(HDF5Utils.getNameFromPath(rootPath), ""); } Please split this test into several, testing each case separately.

Target:
public void testGetNameFromPath() { String path1 = "/group1"; assertEquals(HDF5Utils.getNameFromPath(path1), "group1"); }
Source:
START @Override public END GlusterLocalLogicalVolumeListReturn glusterLogicalVolumeList() { JsonRpcRequest request = new RequestBuilder("GlusterHost.logicalVolumeList").build(); Map<String, Object> response = new FutureMap(this.client, request).withIgnoreResponseKey(); return new GlusterLocalLogicalVolumeListReturn(response); } Coding conventions: Let's have the @Override on its own line please

Target:
public GlusterLocalLogicalVolumeListReturn glusterLogicalVolumeList() { JsonRpcRequest request = new RequestBuilder("GlusterHost.logicalVolumeList").build(); Map<String, Object> response = new FutureMap(this.client, request).withIgnoreResponseKey(); return new GlusterLocalLogicalVolumeListReturn(response); }
Source:
START public String toString() { END return "TypedByteArray[length=" + length() + "]"; } needs `@Override`

Target:
@Override public String toString() { return "TypedByteArray[length=" + length() + "]"; }
Source:
public void onEntityDestroyed(EntityRef entity) { START if (!entity.isPersistent()) { END return; // ignore } entityDeltas.remove(entity.getId()); destroyedEntities.add(entity.getId()); } Not an issue, but could be rewritten as ``` java if (entity.isPersistent()) { // do stuff } ``` to avoid multiple points of return from the method (and save a line of code).

Target:
public void onEntityDestroyed(EntityRef entity) { if (entity.isPersistent()) { entityDeltas.remove(entity.getId()); destroyedEntities.add(entity.getId()); } }
Source:
private OrganizationalUnit getOU( String ouIdentifier, Collection<OrganizationalUnit> organizationalUnits ) { Optional<OrganizationalUnit> targetOU = organizationalUnits.stream() .filter( p -> p.getIdentifier().equalsIgnoreCase( ouIdentifier ) ).findFirst(); START if ( targetOU.isPresent() ) { END return targetOU.get(); } return null; } Isn't this use of `Optional` and returning `null` contradictory? Surely checking `isPresent(..)` in `getDefaultOrganizationalUnit(..)` would be better?

Target:
private Optional<OrganizationalUnit> getOU( String ouIdentifier, Collection<OrganizationalUnit> organizationalUnits ) { Optional<OrganizationalUnit> targetOU = organizationalUnits.stream() .filter( p -> p.getIdentifier().equalsIgnoreCase( ouIdentifier ) ).findFirst(); return targetOU; }
Source:
public void testPutAsync() throws Exception { // put Future<String> f = c.putAsync("k", "v"); testFuture(f, null); testK("v"); f = c.putAsync("k", "v2"); testFuture(f, "v"); START assertEquals("v2", c.get("k")); END } to keep code consistency, you may use `testK("v2");`

Target:
public void testPutAsync() throws Exception { // put Future<String> f = c.putAsync("k", "v"); testFuture(f, null); testK("v"); f = c.putAsync("k", "v2"); testFuture(f, "v"); testK("v2"); }
Source:
public boolean isReady(TaskActionClient taskActionClient) throws Exception { START return false; END } should this return true instead ?

Target:
public boolean isReady(TaskActionClient taskActionClient) throws Exception { return true; }
Source:
START static Map<String, EntryValue> convertBeanToEntryMap(Object bean) { END Map<String, Object> buildAttributeValueMap = BeanUtilsExtended.buildObjectAttributeMap(bean); return Maps.transformEntries(buildAttributeValueMap, new ObjectToEntryValueTransformer()); } why not public

Target:
public static Map<String, EntryValue> convertBeanToEntryMap(Object bean) { Map<String, Object> buildAttributeValueMap = BeanUtilsExtended.buildObjectAttributeMap(bean); return Maps.transformEntries(buildAttributeValueMap, new ObjectToEntryValueTransformer()); }
Source:
public RequestHeader(Struct struct, short headerVersion) { this.data = new RequestHeaderData(struct, headerVersion); START this.headerVersion = headerVersion; END } nit: replace with `this(new RequestHeaderData(struct, headerVersion), headerVersion)`. Consolidates c'tor logic to one place.

Target:
public RequestHeader(Struct struct, short headerVersion) { this(new RequestHeaderData(struct, headerVersion), headerVersion); }
Source:
public void accountSession(String username, String password) throws TmdbInvalidParametersException { START if (username == null || password==null) END throw new TmdbInvalidParametersException(401,"Username and Password may not be null"); this.username = username; this.password = password; hasAccountSession = true; } Please add braces to conditionals (like `if { }`).

Target:
public void accountSession(String username, String password) throws TmdbInvalidParametersException { if (username == null || password == null) { throw new TmdbInvalidParametersException(401, "Username and Password may not be null"); } this.username = username; this.password = password; hasAccountSession = true; }
Source:
public void setProjectName(String projectName) { fProjectName = projectName; // If remote directory field is empty if(fLocationText.getText().equals(EMPTY_STRING)) { fRemoteDirSelected = false; } // If remote directory was not selected yet START if (fRemoteDirSelected == false) { END fLocationText.setText(getDefaultPathDisplayString()); } } Use if (!fRemoteDirSelected) {

Target:
public void setProjectName(String projectName) { fProjectName = projectName; // If remote directory field is empty if(fLocationText.getText().equals(EMPTY_STRING)) { fRemoteDirSelected = false; } // If remote directory was not selected yet if (!fRemoteDirSelected) { fLocationText.setText(getDefaultPathDisplayString()); } }
Source:
public void testAddChildCycle3() { assertNotNull(fFixture); assertNotNull(f42Fixture); assertNotNull(fHiFixture); ((CalledFunction) f42Fixture).addChild(fHiFixture); START assertEquals(Collections.singletonList(fHiFixture), f42Fixture.getChildren()); END } unreachable. Maybe you should remove.

Target:
public void testAddChildCycle3() { assertNotNull(fFixture); assertNotNull(f42Fixture); assertNotNull(fHiFixture); ((CalledFunction) f42Fixture).addChild(fHiFixture); }
Source:
private char formatFieldFirstCharacterToFitDroolsCoreStandards(final String fieldName) { START if (fieldName.length() > 2 && Character.isLowerCase(fieldName.charAt(0)) && Character.isUpperCase(fieldName.charAt(1))) { END return fieldName.charAt(0); } else { return Character.toUpperCase(fieldName.charAt(0)); } } I think the condition needs top start as `fieldName.length() > 1` instead of `fieldName.length() > 2 `. I think the generated code getters/setters has same rules for fields **aField** and **aF**. Or am I wrong?

Target:
private char formatFieldFirstCharacterToFitDroolsCoreStandards(final String fieldName) { if (fieldName.length() > 1 && Character.isLowerCase(fieldName.charAt(0)) && Character.isUpperCase(fieldName.charAt(1))) { return fieldName.charAt(0); } else { return Character.toUpperCase(fieldName.charAt(0)); } }
Source:
public void start() { START logger.debug("start()"); END for (final Class<?> stepDefinitionType : cachedStepsInstances.keySet()) { cachedStepsInstances.put(stepDefinitionType, createStepsInstance(stepDefinitionType)); } } Are these logging statements really needed?

Target:
public void start() { logger.trace("start()"); for (final Class<?> stepDefinitionType : cachedStepsInstances.keySet()) { cachedStepsInstances.put(stepDefinitionType, createStepsInstance(stepDefinitionType)); } }
Source:
private WorkingSetDescriptor getSelectedWorkingSet() { IStructuredSelection selection = typesListViewer.getStructuredSelection(); WorkingSetDescriptor descriptor = null; if (!selection.isEmpty()) { descriptor = (WorkingSetDescriptor) START selection.getFirstElement(); END } return descriptor; } I don't have the code now but if the contract od sselection is to return null on getFirstElement() if sselection is empty, the code can be changed to simply return the first element, without the if.

Target:
private WorkingSetDescriptor getSelectedWorkingSet() { return (WorkingSetDescriptor) typesListViewer.getStructuredSelection().getFirstElement(); }
Source:
public void evaluate() throws Throwable { START if (null != previous) { END previous.evaluate(); } for (FrameworkMethod before : befores) { before.invokeExplosively(target); } next.evaluate(); } Is it reasonable for the caller to pass in a null value for previous into the constructor? If not, then the constructor should throw a `NullPointerException` if it is null.

Target:
public void evaluate() throws Throwable { for (FrameworkMethod before : befores) { before.invokeExplosively(target); } next.evaluate(); }
Source:
public Response add(OpenStackVolumeProvider provider) { validateParameters(provider, "name"); StoragePool storagePool = provider.isSetDataCenter() ? START getStoragePool(provider.getDataCenter()) : new StoragePool(); END provider.setDataCenter(DataCenterMapper.map(storagePool, null)); return performCreate( VdcActionType.AddProvider, new ProviderParameters(map(provider)), new QueryIdResolver<Guid>(VdcQueryType.GetProviderById, IdQueryParameters.class) ); } It is a bit weird to create here an empty "StoragePool" to indicate that there is no storage pool to use. Can't we just pass "null" to the backend in that case?

Target:
public Response add(OpenStackVolumeProvider provider) { validateParameters(provider, "name"); if (provider.isSetDataCenter()) { StoragePool storagePool = getStoragePool(provider.getDataCenter()); provider.setDataCenter(DataCenterMapper.map(storagePool, null)); } return performCreate( VdcActionType.AddProvider, new ProviderParameters(map(provider)), new QueryIdResolver<Guid>(VdcQueryType.GetProviderById, IdQueryParameters.class) ); }
Source:
START protected void doStoreUsers() END { try { usersFileManager.store(new UsersDto(new HashSet<>(userMap.values()))); } catch (IOException e) { throw new UndeclaredThrowableException(e); } } private

Target:
private void doStoreUsers() { try { usersFileManager.store(new UsersDto(new HashSet<>(userMap.values()))); } catch (IOException e) { throw new UndeclaredThrowableException(e); } }
Source:
START public void tearDown() throws IOException, SQLException { END try { globalScheduler.shutdown(); } catch (Exception e) { } cleanup(); tearDownOnce(); } Why is this needed now?

Target:
public void tearDown(){ try { globalScheduler.shutdown(); } catch (Exception e) { } cleanup(); tearDownOnce(); }
Source:
private CloudMachineNamer getCloudMachineNamer(ConfigBag config) { String namerClass = config.get(LocationConfigKeys.CLOUD_MACHINE_NAMER_CLASS); if (namerClass != null) { try { return (CloudMachineNamer) getManagementContext().getCatalog().getRootClassLoader().loadClass(namerClass) .getDeclaredConstructor(ConfigBag.class).newInstance(config); } catch (Exception e) { throw Exceptions.propagate(e); } } else { START return new JcloudsMachineNamer(getAllConfigBag()); END } } This shouldn't call `getAllConfigBag()`. It should use the `config` passed in, otherwise we lose the local values passed in to the obtain() method. Do you agree?

Target:
private CloudMachineNamer getCloudMachineNamer(ConfigBag config) { String namerClass = config.get(LocationConfigKeys.CLOUD_MACHINE_NAMER_CLASS); if (namerClass != null) { try { return (CloudMachineNamer) getManagementContext().getCatalog().getRootClassLoader().loadClass(namerClass) .getDeclaredConstructor(ConfigBag.class).newInstance(config); } catch (Exception e) { throw Exceptions.propagate(e); } } else { return new JcloudsMachineNamer(config); } }
Source:
START public IllustratedSelectItem(Object value, String label, String image) { END super(value, label); this.image = image; } Missing JavaDoc.

Target:
IllustratedSelectItem(Object value, String label, String image) { super(value, label); this.image = image; }
Source:
private boolean layerGroupContainmentCheckRequired() { // first, is it WMS? Request request = Dispatcher.REQUEST.get(); if(request == null) { return false; } // layer groups are used only in WMS final String service = request.getService(); boolean isMapService = "WMS".equalsIgnoreCase(service) || "gwc".equalsIgnoreCase(service); if(!isMapService) { return false; } START return true; END } The last six lines can be squashed into: return "WMS".equalsIgnoreCase(service) || "gwc".equalsIgnoreCase(service);

Target:
private boolean layerGroupContainmentCheckRequired() { // first, is it WMS? Request request = Dispatcher.REQUEST.get(); if(request == null) { return false; } // layer groups are used only in WMS final String service = request.getService(); return "WMS".equalsIgnoreCase(service) || "gwc".equalsIgnoreCase(service); }
Source:
public ResteasyUriInfo(final String absoluteUri, final String contextPath, final InitData initData) { START initialize(absoluteUri, contextPath, InitData.canBeCached(absoluteUri) ? initData : null); END } I would do this instead: ``initialize(absoluteUri, contextPath, (initData != null && InitData.canBeCached(absoluteUri)) ? initData : null);`` IOW, no point in spending time on checking if the cache can be used if there's no ``initData`` provided.

Target:
public ResteasyUriInfo(final String absoluteUri, final String contextPath, final InitData initData) { initialize(absoluteUri, contextPath, initData != null && InitData.canBeCached(absoluteUri) ? initData : null); }
Source:
private void buildUnaryExpression(UnaryExpressionTree tree) { START if(tree.is(Tree.Kind.PREFIX_DECREMENT, Tree.Kind.PREFIX_INCREMENT)) { END build(tree.expression()); currentBlock.elements.add(tree); } else { currentBlock.elements.add(tree); build(tree.expression()); } } @benzonico The fact that postfix operators return value before modification shouldn't change order in CFG, because loading of value should anyway happen before operation, i.e. order should be the same.

Target:
private void buildUnaryExpression(UnaryExpressionTree tree) { currentBlock.elements.add(tree); build(tree.expression()); }
Source:
START public Class getRealClass() { END return testNGMethod.getRealClass(); } Class<?>

Target:
public Class<?> getRealClass() { return testNGMethod.getRealClass(); }
Source:
private KeyStore getSecretsStore() { final File secretStoreFile = createStoreIfNeeded(); try { final KeyStore keyStore = KeyStore.getInstance(SECRETS_STORE_KEYSTORE_TYPE); START try (InputStream inputStream = Files.newInputStream(secretStoreFile.toPath())) { END keyStore.load(inputStream, loadStorePassword()); } return keyStore; } catch (Exception e) { Logger.warn(this.getClass(), "unable to load secrets store " + SECRETS_STORE_FILE + ": " + e); throw new DotRuntimeException(e); } } Good it is the way

Target:
private KeyStore getSecretsStore() { final File secretStoreFile = createStoreIfNeeded(); try { final KeyStore keyStore = KeyStore.getInstance(SECRETS_STORE_KEYSTORE_TYPE); try (InputStream inputStream = Files.newInputStream(secretStoreFile.toPath())) { keyStore.load(inputStream, loadStorePassword()); } return keyStore; } catch (Exception e) { Logger.error(this.getClass(), "unable to load secrets store " + SECRETS_STORE_FILE + ": " + e); throw new DotRuntimeException(e); } }
Source:
public AnonymousSpec anonymous(){ if (this.anonymous == null) { this.anonymous = new AnonymousSpec(); } START return this.anonymous.authorities("ROLE_USER"); END } This should be ROLE_ANONYMOUS. However given the defaults in AnonymousSpec you should just delete it

Target:
public AnonymousSpec anonymous(){ if (this.anonymous == null) { this.anonymous = new AnonymousSpec(); } return this.anonymous; }
Source:
public int getNumWaiters() { START return this.connectionPool.getNumActive(); END } ```suggestion return this.connectionPool.getNumWaiters(); ```

Target:
public int getNumWaiters() { return this.connectionPool.getNumWaiters(); }
Source:
private void store() throws IOException { byte[] serialized = state.toCbor().serialize(); System.out.println("Writing "+ serialized.length +" bytes to "+ statePath); Files.write( statePath, serialized, START StandardOpenOption.CREATE); END } can we do this atomically?

Target:
private synchronized void store() throws IOException { byte[] serialized = state.toCbor().serialize(); System.out.println("Writing "+ serialized.length +" bytes to "+ statePath); Files.write( statePath, serialized, StandardOpenOption.CREATE); }
Source:
private static void initFacets(@CheckForNull Fingerprint fingerprint){ if (fingerprint==null) return; START for (FingerprintFacet facet : fingerprint.facets) END facet._setOwner(fingerprint); } Please add curlies here

Target:
private static void initFacets(@CheckForNull Fingerprint fingerprint) { if (fingerprint == null) { return; } for (FingerprintFacet facet : fingerprint.facets) { facet._setOwner(fingerprint); } }
Source:
public Map<FactoryContainer, Attributes> getEnabledContainers() { Map<FactoryContainer, Attributes> map = new LinkedHashMap<>(); synchronized(_path) { for START (Entry<FactoryContainer, END Attributes> entry : getReversed(_path.entrySet())) { Attributes attr = entry.getValue(); if (attr.isEnabled()) { Attributes attrClone = new Attributes(attr); map.put(entry.getKey(), attrClone); } } } return map; } For clarity it's preferable: Map.Entry

Target:
public Map<FactoryContainer, Attributes> getEnabledContainers() { Map<FactoryContainer, Attributes> map = new LinkedHashMap<>(); synchronized(_path) { for (Map.Entry<FactoryContainer, Attributes> entry : getReversed(_path.entrySet())) { Attributes attr = entry.getValue(); if (attr.isEnabled()) { Attributes attrClone = new Attributes(attr); map.put(entry.getKey(), attrClone); } } } return map; }
Source:
private FileListCacheValue getFileList() { START readLock.lock(); END try { FileListCacheValue fileList = (FileListCacheValue) cache.get(fileListCacheKey); if (fileList == null) { fileList = new FileListCacheValue(); FileListCacheValue prev = (FileListCacheValue) cache.putIfAbsent(fileListCacheKey, fileList); if (prev != null) { fileList = prev; } } if (trace) log.trace("Refreshed file listing view"); return fileList; } finally { readLock.unlock(); } } I'm concerned about this lock.. it doesn't seem necessary as each operation invoking this private method is guarded already, and whenever a thread needs to acquire two locks I have an alarm bell ringing in my head.

Target:
private FileListCacheValue getFileList() { FileListCacheValue fileList = (FileListCacheValue) cache.get(fileListCacheKey); if (fileList == null) { fileList = new FileListCacheValue(); FileListCacheValue prev = (FileListCacheValue) cache.putIfAbsent(fileListCacheKey, fileList); if (prev != null) { fileList = prev; } } if (trace) log.trace("Refreshed file listing view"); return fileList; }
Source:
public long size() { build(); START return body.length() + partBoundary.length + partHeader.length; END } What happens when one of these `TypedOutput` instances return `-1` because they don't know their length?

Target:
public long size() { build(); if (body.length() > -1) { return body.length() + partBoundary.length + partHeader.length; } else { return -1; } }
Source:
public boolean canStreamToNextPipe() { START return super.canStreamToNextPipe() && !isCollectResults(); // when collectResults is false, streaming is not necessary or useful END } Performance gezien is het natuurlijk handiger eerst een boolean check te hebben en dan extra logica..

Target:
public boolean canStreamToNextPipe() { return !isCollectResults() && super.canStreamToNextPipe(); // when collectResults is false, streaming is not necessary or useful }
Source:
public FoundViewHolder getFoundViewHolder(JFieldRef idRef, AbstractJClass viewClass) { String idRefString = idRef.name(); FoundViewHolder foundViewHolder = (FoundViewHolder) foundHolders.get(idRefString); if (foundViewHolder == null) { foundViewHolder = createFoundViewAndIfNotNullBlock(idRef, viewClass); START foundHolders.put(idRefString, foundViewHolder); END } return foundViewHolder; } Where do you handle this now?

Target:
public FoundViewHolder getFoundViewHolder(JFieldRef idRef, AbstractJClass viewClass) { return getFoundViewHolder(idRef, viewClass, null); }
Source:
public void tearDown() { try { queryRunner.close(); } START finally { END queryRunner = null; } } `finally` is not really needed. If `close` throws the test will fail anyway and we won't care whether `queryRunner` is `null` or not.

Target:
public void tearDown() { queryRunner.close(); }
Source:
private CommitConfig(Config rc) { commitTemplatePath = rc.getString(ConfigConstants.CONFIG_COMMIT_SECTION, null, ConfigConstants.CONFIG_KEY_COMMIT_TEMPLATE); String i18nCommitEncoding = rc.getString( ConfigConstants.CONFIG_SECTION_I18N, null, ConfigConstants.CONFIG_KEY_COMMIT_ENCODING); if (i18nCommitEncoding != null) { START commitMessageEncoding = Charset.forName(i18nCommitEncoding); END } } What if this throws an exception? Should probably be mapped to a ConfigInvalidException, and the caller should report the error.

Target:
private CommitConfig(Config rc) { commitTemplatePath = rc.getString(ConfigConstants.CONFIG_COMMIT_SECTION, null, ConfigConstants.CONFIG_KEY_COMMIT_TEMPLATE); i18nCommitEncoding = rc.getString(ConfigConstants.CONFIG_SECTION_I18N, null, ConfigConstants.CONFIG_KEY_COMMIT_ENCODING); }
Source:
public int decompress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int maxOutputLength) throws MalformedInputException { START try { END Inflater inflater = new Inflater(true); inflater.setInput(input, inputOffset, inputLength); int resultLength = inflater.inflate(output, outputOffset, maxOutputLength); inflater.end(); return resultLength; } catch (DataFormatException e) { throw Throwables.propagate(e); } } What's broken (add some details in the commit message)? This is not very obvious.

Target:
public int decompress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int maxOutputLength) throws MalformedInputException { try { Inflater inflater = new Inflater(true); inflater.setInput(input, inputOffset, inputLength); int resultLength = inflater.inflate(output, outputOffset, maxOutputLength); inflater.end(); return resultLength; } catch (DataFormatException e) { throw new RuntimeException(e); } }
Source:
START public List<OutputLine> getLog() { END return this.log; } we should return an ImmutableList if we don't intend for users of this method to edit the list.

Target:
public List<OutputLine> getLog() { return new ArrayList<>(this.log); }
Source:
protected void doInit() { super.doInit(); if (!this.evaluationContextSet) { this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory()); } START Assert.state(this.closeStreamAfterSend ? this.isSingleUse : true, END "Single use connection needed with closeStreamAfterSend"); } `!this.closeStreamAfterSend || this.isSingleUse` ?

Target:
protected void doInit() { super.doInit(); if (!this.evaluationContextSet) { this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory()); } Assert.state(!this.closeStreamAfterSend || this.isSingleUse, "Single use connection needed with closeStreamAfterSend"); }
Source:
public ExtensionElementsConverter(XStream xStream, List<DMNExtensionRegister> extensionRegisters) { super(xStream); this.extensionRegisters = new ArrayList<DMNExtensionRegister>(); if(extensionRegisters != null && extensionRegisters.size() > 0) START this.extensionRegisters.addAll(extensionRegisters); END } I'm reworking this code in the context of the class, also to avoid potential NPE if the extensionRegisters field might have not been initialized, from the no-args constructor.

Target:
public ExtensionElementsConverter(XStream xStream, List<DMNExtensionRegister> extensionRegisters) { super(xStream); if ( !extensionRegisters.isEmpty() ) { this.extensionRegisters.addAll(extensionRegisters); } }
Source:
public void executeBatch(OperationsQueue operationsQueue) { START log.tracef( "Executing batch" ); END try { if ( GridDialects.hasFacet( getGridDialect(), BatchableGridDialect.class ) || GridDialects.hasFacet( getGridDialect(), GroupingByEntityDialect.class ) ) { super.executeBatch( operationsQueue ); } } catch ( TupleAlreadyExistsException taee ) { // TODO: Ideally, we should log the entity name + id here; For now we trust the datastore to provide this // information via the original exception; It'd require a fair bit of changes to obtain the entity name here // (we'd have to obtain the persister matching the given entity key metadata which in turn would require // access to the session factory which is not easily available here) throw log.mustNotInsertSameEntityTwice( taee.getMessage(), taee ); } } Maybe we should move that inside the `if` body, since we won't always execute the batch... ?

Target:
public void executeBatch(OperationsQueue operationsQueue) { try { if ( GridDialects.hasFacet( getGridDialect(), BatchableGridDialect.class ) || GridDialects.hasFacet( getGridDialect(), GroupingByEntityDialect.class ) ) { log.tracef( "Executing batch" ); super.executeBatch( operationsQueue ); } } catch ( TupleAlreadyExistsException taee ) { // TODO: Ideally, we should log the entity name + id here; For now we trust the datastore to provide this // information via the original exception; It'd require a fair bit of changes to obtain the entity name here // (we'd have to obtain the persister matching the given entity key metadata which in turn would require // access to the session factory which is not easily available here) throw log.mustNotInsertSameEntityTwice( taee.getMessage(), taee ); } }
Source:
public int hashCode() { START return (((startCommit.hashCode() * 31) + numbers.length) * 31) END + getNumber(); } nit-pick: startCommit.hashCode can just be xored/added in since it is well distributed

Target:
public int hashCode() { return ((startCommit.hashCode() + numbers.length) * 31) + getNumber(); }
Source:
START private void prepareAuthForBrokerCall() throws NoSuchAlgorithmException { END AuthenticationSettings.INSTANCE.setUseBroker(true); } can this function now throw NoSuchAlgorithmException

Target:
private void prepareAuthForBrokerCall() { AuthenticationSettings.INSTANCE.setUseBroker(true); }
Source:
public boolean isWrapperFor(Class<?> iface) { if (gridCoverage instanceof Wrapper) return ((Wrapper) gridCoverage).isWrapperFor(iface); START else if (iface.isInstance(gridCoverage)) return true; END else return false; } I woudl remove this else, if the gridCoverage is a wrapper and says "false" but iface is "GridCoverage2D" you want to fall back on the isInstance check anyways.

Target:
public boolean isWrapperFor(Class<?> iface) { if (gridCoverage instanceof Wrapper) { return ((Wrapper) gridCoverage).isWrapperFor(iface); } return iface.isInstance(gridCoverage); }
Source:
DataSegment uploadDataSegment( DataSegment segment, final int binaryVersion, final long size, final File compressedSegmentData, final String azurePath ) throws StorageException, IOException, URISyntaxException { azureStorage.uploadBlob(compressedSegmentData, config.getContainer(), azurePath); final DataSegment outSegment = segment .withSize(size) .withLoadSpec(this.makeLoadSpec(new URI(azurePath))) .withBinaryVersion(binaryVersion); START log.info("Deleting file [%s]", compressedSegmentData); END compressedSegmentData.delete(); return outSegment; } Would you change the log level to debug? it doesn't look worth to be the info level.

Target:
DataSegment uploadDataSegment( DataSegment segment, final int binaryVersion, final long size, final File compressedSegmentData, final String azurePath ) throws StorageException, IOException, URISyntaxException { azureStorage.uploadBlob(compressedSegmentData, config.getContainer(), azurePath); final DataSegment outSegment = segment .withSize(size) .withLoadSpec(this.makeLoadSpec(new URI(azurePath))) .withBinaryVersion(binaryVersion); log.debug("Deleting file [%s]", compressedSegmentData); compressedSegmentData.delete(); return outSegment; }
Source:
public EEFButtonLifecycleManager(EEFButtonDescription description, IVariableManager variableManager, IInterpreter interpreter, TransactionalEditingDomain editingDomain) { START super(description, variableManager, END interpreter, editingDomain); this.description = description; } not done

Target:
public EEFButtonLifecycleManager(EEFButtonDescription description, IVariableManager variableManager, IInterpreter interpreter, TransactionalEditingDomain editingDomain) { super(variableManager, interpreter, editingDomain); this.description = description; }
Source:
private static boolean isProbablyLog4jFormatterLogger(MethodInvocationTree mit, String formatString) { return mit.symbol().owner().type().is(ORG_APACHE_LOGGING_LOG4J_LOGGER) && START (!formatString.contains("{}") && formatString.contains("%")); END } useless parenthesis

Target:
private static boolean isProbablyLog4jFormatterLogger(MethodInvocationTree mit, String formatString) { return mit.symbol().owner().type().is(ORG_APACHE_LOGGING_LOG4J_LOGGER) && !formatString.contains("{}") && formatString.contains("%"); }
Source:
void setMarker(TextMarker marker, int length) { this.marker = marker; numSkipLines = length; if (checkAndUpdateArrows()) { upArrow.setHTML(PatchUtil.M.expandBefore(NUM_ROWS_TO_EXPAND)); downArrow.setHTML(PatchUtil.M.expandAfter(NUM_ROWS_TO_EXPAND)); } START skipNum.setText(PatchUtil.C.patchSkipRegion(Integer END .toString(length))); } PatchUtil.M

Target:
void setMarker(TextMarker marker, int length) { this.marker = marker; numSkipLines = length; if (checkAndUpdateArrows()) { upArrow.setHTML(PatchUtil.M.expandBefore(NUM_ROWS_TO_EXPAND)); downArrow.setHTML(PatchUtil.M.expandAfter(NUM_ROWS_TO_EXPAND)); } skipNum.setText(PatchUtil.M.patchSkipRegion(Integer .toString(length))); }
Source:
public ExtendedEmailPublisherContext(ExtendedEmailPublisher publisher, AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { this.publisher = publisher; this.run = build; this.workspace = build.getWorkspace(); this.launcher = launcher; START this.listener = listener; END } Wouldn't be better to directly call the new constructor? Just for easier maintenance in the future.

Target:
public ExtendedEmailPublisherContext(ExtendedEmailPublisher publisher, AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { this(publisher, build, build.getWorkspace(), launcher, listener); }
Source:
public void testWrongFormatNumber() throws Exception { NumberCellEditor editor; editor = new NumberCellEditor(shell, Integer.class); //empty string editor.setValue(" "); editor.getValue(); assertNull(editor.getValue() ); //not parsable number editor.setValue("aa"); START editor.getValue(); END assertNull(editor.getValue() ); } this might be obsolete if `isValueValid`is implemented...

Target:
public void testWrongFormatNumber() throws Exception { NumberCellEditor editor; editor = new NumberCellEditor(shell, Integer.class); // empty string editor.getValue(); assertNull(editor.getValue()); // not parsable number editor.setValue("aa"); editor.getValue(); assertNull(editor.getValue()); }
Source:
public void onReloadPlugin(Plugin oldPlugin, Plugin newPlugin) { if (hasAvatarProvider(newPlugin)) { avatarSupport = true; START } else { if (avatarSupport END && hasAvatarProvider(oldPlugin)) { avatarSupport = false; } } } else if on one line.

Target:
public void onReloadPlugin(Plugin oldPlugin, Plugin newPlugin) { update(); }
Source:
START public Class getRealClass() { END return clazz; } `Class<?>`

Target:
public Class<?> getRealClass() { return clazz; }
Source:
private String read(String resourcePath) throws IOException { InputStream is = getClass().getResourceAsStream(resourcePath); try { return Util.read(is); } finally { if (is != null) { START is.close(); END } } } I suppose close() is already done in Util.read(..)

Target:
private String read(String resourcePath) throws IOException { InputStream is = getClass().getResourceAsStream(resourcePath); return Util.read(is); }
Source:
public static String getModelFileWithGAV(ReleaseId releaseId) { START ReleaseIdImpl releaseIdImpl = (ReleaseIdImpl) releaseId; END return Paths.get(MODEL_FILE_DIRECTORY, releaseIdImpl.getGroupId(), releaseIdImpl.getArtifactId(), releaseIdImpl.getVersion(), MODEL_FILE_NAME).toString(); } I don't see why I need this cast. The group and artifact IDs are accessible even at interface level. Also the version is accessible, but I don't think you should add it here: this is for multimodule project compilaton and afaik you cannot have different modules with same GA and different version in the same project.

Target:
public static String getModelFileWithGAV(ReleaseId releaseId) { return Paths.get(MODEL_FILE_DIRECTORY, releaseId.getGroupId(), releaseId.getArtifactId(), MODEL_FILE_NAME).toString(); }
Source:
void removeConnection(String connectionId) { START if (availableConnections.remove(connectionId)) { END availableCount--; } poolCount--; } This operation can be O(n), though the size of the list may be small. Making sense to use a set instead?

Target:
void removeConnection(String connectionId) { availableConnections.remove(connectionId); poolCount--; }
Source:
private Map<Long, ISegmentAspect> getAspectsFromColumnsId(List<Long> desiredColumns) { Map<Long, ISegmentAspect> aspects = new LinkedHashMap<>(); if START (!desiredColumns.isEmpty()) END { for (Long columnsId : desiredColumns) { ISegmentAspect segmentAspect = fAspectMap.get(columnsId); if (segmentAspect != null) { aspects.put(columnsId, segmentAspect); } } return aspects; } return fAspectMap; } return before instantiating the map?

Target:
private Map<Long, ISegmentAspect> getAspectsFromColumnsId(List<Long> desiredColumns) { if (!desiredColumns.isEmpty()) { Map<Long, ISegmentAspect> aspects = new LinkedHashMap<>(); for (Long columnsId : desiredColumns) { ISegmentAspect segmentAspect = fAspectMap.get(columnsId); if (segmentAspect != null) { aspects.put(columnsId, segmentAspect); } } return aspects; } return fAspectMap; }
Source:
static boolean isValidMining(ICodeMining mining) { START return Objects.nonNull(mining) && mining.getLabel() != null && !mining.getLabel().isEmpty(); END } Why Objects.nonNull instead of != null?

Target:
static boolean isValidMining(ICodeMining mining) { return mining != null && mining.getLabel() != null && !mining.getLabel().isEmpty(); }
Source:
public void addInput(Page page) { verify(probe == null); probe = page; probePosition = 0; joinAddresses = null; START joinAddressIndex = 0; END } `-1` would be more correct. AFAIC you can skip this.

Target:
public void addInput(Page page) { verify(probe == null); probe = page; probePosition = 0; joinAddresses = null; }
Source:
public DescriptorImpl() { super(ThrottleJobProperty.class); synchronized(propertiesByCategoryLock) { load(); // Explictly drop queue items loaded from 1.8.1 version if (!propertiesByCategory.isEmpty()) { propertiesByCategory = new HashMap<String,Map<ThrottleJobProperty,Void>>(); save(); // Save the configuration to remove obsolete data } START } END } Simpler to just rename the field. Then XStream will discard the old data automatically.

Target:
public DescriptorImpl() { super(ThrottleJobProperty.class); synchronized(propertiesByCategoryLock) { load(); // Explictly handle the persisted data from the version 1.8.1 if (propertiesByCategory == null) { propertiesByCategory = new HashMap<String,Map<ThrottleJobProperty,Void>>(); } if (!propertiesByCategory.isEmpty()) { propertiesByCategory.clear(); save(); // Save the configuration to remove obsolete data } } }
Source:
public String toString() { // Since the static data arrives from external source it's not guarenteed not to be null so a null check is // mandatory in order to avoid NPE when invoking toString by the logger String domainName = staticData.getName() == null ? "null" : staticData.getName(); START String domainId = staticData.getId() == null ? "null" : staticData.getId().toString(); END return "StorageDomain[" + domainName + ", " + domainId + "]"; } you don't need this. the "+" operator does this for you.

Target:
public String toString() { // Since the static data arrives from external source it's not guarenteed not to be null so a null check is // mandatory in order to avoid NPE when invoking toString by the logger String domainName = staticData == null ? "null" : staticData.getName(); Guid domainId = staticData == null ? null : staticData.getId(); return "StorageDomain[" + domainName + ", " + domainId + "]"; }
Source:
Predicate<Entry<Key,Value>> getScanPredicate() { final Range range = getRange(); START return input -> { if (range != null && !range.contains(input.getKey())) return false; return true; }; END } Can this be simplified to: ```java return input -> range == null || range.contains(input.getKey()); ```

Target:
Predicate<Entry<Key,Value>> getScanPredicate() { final Range range = getRange(); return input -> range == null || range.contains(input.getKey()); }
Source:
public AlluxioHiveMetastore(TableMasterClient client) { START requireNonNull(client, "client is null"); END this.client = client; } nit ```java this.client = requireNonNull(client, "client is null");

Target:
public AlluxioHiveMetastore(TableMasterClient client) { this.client = requireNonNull(client, "client is null"); }
Source:
private void addWorkPackageCriteria() { if (isWorkPackageSpecified()) { ArtifactId workPackArt = atsApi.getQueryService().getArtifactOrSentinel(workPackageId); if (isColorTeamMatch(workPackArt)) { START if (workPackArt.isValid()) END { queryAnd(AtsAttributeTypes.WorkPackageReference, workPackArt.getIdString()); } } } } Should this be above "isColorTeamMatch"? For example, on line #755.

Target:
private void addWorkPackageCriteria() { if (isWorkPackageSpecified()) { ArtifactId workPackArt = atsApi.getQueryService().getArtifactOrSentinel(workPackageId); if (workPackArt.isValid()) { if (isColorTeamMatch(workPackArt)) { queryAnd(AtsAttributeTypes.WorkPackageReference, workPackArt.getIdString()); } } } }
Source:
private void sendToSocket(Socket socket, String cmdString) throws IOException { // remove spaces at beginning and end and replace double spaces in // string with single space byte[] sendBytes = ("A" + cmdString.trim().replaceAll("\\s+", " ") + "\n").getBytes(); START socket.getInputStream().skip(tcpSocket.getInputStream().available()); END socket.getOutputStream().write(sendBytes); socket.getOutputStream().flush(); AstericsErrorHandling.instance.reportInfo(this, "IRTrans sent data: " + cmdString); } you directly use the member variable tcpSocket, but shouldnt it be the parameter socket?

Target:
private void sendToSocket(Socket socket, String cmdString) throws IOException { // remove spaces at beginning and end and replace double spaces in // string with single space byte[] sendBytes = ("A" + cmdString.trim().replaceAll("\\s+", " ") + "\n").getBytes(); socket.getInputStream().skip(socket.getInputStream().available()); socket.getOutputStream().write(sendBytes); socket.getOutputStream().flush(); AstericsErrorHandling.instance.reportInfo(this, "IRTrans sent data: " + cmdString); }
Source:
public int hashCode() { START return getClass().hashCode(); END } can you explain why this is necessary?

Target:
public int hashCode() { return 1; }
Source:
private void reset() { START setId( next = NO_ID ); END } i do not think we need to save this line better make it more readable

Target:
private void reset() { next = NO_ID; setId( NO_ID ); }
Source:
public String getActualDowntime() { START return (actualDowntime == null) ? "(N/A)" : actualDowntime.toString() + "ms"; END } so now you can drop the "toString()"

Target:
public String getActualDowntime() { return (actualDowntime == null) ? "(N/A)" : actualDowntime + "ms"; }
Source:
String resolveTemplatePath(final Context context, final Writer writer, final RenderParams params, final String argument) { if (argument.contains("/")) { START END }else{ return (params.live) ? "/live/" + argument + "." + EXTENSION : "/working/" + argument + "." + EXTENSION; } } @wezell , missing return statement... This is breaking when compiling the code

Target:
String resolveTemplatePath(final Context context, final Writer writer, final RenderParams params, final String argument) { return (params.live) ? "/live/" + argument + "." + EXTENSION : "/working/" + argument + "." + EXTENSION; }
Source:
public DispoConfig findDispoConfig(DispoProgram program) { START ArtifactReadable config = END getQuery().fromBranch(program.getUuid()).andNameEquals("Program Config").getResults().getOneOrNull(); if (config == null) { DispoUtil.getDefaultConfig(); } return DispoUtil.configArtToConfigData(new DispoConfigArtifact(config)); } andNameEquals is un-needed and probably undesired incase name ever changes

Target:
public DispoConfig findDispoConfig(DispoProgram program) { ArtifactReadable config = getQuery().fromBranch(program.getUuid()).andNameEquals("Program Config").getResults().getOneOrNull(); if (config == null) { return DispoUtil.getDefaultConfig(); } return DispoUtil.configArtToConfigData(new DispoConfigArtifact(config)); }
Source:
public boolean hasMatchingOpSig(String name, JavaOperationSigMask mask) { // Indexing on signatures optimises this type of request for (Entry<JavaOperationSignature, Set<String>> entry : operations.entrySet()) { if (mask.covers(entry.getKey())) { START if (operations.get(entry.getKey()).contains(name)) { END return true; } } } return false; } This is wrong, should be `entry.getValue()`

Target:
public boolean hasMatchingOpSig(String name, JavaOperationSigMask mask) { // Indexing on signatures optimises this type of request for (Entry<JavaOperationSignature, Set<String>> entry : operations.entrySet()) { if (mask.covers(entry.getKey())) { if (entry.getValue().contains(name)) { return true; } } } return false; }
Source:
START IonSqlQueryBuilder(TypeManager typeManager) END { this.typeManager = requireNonNull(typeManager, "typeManager is null"); } Make these methods public since they are part of the public API of the class. If we want to restrict access to the class, we would make the class itself package private.

Target:
public IonSqlQueryBuilder(TypeManager typeManager) { this.typeManager = requireNonNull(typeManager, "typeManager is null"); }