auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected OperationController getOperationController() { START return ocList.get(ThreadLocalRandom.current().nextInt(ocList.size())); END } Should we abstract this. I mean the way we choose the operation controller. What in case in future, we wish to choose the one which is less loaded compared to others?

Target:
private OperationController getOperationController() { return ocList.get(ThreadLocalRandom.current().nextInt(ocList.size())); }
Source:
public List<JDK> getJDKs() { START if(jdks==null) END jdks = new ArrayList<JDK>(); return jdks; } So I believe the only way this could be null is if a configuration was saved without the <jdks> entry and then reloaded. I don't see how that could happen - but there may be some old version of Jenkins that could have done it. Would probably make sense to modify a `readResolve()` to set it to an empty list and remove this check and the theoretical possibility?

Target:
public List<JDK> getJDKs() { return jdks; }
Source:
public boolean addAll(int index, Collection<? extends T> c) { Collection<T> uniqueValuesToAdd = getUniqueValues(c); if (uniqueValuesToAdd.isEmpty()) { return false; } try { return super.addAll(index, uniqueValuesToAdd); } catch (IndexOutOfBoundsException ioobException) { comparingSet.removeAll(uniqueValuesToAdd); START throw new IndexOutOfBoundsException(); END } } same as above: please pass on the original exception so that we retain the stacktrace and message.

Target:
public boolean addAll(int index, Collection<? extends T> c) { Collection<T> uniqueValuesToAdd = getUniqueValues(c); if (uniqueValuesToAdd.isEmpty()) { return false; } try { return super.addAll(index, uniqueValuesToAdd); } catch (IndexOutOfBoundsException ioobException) { comparingSet.removeAll(uniqueValuesToAdd); throw ioobException; } }
Source:
public Context getContext() { if (sdkName == null) { sdkName = this.getClass().getPackage().getName(); } return new Context("Sdk-Name", sdkName) START .addData("Sdk-Version", SDK_VERSION); END } why sdk version hardcoded?

Target:
public Context getContext() { return new Context("Sdk-Name", sdkName) .addData("Sdk-Version", SDK_VERSION); }
Source:
START public void setSelectedDevices(List<StorageDevice> selectedDevices) { END getStorageDevices().setSelectedItems(selectedDevices); } Can this be protected. I assume only the ListModel is using it

Target:
protected void setSelectedDevices(List<StorageDevice> selectedDevices) { getStorageDevices().setSelectedItems(selectedDevices); }
Source:
private JsonObject toJson(Timer timer, TimeUnit rateUnit, TimeUnit durationUnit) { Snapshot snapshot = timer.getSnapshot(); JsonObject json = new JsonObject(); // Meter populateMetered(json, timer, rateUnit); // Snapshot double factor = 1.0 / durationUnit.toNanos(1); populateSnapshot(json, snapshot, factor); // Duration rate START String duration = durationUnit.toString().toLowerCase(Locale.US); END json.putString("durationRate", duration); return json; } Why US?

Target:
private JsonObject toJson(Timer timer, TimeUnit rateUnit, TimeUnit durationUnit) { Snapshot snapshot = timer.getSnapshot(); JsonObject json = new JsonObject(); // Meter populateMetered(json, timer, rateUnit); // Snapshot double factor = 1.0 / durationUnit.toNanos(1); populateSnapshot(json, snapshot, factor); // Duration rate String duration = durationUnit.toString().toLowerCase(); json.putString("durationRate", duration); return json; }
Source:
protected void delete(LogEntry delegate, String reason, RequestContext context) throws ResourceDoesNotSupportOperationException { START throw new UnsupportedOperationException("delete not supported"); END } Should be ResourceDoesNotSupportOperationException

Target:
protected void delete(LogEntry delegate, String reason, RequestContext context) throws ResourceDoesNotSupportOperationException { throw new ResourceDoesNotSupportOperationException(); }
Source:
START protected void setConsumerBatchEnabled(boolean consumerBatchEnabled) { END this.consumerBatchEnabled = consumerBatchEnabled; } Why is this `protected` ? Are you going to detect this option internally by the `@RabbitListener(Handler)` method signature?

Target:
public void setConsumerBatchEnabled(boolean consumerBatchEnabled) { this.consumerBatchEnabled = consumerBatchEnabled; }
Source:
public int getLevel() { START return data.optInt("toclevel"); END } old code seems to indicate this should be "level" not "toclevel"? Could be causing failure of getLevel() calls being compared in SectionsFetchTask.processResult?

Target:
public int getLevel() { return data.optInt("toclevel", 1); }
Source:
private void setPagesRecycler(OnThisDayCard card) { if (card.pages() != null) { RecyclerAdapter recyclerAdapter = new RecyclerAdapter(card.pages(), card.wiki(), true, (Activity) START this.getContext()); END recyclerAdapter.setCallback(new ItemCallback()); pagesRecycler.setAdapter(recyclerAdapter); } else { pagesRecycler.setVisibility(GONE); } } use getContext() instead of this.getContext() ?

Target:
private void setPagesRecycler(OnThisDayCard card) { if (card.pages() != null) { RecyclerAdapter recyclerAdapter = new RecyclerAdapter(card.pages(), card.wiki(), true, (Activity) getContext()); recyclerAdapter.setCallback(new ItemCallback()); pagesRecycler.setAdapter(recyclerAdapter); } else { pagesRecycler.setVisibility(GONE); } }
Source:
public String getExtendedLabelForVSM(String providedShapeURI) { for (IConfigurationElement configurationElement : extensions) { String identifier = ((ExtensionHandle) configurationElement.getParent()).getSimpleIdentifier(); if (identifier != null && identifier.equals(providedShapeURI)) { return START configurationElement.getAttribute(LABEL_ATTRIBUTE) + " - " + configurationElement.getNamespaceIdentifier(); //$NON-NLS-1$ END } } return "Unknown URI"; //$NON-NLS-1$ } Add a getExtendedLabelsForVSM(IConfigurationElement) method to avoid duplication

Target:
public String getExtendedLabelForVSM(String providedShapeURI) { for (IConfigurationElement configurationElement : extensions) { String identifier = ((ExtensionHandle) configurationElement.getParent()).getSimpleIdentifier(); if (identifier != null && identifier.equals(providedShapeURI)) { return getExtendedLabelForVSM(configurationElement); } } return "Unknown URI"; //$NON-NLS-1$ }
Source:
public void stopServer() { if (server instanceof GrizzlyServer) { START ((GrizzlyServer) server).setCleanIdleConnections(); END } server.stop(); } I would not use setCleanIdleConnections as the name of the function without parmeters. Maybe add a parameter.

Target:
public void stopServer() { if (server instanceof GrizzlyServer) { ((GrizzlyServer) server).setCleanIdleConnections(true); } server.stop(); }
Source:
protected Supplier<Operation> createOperationSupplier() { START return () -> new DistributedObjectDestroyOperation(parameters.serviceName, parameters.name); END } We can make `DestroyProxyMessageTask` implement the Supplier, so that this method will no create a lamda but return `this` instead.

Target:
protected Supplier<Operation> createOperationSupplier() { return this; }
Source:
public <C extends CtTypedElement> C setType(CtTypeReference<T> type) { if (type != null) { type.setParent(this); } // even if the setter delegates to getExecutable, it makes sense to create an event START getFactory().getEnvironment().getModelChangeListener().onObjectUpdate(this, TYPE, type, getExecutable().getType()); END if (getExecutable() != null) { getExecutable().setType(type); } return (C) this; } So model change listener will be called twice for single modification? I do not like it. @monperrus Could you explain why it is good?

Target:
public <C extends CtTypedElement> C setType(CtTypeReference<T> type) { if (type != null) { type.setParent(this); } if (getExecutable() != null) { getExecutable().setType(type); } return (C) this; }
Source:
public static AuthenticationProfileRepository getInstance() { return instance; START } END I do not understand the above two... but for ut it will be hell.

Target:
public static AuthenticationProfileRepository getInstance() { if (instance == null) { synchronized (AuthenticationProfileRepository.class) { if (instance == null) { instance = new AuthenticationProfileRepository(); } } } return instance; }
Source:
public HttpRequest filterKey(HttpRequest request) throws HttpException { request = replaceDateHeader(request); String signature = calculateSignature(createStringToSign(request)); START request = replaceAuthorizationHeader(request, signature); END return request; } ```suggestion ```

Target:
public HttpRequest filterKey(HttpRequest request) throws HttpException { request = replaceDateHeader(request); String signature = calculateSignature(createStringToSign(request)); return replaceAuthorizationHeader(request, signature); }
Source:
public ScreenshotSize get() { START if (config.getScreenshotSize() == ScreenshotSize.DOUBLE_SIZE) { END return ScreenshotSize.DOUBLE_SIZE; } else if (config.getScreenshotSize() == ScreenshotSize.NORMAL_SIZE) { return ScreenshotSize.NORMAL_SIZE; } else if (config.getScreenshotSize() == ScreenshotSize.HALF_SIZE) { return ScreenshotSize.HALF_SIZE; } else if (config.getScreenshotSize() == ScreenshotSize.QUARTER_SIZE) { return ScreenshotSize.QUARTER_SIZE; } else { return ScreenshotSize.NORMAL_SIZE; } } Again, should just return the value if not null.

Target:
public ScreenshotSize get() { if(config.getScreenshotSize() != null) { return config.getScreenshotSize(); } else { return ScreenshotSize.NORMAL_SIZE; } }
Source:
START public String canonicalID() { END return canonical; } Why make this non-final? Given how important this method is for its serialization/internal representation, it's pretty important that it not be overridden.

Target:
public final String canonicalID() { return canonical; }
Source:
protected void close() { try { START m_sout.flush(); END m_sout.close(); } catch (IOException ex) { } } close does an implicit flush

Target:
protected void close() { try { m_sout.close(); } catch (IOException ex) { } }
Source:
protected boolean isProcessed(ChronicleLogOffsetTracker tracker, long offset) { long last = tracker.readLastCommittedOffset(); START return (last > 0) && (last >= offset); END } No need for parentheses.

Target:
protected boolean isProcessed(ChronicleLogOffsetTracker tracker, long offset) { long last = tracker.readLastCommittedOffset(); return last > 0 && last >= offset; }
Source:
public EList<Diff> getDifferences() { START return new BasicEList<Diff>(this.diffs); END } Please don't create a new list on every call of getDifferences(), but create the list once, e.g., on the first call, and then return the same instance. You might want to use an UnmodifiableEList instead, to fail early, if someone tries to modify it.

Target:
public EList<Diff> getDifferences() { return this.diffs; }
Source:
START public IOWorkers.Selector getWorkerSelector() { END return workerSelector; } @clevertension Why do we need to expose `IOWorkers.Selector`? Looks completely unnecessary to me.

Target:
IOWorkers.Selector getWorkerSelector() { return workerSelector; }
Source:
public Iterable<Tree> children() { List<Tree> result = new ArrayList<>(); if(openParenToken != null) { result.add(openParenToken); } START for (Tree tree : super.children()) { END result.add(tree); } if(closeParenToken != null) { result.add(closeParenToken); } return result; } `super.children().forEach(res::add);` ?

Target:
public Iterable<Tree> children() { List<Tree> result = new ArrayList<>(); if(openParenToken != null) { result.add(openParenToken); } super.children().forEach(result::add); if (closeParenToken != null) { result.add(closeParenToken); } return result; }
Source:
public void setName(String name) { Objects.requireNonNull(name); START this.name = name; END } `requireNonNull` could be on same line than affectation.

Target:
public void setName(String name) { this.name = requireNonNull(name); }
Source:
public Query existsQuery(QueryShardContext context) { if (hasDocValues()) { return new DocValuesFieldExistsQuery(name()); START } else if (omitNorms()) { END return new TermQuery(new Term(FieldNamesFieldMapper.NAME, name())); } else { return new NormsFieldExistsQuery(name()); } } I believe it should be `omitNorms() || indexOptions() != IndexOptions.NONE`

Target:
public Query existsQuery(QueryShardContext context) { if (hasDocValues()) { return new DocValuesFieldExistsQuery(name()); } else { return new TermQuery(new Term(FieldNamesFieldMapper.NAME, name())); } }
Source:
START private void handleYieldExpression(SubscriptionContext ctx, PyYieldExpressionTree yieldExpr) { END if (yieldExpr.fromKeyword() == null && yieldExpr.expressions().size() == 1) { yieldExpr.expressions().forEach(e -> checkExpr(e, ctx, "yield")); } } This method should be static

Target:
private static void handleYieldExpression(SubscriptionContext ctx, PyYieldExpressionTree yieldExpr) { if (yieldExpr.fromKeyword() == null && yieldExpr.expressions().size() == 1) { yieldExpr.expressions().forEach(e -> checkExpr(e, ctx, "yield")); } }
Source:
START private void importLdif(InMemoryDirectoryServer directoryServer) throws LDAPException { END if (StringUtils.hasText(this.ldif)) { try { Resource resource = locateResource(); try (InputStream inputStream = resource.getInputStream()) { directoryServer.importFromLDIF(false, new LDIFReader(inputStream)); } } catch (Exception ex) { throw new IllegalStateException("Unable to load LDIF " + this.ldif, ex); } } } We do not need to declare that this throws an `LDAPException`.

Target:
private void importLdif(InMemoryDirectoryServer directoryServer) { if (StringUtils.hasText(this.ldif)) { try { Resource resource = locateResource(); try (InputStream inputStream = resource.getInputStream()) { directoryServer.importFromLDIF(false, new LDIFReader(inputStream)); } } catch (Exception ex) { throw new IllegalStateException("Unable to load LDIF " + this.ldif, ex); } } }
Source:
START public XSSFTableColumn(XSSFTable table, CTTableColumn ctTableColumn) { END this.table = table; this.ctTableColumn = ctTableColumn; } I would insist in having all methods that use a `CT*` parameter to be annotated as `@Internal` when they are not private.

Target:
protected XSSFTableColumn(XSSFTable table, CTTableColumn ctTableColumn) { this.table = table; this.ctTableColumn = ctTableColumn; }
Source:
private boolean isDateSelectable(Date date) { START if (isCheckDayInSelectableCals && !containsDate(selectableCals, date)) return false; END return dateConfiguredListener == null || dateConfiguredListener.isDateSelectable(date); } We'd use `{` and `}` here or just fold the conditional into a single `return` statement.

Target:
private boolean isDateSelectable(Date date) { if (isCheckDayInSelectableCals && !containsDate(selectableCals, date)) { return false; } return dateConfiguredListener == null || dateConfiguredListener.isDateSelectable(date); }
Source:
START public void updatePathGroup(List<Variable> END variables, IPath node, IPath selection) { final int segmentsSelection = selection.segmentCount(); for (final Variable variable : variables) if (variable.getPath().uptoSegment(segmentsSelection).equals(selection.makeAbsolute())) { final IPath oldPath = variable.getPath(); final int count = selection.segmentCount(); variable.setPath(buildPath(oldPath, node, count)); } } make static

Target:
public static void updatePathGroup(List<Variable> variables, IPath node, IPath selection) { final int segmentsSelection = selection.segmentCount(); for (final Variable variable : variables) if (variable.getPath().uptoSegment(segmentsSelection).equals(selection.makeAbsolute())) { final IPath oldPath = variable.getPath(); final int count = selection.segmentCount(); variable.setPath(buildPath(oldPath, node, count)); } }
Source:
private FactorComparator(String factorName, int weight, Comparator<T> comparator){ this.factorName = factorName; this.weight = weight; this.comparator = comparator; START logger.info("comparator created for " + this.factorName); END } is this necessary?

Target:
private FactorComparator(String factorName, int weight, Comparator<T> comparator){ this.factorName = factorName; this.weight = weight; this.comparator = comparator; }
Source:
START public PatternMatcher(TermContext context) { END this.termContext = context; multiSubstitutions = new ArrayList<java.util.Collection<Map<Variable, Term>>>(); } why was this done?

Target:
private PatternMatcher(TermContext context) { this.termContext = context; multiSubstitutions = new ArrayList<Collection<Map<Variable, Term>>>(); }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getArtUuid() == null) ? 0 : getArtUuid().hashCode()); START result = prime * result + ((getBranchId().isInvalid()) ? 0 : getBranchId().hashCode()); END return result; } result = prime * result + getBranchId().hashCode(); can use BranchId's hashCode method directly since branchId is not allowed to be null and it will work whether the id is valid or not

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getArtUuid() == null) ? 0 : getArtUuid().hashCode()); result = prime * result + getBranchId().hashCode(); return result; }
Source:
START protected void END setUpGetUnregisteredVmTemplateExpectations(boolean notFound) { setUpEntityQueryExpectations( QueryType.GetUnregisteredVmTemplate, GetUnregisteredEntityQueryParameters.class, new String[] { "StorageDomainId", "EntityId" }, new Object[] { STORAGE_DOMAIN_ID, TEMPLATE_ID }, notFound ? null : getEntity(1)); } Can be private

Target:
private void setUpGetUnregisteredVmTemplateExpectations(boolean notFound) { setUpEntityQueryExpectations( QueryType.GetUnregisteredVmTemplate, GetUnregisteredEntityQueryParameters.class, new String[] { "StorageDomainId", "EntityId" }, new Object[] { STORAGE_DOMAIN_ID, TEMPLATE_ID }, notFound ? null : getEntity(1)); }
Source:
START public boolean isDomainXmlEnabledForVds(Guid vdsId) { END return FeatureSupported.isDomainXMLSupported(getVdsManager(vdsId).getCompatibilityVersion()); } The whole purpose of FullListAdapter is to abstract the implementation details of querying the device list from the caller - so how about moving the changes that are done in VmDevicesMonitoring to FullListVDSCommand ?

Target:
private boolean isDomainXmlEnabledForVds(Guid vdsId) { return FeatureSupported.isDomainXMLSupported(getVdsManager(vdsId).getCompatibilityVersion()); }
Source:
public void mousePressed(MouseEvent e) { START if (e.isPopupTrigger()) END doPop(e); } Please add also for `if` blocks with only one statement.

Target:
public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { doPop(e); } }
Source:
public boolean isSuggestionListDisplayed() { try { START waitForElementByElement(searchSuggestions.get(0)); END return searchSuggestions.get(0).isDisplayed(); } catch (NoSuchElementException|IndexOutOfBoundsException e) return false; } Use .getSize to see if element is on page

Target:
public boolean isSuggestionListDisplayed() { try { if (searchSuggestions.size() > 0) { waitForElementByElement(searchSuggestions.get(0)); return searchSuggestions.get(0).isDisplayed(); } } catch (NoSuchElementException e) return false; }
Source:
public ConnectionId(final String host, final int port, final String connectionId) { Objects.requireNonNull(host); if (port <= 0) { START throw new IllegalArgumentException(String.format("Port must be greater than 0")); END } this.host = host; this.port = port; this.connectionId = connectionId; } no need to use String.format as there is no parameter. Either provide directly throw new IllegalArgumentException("Port must be greater than 0"); or maybe improve message with somethign like: throw new IllegalArgumentException(String.format("Port must be greater than 0 (provided {0})", port));

Target:
public ConnectionId(final String host, final int port, final String connectionId) { Objects.requireNonNull(host); if (port <= 0) { throw new IllegalArgumentException("Port must be greater than 0"); } this.host = host; this.port = port; this.connectionId = connectionId; }
Source:
public RecursiveLoggerContextInstantiationException(String message) { START super(I18nMessageFactory.createStaticMessage(message)); END } use static import.

Target:
public RecursiveLoggerContextInstantiationException(String message) { super(createStaticMessage(message)); }
Source:
START public Map<String, MetricPlotDTOs> createTaskPlots() { END sessionId = getSessionIdProvider().getSessionId(); // check new model List<MetricPointEntity> metricDetails = getHibernateTemplate().find( "select m from MetricPointEntity m where m.metricDescription.taskData.sessionId=?", sessionId); if (metricDetails == null || metricDetails.isEmpty()) { return oldWay(); } else { return newWay(metricDetails); } } why is it public?

Target:
private Map<String, MetricPlotDTOs> createTaskPlots() { // check new model List<MetricPointEntity> metricDetails = getHibernateTemplate().find( "select m from MetricPointEntity m where m.metricDescription.taskData.sessionId=?", sessionId); if (metricDetails == null || metricDetails.isEmpty()) { return oldWay(); } else { return newWay(metricDetails); } }
Source:
public void testDeadlock() throws Exception { doTest(1000 * 30); // 30 secs almost always locks boolean START interrupted = END Thread.interrupted(); if (interrupted) { fail("Thread was interrupted at end of test"); } } Why not inline this variable?

Target:
public void testDeadlock() throws Exception { doTest(1000 * 30); // 30 secs almost always locks if (Thread.interrupted()) { fail("Thread was interrupted at end of test"); } }
Source:
public static QueryGranularity fromString(String str) { String name = str.toUpperCase(); if(name.equals("ALL")) { return QueryGranularity.ALL; } else if(name.equals("NONE")) { return QueryGranularity.NONE; } else if(CALENDRIC_GRANULARITIES.containsKey(name)) { START return new PeriodGranularity(CALENDRIC_GRANULARITIES.get(name), null, null); END } return new DurationGranularity(convertValue(str), 0); } instead of creating a new object every time, it might make more sense to store constants for each predefined granularity string

Target:
public static QueryGranularity fromString(String str) { String name = str.toUpperCase(); if(name.equals("ALL")) { return QueryGranularity.ALL; } else if(name.equals("NONE")) { return QueryGranularity.NONE; } else if(CALENDRIC_GRANULARITIES.containsKey(name)) { return CALENDRIC_GRANULARITIES.get(name); } return new DurationGranularity(convertValue(str), 0); }
Source:
public Object[] getElements(Object element) { START if (element instanceof Object[]) { END return (Object[]) element; } if (element instanceof Collection) { return ((Collection) element).toArray(); } return new Object[0]; } style nit: we don't use braces around single line blocks

Target:
public Object[] getElements(Object element) { if (element instanceof Object[]) return (Object[]) element; if (element instanceof Collection) return ((Collection) element).toArray(); return new Object[0]; }
Source:
public void setUp() throws Exception { super.setUp(); START if (SystemUtils.IS_OS_LINUX) { END try { eventLoopGroup = new EpollEventLoopGroup(); } catch (Throwable t) { LOG.warn("Could not use Netty Epoll event loop {}", t.getMessage()); eventLoopGroup = new NioEventLoopGroup(); } } else { eventLoopGroup = new NioEventLoopGroup(); } executor = OrderedSafeExecutor.newBuilder() .name("BKClientOrderedSafeExecutor") .numThreads(2) .build(); } maybe we should create a common utility function to build EventLoopGroups and do not duplicate this kind of code

Target:
public void setUp() throws Exception { super.setUp(); eventLoopGroup = new NioEventLoopGroup(); executor = OrderedSafeExecutor.newBuilder() .name("BKClientOrderedSafeExecutor") .numThreads(2) .build(); }
Source:
private void readInternal(long position, byte[] buffer, int bufferOffset, int bufferLength) { try { long readStart = System.nanoTime(); inputStream.readFully(position, buffer, bufferOffset, bufferLength); stats.readDataBytesPerSecond(bufferLength, System.nanoTime() - readStart); } catch (PrestoException e) { // just in case there is a Presto wrapper or hook throw e; } catch (Exception e) { START throw new PrestoException(HIVE_FILESYSTEM_ERROR, format("Error reading from %s at position %s", id.toString(), position), e); END } } Don't need the `toString` call.

Target:
private void readInternal(long position, byte[] buffer, int bufferOffset, int bufferLength) { try { long readStart = System.nanoTime(); inputStream.readFully(position, buffer, bufferOffset, bufferLength); stats.readDataBytesPerSecond(bufferLength, System.nanoTime() - readStart); } catch (PrestoException e) { // just in case there is a Presto wrapper or hook throw e; } catch (Exception e) { throw new PrestoException(HIVE_FILESYSTEM_ERROR, format("Error reading from %s at position %s", id, position), e); } }
Source:
public void invalidPropertiesFormat() { VmDevice device = new VmDevice(); device.setType(VmDeviceGeneralType.DISK); device.setCustomProperties("bootable"); DevicePropertiesUtils utils = mockDevicePropertiesUtils(); List<ValidationError> errors = utils.validateDeviceProperties(Version.v3_3, device); assertFalse(errors.isEmpty()); START assertTrue(errors.get(0).getReason() == ValidationFailureReason.SYNTAX_ERROR); END } Don't you prefer to use assertEquals?

Target:
public void invalidPropertiesFormat() { VmDevice device = new VmDevice(); device.setType(VmDeviceGeneralType.DISK); device.setCustomProperties("bootable"); DevicePropertiesUtils utils = mockDevicePropertiesUtils(); List<ValidationError> errors = utils.validateDeviceProperties(Version.v3_3, device); assertFalse(errors.isEmpty()); assertEquals(ValidationFailureReason.SYNTAX_ERROR, errors.get(0).getReason()); }
Source:
private boolean isMandatory(MethodExpression expression) { START return expression.getMethod().getWords().get(0).equals(MANDATORY) ? true : false; END } If this is the use of the "MANDATORY" constant then you may want to define it as a "Name" instead of "String": privates static final Name MANDATORY = NameParser.parseUsingCase("Mandatory"); Then you can compare it easily: return expression.getMethod().equals(MANDATORY);

Target:
private boolean isMandatory(MethodExpression expression) { return expression.getMethod().equals(MANDATORY) ? true : false; }
Source:
START private DeltaVisit next() { END // If our parent has no more children, discard it. if (parent != null && parent.nextChild == null) { parent.data = null; parent = parent.parent; } if (nextChild != null) return new DeltaVisit(this); // If we have no child ourselves, our parent must (if it exists), // due to the discard rule above. With no parent, we are done. if (parent != null) return new DeltaVisit(parent); return null; } Good change making this an instance member, thanks.

Target:
DeltaVisit next() { // If our parent has no more children, discard it. if (parent != null && parent.nextChild == null) { parent.data = null; parent = parent.parent; } if (nextChild != null) return new DeltaVisit(this); // If we have no child ourselves, our parent must (if it exists), // due to the discard rule above. With no parent, we are done. if (parent != null) return new DeltaVisit(parent); return null; }
Source:
boolean delayNextTimeToRun(Date timeToRunTheVm) { this.timeToRunTheVm = timeToRunTheVm; START return ++numOfSkips < MAXIMUM_NUM_OF_SKIPS_BEFORE_AUTO_START_VM; END } we can do something like: numOfSkips = ++numOfSkips % MAXIMUM_NUM_OF_SKIPS_BEFORE_AUTO_START_VM; return numOfSkips == 0; and remove clearSkipCounter, no? if this was already properly verified, we can merge this and think about the change above on master-only

Target:
boolean delayNextTimeToRun(Date timeToRunTheVm) { this.timeToRunTheVm = timeToRunTheVm; numOfSkips = ++numOfSkips % MAXIMUM_NUM_OF_SKIPS_BEFORE_AUTO_START_VM; return numOfSkips != 0; }
Source:
protected boolean isTransientException(Throwable e) { if(e instanceof SQLException) { final String sqlState = ((SQLException) e).getSQLState(); // retry on connection errors and insufficient resources // (see http://www.postgresql.org/docs/current/static/errcodes-appendix.html) START return sqlState.startsWith("08") || sqlState.startsWith("53"); END } return false; } Of the "53" class of errors, I think only "53300" might be transient, no?

Target:
protected boolean isTransientException(Throwable e) { if(e instanceof SQLException) { final String sqlState = ((SQLException) e).getSQLState(); // limited to errors that are likely to be resolved within a few retries // retry on connection errors and insufficient resources // see http://www.postgresql.org/docs/current/static/errcodes-appendix.html for details return sqlState != null && (sqlState.startsWith("08") || sqlState.startsWith("53")); } return false; }
Source:
public JupiterActivity generateJupiterActivity(Operation op, User source, SPath editor) { // send(op, myMsgs, otherMsgs); JupiterActivity jupiterActivity = new JupiterActivity(this.vectorTime, op, source, editor); // add(op, myMsgs) to outgoing; START if (!(op instanceof TimestampOperation)) { END this.ackJupiterActivityList.add( new OperationWrapper(op, this.vectorTime.getLocalOperationCount())); } // myMsgs = myMsgs + 1; this.vectorTime = this.vectorTime.incrementLocalOperationCount(); return jupiterActivity; } So you pointed me to this line and what is the problem here ? The problem is that discardAcknowledgedOperations is never called. This was never done in this method anyway.

Target:
public JupiterActivity generateJupiterActivity(Operation op, User source, SPath editor) { // send(op, myMsgs, otherMsgs); JupiterActivity jupiterActivity = new JupiterActivity(this.vectorTime, op, source, editor); // add(op, myMsgs) to outgoing; this.ackJupiterActivityList.add( new OperationWrapper(op, this.vectorTime.getLocalOperationCount())); // myMsgs = myMsgs + 1; this.vectorTime = this.vectorTime.incrementLocalOperationCount(); return jupiterActivity; }
Source:
public void testAssignExecutorInvalidExecutor() throws Exception { final ExecutableFlow flow = TestUtils.createExecutableFlow("exectest1", "exec1"); this.executionFlowDao.uploadExecutableFlow(flow); assertThatThrownBy( START () -> this.assignExecutor.assignExecutor(flow.getExecutionId(), 1)) END .isInstanceOf(ExecutorManagerException.class) .hasMessageContaining("non-existent executor"); } Should it be assignExecutor(1, flow.getExecutionId())? Also how do you know 1 is a non-existent executor?

Target:
public void testAssignExecutorInvalidExecutor() throws Exception { final ExecutableFlow flow = TestUtils.createExecutableFlow("exectest1", "exec1"); this.executionFlowDao.uploadExecutableFlow(flow); // Since we haven't inserted any executors, 1 should be non-existent executor id. assertThatThrownBy( () -> this.assignExecutor.assignExecutor(1, flow.getExecutionId())) .isInstanceOf(ExecutorManagerException.class) .hasMessageContaining("non-existent executor"); }
Source:
private static BackgroundHiveSplitLoader backgroundHiveSplitLoaderOfflinePartitions() START throws Exception END { ConnectorSession connectorSession = new TestingConnectorSession( new HiveSessionProperties(new HiveClientConfig().setMaxSplitSize(new DataSize(1.0, GIGABYTE))).getSessionProperties()); return new BackgroundHiveSplitLoader( SIMPLE_TABLE, createPartitionMetadataWithOfflinePartitions(), TupleDomain.all(), createBucketSplitInfo(Optional.empty(), ImmutableList.of()), connectorSession, new TestingHdfsEnvironment(), new NamenodeStats(), new TestingDirectoryLister(TEST_FILES), directExecutor(), 2, false); } no `Exception` is thrown here

Target:
private static BackgroundHiveSplitLoader backgroundHiveSplitLoaderOfflinePartitions() { ConnectorSession connectorSession = new TestingConnectorSession( new HiveSessionProperties(new HiveClientConfig().setMaxSplitSize(new DataSize(1.0, GIGABYTE))).getSessionProperties()); return new BackgroundHiveSplitLoader( SIMPLE_TABLE, createPartitionMetadataWithOfflinePartitions(), TupleDomain.all(), createBucketSplitInfo(Optional.empty(), ImmutableList.of()), connectorSession, new TestingHdfsEnvironment(), new NamenodeStats(), new TestingDirectoryLister(TEST_FILES), directExecutor(), 2, false); }
Source:
public String toString() { START return methodPrefix.toString(); END } 'methodPrefix.toString()' is redundant

Target:
public String toString() { return methodPrefix; }
Source:
private void setPlatformTextClassifier(@Nullable TextClassifier textClassifier) { android.view.textclassifier.TextClassificationManager START textClassificationManager = END (android.view.textclassifier.TextClassificationManager) mContext.getSystemService(Context.TEXT_CLASSIFICATION_SERVICE); android.view.textclassifier.TextClassifier platformTextClassifier = textClassifier == null ? null : new PlatformTextClassifier(mContext, textClassifier); textClassificationManager.setTextClassifier(platformTextClassifier); } TCM is an optional Android system service. Check for null.

Target:
private void setPlatformTextClassifier(@Nullable TextClassifier textClassifier) { android.view.textclassifier.TextClassificationManager textClassificationManager = (android.view.textclassifier.TextClassificationManager) mContext.getSystemService(Context.TEXT_CLASSIFICATION_SERVICE); if (textClassificationManager == null) { return; } android.view.textclassifier.TextClassifier platformTextClassifier = textClassifier == null ? null : new PlatformTextClassifier(mContext, textClassifier); textClassificationManager.setTextClassifier(platformTextClassifier); }
Source:
Object loadServiceCapabilities(String serviceUrl) throws IOException { HttpGet request = new HttpGet(serviceUrl); request.setHeader(new BasicHeader(HttpHeaders.ACCEPT, ACCEPT_SERVICE_CAPABILITIES)); CloseableHttpResponse httpResponse = execute(request, serviceUrl, "retrieve help"); validateResponse(httpResponse, serviceUrl); HttpEntity httpEntity = httpResponse.getEntity(); ContentType contentType = ContentType.getOrDefault(httpEntity); START if ("text/plain".equals(contentType.getMimeType())) { END return getContent(httpEntity); } return parseJsonMetadata(httpEntity); } mime type is mandatory

Target:
Object loadServiceCapabilities(String serviceUrl) throws IOException { HttpGet request = new HttpGet(serviceUrl); request.setHeader(new BasicHeader(HttpHeaders.ACCEPT, ACCEPT_SERVICE_CAPABILITIES)); CloseableHttpResponse httpResponse = execute(request, serviceUrl, "retrieve help"); validateResponse(httpResponse, serviceUrl); HttpEntity httpEntity = httpResponse.getEntity(); ContentType contentType = ContentType.getOrDefault(httpEntity); if (contentType.getMimeType().equals("text/plain")) { return getContent(httpEntity); } return parseJsonMetadata(httpEntity); }
Source:
protected void doStop() { log.info("Stopping Netty server"); boss.shutdownGracefully(); if(!datagram) { START wrkr.shutdownGracefully(); END } try { sock.channel().closeFuture().sync(); } catch (InterruptedException e) { log.warn("Netty server stop interrupted"); Thread.currentThread().interrupt(); } log.info("Netty server stopped"); notifyStopped(); } I think it is the boss who should be shut down if (!datagram)

Target:
protected void doStop() { log.info("Stopping Netty server"); wrkr.shutdownGracefully(); if(!datagram) { boss.shutdownGracefully(); } try { sock.channel().closeFuture().sync(); } catch (InterruptedException e) { log.warn("Netty server stop interrupted"); Thread.currentThread().interrupt(); } log.info("Netty server stopped"); notifyStopped(); }
Source:
public ChannelViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { START LayoutInflater inflater = LayoutInflater.from(parent.getContext()); END return new ChannelViewHolder((ChannelView) inflater.inflate(R.layout.channel_item_layout, parent, false)); } Maybe pass the layout inflater as a param to the adapter.

Target:
public ChannelViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ChannelViewHolder((ChannelView) inflater.inflate(R.layout.channel_item_layout, parent, false)); }
Source:
public void onSelectionChanged(int selectedItemCnt) { int numberMergeSelections = adapter.numberMergeSelections; if (adapter.isMergeSelection && selectedItemCnt >= numberMergeSelections) { START ToastUtil.showError(getContext(), "We can only merge " + numberMergeSelections + " projects"); END } updateSelectionToggle(actionMode.getMenu().findItem(R.id.toggle_selection)); actionMode.setTitle(getResources() .getQuantityString(getActionModeTitleId(actionModeType), selectedItemCnt, selectedItemCnt)); } is there a reason that this is displayed everytime? since this is shown when the second project is selected, it will always be there.

Target:
public void onSelectionChanged(int selectedItemCnt) { updateSelectionToggle(actionMode.getMenu().findItem(R.id.toggle_selection)); actionMode.setTitle(getResources() .getQuantityString(getActionModeTitleId(actionModeType), selectedItemCnt, selectedItemCnt)); }
Source:
private boolean shouldBeDistributed(PlanNode planNode) { return planNode instanceof AggregationNode || planNode instanceof JoinNode || START (planNode instanceof TopNNode && ((TopNNode) planNode).getStep().equals(TopNNode.Step.PARTIAL)); END } The method will grow (i once already wanted to add something here), so what about putting this in a more lengthy but more readable way? (Note, I also changed TopNNode's condition) ``` if (planNode instanceof JoinNode) { return true; } if (planNode instanceof AggregationNode) { return true; // here you could differentiate between partial/... } if (planNode instanceof TopNNode) { return ((TopNNode) planNode).getStep() != TopNNode.Step.FINAL; } return false; ```

Target:
private boolean shouldBeDistributed(PlanNode planNode) { if (planNode instanceof JoinNode) { return true; } if (planNode instanceof AggregationNode) { // TODO: differentiate aggregation with empty grouping set return true; } if (planNode instanceof TopNNode) { return ((TopNNode) planNode).getStep() == TopNNode.Step.PARTIAL; } return false; }
Source:
public void testConcurrency() { final ServerTemplate serverTemplate = templateStorage.load(serverTemplateId); marshal("application/xml", serverTemplate); Thread disconnect = new Thread(() -> disconnect()); disconnect.start(); String response = marshal("application/xml", serverTemplate); START LOGGER.info(response); END } ```suggestion assertNotNull(response); ```

Target:
public void testConcurrency() { final ServerTemplate serverTemplate = templateStorage.load(serverTemplateId); marshal("application/xml", serverTemplate); Thread disconnect = new Thread(() -> disconnect()); disconnect.start(); String response = marshal("application/xml", serverTemplate); assertNotNull(response); }
Source:
protected Void visitIntegerLiteral(IntegerLiteral node, Integer indent) { START builder.append(String.format(Locale.ENGLISH, "%d", node.getValue())); END return null; } ```suggestion builder.append(Integer.toString(node.getValue())); ``` Cheaper than going through `String.format`

Target:
protected Void visitIntegerLiteral(IntegerLiteral node, Integer indent) { builder.append(node.getValue()); return null; }
Source:
START private List<GerritQueryResult> executeQueryRest(String query) throws GerritException { END List<GerritQueryResult> results = null; results = client.executeQueryRest(new NullProgressMonitor(), query); return results; } This is essentially one line of code, I'd prefer to inline this.

Target:
private List<GerritQueryResult> executeQueryRest(String query) throws GerritException { return client.executeQueryRest(new NullProgressMonitor(), query); }
Source:
public QueryWrapper(@JsonProperty("query") String query, @JsonProperty("queryType") String queryType) { START this(query, queryType, ""); END } to avoid redundant pattern check : ```suggestion this(query, queryType, null); ```

Target:
public QueryWrapper(@JsonProperty("query") String query, @JsonProperty("queryType") String queryType) { this(query, queryType, null); }
Source:
private List<CoordinatorDuty> makeCompactSegmentsDuty() { START List<CoordinatorDuty> duties = new ArrayList<>(); duties.add(compactSegments); return ImmutableList.copyOf(duties); END } Why not `return ImmutableList.of(compactSegments);` instead?

Target:
private List<CoordinatorDuty> makeCompactSegmentsDuty() { return ImmutableList.of(compactSegments); }
Source:
public CreateServerOptions networks(String... networks) { START return networks(ImmutableSet.copyOf(checkNotNull(networks, "network should not be empty"))); END } The "standard" jclouds pattern would be `checkNotNull(networks, "networks")`, but in this case it's not doing the expected thing since a varargs argument cannot be `null`, it will be an empty array instead. If we want to enforce this check, it probably should be: ``` checkArgument(networks.length > 0, "networks should not be empty"); return networks(ImmutableSet.copyOf(networks)); ``` but since `networks(Iterable<String> networks)` already checks I don't think we need the check here.

Target:
public CreateServerOptions networks(String... networks) { return networks(ImmutableSet.copyOf(networks)); }
Source:
private static AbbreviatedObjectId id(DiffEntry de) { START return (de.changeType == ChangeType.DELETE ? de.oldId : de.newId); END } Style-nit: We don't put () around ?: in a return.

Target:
private static AbbreviatedObjectId id(DiffEntry de) { return de.changeType == ChangeType.DELETE ? de.oldId : de.newId; }
Source:
protected VariableReferenceExpression getVariableReference(RowExpression expression) { if (expression instanceof VariableReferenceExpression) { return ((VariableReferenceExpression) expression); } else { START throw new PinotException(PINOT_UNSUPPORTED_EXPRESSION, Optional.empty(), "Expected a variable reference but got " + expression); END } } private

Target:
protected VariableReferenceExpression getVariableReference(RowExpression expression) { if (expression instanceof VariableReferenceExpression) { return ((VariableReferenceExpression) expression); } throw new PinotException(PINOT_UNSUPPORTED_EXPRESSION, Optional.empty(), "Expected a variable reference but got " + expression); }
Source:
public boolean isLocalOnly() { START switch (this) { END case LOCAL: return true; default: return false; } } it could be simpler `return this == LOCAL`

Target:
public boolean isLocalOnly() { return this == LOCAL; }
Source:
protected void findUsers(String searchString, AsyncQuery query) { Frontend.getInstance() .runQuery(VdcQueryType.Search, START new DirectorySearchParameters("ADUSER@" + ((ProfileEntry) getProfile().getSelectedItem()).getAuthz() + ": " + searchString, SearchType.DirectoryUser, (String) getNamespace().getSelectedItem()), query); //$NON-NLS-1$ //$NON-NLS-2$ END } Done

Target:
protected void findUsers(String searchString, AsyncQuery query) { Frontend.getInstance() .runQuery(VdcQueryType.Search, new DirectorySearchParameters("ADUSER@" + ((ProfileEntry) getProfile().getSelectedItem()).getAuthz() + ": " + searchString, SearchType.DirectoryUser, getNamespace().getSelectedItem()), query); //$NON-NLS-1$ //$NON-NLS-2$ }
Source:
public String getImageUrl(String id) { return getProvider().getUrl() + API_VERSION + "/images/" + id + START "/file"; END } if it's v2 older hosts won't work since they use HEAD, no?

Target:
public String getImageUrl(String id) { return getProvider().getUrl() + API_VERSION + "/images/" + id; }
Source:
public User(@NonNull String username, @NonNull String password) { this(username, password, START new HashMap<String, Integer>(), null); END } I recommend using Collections.emptyMap() instead

Target:
public User(@NonNull String username, @NonNull String password) { this(username, password, null, null); }
Source:
public final String consoleClientResourcesUrl() { String url = getString(DynamicMessageKey.CONSOLE_CLIENT_RESOURCES_URL); boolean isAbsolute = url.contains("://"); return isAbsolute ? url : Window.Location.getProtocol() + "//" + Window.Location.getHost() + //$NON-NLS-1$ START "/" + BaseContextPathData.getInstance().getRelativePath() + url; //$NON-NLS-1$ END } no... this can be relative as well... see: frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/ReportInit.java

Target:
public final String consoleClientResourcesUrl() { String url = getString(DynamicMessageKey.CONSOLE_CLIENT_RESOURCES_URL); boolean isAbsolute = url.contains("://"); return isAbsolute ? url : "/" + BaseContextPathData.getInstance().getRelativePath() + url; //$NON-NLS-1$ }
Source:
private boolean isFileEntryPackageable(ZipEntry entry) { START String entryName = entry.getName(); END return ApkBuilder.checkFileForPackaging(entry.getName()) && isValidMetaInfEntry(entryName); } don't need this. Just refer to entry.getName() in both places

Target:
private boolean isFileEntryPackageable(ZipEntry entry) { return ApkBuilder.checkFileForPackaging(entry.getName()) && isValidMetaInfEntry(entry.getName()); }
Source:
public void testList() { List<VirtualMachine> list = api().list(); START for (VirtualMachine machine : list) { END assertTrue(!machine.name().isEmpty()); } } I'd just assert that it contains the created VM.

Target:
public void testList() { List<VirtualMachine> list = api().list(); VirtualMachine vm = api().get(getName()); assertTrue(list.contains(vm)); }
Source:
START void addLayer(String id, StyleLayer layer) { END layersById.put(id, layer); } package-private?

Target:
public void addLayer(String id, StyleLayer layer) { layersById.put(id, layer); }
Source:
public void setSelection(ITimeGraphEntry trace) { /* if there is a pending selection, ignore this one */ synchronized (fListenerNotifierLock) { START if (fListenerNotifier != null && fListenerNotifier.hasSelectionChanged()) { END return; } } fSelectedEntry = trace; fTimeGraphCtrl.selectItem(trace, false); adjustVerticalScrollBar(); } idem

Target:
public void setSelection(ITimeGraphEntry trace) { /* if there is a pending selection, ignore this one */ if (fListenerNotifier != null && fListenerNotifier.hasSelectionChanged()) { return; } fSelectedEntry = trace; fTimeGraphCtrl.selectItem(trace, false); adjustVerticalScrollBar(); }
Source:
private ClassFile newClassFile(String name, int accessFlags, String superclass, String... interfaces) { try { START return SecurityActions.getConstructor(ClassFile.class, String.class, int.class, String.class, ClassLoader.class, Arrays2.EMPTY_STRING_ARRAY.getClass()) END .newInstance(name, accessFlags, superclass, classLoader, interfaces); } catch (Exception e) { throw BeanLogger.LOG.unableToCreateClassFile(name, e.getCause()); } } Why not use the constructor right away, i.e. without reflection?

Target:
private ClassFile newClassFile(String name, int accessFlags, String superclass, String... interfaces) { try { return new ClassFile(name, accessFlags, superclass, classLoader, interfaces); } catch (Exception e) { throw BeanLogger.LOG.unableToCreateClassFile(name, e.getCause()); } }
Source:
public boolean addListener(String type, long id, ClassLoaderListener classLoaderListener) { START final VirtualClassLoader localClassLoader = ((VirtualClassLoader) getLocalClassLoader(type, id)); END return localClassLoader.addListener(classLoaderListener); } We can change the return type of getLocalClassLoader only in the implementation to avoid the cast.

Target:
public boolean addListener(String type, long id, ClassLoaderListener classLoaderListener) { final VirtualClassLoader localClassLoader = getLocalClassLoader(type, id); return localClassLoader.addListener(classLoaderListener); }
Source:
public static final void setPreferenceNodeId (String id) { if (fgPreferenceNodeId == null) { START fgPreferenceNodeId = END id; } } JDT uses compact assignement, e.g. i= 3;

Target:
public static final boolean setPreferenceNodeId (String id) { if (fgPreferenceNodeId == null || id == null) { fgPreferenceNodeId= id; return true; } return false; }
Source:
private void init() { // get the localhost. try { hostname = InetAddress.getLocalHost().getHostName(); START hostname = "localhost"; END } catch (UnknownHostException e) { logger.warn("Error getting the value of localhost. " + "Proceeding with 'localhost'.", e); } } Please remove this. This is probably due to an incorrect /etc/hosts file in your test environment

Target:
private void init() { // get the localhost. try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { logger.warn("Error getting the value of localhost. " + "Proceeding with 'localhost'.", e); } }
Source:
START protected OSImageToImage(JustProvider provider) { END this.provider = provider; } Make it package private by removing the `protected` modifier.

Target:
OSImageToImage(JustProvider provider) { this.provider = provider; }