auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testFilterInitiator(){ String variableNameWithInitiator = "initiator"; String variableValueWithInitiator = "initiator people"; String variableNameWithoutInitiator = "noinitiator"; String variableValueWithoutInitiator = "other people"; assertEquals(presenter.filterInitiator(variableNameWithInitiator,variableValueWithInitiator,variableValueWithInitiator),true); assertEquals(presenter.filterInitiator(variableNameWithoutInitiator,variableValueWithoutInitiator,variableValueWithoutInitiator),false); assertEquals(presenter.filterInitiator(variableNameWithInitiator,variableValueWithInitiator,variableValueWithoutInitiator),false); assertEquals(presenter.filterInitiator(variableNameWithoutInitiator,variableValueWithoutInitiator,variableValueWithInitiator),false); }

Target:
expected value should be the first parameter in _assertEquals_
Source:
public void onProcessSelectionEvent(@Observes final ProcessDefSelectionEvent event) { String containerId = event.getDeploymentId(); String serverTemplateId = event.getServerTemplateId(); String processId = event.getProcessId(); processImageService.call((String svgContent) -> displayImage(svgContent), (String message, Throwable throwable) -> { displayImage(""); return false; }).getProcessDiagram(serverTemplateId, containerId, processId); }

Target:
I think in general we should avoid using the remote callback error like this because we might suppress other errors. Best would be handle it with the spec management call, testing if the container is started or not.
Source:
public void init() { caseService = new CallerMock<>(caseManagementService); when(caseManagementService.getCaseInstances(any(CaseInstanceSearchRequest.class))).thenReturn(caseInstanceSummaryList); presenter.setCaseService(caseService); when(view.getCaseInstanceSearchRequest()).thenReturn(new CaseInstanceSearchRequest()); doAnswer((i) ->{ presenter.refreshData(); return null; }).when(actions).onRefreshCaseClick(any(MouseEvent.class)); }

Target:
I gave a second thought on this test class and I think in here you're actually mocking the bit that needs to be tested. It would be better if you create a new test class for `CaseInstanceListSearchViewImpl` and then mock the presenter to verify it was actually called.
Source:
public AdvancedFilterEditor(DataSetClientServices dataSetClientServices) { initWidget(uiBinder.createAndBindUi(this)); this.dataSetClientServices = dataSetClientServices; okButton.setType(ButtonType.PRIMARY); okButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { ok(); } }); }

Target:
perhaps use lambda style in here :)
Source:
public void displayNotification(String text) { notification.fire(new NotificationEvent(text)); }

Target:
private?
Source:
private boolean isInvalidCommandTypeError(Throwable throwable) { String message = ""; if (throwable.getMessage() != null) { message = throwable.getMessage(); } else if (throwable.getCause() != null) { message = throwable.getCause().getMessage(); } return message.contains("Invalid command type"); }

Target:
As I mentioned, here we have a potential _NullPointerException_ gap. The _else if_ expression should be expanded to: ```else if (throwable.getCause() != null && throwable.getCause().getMessage() != null)```
Source:
public void openErrorView(final String id){ final PlaceRequest request = new DefaultPlaceRequest(EXECUTION_ERRORS); if(TASK_TYPE.equals(type)) { request.addParameter(SEARCH_PARAMETER_TASK_ID, id); } else { request.addParameter(SEARCH_PARAMETER_PROCESS_INSTANCE_ID, id); } request.addParameter(SEARCH_PARAMETER_IS_ERROR_ACK, Boolean.toString(false)); viewPresenter.openView(request); }

Target:
@mcivantos-tribalyte in here, I believe this class should not dependend on the domain ( task or process ), you could simply delegate back to the presenter that would know which paramters to add into the place request. Same goes for the _TASK_INSTANCE_ATTRIBUTE_ and _PROCESS_INSTANCE_ATTRIBUTE_ that could be generic as _data-jbpm-id_.
Source:
public void openErrorView(final String id){ final PlaceRequest request = new DefaultPlaceRequest(EXECUTION_ERRORS); request.addParameter(SEARCH_PARAMETER_IS_ERROR_ACK, Boolean.toString(false)); viewPresenter.openView(request,id); }

Target:
@mcivantos-tribalyte I still think that all of these should be moved to the presenter, in here you should only call the _openErrorView_ in the presenter.
Source:
public boolean isSupportedArrayComponentType(Class<?> componentType) { return byte.class == componentType || boolean.class == componentType || short.class == componentType || int.class == componentType || long.class == componentType || double.class == componentType; }

Target:
Swap the order so all the numbers are together
Source:
public boolean[] readBoolArray() throws TException { TList tList = protocol.readListBegin(); boolean[] array = new boolean[tList.size]; for (int i = 0; i < tList.size; i++) { array[i] = readBool(); } protocol.readListEnd(); return array; }

Target:
Just name this `list`?
Source:
public boolean[] read(TProtocol protocol) throws Exception { Preconditions.checkNotNull(protocol, "protocol is null"); return new TProtocolReader(protocol).readBoolArray(); }

Target:
Static import
Source:
public boolean isSupportedArrayComponentType(Class<?> componentType) { if (boolean.class == componentType) { return true; } if (short.class == componentType) { return true; } if (int.class == componentType) { return true; } if (long.class == componentType) { return true; } if (double.class == componentType) { return true; } return false; }

Target:
This would be easier to read if collapsed
Source:
public ThriftClient(ThriftClientManager clientManager, Class<T> clientType, ThriftClientConfig clientConfig, String clientName) { this(clientManager, clientType, defaultChannelFactory, clientConfig, clientName); }

Target:
a default value in the middle of the arguments (one c'tor being A, B, C, D, E, the other A, B, D, E) looks strange.
Source:
private void createScheduler() throws SchedulerException { // backwards compatibility - only use this when something is provided in // the config if (!configuration.getQuartzConfiguration().isEmpty()) { StdSchedulerFactory factory = new StdSchedulerFactory(); factory.initialize(createProperties()); scheduler = factory.getScheduler(); return; } scheduler = StdSchedulerFactory.getDefaultScheduler(); }

Target:
if you put it the other way around ```java if (configuration.getQuartzConfiguration().isEmpty()){ scheduler = StdSchedulerFactory.getDefaultScheduler(); } ``` you avoid the double negation - I find that a lot easier to read.
Source:
public String getEndpointHost() { if(endpointHost.startsWith("https://")){ return endpointHost.substring(8); } return endpointHost; }

Target:
```suggestion return endpointHost.substring("https://".length()); ``` Just a but more clear than the magic numbe `8`
Source:
private Resource getComponentResource(String resourceType, ResourceResolver resourceResolver) { String[] resolverSearchPaths = resourceResolver.getSearchPath(); for (String searchPath : resolverSearchPaths) { String tempResourceType = searchPath + resourceType; if (resourceResolver.getResource(tempResourceType) != null) { resourceType = searchPath + resourceType; return resourceResolver.getResource(resourceType); } } return null; }

Target:
```suggestion Resource resource = resourceResolver.getResource(searchPath + resourceType); if (resource != null) { return resource; ```
Source:
private String applyUrlRewrites(String url) { String path = URI.create(url).getPath(); for (Map.Entry<String, String> rewrite : urlRewrites.entrySet()) { if (path.startsWith(rewrite.getKey())) { return url.replaceFirst(rewrite.getKey(), rewrite.getValue()); } } return url; }

Target:
@leonbe02 LGTM - just want to double check that url will always be a valid param for `URI.create(..)`? I'd think if it isnt, and an IllegalArgumentException is thrown, it would be best just to use the param's original value?
Source:
public String getValue(Object obj) { Resource result = (Resource) obj; PageManager pageMgr = result.getResourceResolver().adaptTo(PageManager.class); Page page = Optional.ofNullable(pageMgr).map(p -> p.getContainingPage(result)).orElse(null); return page != null ? page.getPath() : ""; }

Target:
Instead of using orElse on line 42 you could combine the next line as another map call and then to orElse(null) in the return statement
Source:
public void addClientLibraries(ClientLibraryType type, Collection<String> categories) { Set<String> categoriesSet = clientLibraries.getOrDefault(type, new LinkedHashSet<>()); for (String category : categories) { categoriesSet.add(category); } clientLibraries.put(type, categoriesSet); }

Target:
Shouldn't this method simply call `public void addClientLibraries(ClientLibraryType type, String... categories)` after converting the collection to an array (or vice versa)? Codeclimate is gonna complain.
Source:
public String[] getAuthorizedGroups() { return new String[]{"administrators"}; }

Target:
this method should probably be final. Also it is missing the @Override annotation AFAICT
Source:
public void activate(ComponentContext context) throws LoginException { log.info("activate"); bctx = context.getBundleContext(); refreshCache(); log.info("Activation successful!"); }

Target:
trace?
Source:
public void deactivate(ComponentContext context) throws LoginException { log.info("deactivate"); for (String id : registeredServices.keySet()) { unregisterService(id); } log.info("Deactivation successful!"); }

Target:
trace?
Source:
public void start(Context c) { mContext = c; LocationManager lm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); if (mLastLocation == null) { mLastLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); } if (mLastLocation != null) { lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mNetworkLocationListener); } }

Target:
Why is this null checking before requesting locations? I would think it's ok to request new locations even if we didn't have a last known location in the GPS provider.
Source:
public static boolean shouldLog(ScanResult scanResult) { if (SSIDBlockList.isOptOut(scanResult)) { Log.w(LOG_TAG, "Blocked opt-out SSID"); return false; } if (BSSIDBlockList.contains(scanResult)) { Log.w(LOG_TAG, "Blocked BSSID: " + scanResult); return false; } if (SSIDBlockList.contains(scanResult)) { Log.w(LOG_TAG, "Blocked SSID: " + scanResult); return false; } return true; }

Target:
I don't think we need the warning level log here. Let's change that to a Log.d for debugging.
Source:
public void removeListener() { if (mLocationManager == null) { return; } mLocationManager.removeGpsStatusListener(mSatelliteListener); enableLocationListener(false, mGpsLocationListener); enableLocationListener(false, mNetworkLocationListener); mLocationManager = null; }

Target:
In my branch I have mLocationManager as final in this class, so I was planning to merge that. I don't understand setting the location manager to null, is there a reason? @cascheberg I apologize for being to be so slow with reviews, @crankycoder and I haven't been available much this week. Stumbler does need an update with this fix, and also we need to figure out why certain users are reporting stumbler pausing and not starting.
Source:
public static void createGlobalInstance(Context c) { if (sInstance != null) { return; } sInstance = new ClientPrefs(c); }

Target:
I generally like to have singletons to be synchronized. ClientPrefs is only instantiated in one place anyway, and that's single threaded, so this is more of a nit.
Source:
public static ClientPrefs getInstance() { assert(sInstance != null); assert(sInstance.getClass().isInstance(ClientPrefs.class)); return (ClientPrefs)sInstance; }

Target:
Does it make sense to change this to `getInstance(Context c)` and merge this with `createGlobalInstance`?
Source:
public Lease_newBreakOption(Lease lease) { super(Lease_newBreakOption.class); this.lease = lease; }

Target:
remove super(...) call
Source:
public boolean equals(final Object obj) { if (!(obj instanceof DueDateAmountMap)) { return false; } return innerMap.equals(obj); }

Target:
Why not just do this instead: `return obj instanceof DueDateAmountMap && innerMap.equals(obj);`
Source:
private Department getDepartment(HttpServletRequest request, List<Department> departments) { Department department = getDomainObject(request, "departmentID"); return department != null ? department : departments.stream().findAny().orElse(null); }

Target:
Creating a Stream for the sole purpose of retrieving a single element from the a List is a bit excessive. I suggest something like this instead: `return department != null ? department : departments.isEmpty() ? null : departments.get(0);`
Source:
public PhoneNumber parsePhoneNumber(String numberText) { if (!StringUtils.isEmpty(numberText)) { if (numberText.startsWith("00")) { numberText = numberText.replaceFirst("00", "+"); } try { final PhoneNumber phoneNumber = PHONE_UTIL.parse(numberText, null); if (PHONE_UTIL.isValidNumber(phoneNumber)) { return phoneNumber; } } catch (NumberParseException e) { System.out.println("O n�mero n�o � v�lido:" + e); return null; } } return null; }

Target:
Using System.out is strictly forbidden. This line should be deleted.
Source:
public String getInternationalFormatNumber(String numberText) { final PhoneNumber phoneNumber = parsePhoneNumber(numberText); if (phoneNumber != null) { return PHONE_UTIL.format(phoneNumber, PhoneNumberFormat.E164); } return null; }

Target:
Using the ternary operator here will result in nicer code: `return phoneNumber != null ? PHONE_UTIL.format(phoneNumber, PhoneNumberFormat.E164) : null`
Source:
private List<PhdCandidacyPeriod> getCandidacyPeriods() { List<PhdCandidacyPeriod> candidacyPeriodList = new ArrayList<>(); CollectionUtils.select(Bennu.getInstance().getCandidacyPeriodsSet(), new Predicate() { @Override public boolean evaluate(Object arg0) { return arg0 instanceof PhdCandidacyPeriod; } }, candidacyPeriodList); return candidacyPeriodList; }

Target:
this change is not in the scope of this issue.
Source:
static private String getDegreeCurricularPlansPresentationString(final Set<DegreeCurricularPlan> input) { String result = " [ "; for (Iterator<DegreeCurricularPlan> iterator = input.iterator(); iterator.hasNext();) { final DegreeCurricularPlan iter = iterator.next(); result += iter.getName(); if (iterator.hasNext()) { result += " , "; } } result += " ]"; return result; }

Target:
This should use a `StringBuilder` (the same goes for all the other usages of `+=` on Strings for this PR).
Source:
final public Double getWeight(ExecutionSemester semester) { if (isBolonhaDegree()) { return getEctsCredits(semester); } if (getDegreeType().isMasterDegree()) { return getCredits(); } final Double weigth = super.getWeigth(); return (weigth == null || weigth == 0.0) ? WEIGHT_FOR_PRE_BOLONHA : weigth; }

Target:
shouldn't the constants be removed from the source code?
Source:
public Degree getDegree() { return ((DegreeUnit) getDelegateFunction().getFunction().getUnit()).getDegree(); }

Target:
Why did you change the visibility of getDegree in this case?
Source:
private static void loadPokeZPowers() { if (zpowerloaded) { return; } testLoad();; zpowerloaded = true; String path = "db/moves/" + thisGen + "G/zpower.txt"; InfoFiller.fill(path, new FillerByte() { @Override void fillByte(int i, byte b) { moveNames.get(i).zpower = b; } }); }

Target:
a semicolon too much
Source:
public boolean accept(Path path) { String name = path.getName(); if (name.startsWith("_") || name.startsWith(".")) { return false; } return true; }

Target:
You can replace this with return !(name.startsWith("_") || name.startsWith(".")) Also can you add java docs for this class
Source:
public void after() throws IOException { EasyMock.verify(_mocks.toArray()); // Delete all camus data folder.delete(); }

Target:
Is calling verify() in After method a good practice? What if there's a test that doesn't need to verify all these mocks?
Source:
private boolean shouldFetchFromSchemaRegistry(String id) { if (!failedFetchHistories.containsKey(id)) { return true; } FailedFetchHistory failedFetchHistory = failedFetchHistories.get(id); boolean maxRetriesNotExceeded = failedFetchHistory.numOfAttempts < getByIdMaxRetries; boolean minRetryIntervalSatisfied = System.nanoTime() - failedFetchHistory.previousAttemptTime >= TimeUnit.SECONDS .toNanos(getByIdMinIntervalSeconds); return maxRetriesNotExceeded && minRetryIntervalSatisfied; }

Target:
Do you want to synchronize on this method?
Source:
public static Map<String, Partitioner> getPartitioners() { return partitionersByTopic; }

Target:
Should this method return the map or the values collection or values set?
Source:
public List<HashMap<String,Object>> getLoggedEvents(@RequestParam String site, @RequestParam long since) { return CircularQueueLogAppender.loggerQueue().getLoggedEvents(site, since); }

Target:
Please return a `Map`, not a `HashMap`.
Source:
protected boolean shouldNotFilter(final HttpServletRequest request) throws ServletException { SiteContext siteContext = SiteContext.getCurrent(); HierarchicalConfiguration config = siteContext.getConfig(); try { HierarchicalConfiguration corsConfig = config.configurationAt(CONFIG_KEY); if (corsConfig != null) { boolean enable = corsConfig.getBoolean(ENABLE_KEY, false); return !enable; } } catch (Exception e) { logger.debug("Site '{}' has no CORS configuration", siteContext.getSiteName()); } return true; }

Target:
Just return the result of corsConfig.getBoolean, instead of using a variable and then immediately returning it. The variable is not necessary and I think even Codacy wil complain.
Source:
private Set<Location> getAllChildAndGrandLocations(Set<Location> visitLocations){ Set<Location>allchildAndGrandVisitLocations=new HashSet<Location>(); for(Location visitLocation:visitLocations) { allchildAndGrandVisitLocations.addAll(visitLocation.getChildLocations()); if(visitLocation.getChildLocations() !=null) { getAllChildAndGrandLocations(allchildAndGrandVisitLocations); } else { break; } } return allchildAndGrandVisitLocations; }

Target:
Can you write a quick test to make sure this worked properly? I may be wrong, but I'm not sure the accumulation of results will work correctly?
Source:
public void started() { Context.getService(HtmlFormEntryService.class).addHandler("encounterProviderAndRole", new EncounterProviderAndRoleTagHandler()); log.info("Started HTML Form Entry Module"); }

Target:
Instead of adding this here, this should be added as an entry on the "handlers" bean in moduleApplicationContext, where the other ones were added. (Adding it via the activator in the 19ext module was a bit of a hack)
Source:
public void stopped() { HtmlFormEntryService hfes = Context.getService(HtmlFormEntryService.class); if (hfes != null) hfes.getHandlers().remove("encounterProviderAndRole"); log.info("Stopped HTML Form Entry Module"); }

Target:
This can be removed too, once we add the handler via moduleApplicationContext
Source:
protected void writeEntityToNBT(NBTTagCompound tags) { if(type == null) setDead(); else { tags.setString("Type", type.shortName); if(player != null) tags.setString("Player", player.get().getName()); tags.setFloat("RotationYaw", axes.getYaw()); tags.setFloat("RotationPitch", axes.getPitch()); } }

Target:
`player` won't be null since you set it to an Optional above.
Source:
public Team getTeam(EntityPlayer player) { String username = player.getName(); for(Team team : teams) { for (String name : team.members) { if (username.equals(name)) { return team; } } } return null; }

Target:
Would be worth returning an Optional in this method instead of returning null and having possible issues down the line.
Source:
public void launch(ISelection selection, String mode) { if (selection instanceof IStructuredSelection) { Object element = ((IStructuredSelection) selection).getFirstElement(); if (element != null && element instanceof IResource) { try { IResource selectedResource = (IResource) element; launchBower(selectedResource); } catch (CoreException e) { Activator.logError(e); } } } }

Target:
Check for null is not required here, because (element instance of IResource) returns false for null element.
Source:
public PaletteItemDropCommand(IPaletteItem paletteItem, boolean doNotShowWizard){ super(); this.paletteItem = paletteItem; this.doNotShowWizard = doNotShowWizard; wizard = paletteItem.createWizard(); corrector = paletteItem.createPositionCorrector(); }

Target:
Wizard instance is created too early. It should not be cached, and should be created by requesting paletteItem only in createDropWizard(). Implementation of getCustomWizardName() is not needed - it is used here only to check if wizard is available. Hence IPaletteItem just needs method hasWizard(). Old implementations called getCustomWizardName() to create wizard. Here, as wizard is created by IPaletteItem it should also answer if it can be created without actually creating it.
Source:
public void setCommand(IDropCommand command) { super.setCommand(command); IHTMLLibraryVersion vName = ((PaletteItemDropCommand)command).getPaletteItem().getCategory().getVersionGroup().getVersion(); for (IonicVersion v: IonicVersion.ALL_VERSIONS) { if(v.equals(vName)) { version = v; } } preferredVersions = new PreferredJSLibVersions(getFile(), getVersion()); preferredVersions.updateLibEnablementAndSelection(); }

Target:
It should be just version = (IonicVersion)((PaletteItemDropCommand)command).getPaletteItem().getCategory().getVersionGroup().getVersion(); even without check for instance of, because NewIonicWidgetWizard may not be initialized with other version than IonicVersion, it is an error that should cause failure. The same should be done in NewJQueryWidgetWizard.setCommand.
Source:
public String getKeywordsAsString(){ if(keywords == null){ List<String> list = PaletteInsertManager.getInstance().getKeyWords(xobject.getPath()); keywords = ""; if(list != null){ for(String word : list){ keywords += word + " "; } }else{ keywords = getLabel(); } } return keywords; }

Target:
Use StringBuilder instead.
Source:
public void resourceChanged(IResourceChangeEvent event) { if(event.getType() == IResourceChangeEvent.PRE_DELETE) { IResource resource = event.getResource(); IProject project = (IProject)resource.getAdapter(IProject.class); if(project != null) { if(mockProjectStore.containsKey(project)) { System.out.println("remove " + project); } mockProjectStore.remove(project); } } }

Target:
Remove this System.out.println please.
Source:
public JSLibModel getWorkingCopy() { if(workingCopy == null) { synchronized (this) { workingCopy = createCopy(getPreferenceModel()); } } return workingCopy; }

Target:
If you want to make this method thread safe then both if(workingCopy == null) and workingCopy = ... should be in the same synchronized block.
Source:
public void init(IWorkbench workbench, IStructuredSelection selection) { System.out.println("!!!!!!!!!!!!!!!!"); }

Target:
You forgot to remove this println.
Source:
public int hashCode() { final int iHash = Double.hashCode( getRealDouble() ); final int rHash = Double.hashCode( getImaginaryDouble() ); return Util.combineHash( iHash, rHash ); }

Target:
You probably want to swap these, so that `rHash <= getRealDouble()` and `iHash <= getImaginaryDouble()`, no?
Source:
protected T cache( final T type ) { if ( t == null ) t = type; return type == null ? t : type; }

Target:
This type cache in ImgFactory is unnecessary complicated. See https://github.com/maarzt/imglib2/commit/ce7966f27abab694e4b261671fe1d4f270bf19e8
Source:
final static public < A extends LongAccess > ArrayImg< Unsigned4BitType, A > unsigned4Bits( final A access, final long... dim ) { final ArrayImg< Unsigned4BitType, A > img = new ArrayImg<>( access, dim, new Fraction( 1, 64 ) ); final Unsigned4BitType t = new Unsigned4BitType( img ); img.setLinkedType( t ); return img; }

Target:
Shouldn't this be `new Fraction( t.getBitsPerPixel(), 64 )` instead of `new Fraction( 1, 64 )` here?
Source:
final static public < A extends LongAccess > ArrayImg< Unsigned2BitType, A > unsigned2Bits( final A access, final long... dim ) { final ArrayImg< Unsigned2BitType, A > img = new ArrayImg<>( access, dim, new Fraction( 1, 64 ) ); final Unsigned2BitType t = new Unsigned2BitType( img ); img.setLinkedType( t ); return img; }

Target:
Shouldn't this be `new Fraction( t.getBitsPerPixel(), 64 )` instead of `new Fraction( 1, 64 )` here?
Source:
final static public < A extends LongAccess > ArrayImg< UnsignedVariableBitLengthType, A > unsignedVariableBitLengths( final A access, final int nbits, final long... dim ) { final ArrayImg< UnsignedVariableBitLengthType, A > img = new ArrayImg<>( access, dim, new Fraction( 1, 64 ) ); final UnsignedVariableBitLengthType t = new UnsignedVariableBitLengthType( img, nbits ); img.setLinkedType( t ); return img; }

Target:
Shouldn't this be `new Fraction( t.getBitsPerPixel(), 64 )` instead of `new Fraction( 1, 64 )` here?
Source:
public boolean valueEquals( C t ) { if ( t.length == length ) { final Iterator< T > a = iterator(); final Iterator< T > b = iterator(); while ( a.hasNext() ) if ( !a.next().valueEquals( b.next() ) ) return false; return true; } else return false; }

Target:
One of these should be `t.iterator()`.
Source:
public static < A, B > RandomAccessiblePair< A, B > pair( final RandomAccessible< A > sourceA, final RandomAccessible< B > sourceB ) { return new RandomAccessiblePair< A, B >( sourceA, sourceB ); }

Target:
I would suggest to make the return type `RandomAccessible<Pair<A, B>>` or even `RandomAccessible<? extends Pair<A, B>>`, if there is no strong need for being _exactly_ `RandomAccessiblePair<A, B>`. I can imagine that we might want to add other variants implementing this later.
Source:
public HttpHeaders getHttpHeader(MediaType mediaType) { return HttpHeaders .of(HttpStatus.OK) .add(HttpHeaderNames.SERVER, "armeria") .add(HttpHeaderNames.DATE, DateTimeFormatter.RFC_1123_DATE_TIME .format(ZonedDateTime.now(ZoneOffset.UTC))) .contentType(mediaType); }

Target:
This method doesn't depend on any internal state so it can be `static`: ```java public static HttpHeaders getHttpHeader(MediaType mediaType) { ``` That way you don't need to create a new instance of `HttpHeadersHelper` in order to use the method. Where you call it, it'll look like: ```java HttpHeadersHelper.getHttpHeader(...) ``` rather than: ```java new HttpHeadersHelper().getHttpHeader(...) ```
Source:
public boolean configure(StaplerRequest req, JSONObject json) throws FormException { BulkChange b = new BulkChange(this); SMTPAuthentication current = this.authentication; try { // reset optional authentication to default before data-binding // Would not be necessary by https://github.com/jenkinsci/jenkins/pull/3669 this.authentication = null; req.bindJSON(this, json); b.commit(); } catch (IOException e) { this.authentication = current; b.abort(); throw new FormException("Failed to apply configuration", e, null); } return true; }

Target:
Should be in `finally` just in case
Source:
public void autoService() { JavaSourcesSubject.assertThat( JavaFileObjects.forResource("test/SomeService.java"), JavaFileObjects.forResource("test/SomeServiceProvider1.java"), JavaFileObjects.forResource("test/SomeServiceProvider2.java"), JavaFileObjects.forResource("test/Enclosing.java"), JavaFileObjects.forResource("test/AnotherService.java"), JavaFileObjects.forResource("test/AnotherServiceProvider.java")) .processedWith(new AutoServiceProcessor()) .compilesWithoutError() .and().generatesFiles( JavaFileObjects.forResource("META-INF/services/test.SomeService"), JavaFileObjects.forResource("META-INF/services/test.AnotherService")); }

Target:
nit: Can you static import `assertThat`
Source:
Set<ExecutableElement> abstractBuildMethods() { return ImmutableSet.copyOf(buildMethods).stream() .filter(MoreElements.hasModifiers(Modifier.ABSTRACT)) .collect(Collectors.toSet()); }

Target:
The `copyOf` seems superfluous here
Source:
private <K, V> ImmutableBiMap<K, V> newImmutableBiMapRemovingKeys(ImmutableBiMap<K, V> original, Set<K> keysToRemove) { ImmutableBiMap.Builder<K, V> builder = ImmutableBiMap.builder(); for (Map.Entry<K, V> property : original.entrySet()) { if (!keysToRemove.contains(property.getKey())) { builder.put(property); } } return builder.build(); }

Target:
Ugh, nevermind. **Immutable**BiMap
Source:
private <T> ImmutableSet<T> newFilteredImmutableSet(ImmutableSet<T> original, Predicate<T> predicate) { ImmutableSet.Builder<T> builder = ImmutableSet.builder(); for (T item : original) { if (predicate.apply(item)) builder.add(item); } return builder.build(); }

Target:
also looks like this method can be static
Source:
public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); if (extensions == null) { extensions = ServiceLoader.load(AutoValueExtension.class, getClass().getClassLoader()); } errorReporter = new ErrorReporter(processingEnv); }

Target:
I think I would do this directly in the no-arg constructor, i.e. ``` java this(ServiceLoader.load(AutoValueExtension.class, getClass().getClassLoader())); ```
Source:
protected Object readResolve() { if (dirName != null && delegate == null) { delegate = new AbstractOnDiskBinding.UnbinderImpl(dirName); } return this; }

Target:
Here `dirName` should never be null, and `delegate` should always be null.
Source:
private String result() { return new String(stream.toString()); }

Target:
I don't think you need this `new String`
Source:
public void clearErrors() { this.errors = Collections.emptyList(); }

Target:
errors can keep final, and instead of attribute `emptyList` here, you can call `List.clear()` method.
Source:
public RegexParseSpec( @JsonProperty("timestampSpec") TimestampSpec timestampSpec, @JsonProperty("dimensionsSpec") DimensionsSpec dimensionsSpec, @JsonProperty("listDelimiter") String listDelimiter, @JsonProperty("columns") List<String> columns, @JsonProperty("pattern") String pattern ) { super(timestampSpec, dimensionsSpec); this.listDelimiter = listDelimiter; Preconditions.checkNotNull(columns, "columns"); this.columns = columns; this.pattern = pattern; verify(dimensionsSpec.getDimensions()); }

Target:
are you sure you don't want this to be optional?
Source:
public Parser<String, Object> makeParser() { if(flattenSpec != null) { return new JSONPathParser(convertFieldSpecs(flattenSpec.getFields()), flattenSpec.isUseFieldDiscovery(), null); } else { return new JSONParser(objectMapper, null); } }

Target:
If possible I think we should always use the JSONPathParser (so, if there is no flattenSpec, use an empty fieldSpecs list and always enable discovery). I think for it to be possible we need: - `new JSONPathParser(ImmutableList.of(), true, objectMapper)` should behave effectively the same as `new JSONParser(objectMapper, null)` - performance should be similar or better I think this is a good goal because it means the underlying implementation won't be switched around just because someone has one thing they want to un-nest.
Source:
public TimestampSpec( @JsonProperty("column") String timestampColumn, @JsonProperty("format") String format ) { this.timestampColumn = (timestampColumn == null) ? defaultColumn : timestampColumn.toLowerCase(); this.timestampFormat = format == null ? defaultFormat : format; try { this.timestampConverter = ParserUtils.createTimestampParser(timestampFormat); } catch (ParseException e) { throw Throwables.propagate(e); } }

Target:
I don't think ParseException wrapping is the right thing here, because it is creating a parser, not actually parsing anything
Source:
private void setVendorFaxNumberValue(VendorAddress vendorAddress, String vendorFaxNumber) { try { Class type = ObjectUtils.easyGetPropertyType(vendorAddress, VendorPropertyConstants.VENDOR_FAX_NUMBER); ObjectUtils.setObjectProperty(vendorAddress, VendorPropertyConstants.VENDOR_FAX_NUMBER, type, vendorFaxNumber); } catch (FormatException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { vendorAddress.setVendorFaxNumber(null); LOG.error("setVendorFaxNumberValue: Vendor Fax Number cannot be set due to exception: " + e); e.printStackTrace(); } }

Target:
It would be better to use Log4j to print the stack trace, rather than using the exception's printStackTrace() method.
Source:
private String getSubmitter(String documentId) { String submitterPrincipalId = null; String principalId = workflowDocumentService.getRoutedByPrincipalIdByDocumentId(documentId); List<ActionTaken> actionTakenDTOs = workflowDocumentService.getActionsTaken(documentId); for (ActionTaken actionTaken : actionTakenDTOs) { if (principalId.equals(actionTaken.getPrincipalId())) { submitterPrincipalId = principalId; } } return submitterPrincipalId; }

Target:
I would suggest doing this principalId comparison in a null-safe way.
Source:
private Object[] buildClosedAccountsForItChartArgumentList(Map<String, Date> dateRange) { List<Object> argumentList = new ArrayList<>(); SimpleDateFormat formatter = new SimpleDateFormat(CUKFSConstants.DATE_FORMAT_dd_MMM_yy, Locale.US); argumentList.add(formatter.format(dateRange.get(CuCoaBatchConstants.ClosedAccountsFileCreationConstants.FROM_DATE))); argumentList.add(formatter.format(dateRange.get(CuCoaBatchConstants.ClosedAccountsFileCreationConstants.TO_DATE))); return argumentList.toArray(); }

Target:
Now that the query is using parameters for the dates, do you still need to format them as strings? I believe the parameter replacement can handle the dates as-is, as long as they're using the java.sql.Date or java.sql.Timestamp type.
Source:
private List<String> buildFileNameList(String... fileNames) { List<String> fileNameList = new ArrayList<String>(); for (String fileName : fileNames) { fileNameList.add(fileName); } return fileNameList; }

Target:
You could greatly simplify this code by using Arrays.asList() instead.
Source:
protected boolean defaultAccountIndicatorIsActive(String rowIndicatorValue) { return StringUtils.equals(rowIndicatorValue, KFSConstants.ACTIVE_INDICATOR) ? true : false; }

Target:
You can just return the StringUtils.equals() result directly; making it a ternary of "? true : false" is redundant.
Source:
protected void sendReport(RassBatchJobReport report) { LOG.debug("sendReport, The report-sending functionality has not been implemented yet."); rassReportService.sendReportEmail(); }

Target:
Now that you've implemented the reporting functionality, this log statement can be removed.
Source:
private void safelyAddProperty(Properties properties, String key, KualiDecimal value) { properties.put(key, ObjectUtils.isNull(value) ? KFSConstants.EMPTY_STRING : value.floatValue()); }

Target:
Should the KualiDecimal's value just be converted to a String instead of a float, to help avoid the risk of losing data? If you need to convert it to a primitive, I would suggest converting to a "double" instead if you can. The same goes for the equivalent BigDecimal method below.
Source:
private void safelyAddProperty(Properties properties, String key, Integer value) { properties.put(key, ObjectUtils.isNull(value) ? KFSConstants.EMPTY_STRING : value.intValue()); }

Target:
Do you need to call intValue() here? This particular line of code is just going to implicitly convert the primitive int back into an Integer.
Source:
public static <T extends Document> T buildMockDocument(Class<T> documentClass) { PowerMockito.suppress(PowerMockito.constructor(LedgerPostingDocumentBase.class)); T document = null; try { document = PowerMockito.spy(documentClass.newInstance()); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); throw new RuntimeException(e); } performInitializationFromSkippedConstructor(document); return document; }

Target:
should this be logged instead of printed?
Source:
private static CuRequisitionDocument buildMockCuRequisitionDocument() { PowerMockito.suppress(PowerMockito.constructor(LedgerPostingDocumentBase.class)); CuRequisitionDocument document = PowerMockito.spy(new CuRequisitionDocument()); return document; }

Target:
This exact same suppression is being called by all three of the document-building methods in this class. Would it be possible to perform the suppression in a "Before" or "BeforeClass" annotated method? Or is it necessary to suppress this right before the constructor call?
Source:
public int hashCode() { return Objects.hash(proposalNumber, status, projectTitle, startDate, stopDate, directCostAmount, indirectCostAmount, totalAmount, grantNumber, grantDescription, federalPassThrough, federalPassThroughAgencyNumber, cfdaNumber, organizationCode, costShareRequired, finalReportDueDate, principalAndCoPrincipalInvestigators, principalAndCoPrincipalInvestigators); }

Target:
The "principalAndCoPrincipalInvestigators" list is being hashed twice. I would suggest using it only once when building the hashCode.
Source:
private DateTime parseShortDate(String dateString) { if (StringUtils.isNotBlank(dateString)) { return new DateTime(RassStringToJavaShortDateTimeAdapter.parseToDateTime(dateString).toDate()); } else { return null; } }

Target:
The method RassStringToJavaShortDateTimeAdapter.parseToDateTime() is already returning a DateTime, so extracting its Date value and re-wrapping it in a new DateTime seems redundant.
Source:
private RassXmlDocumentWrapperFixture(String extractDateString, RassXmlAwardEntryFixture[] awardsArray, RassXmlAgencyEntryFixture[] agencyArray) { extractDate = new DateTime(RassStringToJavaLongDateTimeAdapter.parseToDateTime(extractDateString).toDate()); awards = XmlDocumentFixtureUtils.toImmutableList(awardsArray); agencies = XmlDocumentFixtureUtils.toImmutableList(agencyArray); }

Target:
Another potential redundant re-wrap of a DateTime value.
Source:
public void testFindMimeTypeNullFileName() { String mimeType = attachmentService.findMimeType(StringUtils.EMPTY); assertEquals(StringUtils.EMPTY, mimeType); }

Target:
This test case is actually using an empty string instead of a null string. Should it be updated to use a null string, or should this test method just be removed altogether?
Source:
public List<IndirectCostRecoveryAccount> getActiveIndirectCostRecoveryAccounts() { List<IndirectCostRecoveryAccount> activeList = new ArrayList(); for (IndirectCostRecoveryAccount icr : getIndirectCostRecoveryAccounts()) { if (icr.isActive()) { activeList.add(IndirectCostRecoveryAccount.copyICRAccount(icr)); } } return activeList; }

Target:
Diamond operator is missing from this statement.
Source:
protected boolean shouldValidateOnBudgetTotal() { Boolean validateOnBudgetTotal = parameterService.getParameterValueAsBoolean(ArConstants.AR_NAMESPACE_CODE, ArConstants.CONTRACTS_GRANTS_INVOICE_COMPONENT, CuArConstants.CG_INVOICE_AMT_BILLED_SUSPENSION_BY_BUDGET_TOTAL, Boolean.TRUE.booleanValue()); if (LOG.isDebugEnabled()) { LOG.debug("shouldValidateOnBudgetTotal, the value of " + CuArConstants.CG_INVOICE_AMT_BILLED_SUSPENSION_BY_BUDGET_TOTAL + " is " + validateOnBudgetTotal.booleanValue()); } return validateOnBudgetTotal.booleanValue(); }

Target:
This ParameterService method accepts a Boolean object, so you don't need to unbox Boolean.TRUE here.
Source:
private void configureParameterServiceForSuspensionCheck(Boolean value) { Mockito.when(parameterService.getParameterValueAsBoolean(ArConstants.AR_NAMESPACE_CODE, ArConstants.CONTRACTS_GRANTS_INVOICE_COMPONENT, CuArConstants.CG_INVOICE_AMT_BILLED_SUSPENSION_BY_BUDGET_TOTAL, Boolean.TRUE.booleanValue())).thenReturn(value); suspensionCategory.setParameterService(parameterService); }

Target:
Another area where Boolean unboxing may not be needed.
Source:
protected boolean checkContinuationAccountsForNewSubAccounts(MaintenanceDocument maintenanceDocument) { SubAccountGlobal subAccountGlobal = (SubAccountGlobal) maintenanceDocument.getNewMaintainableObject().getBusinessObject(); subAccountGlobal.getSubAccountGlobalNewAccountDetails().stream() .forEach(this::updateDetailToUseContinuationAccountIfNecessary); return true; }

Target:
Is .stream() needed since the getSubAccountGlobalNewAccountDetails() returns a List?
Source:
protected String getDescriptivePayeeTypesAsString(Collection<String> payeeTypeCodes) { List<String> payeeTypeDescriptions = new ArrayList<>(); for (String payeeTypeCode : payeeTypeCodes) { String description = disbursementVoucherPayeeService.getPayeeTypeDescription(payeeTypeCode); if (payeeTypeDescriptions.indexOf(description) == -1) { payeeTypeDescriptions.add(description); } } return this.convertListToString(payeeTypeDescriptions); }

Target:
Is "this" needed here?
Source:
public List<? extends GlobalBusinessObjectDetail> getAllDetailObjects() { List<GlobalBusinessObjectDetail> detailObjects = new ArrayList<>(); detailObjects.addAll(subAccountGlobalDetails); detailObjects.addAll(subAccountGlobalNewAccountDetails); return subAccountGlobalDetails; }

Target:
I think the return object needs to be updated to return the new detailObjects
Source:
private KfsVendorDataWrapper createInsuranceCertificateNote(PaymentWorksVendor pmwVendor, KfsVendorDataWrapper kfsVendorDataWrapper) { if (paymentWorksVendorIsPurchaseOrderVendor(pmwVendor) && StringUtils.isNotBlank(pmwVendor.getInsuranceCertificate())) { StringBuilder sbText = new StringBuilder(getConfigurationService().getPropertyValueAsString(PaymentWorksKeyConstants.NEW_VENDOR_PVEN_NOTES_INSURANCE_CERTIFICATE_URL_EXISTS_MESSAGE)); kfsVendorDataWrapper = getPaymentWorksBatchUtilityService().createNoteRecordingAnyErrors(kfsVendorDataWrapper, sbText.toString(), PaymentWorksConstants.ErrorDescriptorForBadKfsNote.INSURANCE_CERTIFICATE.getNoteDescriptionString()); } return kfsVendorDataWrapper; }

Target:
Nothing is being appended to this StringBuilder after constructing it with the initial text, so this could be replaced with a plain String instead.
Source:
public void updateExistingPaymentWorksVendorInStagingTable(Integer id, String kfsVendorProcessingStatus, Integer vendorHeaderGeneratedIdentifier, Integer vendorDetailAssignedIdentifier, Timestamp processingTimeStamp) { updateExistingPaymentWorksVendorInStagingTable(id, null, kfsVendorProcessingStatus, KFSConstants.EMPTY_STRING, KFSConstants.EMPTY_STRING, KFSConstants.EMPTY_STRING, processingTimeStamp, vendorHeaderGeneratedIdentifier, vendorDetailAssignedIdentifier, null); }

Target:
The second arg for this call should also be set to an empty string.
Source:
protected org.kuali.kfs.fp.businessobject.DisbursementVoucherNonEmployeeExpense buildNonEmployeeExpense() { org.kuali.kfs.fp.businessobject.DisbursementVoucherNonEmployeeExpense nonEmployeeExpense = new org.kuali.kfs.fp.businessobject.DisbursementVoucherNonEmployeeExpense(); return nonEmployeeExpense; }

Target:
Would it be better to shorten this to return new org.kuali.kfs.fp.businessobject.DisbursementVoucherNonEmployeeExpense() in one line?
Source:
protected org.kuali.kfs.fp.businessobject.DisbursementVoucherNonEmployeeExpense buildNonEmployeeExpense() { org.kuali.kfs.fp.businessobject.DisbursementVoucherNonEmployeeExpense expense = Mockito.spy(new org.kuali.kfs.fp.businessobject.DisbursementVoucherNonEmployeeExpense()); Mockito.doNothing().when(expense).refreshNonUpdateableReferences(); return expense; }

Target:
Could you import this Class to make the method cleaner?
Source:
protected void findAndResetInvoiceColumn(ResultRow row) { row.getColumns().stream() .filter(col -> StringUtils.equalsAnyIgnoreCase(col.getPropertyName(), INVOICE_LINK_COLUMN_NAME)) .findFirst() .ifPresent(col -> resetInvoiceColumn(row, col)); }

Target:
Another spot where you could use "equalsIgnoreCase" instead of "equalsAnyIgnoreCase".
Source:
private boolean recordPvenRouteStatusChangeForPaymentWorksIsEnabled() { return (getPaymentWorksBatchUtilityService().retrievePaymentWorksParameterValue(PaymentWorksParameterConstants.PMW_INTEGRATION_IS_ACTIVE_IND).equalsIgnoreCase(KFSConstants.ParameterValues.YES) ? true : false); }

Target:
You're already getting a boolean result from this check, so adding a ternary operation of "? true : false" is redundant.
Source:
private boolean servicesAreBeingProvided(PaymentWorksVendor pmwVendor) { return (StringUtils.isNotBlank(pmwVendor.getServicesProvided()) && (StringUtils.equalsIgnoreCase(pmwVendor.getServicesProvided(), PaymentWorksConstants.PaymentWorksGoodsVsServicesOptions.SERVICES.getOptionValueAsString()) | StringUtils.equalsIgnoreCase(pmwVendor.getServicesProvided(), PaymentWorksConstants.PaymentWorksGoodsVsServicesOptions.GOODS_WITH_SERVICES.getOptionValueAsString()))); }

Target:
This operator should be changed from a bitwise OR to a logical OR.
Source:
public boolean equals(Object comparingDefaultKfsAccountForAws) { if (comparingDefaultKfsAccountForAws == null) { return false; } if (!(comparingDefaultKfsAccountForAws instanceof DefaultKfsAccountForAws)) { return false; } final DefaultKfsAccountForAws defaultKfsAccountForAws = (DefaultKfsAccountForAws) comparingDefaultKfsAccountForAws; return ObjectUtils.equals(defaultKfsAccountForAws.getKfsDefaultAccount(), kfsDefaultAccount) && ObjectUtils.equals(defaultKfsAccountForAws.getAwsAccount(), awsAccount) && ObjectUtils.equals(defaultKfsAccountForAws.getUpdatedAt(), updatedAt); }

Target:
I think StringUtils would be better here
Source:
private boolean pmwDtosCouldConvertCustomAttributesToPmwJavaClassAttributes(PaymentWorksVendor stgNewVendorRequestDetailToProcess) { if (stgNewVendorRequestDetailToProcess.isCustomFieldConversionErrors()) { return false; } else{ return true; } }

Target:
could probably just return !stgNewVendorRequestDetailToProcess.isCustomFieldConversionErrors()?
Source:
public KualiAddress() { super(); this.active = true; this.objectId = UUID.randomUUID().toString(); }

Target:
there is no need to set the value for the object id
Source:
private void logAccountingLineBaseList(List accountingLines, StringBuilder sb) { List<AccountingLineBase> accountingLineBases = accountingLines; accountingLineBases.stream().map(line -> line.toString()).forEach(sb::append); }

Target:
You could simplify this by using a method reference for the "toString" call.
Source:
protected void cleanTransactionsTable() { LOG.info("cleanTransactionsTable, cleaning CorporateBilledCorporatePaidTransaction table"); businessObjectService.deleteMatching(CorporateBilledCorporatePaidTransaction.class, new HashMap()); }

Target:
Missing generics on HashMap.
Source:
private boolean corporateAddressExists(PaymentWorksNewVendorDetailDTO paymentWorksNewVendorDetailDTO) { if (ObjectUtils.isNotNull(paymentWorksNewVendorDetailDTO.getRequesting_company().getCorp_address())) { return true; } else { return false; } }

Target:
do you need to check for nulls on paymentWorksNewVendorDetailDTO and paymentWorksNewVendorDetailDTO.getRequesting_company()?
Source:
private void logErrorsWithOriginalAccountingDetails(ConcurStandardAccountingExtractDetailLine line) { ConcurAccountInfo accountingInformation = buildConcurAccountingInformation( line, line.getJournalAccountCode(), line.getSubObjectCode()); buildValidationResult(accountingInformation, false); }

Target:
This line should be updated to call the new one-arg buildConcurAccountingInformation() method so that it logs errors for the correct sub-object code.
Source:
public boolean validateConcurStandardAccountingExtractDetailLineWithObjectCodeOverride(ConcurStandardAccountingExtractDetailLine line, ConcurStandardAccountingExtractBatchReportData reportData, String overriddenObjectCode, String overriddenSubObjectCode) { boolean valid = validateConcurStandardAccountingExtractDetailLineBase(line, reportData); valid = validateAccountingLineWithObjectCodeOverrides(line, reportData, overriddenSubObjectCode, null) && valid; return valid; }

Target:
Based on the new method signature, the third arg should be the object code and the fourth should be the sub-object code.
Source:
private ConcurAccountInfo buildConcurAccountingInformation(ConcurStandardAccountingExtractDetailLine line) { String objectCode = line.getJournalAccountCode(); String subObjectCode; if (getConcurBatchUtilityService().lineRepresentsPersonalExpenseChargedToCorporateCard(line)) { subObjectCode = line.getSubObjectCode(); } else { subObjectCode = line.getReportSubObjectCode(); } ConcurAccountInfo accountingInformation = buildConcurAccountingInformation(line, objectCode, subObjectCode); return accountingInformation; }

Target:
The if-else results here need to be reversed, so that the original sub-object code is used for non-personal-expense situations.
Source:
private boolean isDetailFileLineValidCashAdvanceRequest(ConcurRequestExtractRequestDetailFileLine detailFileLine) { if (detailFileLine.getValidationResult().isCashAdvanceLine() && detailFileLine.getValidationResult().isValidCashAdvanceLine()) { return true; } else { return false; } }

Target:
Can we just return the boolean expression?