auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void saveContainer(String id) { HashMap<String, String> map = new HashMap<>(); //setting the node id in case it exists on graph START Optional.ofNullable(canvasHandler.getGraphIndex().get(id)).ifPresent(node -> { END map.put(DEFAULT_NODE_ID, id); map.put(svgNodeId, id); }); context.saveGroup(map); } In this case, `Optional` doesn't really give you anything. A simple null check does the exact same thing, doesn't allocate a new object on the heap, and doesn't require a lambda. Also, this seems much better readable: String node = canvasHandler.getGraphIndex().get(id); if (canvasHandler.getGraphIndex().get(id) == null) { context.saveGroup(Collections.emptyMap()); } else { HashMap<String, String> map = new HashMap<>(2); map.put(DEFAULT_NODE_ID, id); map.put(svgNodeId, id); context.saveGroup(map); } Overall, this is also much more efficient that the original.

Target:
public void saveContainer(String id) { HashMap<String, String> map = new HashMap<>(); //setting the node id in case it exists on graph if (canvasHandler.getGraphIndex().get(id) != null) { map.put(DEFAULT_NODE_ID, id); map.put(svgNodeId, id); } context.saveGroup(map); }
Source:
protected void executeQueryCommand() { START getQueryReturnValue().setReturnValue(DbFacade.getInstance() END .getGlusterVolumeDao() .getById(getParameters().getVolumeId())); } please extract method : protected GlusterVolumeInfoDao getGlusterVolumeInfoDao() The reason for doing this, is so you will be able to write a test using mockito (and not pockermock / static mocking) for this query.

Target:
protected void executeQueryCommand() { getQueryReturnValue().setReturnValue(getGlusterVolumeDao().getById(getParameters().getVolumeId())); }
Source:
public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); START Prefs.crashedBeforeActivityCreated(false); END ActivityUtil.requestFullUserOrientation(this); setTheme(); removeSplashBackground(); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } forceOverflowMenuIcon(this); } If I'm understanding this patch correctly, the idea is that if we've reached this point, we're not in an infinite crash loop -- is that right?

Target:
public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityUtil.requestFullUserOrientation(this); setTheme(); removeSplashBackground(); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } forceOverflowMenuIcon(this); }
Source:
void shareFreeList(final BlockRevQueue q) { START q.shareFreeList(pending); END } I would probably implement this the other way around. Since pending is "this" (well, the backing store) we should do: pending.shareFreeList(q); to mirror the intent of the caller of invoking this.shareFreeList(q). Its a subtle issue about how we are discarding a potentially large free list from the bottom of the stack by pushing down an empty free list from the top of the stack. Weird, I know. But at least mirror the caller's intent.

Target:
void shareFreeList(final BlockRevQueue q) { pending.shareFreeList(q); }
Source:
public static boolean isDomainSocketSupported(WorkerNetAddress workerNetAddress) { START boolean isDomainSocketSupported = !workerNetAddress.getDomainSocketPath().isEmpty(); END if (isDomainSocketSupported) { if (Configuration.getBoolean(PropertyKey.WORKER_DATA_SERVER_DOMAIN_SOCKET_AS_UUID)) { isDomainSocketSupported = FileUtils.exists(workerNetAddress.getDomainSocketPath()); } else { isDomainSocketSupported = workerNetAddress.getHost().equals(NetworkAddressUtils.getClientHostName()); } } return isDomainSocketSupported && CHANNEL_TYPE == ChannelType.EPOLL; } we could simplify this by immediately returning `false` if `workerNetAddress.getDomainSocketPath().isEmpty()`

Target:
public static boolean isDomainSocketSupported(WorkerNetAddress workerNetAddress) { if (workerNetAddress.getDomainSocketPath().isEmpty() || CHANNEL_TYPE != ChannelType.EPOLL) { return false; } if (Configuration.getBoolean(PropertyKey.WORKER_DATA_SERVER_DOMAIN_SOCKET_AS_UUID)) { return FileUtils.exists(workerNetAddress.getDomainSocketPath()); } else { return workerNetAddress.getHost().equals(NetworkAddressUtils.getClientHostName()); } }
Source:
public static GrpcDataWriter create(FileSystemContext context, WorkerNetAddress address, long id, long length, RequestType type, OutStreamOptions options) throws IOException { long chunkSize = Configuration.getBytes(PropertyKey.USER_NETWORK_WRITER_CHUNK_SIZE_BYTES); BlockWorkerClient grpcClient = context.acquireBlockWorkerClient(address); try { return new GrpcDataWriter(context, address, id, length, chunkSize, type, options, grpcClient); } catch (Exception e) { // Close the client before releasing in order to get it removed from the pool. START grpcClient.close(); END context.releaseBlockWorkerClient(address, grpcClient); throw e; } } Is there a way to tell that the gRPC channel is in a bad state without having to manually close it?

Target:
public static GrpcDataWriter create(FileSystemContext context, WorkerNetAddress address, long id, long length, RequestType type, OutStreamOptions options) throws IOException { long chunkSize = Configuration.getBytes(PropertyKey.USER_NETWORK_WRITER_CHUNK_SIZE_BYTES); BlockWorkerClient grpcClient = context.acquireBlockWorkerClient(address); try { return new GrpcDataWriter(context, address, id, length, chunkSize, type, options, grpcClient); } catch (Exception e) { context.releaseBlockWorkerClient(address, grpcClient); throw e; } }
Source:
public static RowMapperFactory of(Type type, RowMapper<?> mapper) { START return (t, ctx) -> t == type END ? Optional.of(mapper) : Optional.empty(); } Better to use `t.equals(type)` so parameterized types can satisfy test.

Target:
public static RowMapperFactory of(Type type, RowMapper<?> mapper) { return (t, ctx) -> t.equals(type) ? Optional.of(mapper) : Optional.empty(); }
Source:
private void updateQosChangeability() { START getQosModel().setIsChangable(getQosOverridden().getEntity() && (!getIsToSync().getIsChangable() || getIsToSync().getEntity())); END } I would check getQosOverridden().getIsChangeable() instead of (!getIsToSync().getIsChangable() || getIsToSync().getEntity()) but as you wish...

Target:
private void updateQosChangeability() { getQosModel().setIsChangable(getQosOverridden().getEntity() && getQosOverridden().getIsChangable()); }
Source:
public boolean isRelevant() { START if (!jenkins.hasPermission(Jenkins.RUN_SCRIPTS))) { END return false; } if (rule.getMasterKillSwitch()) { return true; // always relevant if it is enabled. } return jenkins.isUseSecurity() // if security is off, there's no point && (jenkins.getComputers().length>1 // if there's no slave, || !jenkins.clouds.isEmpty() // and no clouds, likewise this is pointless || Relevance.fromExtension() // unless a plugin thinks otherwise ) ; } :bug: uncompilable extra `)`

Target:
public boolean isRelevant() { return jenkins.hasPermission(Jenkins.RUN_SCRIPTS) && jenkins.isUseSecurity(); }
Source:
public final void validateNullUser() { final AuthKeys authKeys = new AuthKeys(); final String user = null; START final String password = "password"; END authKeys.authenticate(user, password); } avoid one time variables, see https://github.com/tpc2/qulice/wiki/mistakes#one-time-variables

Target:
public final void validateNullUser() throws Exception { final AuthKeys authKeys = new AuthKeys(); authKeys.authenticate(null, "password"); }
Source:
public int getRackId() { if (rackId == null) { START throw new IllegalStateException("rackId not defined for the data node " + hostname + ":" + port); END } return rackId; } `IllegalStateException` is actually thrown (not `IllegalArgument`).

Target:
public long getRackId() { return rackId; }
Source:
START public Collection<String> getProductSearchName() { END if (aias != null) { return ActionableItems.getNames(aias); } return Collections.emptyList(); } Interesting that this method will handle nulls for aias but performSearch would NPE. This was exposed in a change to the test for this class.

Target:
public Collection<String> getProductSearchName() { return ActionableItems.getNames(aias); }
Source:
protected boolean validateScreenDescriptor() { START if (screenBackgroundColor >= screenColors) { END // Not in the specification, but here the background color would refer to a color // index not within the bounds of the Global Color Table. return false; } return true; } Please simplify this.

Target:
protected boolean validateScreenDescriptor() { // Not in the specification, but check whether the background color index is within // the bounds of the Global Color Table just to be sure. return screenBackgroundColor < screenColors; }
Source:
public void testEmptyKeyDefaults() { for (PropertyKey key : PropertyKey.defaultKeys()) { START assertNotEquals(key.getDefaultValue(), "", String.format( END "Property keys cannot have a default value of \"\". Offending key: %s", key.getName())); } } could we also check that the default value is not `null`?

Target:
public void testEmptyKeyDefaults() { for (PropertyKey key : PropertyKey.defaultKeys()) { assertNotEquals(String.format( "Property keys cannot have a default value of \"\". Offending key: %s", key.getName()), key.getDefaultValue(), ""); } }
Source:
START private boolean shouldAdd(String dimName) END { final boolean belowThreshold = pQueue.size() < this.threshold; final boolean belowMax = belowThreshold || this.comparator.compare(pQueue.peek().getTopNMetricVal(), dimName) < 0; return belowMax && comparator.compare(dimName, previousStop) > 0; } Is it possible to avoid copy pasting the code and reuse the code from the other topnresultbuilders?

Target:
private boolean shouldAdd(String dimName) { final boolean belowThreshold = pQueue.size() < threshold; final boolean belowMax = belowThreshold || comparator.compare(pQueue.peek().getTopNMetricVal(), dimName) < 0; // Only add if dimName is after previousStop return belowMax && (previousStop == null || comparator.compare(dimName, previousStop) > 0); }
Source:
public int hashCode() { int result = Objects.hash(entity); START result = 31 * result + Arrays.hashCode(values); END return result; } Any reason why this doesn't use Objects.hash()? Because of the 31 instead of 37? I am ok for changing the hashcode formula here as long as it doesn't violate the equals contract.

Target:
public int hashCode() { return Objects.hash(entity, Arrays.hashCode(values)); }
Source:
Store getStore(PartitionId id) throws StoreException { BlobStore store = stores.get(id); if (store == null) { START throw new StoreException("Could not find partition " + id + " on disk " + disk, END StoreErrorCodes.Partition_Not_Found); } if (!store.isStarted()) { throw new StoreException("Store for partition " + id + " on disk " + disk + " has not been started successfully", StoreErrorCodes.Store_Not_Started); } return store; } don't need to throw exceptions - just return `null`.

Target:
Store getStore(PartitionId id) { BlobStore store = stores.get(id); return (store != null && store.isStarted()) ? store : null; }
Source:
public static int getValue(String text) { if (text == null || text.isEmpty() || text.equals("build")) { //$NON-NLS-1$ return BUILD; } if (text.equals("codan")) { //$NON-NLS-1$ return CODAN; } START if (text.equals("build,codan")) { //$NON-NLS-1$ END return BUILD_AND_CODAN; } throw new IllegalArgumentException("Unknown context value: " + text); //$NON-NLS-1$ } This is apparently out of date.

Target:
public static int getValue(String text) { if (text == null || text.isEmpty() || text.equals("build")) { //$NON-NLS-1$ return BUILD; } if (text.equals("codan")) { //$NON-NLS-1$ return CODAN; } throw new IllegalArgumentException("Unknown context value: " + text); //$NON-NLS-1$ }
Source:
public String getToolTipText(Object element) { if (element instanceof TestCaseElement) { String ignoreReason= ((TestCaseElement) element).getIgnoreReason(); if (ignoreReason != null && START ignoreReason.length() > 0) { END return ignoreReason; } } return super.getToolTipText(element); } !ignoreReason.isEmpty() can be used

Target:
public String getToolTipText(Object element) { if (element instanceof TestCaseElement) { String ignoreReason= ((TestCaseElement) element).getIgnoreReason(); if (ignoreReason != null && !ignoreReason.isEmpty()) { return ignoreReason; } } return super.getToolTipText(element); }
Source:
public String getResourceContent(String name) throws IOException { if (getEngineContext() != null) { try (InputStream is = getResourceAsStream(name)) { if (is == null) { // Resources should always be encoded as UTF-8, to reduce the dependency on the system encoding return FileUtils.readFileToString(new File(name), DEFAULT_ENCODING); } return IOUtils.toString(is, DEFAULT_ENCODING); START } catch (Exception e) { END } } return null; } There is no reason to catch all exceptions like this.

Target:
public String getResourceContent(String name) throws IOException { if (getEngineContext() != null) { try (InputStream is = getResourceAsStream(name)) { if (is != null) { return IOUtils.toString(is, DEFAULT_ENCODING); } } } // Resources should always be encoded as UTF-8, to reduce the dependency on the system encoding return FileUtils.readFileToString(new File(name), DEFAULT_ENCODING); }
Source:
START public void testGetLevel() throws Exception { END assertEquals(building.getLevel(0), levelA); assertNotSame(building.getLevel(0), levelB); } Dodaj testowanie drugiego Levelu. Moim zdaniem ten test sfailuje dla levelu 1.

Target:
public void testGetLevel() throws Exception { assertEquals(building.getLevel(0), levelA); assertNotSame(building.getLevel(0), levelB); assertEquals(building.getLevel(1), levelB); assertNotSame(building.getLevel(1), levelA); }
Source:
public Optional<Shape> getShapeAt(final double x, final double y) { START return null; END } I know this is just test class, but this is what `Optinal.empty()` is for - avoiding necessity to sometimes use null ;-)

Target:
public Optional<Shape> getShapeAt(final double x, final double y) { return Optional.empty(); }
Source:
public void setElement( IAdaptable element ) { START if (element instanceof ICLineBreakpoint) { END fElement = new CBreakpointContext((ICBreakpoint)element, null); } else { fElement = element; } } I think we should check for ICBreakpoint instead to include any other kind of breakpoints that uses this properties page. For example a watchpoint or an eventBreakpoing can trigger this code.

Target:
public void setElement( IAdaptable element ) { if (element instanceof ICBreakpoint) { fElement = new CBreakpointContext((ICBreakpoint)element, null); } else { fElement = element; } }
Source:
private boolean TxBegin() { START if (!TransactionalContext.isInTransaction()) { END corfuRuntime.getObjectsView() .TXBuild() .type(TransactionType.OPTIMISTIC) .build().begin(); return true; } return false; } I don't like the Idea of managing transactions inside table class

Target:
private boolean TxBegin() { if (TransactionalContext.isInTransaction()) { return false; } corfuRuntime.getObjectsView() .TXBuild() .type(TransactionType.OPTIMISTIC) .build() .begin(); return true; }
Source:
public UUID send(Iterable<? extends MimeMessage> messages, Session session) throws MessagingException { MailListener listener = getListener("memory"); UUID batchID = sendAsynchronously(messages, session, listener); waitTillSent(Long.MAX_VALUE); Iterator<MailStatus> errors = listener.getErrors(); if (errors.hasNext()) { throw new MessagingException( START String.format("Failed to send mail message [%s] ", errors.next().getException())); END } return batchID; } This is not good enough. How do we know which emails failed to be sent? In addition you're sending an exception only for the frist error... what about all the rest?

Target:
public UUID send(Iterable<? extends MimeMessage> messages, Session session) throws MessagingException { MailListener listener = getListener("memory"); UUID batchID = sendAsynchronously(messages, session, listener); waitTillSent(Long.MAX_VALUE); return batchID; }
Source:
public java.io.File toLocalFile(int options, IProgressMonitor monitor) throws CoreException { SubMonitor START subMonitor = END SubMonitor.convert(monitor); //caching is the only recognized option if (options != EFS.CACHE) return null; return FileCache.getCache().cache(this, subMonitor); } No submonitor is needed in this method. The original monitor can be passed to a single method call as is.

Target:
public java.io.File toLocalFile(int options, IProgressMonitor monitor) throws CoreException { //caching is the only recognized option if (options != EFS.CACHE) return null; return FileCache.getCache().cache(this, monitor); }
Source:
public NewCommentsConsumer(JiraEndpoint endpoint, Processor processor) { super(endpoint, processor); START LOG.info("JIRA NewCommentsConsumer: Indexing current issue comments."); END getComments(); } We should move such tasks to doStart and not in constructors

Target:
public NewCommentsConsumer(JiraEndpoint endpoint, Processor processor) { super(endpoint, processor); }
Source:
private boolean isCatalogAccessible(String catalogName) { return accessControl.filterCatalogs(session.getIdentity(), ImmutableSet.of(catalogName)).contains(catalogName) START && metadata.catalogExists(session, catalogName); END } i would reverse -- check access control only for existing catalogs. I think an access control impl may have problems for non-existing catalogs. (here & below)

Target:
private boolean isCatalogAccessible(String catalogName) { return metadata.catalogExists(session, catalogName) && accessControl.filterCatalogs(session.getIdentity(), ImmutableSet.of(catalogName)).contains(catalogName); }
Source:
public static void invalidateThumbnail(PublishedInfo layer) { //Allow a bit of leeway, to support GetMap composer format //(in case of getMap returning before put layer) START Date d = new Date(new Date().getTime()-1000); END if (Metadata.modified(layer) != null && d.before(Metadata.modified(layer))) { return; } Metadata.map(layer).remove(Metadata.THUMBNAIL); } use `System.currentTimeMillis()` and avoid creating Date objects. Not sure why we're using Date objects anyway (for Metadata) but I guess we're stuck now. `Long` would be preferable.

Target:
public static void invalidateThumbnail(PublishedInfo layer) { Metadata.map(layer).remove(Metadata.THUMBNAIL); }
Source:
public void setScrollView(@Nullable ObservableWebView webView) { this.webView = webView; if (this.webView != null) { START this.webView.clearAllListeners(); END this.webView.addOnScrollChangeListener(this); this.webView.addOnDownMotionEventListener(this); this.webView.addOnUpOrCancelMotionEventListener(this); } } I think this should clear any previous webView's listeners, not the current one.

Target:
public void setScrollView(@Nullable ObservableWebView webView) { if (this.webView != null) { this.webView.clearAllListeners(); } this.webView = webView; if (this.webView != null) { this.webView.addOnScrollChangeListener(this); this.webView.addOnDownMotionEventListener(this); this.webView.addOnUpOrCancelMotionEventListener(this); } }
Source:
private void verifyFetchedLog(List<String> logs, String[] expectedLogs) { StringBuilder stringBuilder = new StringBuilder(); for (String log : logs) { stringBuilder.append(log); } String accumulatedLogs = stringBuilder.toString(); for (String expectedLog : expectedLogs) { START LOG.error("Checking match for " + expectedLog); END assertTrue(accumulatedLogs.contains(expectedLog)); } } Can be info log.

Target:
private void verifyFetchedLog(List<String> logs, String[] expectedLogs) { StringBuilder stringBuilder = new StringBuilder(); for (String log : logs) { stringBuilder.append(log); } String accumulatedLogs = stringBuilder.toString(); for (String expectedLog : expectedLogs) { LOG.info("Checking match for " + expectedLog); assertTrue(accumulatedLogs.contains(expectedLog)); } }
Source:
private String uriWithoutExtension(String requestUri) { int suffixStart = requestUri.lastIndexOf("."); if (suffixStart >= 0) { return requestUri.substring(0, suffixStart); } START return null; END } If we can't find an extension, shouldn't we just return `requestUri`?

Target:
private String uriWithoutExtension(String requestUri) { int suffixStart = requestUri.lastIndexOf("."); if (suffixStart >= 0) { return requestUri.substring(0, suffixStart); } return requestUri; }
Source:
private static URL deploymentStaticOne() throws Throwable { START System.out.println("deploymentStatic"); END return new URL("http://blah.com/static"); } Remove this

Target:
private static URL deploymentStaticOne() throws Throwable { return new URL("http://blah.com/static"); }
Source:
public void createAndDropViewTest() throws DatabaseEngineException { test5Columns(); try { engine.dropView("VN"); } catch (final Throwable a) { START } END engine.executeUpdate( createView("VN").as(select(all()).from(table("TEST"))) ); engine.dropView("VN"); } I know this was already like this, but it is weird we are dropping the view before creating. If the goal is to assert that it throws an exception, then we should assert on it, otherwise this is not doing anything.

Target:
public void createAndDropViewTest() throws DatabaseEngineException { test5Columns(); engine.executeUpdate( createView("VN").as(select(all()).from(table("TEST"))) ); engine.dropView("VN"); }
Source:
START private void ensureIndexes() { END storageStrategy.ensureIndexes(template.eventCollection(), template.snapshotCollection()); } Adjusting this to `private` will be a breaking change - please keep it `public`. Just replacing the `@PostConstruct` for an `@Deprecated` is sufficient I think.

Target:
public void ensureIndexes() { storageStrategy.ensureIndexes(template.eventCollection(), template.snapshotCollection()); }
Source:
public <T> ResourceOperations<T> getResourceOperations(Class<T> type) { START return (ResourceOperations<T>) (File.class.equals(type) ? DefaultFileOperations.INSTANCE : null); END } No need to return anything different than DefaultFileOperations.INSTANCE here

Target:
public <T> ResourceOperations<T> getResourceOperations(Class<T> type) { return (ResourceOperations<T>) DefaultFileOperations.INSTANCE; }
Source:
public REVERSE_DEBUG_ACTIONS_ENUM getOperation() { START String item = combo.getItem(combo.getSelectionIndex()); END return REVERSE_DEBUG_ACTIONS_ENUM.valueOf(item.toUpperCase()); } What string is this? Is it the one we defined in messages.properties? If so, this won't work when translated.

Target:
public REVERSE_DEBUG_ACTIONS_ENUM getOperation() { int index = combo.getSelectionIndex(); return REVERSE_DEBUG_ACTIONS_ENUM.getValue(index); }
Source:
public int fill(final FluidStack resource, final boolean doFill) { if (resource == null) return 0; if (resource.amount <= 0) return 0; START if (!matchesFilter(resource)) END return 0; int ret = super.fill(resource, doFill); if (ret != 0 && updateCallback != null) updateCallback.accept(this); return ret; } This is unnecessary, its called via canFillFluidType() in super.fill().

Target:
public int fill(final FluidStack resource, final boolean doFill) { if (resource == null) return 0; if (resource.amount <= 0) return 0; int ret = super.fill(resource, doFill); if (ret != 0 && updateCallback != null) updateCallback.accept(this); return ret; }
Source:
private ChannelPipelineFactory initChannelPipelineFactory() { ChannelPipelineFactory pipelineFactory; boolean enableCompression = compressionType.equalsIgnoreCase("deflate"); if (enableCompression || enableSsl || enableIpFilter) { pipelineFactory = new AdvancedChannelPipelineFactory( enableCompression, enableSsl, keystore, keystorePassword, keystoreType, enableIpFilter, patternRuleConfigDefinition); } else { START pipelineFactory = () -> Channels.pipeline(); END } return pipelineFactory; } This can be replaced by method reference, i.e. `pipelineFactory = Channels::pipeline`

Target:
private ChannelPipelineFactory initChannelPipelineFactory() { ChannelPipelineFactory pipelineFactory; boolean enableCompression = compressionType.equalsIgnoreCase("deflate"); if (enableCompression || enableSsl || enableIpFilter) { pipelineFactory = new AdvancedChannelPipelineFactory( enableCompression, enableSsl, keystore, keystorePassword, keystoreType, enableIpFilter, patternRuleConfigDefinition); } else { pipelineFactory = Channels::pipeline; } return pipelineFactory; }
Source:
public String getOpenPinName() { waitForElementByElement(pinTitle); String pinName = pinTitle.getText(); START return pinName; END } return the String in one line

Target:
public String getOpenPinName() { waitForElementByElement(pinTitle); return pinTitle.getText(); }
Source:
public IBuildServer getServer() { START if (parent != null) { END return parent.getServer(); } if (server != null && ((EObject) server).eIsProxy()) { InternalEObject oldServer = (InternalEObject) server; server = (IBuildServer) eResolveProxy(oldServer); if (server != oldServer) { if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.RESOLVE, BuildPackage.BUILD_PLAN__SERVER, oldServer, server)); } } } return server; } we shouldn't modify the @generated methods. I think you won't need this anyway based on what you are doing in merge()

Target:
public IBuildServer getServer() { if (server != null && ((EObject) server).eIsProxy()) { InternalEObject oldServer = (InternalEObject) server; server = (IBuildServer) eResolveProxy(oldServer); if (server != oldServer) { if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.RESOLVE, BuildPackage.BUILD_PLAN__SERVER, oldServer, server)); } } } return server; }
Source:
START public <T extends Object> boolean contains(AttributeDefinition<T> def) { END return contains(def.name()); } I don't think `<T extends Object>` is needed, `<T>` is enough.

Target:
public <T> boolean contains(AttributeDefinition<T> def) { return contains(def.name()); }
Source:
public boolean equals(Object o) { if(!(o instanceof MethodKey)) return false; MethodKey m = (MethodKey) o; if(m.k != k) return false; if(m.nArgs != nArgs) return false; START if(!m.method.equals(method)) return false; END return true; } `return m.method.equals(method);`, instead of this line and next?

Target:
public boolean equals(Object o) { if(!(o instanceof MethodKey)) return false; MethodKey m = (MethodKey) o; if(m.k != k) return false; if(m.nArgs != nArgs) return false; return m.method.equals(method)); }
Source:
private static int countExternalReferences(PDOMBinding binding) throws Exception { IPDOMIterator<PDOMName> extRefs = binding.getExternalReferences(); assertNotNull(extRefs); int count = 0; START for( ; extRefs.hasNext(); ++count) END extRefs.next(); return count; } Since incrementing count is the main purpose of this loop, it's better to rewrite the loop as: for (; extRefs.hasNext(); extRefs.next()) { ++count; }

Target:
private static int countExternalReferences(PDOMBinding binding) throws Exception { IPDOMIterator<PDOMName> extRefs = binding.getExternalReferences(); assertNotNull(extRefs); int count = 0; for( ; extRefs.hasNext(); extRefs.next()) ++count; return count; }
Source:
public void addCookie(Cookie cookie) { START this.cookies.add(new ZestCookie(cookie.getDomain(), cookie.getName(), cookie.getValue(), END cookie.getPath(), cookie.getExpiryDate(), cookie.getSecure())); } Could call the method `addCookie(String domain,....)` instead.

Target:
public void addCookie(Cookie cookie) { addCookie(cookie.getDomain(), cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getExpiryDate(), cookie.getSecure()); }
Source:
public void testJsonEmptyDiskDescription() throws IOException { START String jsonDescription = null; END jsonDescription = ImagesHandler.getJsonDiskDescription("DiskAlias", ""); assertTrue("Should be map of disk alias and disk description", jsonDescription.equals("{\"DiskDescription\":\"\",\"DiskAlias\":\"DiskAlias\"}")); } please just define on the next row.

Target:
public void testJsonEmptyDiskDescription() throws IOException { String jsonDescription = ImagesHandler.getJsonDiskDescription("DiskAlias", ""); assertTrue("Should be map of disk alias and disk description", jsonDescription.equals("{\"DiskDescription\":\"\",\"DiskAlias\":\"DiskAlias\"}")); }
Source:
public void MobileLogin_003_failedLoginWrongLogin() { MobileBasePageObject mobile = new MobileBasePageObject(driver); mobile.openHome(wikiURL); mobile.openRandomPage(); START System.out.println(credentials.userName12); END MobileSpecialUserLogin login = mobile.loginFailedDropDown(mobile.getTimeStamp(), mobile.getTimeStamp()); login.verifyWrongLoginErrorMessage(); } remove this line

Target:
public void MobileLogin_003_failedLoginWrongLogin() { MobileBasePageObject mobile = new MobileBasePageObject(driver); mobile.openHome(wikiURL); mobile.openRandomPage(); MobileSpecialUserLogin login = mobile.loginFailedDropDown(mobile.getTimeStamp(), mobile.getTimeStamp()); login.verifyWrongLoginErrorMessage(); }
Source:
private void validateStateOfWrittenEntry(long address, @Nonnull ILogData ld) { ILogData logData; try { START logData = read(address, defaultReadOptions); END } catch (TrimmedException te) { // We cannot know if the write went through or not throw new UnrecoverableCorfuError("We cannot determine state of an update because of a trim."); } if (!logData.equals(ld)){ throw new OverwriteException(OverwriteCause.DIFF_DATA); } } You can just use `read(long address)` here which also uses defaultReadOptions.

Target:
private void validateStateOfWrittenEntry(long address, @Nonnull ILogData ld) { ILogData logData; try { logData = read(address); } catch (TrimmedException te) { // We cannot know if the write went through or not throw new UnrecoverableCorfuError("We cannot determine state of an update because of a trim."); } if (!logData.equals(ld)){ throw new OverwriteException(OverwriteCause.DIFF_DATA); } }
Source:
public void testReparentingToGrandparent() { START RulesetModel child = rm.addRuleset("child", rootId, id1); END RulesetModel grandchild = rm.addRuleset("grandchild", id1, id2); assertEquals(id1, grandchild.getParentRulesetId()); rm.removeRuleset(id1); assertEquals(rootId, grandchild.getParentRulesetId()); } ```suggestion rm.addRuleset("child", rootId, id1); ``` `child` is unused

Target:
public void testReparentingToGrandparent() { rm.addRuleset("child", rootId, id1); RulesetModel grandchild = rm.addRuleset("grandchild", id1, id2); assertEquals(id1, grandchild.getParentRulesetId()); rm.removeRuleset(id1); assertEquals(rootId, grandchild.getParentRulesetId()); }
Source:
public void unsetMavenWorkspaceRepository(MavenWorkspaceRepository mavenWorkspaceRepository) { START this.mavenWorkspaceRepository = null; END } Isn't the correct thing: ```java if (this.mavenWorkspaceRepository == mavenWorkspaceRepository) { this.mavenWorkspaceRepository = null; } ``` to properly handle replacement?

Target:
public void unsetMavenWorkspaceRepository(MavenWorkspaceRepository mavenWorkspaceRepository) { if (this.mavenWorkspaceRepository == mavenWorkspaceRepository) { this.mavenWorkspaceRepository = null; } }
Source:
public void assertAuthentication(MockWebServer server) { START assertEquals(server.getRequestCount(), 2); END try { assertEquals(server.takeRequest().getRequestLine(), "POST /tokens HTTP/1.1"); } catch (InterruptedException e) { Throwables.propagate(e); } } You can't assert that the request count will be 2 in a base class like this. There are many mock tests that have more requests than that.

Target:
public void assertAuthentication(MockWebServer server) { assertTrue(server.getRequestCount() >= 1); try { assertEquals(server.takeRequest().getRequestLine(), "POST /tokens HTTP/1.1"); } catch (InterruptedException e) { Throwables.propagate(e); } }
Source:
void whenCreateLedger_thenSuccess() throws Exception { START END LedgerHandle lh = bk.createLedger(BookKeeper.DigestType.MAC, ledgerPassword); assertNotNull(lh); assertNotNull(lh.getId()); log.info("[I33] Ledge created: id=" + lh.getId()); } Again let's remove this blank lines.

Target:
void whenCreateLedger_thenSuccess() throws Exception { LedgerHandle lh = bk.createLedger(BookKeeper.DigestType.MAC, ledgerPassword); assertNotNull(lh); assertNotNull(lh.getId()); LOG.info("[I33] Ledge created: id=" + lh.getId()); }
Source:
public String toString() { START Map<String, Object> display = new ConcurrentHashMap<String, Object>(this.values); END display.remove(VALUES_KEY); return display.toString(); } HashMap is enough, here.

Target:
public String toString() { Map<String, Object> display = new HashMap<String, Object>(this.values); display.remove(VALUES_KEY); return display.toString(); }
Source:
public void setup() { openTSDBMessageFormatter = Mockito.mock(OpenTSDBMessageFormatter.class); writer = new TCollectorUDPWriter2(openTSDBMessageFormatter); outputWriter = Mockito.mock(Writer.class); result = Mockito.mock(Result.class); START server = ServerFixtures.dummyServer(); END } This instance variable can be inlined.

Target:
public void setup() { openTSDBMessageFormatter = Mockito.mock(OpenTSDBMessageFormatter.class); writer = new TCollectorUDPWriter2(openTSDBMessageFormatter); outputWriter = Mockito.mock(Writer.class); result = Mockito.mock(Result.class); }
Source:
void addRevisionType(Element anyMapping, Element anyMappingEnd, boolean isKey) { final Element revTypeProperty = MetadataTools.addProperty( anyMapping, verEntCfg.getRevisionTypePropName(), verEntCfg.getRevisionTypePropType(), true, isKey ); revTypeProperty.addAttribute( "type", "org.hibernate.envers.internal.entities.RevisionTypeType" ); // Add further columns to the aud table addAdditionalColumns( anyMappingEnd ); START } END The arguments being passed should also be proceeded and followed by a space. See line 173 as an example.

Target:
void addRevisionType(Element anyMapping, Element anyMappingEnd, boolean isKey) { final Element revTypeProperty = MetadataTools.addProperty( anyMapping, verEntCfg.getRevisionTypePropName(), verEntCfg.getRevisionTypePropType(), true, isKey ); revTypeProperty.addAttribute( "type", "org.hibernate.envers.internal.entities.RevisionTypeType" ); }
Source:
public void walk(Consumer<Node> consumer) { START treeIterable(TreeTraversal.PREORDER).forEach(consumer); END } Quite classy code!

Target:
public void walk(Consumer<Node> consumer) { walk(PREORDER, consumer); }
Source:
public void onStateReceived(int segmentId, boolean isLastChunk) { if (!isCancelled && isLastChunk) { boolean isCompleted = false; synchronized (segments) { START if (segments.contains((Object) segmentId)) { END finishedSegments.add((Integer) segmentId); if (finishedSegments.size() == segments.size()) { log.debugf("Finished receiving state for segments %s", segments); isCompleted = true; } } } if (isCompleted) { notifyCompletion(true); } } } why not implement in ```IntSet``` methods to avoid this casts and (un)boxing?

Target:
public void onStateReceived(int segmentId, boolean isLastChunk) { if (!isCancelled && isLastChunk) { boolean isCompleted = false; synchronized (segments) { if (segments.contains(segmentId)) { finishedSegments.add(segmentId); if (finishedSegments.size() == segments.size()) { log.debugf("Finished receiving state for segments %s", segments); isCompleted = true; } } } if (isCompleted) { notifyCompletion(true); } } }
Source:
public Matrix removeColumn(int j) { START return removeColumn(j, this.factory); END } Unnecessary `this`.

Target:
public Matrix removeColumn(int j) { return removeColumn(j, factory); }
Source:
void readLogFile() { START getDisplay().asyncExec(() -> END setContentDescription(Messages.LogView_readLog_loading)); fetchLogEntries().thenAccept(this::updateLogViewer); } This does not need to be async, or IF it should be async, it should have the same guard. But here we really don'T do anything bad, we can and should do this without asyncExec.

Target:
void readLogFile() { setContentDescription(Messages.LogView_readLog_loading); fetchLogEntries().thenAccept(this::updateLogViewer); }
Source:
public void triggerPoolMonitoringJob() { try { START poolMonitoringJob.cancel(true); END } catch (Throwable t) { log.debug("Exception cancelling existing job: {}", ExceptionUtils.getRootCauseMessage(t)); } poolMonitoringJob = schedulerService.scheduleWithFixedDelay( this::managePrestartedVmsInAllVmPools, 0, vmPoolMonitorIntervalInMinutes, TimeUnit.MINUTES); } (1) it seems like the code here won't function well when being executed by several threads simultaneously; and (2) are we sure the commands (run stateless vm in this case) behaves properly when their thread is interrupted? I think that maybe we should not cancel running tasks and trigger a new task only if we are sure that the previous one is canceled

Target:
public void triggerPoolMonitoringJob() { try { poolMonitoringJob.cancel(false); } catch (Throwable t) { log.debug("Exception cancelling existing job: {}", ExceptionUtils.getRootCauseMessage(t)); } poolMonitoringJob = schedulerService.scheduleWithFixedDelay( this::managePrestartedVmsInAllVmPools, 0, vmPoolMonitorIntervalInMinutes, TimeUnit.MINUTES); }
Source:
START public ITmfTrace getTrace() throws RuntimeException { END for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { if (trace.getResource().equals(getResource())) { return trace; } } return null; } Shouldn't receive a RuntimeException anymore?

Target:
public ITmfTrace getTrace() { for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { if (trace.getResource().equals(getResource())) { return trace; } } return null; }
Source:
private void assertAsSetContainsAll(MetricTarget... targets) { START assertContainsAll(asSet(targets), asList(targets)); END } Minor: I wouldn't static import these for clarity.

Target:
private void assertAsSetContainsAll(MetricTarget... targets) { assertContainsAll(MetricTarget.asSet(targets), asList(targets)); }
Source:
public void appendColumn( final BaseColumn column ) throws MoveColumnVetoException { final MetaData metaData = new BaseColumnSynchronizer.ColumnMetaDataImpl( column ); for ( int i = 0; i < synchronizers.size(); i++ ) { START final Synchronizer synchronizer = synchronizers.get( i ); END if ( synchronizer.handlesAppend( metaData ) ) { synchronizer.append( metaData ); break; } } eventBus.fireEvent( new AfterColumnInserted() ); } @manstis Any obscure reason to make this change? Seems like a slower iterator on a List.

Target:
public void appendColumn( final BaseColumn column ) throws MoveColumnVetoException { final MetaData metaData = new BaseColumnSynchronizer.ColumnMetaDataImpl( column ); for ( Synchronizer synchronizer : synchronizers ) { if ( synchronizer.handlesAppend( metaData ) ) { synchronizer.append( metaData ); break; } } eventBus.fireEvent( new AfterColumnInserted() ); }
Source:
private ConceptReferenceTerm getConceptReferenceTermByConceptSource(Concept concept, ConceptSource conceptSource) { Collection<ConceptMap> conceptMappings = concept.getConceptMappings(); if(conceptMappings != null && conceptSource != null) { for (ConceptMap cm : conceptMappings) { ConceptReferenceTerm term = cm.getConceptReferenceTerm(); START if (term.getConceptSource() != null && term.getConceptSource().equals(conceptSource)) { END return term; } } } return null; } You won't need to test for the nullity of `term.getConceptSource()` if you do this: ```java if (conceptSource.equals(term.getConceptSource())) { ... ``` Because at this point you already know that `conceptSource` is not null.

Target:
private ConceptReferenceTerm getConceptReferenceTermByConceptSource(Concept concept, ConceptSource conceptSource) { Collection<ConceptMap> conceptMappings = concept.getConceptMappings(); if(conceptMappings != null && conceptSource != null) { for (ConceptMap cm : conceptMappings) { ConceptReferenceTerm term = cm.getConceptReferenceTerm(); if (conceptSource.equals(term.getConceptSource())) { return term; } } } return null; }
Source:
public void testMapSubscript() { assertQuery("SELECT map(array[1], array['aa'])[1]", "SELECT 'aa'"); assertQuery("SELECT map(array['a'], array['aa'])['a']", "SELECT 'aa'"); assertQuery("SELECT map(array[array[1,1]], array['a'])[array[1,1]]", "SELECT 'a'"); assertQuery("SELECT map(array[(1,2)], array['a'])[(1,2)]", "SELECT 'a'"); // Force the last value in the key BlockBuilder to the end of the internal Slice, so that searching for longer key values can be tested. // 'idv_fail' and 'request_fail' has the same hash value. START assertQuery("SELECT map(array['0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456', 'idv_fail'], array['aa', 'bb'])['request_fail']", "SELECT NULL"); END assertQuery("SELECT map(array['0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456', 'idv_fail'], array['aa', 'bb'])['idv_fail']", "SELECT 'bb'"); } @yingsu00 I don't think I understand how this works. Would you clarify? Perhaps, a unit tests would be easier to understand. What is the very long string here for?

Target:
public void testMapSubscript() { assertQuery("SELECT map(array[1], array['aa'])[1]", "SELECT 'aa'"); assertQuery("SELECT map(array['a'], array['aa'])['a']", "SELECT 'aa'"); assertQuery("SELECT map(array[array[1,1]], array['a'])[array[1,1]]", "SELECT 'a'"); assertQuery("SELECT map(array[(1,2)], array['a'])[(1,2)]", "SELECT 'a'"); }
Source:
public ImageData getImageDataFor(ImageDescriptor descriptor) { START if (descriptorToImageData.containsKey(descriptor)) { return descriptorToImageData.get(descriptor); } return null; END } return descriptorToImageData.get(descriptor);

Target:
public ImageData getImageDataFor(ImageDescriptor descriptor) { return descriptorToImageData.get(descriptor); }
Source:
protected boolean checkCanDisableVirtIoScsi() { VmValidator vmValidator = createVmValidator(vmFromConfiguration); if (Boolean.FALSE.equals(getParameters().isVirtioScsiEnabled()) && !validate(vmValidator.canDisableVirtioScsi(getAdjustedDiskImagesFromConfiguration()))) { return false; } START else return true; END } please use project formatter, this should be inside

Target:
protected boolean checkCanDisableVirtIoScsi() { VmValidator vmValidator = createVmValidator(vmFromConfiguration); if (Boolean.FALSE.equals(getParameters().isVirtioScsiEnabled()) && !validate(vmValidator.canDisableVirtioScsi(getAdjustedDiskImagesFromConfiguration()))) { return false; } else { return true; } }
Source:
private void doUnmarshal() { START try { END if(this.response != null && this.response.trim().startsWith("{")){ unmarshal(); } } catch (Exception e) { e.printStackTrace(); if(this.exception == null){ this.exception = e; } } } if this.exception != null || this. response == null || !this.response.trim().startsWith("{"){ return; } try ... catch ...

Target:
private void doUnmarshal() { if (this.exception != null || this.response == null || !this.response.trim().startsWith("{")) { return; } try { unmarshal(); } catch (Exception e) { e.printStackTrace(); if (this.exception == null) { this.exception = e; } } }
Source:
private boolean validateHostsConnectionResults(List<Pair<Guid, Boolean>> hostsConnectionResults) { for (Pair<Guid, Boolean> hostsConnectionResult : hostsConnectionResults) { START if (hostsConnectionResult.getSecond() == true) { END return true; } } return false; } don't need the "== true", it's a boolean :-)

Target:
private boolean validateHostsConnectionResults(List<Pair<Guid, Boolean>> hostsConnectionResults) { for (Pair<Guid, Boolean> hostsConnectionResult : hostsConnectionResults) { if (hostsConnectionResult.getSecond()) { return true; } } return false; }
Source:
public String getModifiedIndex() { Objects.requireNonNull(eventIndexName, "null value"); START if(!eventIndexName.equals("netflow")) { END return String.format("%s-%s", eventIndexName, TYPE); } return TYPE; } Here we can check if the String is empty once we change the default value using: `if(!eventIndexName.isEmpty())`

Target:
private String getModifiedIndex() { if (!eventIndexName.isEmpty()) { return String.format("%s-%s", eventIndexName, TYPE); } return TYPE; }
Source:
public void applyTitle(final String title, START final MutationContext mutationContext) { END if (title != null && title.trim().length() > 0 && getShapeView() instanceof HasTitle) { final HasTitle hasTitle = (HasTitle) getShapeView(); hasTitle.setTitle(title); hasTitle.refreshTitle(); } } mutationContext parameter is never used in this Class (but used in 8 method declaration). I suppose add this parameter in the future will be easier than clean up it.

Target:
public void applyTitle(final String title, final MutationContext mutationContext) { if (title != null && getShapeView() instanceof HasTitle) { final HasTitle hasTitle = (HasTitle) getShapeView(); hasTitle.setTitle(title); hasTitle.refreshTitle(); } }
Source:
public void processAdminDistribution(EDXLDistribution body, AssertionType assertion) { START GenericDBUtils.logInfoServiceProcess(this.getClass()); END sendToAdapter(body, assertion, adminUtils, adapterFactory); } What is the point of all these logs here? "Flag service processing debug: PassthroughInboundAdminDistribution" would be outputted.

Target:
public void processAdminDistribution(EDXLDistribution body, AssertionType assertion) { logInfoServiceProcess(this.getClass()); sendToAdapter(body, assertion, adminUtils, adapterFactory); }
Source:
public void testReceivedJobMessageWithWrongJobID() { exception.expect(IllegalStateException.class); JobMessage message = mock(JobMessage.class); when(message.getJobID()).thenReturn(JOB_ID); try { START jobHandler.onJobMessage(message); END } finally { verify(jobSpy, atLeast(0)).getState(); verify(jobSpy, atLeast(0)).getJobID(); verifyNoMoreInteractions(jobSpy); } } if this is supposed to throw an exception (which i guess from the looks of this), then add a fail statement below stating with what exception this should have thrown.

Target:
public void testReceivedJobMessageWithWrongJobID() { JobMessage message = mock(JobMessage.class); when(message.getJobID()).thenReturn(JOB_ID); exception.expect(IllegalStateException.class); try { jobHandler.onJobMessage(message); } finally { verify(jobSpy, atLeast(0)).getState(); verify(jobSpy, atLeast(0)).getJobID(); verifyNoMoreInteractions(jobSpy); } }
Source:
public UserProfile() { this.userPortalVmLoginAutomatically = true; START this.sshPublicKey = ""; END } no need for explicitly using 'this'

Target:
public UserProfile() { userPortalVmLoginAutomatically = true; sshPublicKey = ""; }
Source:
public static void subqueryRestriction(RelNode relNode) { if(relNode instanceof HiveAggregate) { HiveAggregate aggregate = (HiveAggregate)relNode; if(!aggregate.getAggCallList().isEmpty() && aggregate.getGroupSet().isEmpty()) { throw new CalciteSubqueryRuntimeException("Subquery rewrite: Aggregate without group by is not allowed"); } } else if(relNode instanceof HiveProject || relNode instanceof HiveFilter) { subqueryRestriction(relNode.getInput(0)); } else { START return; END } } This is not needed?

Target:
public static void subqueryRestriction(RelNode relNode) { if (relNode instanceof HiveAggregate) { HiveAggregate aggregate = (HiveAggregate) relNode; if (!aggregate.getAggCallList().isEmpty() && aggregate.getGroupSet().isEmpty()) { throw new CalciteSubqueryRuntimeException( "Subquery rewrite: Aggregate without group by is not allowed"); } } else if (relNode instanceof HiveProject || relNode instanceof HiveFilter) { subqueryRestriction(relNode.getInput(0)); } }
Source:
protected Map<String, Pair<String, String>> getExclusiveLocks() { if (isImageLockNeeded()) { START return Collections.singletonMap(getDisk().getId().toString(), LockMessagesMatchUtil.DISK); END } return Collections.EMPTY_MAP; } This method is called before canDoAction(), so if getDisk() is indeed null - which you check in CDA, this will result in a NullPointerException. Instead, just get the ID from the parameters

Target:
protected Map<String, Pair<String, String>> getExclusiveLocks() { if (getDisk() != null && isImageLockNeeded()) { return Collections.singletonMap(getDisk().getId().toString(), LockMessagesMatchUtil.DISK); } return null; }