auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void DeleteAndRestoreMapTests_004_StaffUserCanDeleteMap() { WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); InteractiveMapPageObject selectedMap = base.openInteractiveMapById(wikiURL, InteractiveMapsContent.mapToDeleteAndRestore); selectedMap.verifyMapOpened(); String deletedMapId = selectedMap.getEmbedMapID(); DeleteAMapComponentObject deleteMapModal = selectedMap.deleteMap(); InteractiveMapsPageObject specialMap = deleteMapModal.deleteMap(); specialMap.verifyMapDeletedMessage(); }

Target:
Would suggest using another MapID for 004 and 005 to break dependency from 001 and 002 to be successful
Source:
public void DeleteAndRestoreMapTests_005_StaffUserCanRestoreMap() { WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); InteractiveMapPageObject selectedMap = base.openInteractiveMapById(wikiURL, InteractiveMapsContent.mapToDeleteAndRestore); selectedMap.verifyMapOpened(); selectedMap.verifyMapDeletedMsg(); selectedMap.restoreMap(); selectedMap.verifyMapDeletedMsgNotVisible(); }

Target:
Would suggest using another MapID for 004 and 005 to break dependency from 001 and 002 to be successful
Source:
public void DeleteAndRestoreMapTests_006_SysOpCanDeleteMap() { WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userNameSysop, credentials.passwordSysop, wikiURL); InteractiveMapPageObject selectedMap = base.openInteractiveMapById(wikiURL, InteractiveMapsContent.mapToDeleteAndRestore); selectedMap.verifyMapOpened(); String deletedMapId = selectedMap.getEmbedMapID(); DeleteAMapComponentObject deleteMapModal = selectedMap.deleteMap(); InteractiveMapsPageObject specialMap = deleteMapModal.deleteMap(); specialMap.verifyMapDeletedMessage(); }

Target:
Would suggest using another MapID for 006 and 007 to break dependency from 001 and 002 to be successful
Source:
public void DeleteAndRestoreMapTests_007_SysOpCanRestoreMap() { WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userNameSysop, credentials.passwordSysop, wikiURL); InteractiveMapPageObject selectedMap = base.openInteractiveMapById(wikiURL, InteractiveMapsContent.mapToDeleteAndRestore); selectedMap.verifyMapOpened(); selectedMap.verifyMapDeletedMsg(); selectedMap.restoreMap(); selectedMap.verifyMapDeletedMsgNotVisible(); }

Target:
Would suggest using another MapID for 006 and 007 to break dependency from 001 and 002 to be successful
Source:
public int getNumberOfResultTemplates() { switchToIFrame(); int numberOfTemplates = -1; if (checkIfElementOnPage(resultTemplatesBy)) { numberOfTemplates = resultTemplates.size(); } else { numberOfTemplates = 0; } switchOutOfIFrame(); PageObjectLogging.log("getNumberOfResultTemplates", "Number of result templates found: " + numberOfTemplates, true); return numberOfTemplates; }

Target:
Why are you assigning -1 to numberOfTemplates, if you assigning different value in the next line?
Source:
public int getNumberOfResultTemplates() { switchToIFrame(); int numberOfTemplates = 0; if (checkIfElementOnPage(resultTemplatesBy)) { numberOfTemplates = resultTemplates.size(); } switchOutOfIFrame(); PageObjectLogging.log("getNumberOfResultTemplates", "Number of result templates found: " + numberOfTemplates, true); return numberOfTemplates; }

Target:
method can look like this: ``` switchToIFrame(); try { if (resultTemplates.isEmpty()) { return 0; } else { return resultTemplates.size(); } } finally { PageObjectLogging.log("getNumberOfResultTemplates", "Number of result templates found: " + resultTemplates.size(), true); switchOutOfIFrame(); } ``` decide if this is more readable to you
Source:
protected boolean checkIfElementOnPage(By cssSelectorBy) { changeImplicitWait(500, TimeUnit.MILLISECONDS); boolean isElementOnPage = true; try { if (driver.findElements(cssSelectorBy).size() < 1) { isElementOnPage = false; } } catch (Exception ex) { isElementOnPage = false; } finally { restoreDeaultImplicitWait(); } return isElementOnPage; }

Target:
why catch all exception?
Source:
public void verifyMonetizationModuleShown() { Assertion.assertTrue(checkIfElementOnPage(monetizationModuleContainer)); PageObjectLogging.log("verifyMonetizationModuleShown", "Monetization module is shown", true); waitForElementByElement(monetizationModuleContainer); PageObjectLogging.log("verifyMonetizationModuleShown", "Monetization module is visible", true); }

Target:
is it necessary to log here? The assertion above would put logging into the file already. Also, I see that there's another logging at the end of the method
Source:
public void verifyMonetizationModuleAdsenseShown() { Assertion.assertTrue(checkIfElementOnPage(adsenseContainer)); Assertion.assertTrue(checkIfElementOnPage(adsenseIns)); PageObjectLogging.log("verifyMonetizationModuleAdsenseShown", "Monetization module is shown (adsense)", true); waitForElementByElement(adsenseContainer); PageObjectLogging.log("verifyMonetizationModuleAdsenseShown", "Monetization module is visible (adsense)", true); }

Target:
s it necessary to log here? The assertion above would put logging into the file already. Also, I see that there's another logging at the end of the method
Source:
public void setCookieGeo(String countryCode) { String cookieName = "Geo"; try { JSONObject geo = new JSONObject(); geo.put("country", countryCode); String value = geo.toString(); setCookie(cookieName, value); } catch (JSONException ex) { PageObjectLogging.log("setCookieGeo", "Cannot set cookie ('" + cookieName + "')", true); } }

Target:
This variable is not necessary since you are only using it for the next line.
Source:
public DeleteAMapComponentObject deleteMap() { waitForElementByElement(actionDropDown); Actions actions = new Actions(driver); actions .click(actionDropDown) .click(deleteMapButton) .build() .perform(); return new DeleteAMapComponentObject(driver); }

Target:
Why is action object necessary here? Isn't it enough with clicking just the two desired elements below using click methods?
Source:
public ArticlePageObject savePage() { switchToIFrame(); waitForElementInViewPort(editSummary); WebElement publishButton = driver.findElement(By.cssSelector(".oo-ui-window-foot .oo-ui-flaggableElement-constructive .oo-ui-labeledElement-label")); waitForElementClickableByElement(publishButton); //Temp work around - The dialog needs time to transition to the front try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } publishButton.click(); PageObjectLogging.log("savePage", "The 2nd Publish Button is clicked", true); switchOutOfIFrame(); return new ArticlePageObject(driver); }

Target:
please move 'By.cssSelector(".oo-ui-window-foot .oo-ui-flaggableElement-constructive .oo-ui-labeledElement-label")' on the top of class as By
Source:
public void clickPublishButtonDropdown() { scrollAndClick(cssPublishButtonDropdown); PageObjectLogging.log("clickCssPublishButton", "click on publish button dropdown", true); waitForElementByElement(cssPublishButtonDropdown); }

Target:
is there any reason that you wait for element after clicking it? if not please remove it from the method :)
Source:
public String getEmbedMapWikiCode(){ String mapID = mapFrame.getAttribute("data-mapid"); String r = "<imap map-id='"+mapID+"'/>"; return r; }

Target:
I believe you could just combine the two lines and just return "<imap map-id='"+mapID+"'/>";
Source:
public void verifyTemplateWasFound() { waitForElementVisibleByElement(templatesBox); waitForElementByElement(thumbCollection.get(0)); System.out.println(thumbCollection.get(0)); System.out.println(checkIfElementOnPage(thumbCollection.get(0))); Assertion.assertEquals(checkIfElementOnPage(thumbCollection.get(0)), true); }

Target:
remove the console printout system.out.println
Source:
public String getAssociatedArticleImageSrc() { waitForElementByElement(associatedArticleImage); String imageSrc = articleImageUrl.getAttribute("src"); System.out.println(imageSrc); return imageSrc; }

Target:
remove system out print
Source:
public String getAssociatedArticleImageSrc() { waitForElementByElement(associatedArticleImage); String imageSrc = articleImageUrl.getAttribute("src"); return imageSrc; }

Target:
Could return articleImageUrl.getAttribute("src"); in one line since imageSrc is not being used anywhere else.
Source:
public void typePinDescription(String pinDescription) { waitForElementByElement(descriptionField); descriptionField.sendKeys(pinDescription); PageObjectLogging.log("typePinDescription", "Pin description was typed in", true); }

Target:
As I see that in the other method, the parameter is also in the log. Consider adding pinDescription into the log?
Source:
public void verifyAllPinTypesIsUncheck() { try { waitForElementVisibleByElement(mapFrame); driver.switchTo().frame(mapFrame); waitForElementVisibleByElement(allPinTypes); if (!allPinTypes.getAttribute("class").contains("enabled")) { PageObjectLogging.log("verifyAllPointTypesIsUnCheck", "All pin types were unchecked", true); } driver.switchTo().defaultContent(); }catch (Exception e) { PageObjectLogging.log("verifyAllPointTypesIsUnCheck", "All pin types were checked", false); } }

Target:
log the error stack instead
Source:
public void verifyPinNotExist(String pinTitle) { Integer pinSize = pinCollection.size() - 1; while (pinSize >= 0) { if (pinCollection.get(pinSize).getText().contains(pinTitle)) { break; } pinSize--; } Assertion.assertEquals(pinSize.intValue(), -1, "Pin was deleted correctly"); }

Target:
why is Integer needed here instead of int?
Source:
public void verifyPinDataWasChanged(String pinName, String pinDesc) { waitForElementVisibleByElement(mapFrame); driver.switchTo().frame(mapFrame); waitForElementVisibleByElement(popUpContent); scrollToElement(popUpContent); waitForElementVisibleByElement(pinTitle); waitForElementVisibleByElement(pinDescription); String actualTitle = pinTitle.getText(); String actualDesc = pinDescription.getText(); Assertion.assertNotEquals(pinName, actualTitle); Assertion.assertNotEquals(pinDesc, actualDesc); }

Target:
use pinTitle.getText(); and remove the variable that is being used once.
Source:
public String getMapLink(int mapIndex) { String mapLink = mapList.get(mapIndex).getAttribute("href"); return mapLink; }

Target:
return in one line
Source:
public String getMapTitle(int mapIndex) { String mapTitle = mapTitleList.get(mapIndex).getText(); return mapTitle; }

Target:
return in one line
Source:
public File getUploadedImage() { waitForElementByElement(thumbnailImage); File uploadedImageFile = new File(PageContent.resourcesPath + "shouldBeDeleted.png"); try { URL url = new URL(thumbnailImage.getAttribute("src")); BufferedImage bufImgOne = ImageIO.read(url); ImageIO.write(bufImgOne, "png", uploadedImageFile); } catch (IOException e) { e.printStackTrace(); } return uploadedImageFile; }

Target:
maybe instead of printing stack trace to console you can throw RuntimeException? It doesn't have to be declared and if something goes wrong you are notified about it in the right way - you don't need to look for the cause in logs
Source:
public void RTEDisabledEditorEntryDefaultPreferredTests_001_CreatePageEntry() { String articleName = PageContent.articleNamePrefix + base.getTimeStamp(); ArticlePageObject article = base.openArticleByName(wikiURL, articleName); VisualEditorPageObject ve = article.createArticleInVEUsingDropdown(articleName); ve.verifyVEToolBarPresent(); ve.verifyEditorSurfacePresent(); ve.logOut(wikiURL); }

Target:
It'll fit in one line
Source:
public void verifyUndoSucceeded() { driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); waitForElementByElement(notification); String notificationMsg = notification.getText(); Assertion.assertEquals(notificationMsg, "This page has been restored."); PageObjectLogging.log("verifyUndoSucceeded", "able to undo a swapped video", true); }

Target:
Please remove this line. It is not needed
Source:
public void banUser(String userName, WebDriver driver) { clickBanUser(userName, driver); chatBanModalButton.click(); waitForElementNotVisibleByElement(chatBanModal); PageObjectLogging.log("clickBanUser", userName+" ban modal is closed", true, driver); }

Target:
remove 'driver' parameter from log( ... ) method with "driver" parameter screenshot will be taken, thus test will execute longer, we possibly omit taking screnshoots, as it increases execution tmie
Source:
public void unBanUser(String userName, WebDriver driver) { WebElement unbanLink = driver.findElement(By.xpath( String.format(userUnbanLink, userName) )); waitForElementByElement(unbanLink); unbanLink.click(); verifyChatUnbanMessage(userName); PageObjectLogging.log("unBanUser", userName+" is no longer banned", true, driver); }

Target:
remove 'driver' parameter from log( ... ) method
Source:
public String getLastEditHistoryDevice() { return editHistoriesDevice.get(0).getText(); }

Target:
change to private
Source:
public void MobileLogin_002_failedLoginWrongPassword() { MobileBasePageObject mobile = new MobileBasePageObject(driver); mobile.openHome(wikiURL); mobile.openRandomPage(); System.out.println(credentials.userName12); MobileSpecialUserLogin login = mobile.loginFailedDropDown(credentials.userName12, mobile.getTimeStamp()); login.verifyWrongPasswordErrorMessage(); }

Target:
remove this line
Source:
public void MobileLogin_004_failedLoginEmptyPassword_MOB_760() { MobileBasePageObject mobile = new MobileBasePageObject(driver); mobile.openHome(wikiURL); mobile.openRandomPage(); System.out.println(credentials.userName12); MobileSpecialUserLogin login = mobile.loginFailedDropDown(credentials.userName12, ""); login.verifyEmptyPasswordErrorMessage(); }

Target:
remove this line
Source:
public void appendNewLine(String content) { waitForElementByElement(sourceModeTextArea); sourceModeTextArea.sendKeys(Keys.ENTER); sourceModeTextArea.sendKeys(content); PageObjectLogging.log("appendNewLine", "text "+content+" added to the source mode in new line", true); }

Target:
This can be reverted back to being private
Source:
public String removeQueryStringsFromURL(String url) { if (url.contains("?")) { return url.substring(0, url.indexOf("?")); } else return url; }

Target:
you can either remove else or add pair of curly brackets
Source:
public void verifyAddTableLightbox() { waitForElementByElement(addTableLightbox); Assertion.assertTrue(lightboxBackground.getCssValue("background-color").equals(backgroundLigthboxColor)); }

Target:
why this assertion is necessary?
Source:
public TableBuilderComponentObject clickAddTableButton(){ waitForElementClickableByElement(addTableButton); addTableButton.click(); PageObjectLogging.log("addTable", "add table button clicked", true); return new TableBuilderComponentObject(driver); }

Target:
you don't have to wait for it
Source:
public void addContent(String content) { sourceModeTextArea.sendKeys(content); PageObjectLogging.log("addContent", "content was added", true, driver); }

Target:
remove driver, there is no need to capture screenshot after sending keys
Source:
public String getFirstDescription() { waitForElementByElement(firstResult); return firstResultDescription.getText(); }

Target:
this element is load by ajax? you probably don't have to wait for an element here
Source:
public void verifyQuery(String query) { boolean flag = false; for (WebElement element:resultLinks) { if (element.getText().contains(query)){ flag=true; } } Assertion.assertTrue(flag, "there is no result link in the page"); }

Target:
change flag to isPresent
Source:
public void switchAndQuoteMessageWall(String reply) { driver.switchTo().defaultContent(); driver.switchTo().frame(quoteMessageWallFrame); driver.findElement(By.cssSelector("body#bodyContent")).clear(); driver.findElement(By.cssSelector("body#bodyContent")).sendKeys(reply); PageObjectLogging.log("switchAndQuoteMessageWall", "quote typed", true); }

Target:
remove this line
Source:
public NewMessageWallThreadPageObject openThread(String threadName) { for (WebElement thread:threadList) { if (thread.getText().contains(threadName)){ scrollAndClick(thread); } break; } return new NewMessageWallThreadPageObject(driver); }

Target:
with break statement here the process will get outside of the "for" loop after the first round. So only one element of threadList will be considered...
Source:
public void verifyInputExpand(String comment) { showCommentsSection(); String inputHeight = commentInputArea.getCssValue("height"); commentInputArea.sendKeys(comment); String inputExpandedHeight = commentInputArea.getCssValue("height"); Assertion.assertTrue(Integer.parseInt(inputExpandedHeight.substring(0, 1)) > Integer.parseInt(inputHeight.substring(0, 1)), "input is not bigger" ); }

Target:
wrong formatting, hard to read
Source:
public void verifySectionVisibility(){ waitForElementByElement(sectionVisibilityElement); PageObjectLogging.log("verifySectionVisibility", "section is opened and visible", true, driver); }

Target:
I know its not your line, but please remove "driver" parameter. This parameter is not needed here, because screenshot is not needed in verification methods.
Source:
public void switchAndWrite(String text) { driver.switchTo().frame(miniEditorIframe); waitForElementByElement(messageBodyField); messageBodyField.sendKeys(text); }

Target:
use writeMiniEditor() method instead of waitForElementByElement(messageBodyField); messageBodyField.sendKeys(text);
Source:
public void SignUp_validation_1() { SignUpPageObject signUpPage = new SignUpPageObject(driver); signUpPage.openSignUpPage(); signUpPage.typeInUserName(signUpPage.getTimeStamp()); String userNameEmail = Properties.emailQaart4; signUpPage.typeInEmail(userNameEmail); signUpPage.typeInPassword(signUpPage.getTimeStamp()); signUpPage.enterBirthDate( PageContent.wikiSignUpBirthMonth, PageContent.wikiSignUpBirthDay, PageContent.wikiSignUpBirthYear ); signUpPage.enterWrongBlurryWord(); signUpPage.clickCreateAccountButton(); signUpPage.verifyWrongBlurryWordValidation(); }

Target:
pass the Properties.emailQaart4 as argument / no need to create additional string
Source:
public void typeInUserName(String userName) { userNameField.sendKeys(userName); userNameField.sendKeys(Keys.TAB); PageObjectLogging.log("typeInUserName ", "User name field populated " +userName, true, driver); }

Target:
PageObjectLogging.log( "typeInUserName ", +"User name field populated " +userName, true, driver ); Remember about spaces between + and String, put trailing ")" in seperate line Remove the driver from PageObjectLogging (no need to take screenshot)
Source:
public void waitForTooYoungErrorMsg() { waitForElementByElement(tooYoungError); Assertion.assertTrue(tooYoungError.isDisplayed()); PageObjectLogging.log("typeInBirthDate ", "BirthDate field selected", true, driver); }

Target:
remove driver from PageObjectLogging (no need to take screenshot)
Source:
public void enterBlurryWord() { String word = getWordFromCaptcha(); blurryWordField.sendKeys(word); PageObjectLogging.log("enterBlurryWord ", "Blurry word field populated", true, driver); }

Target:
remove the driver
Source:
private void typeSearchQuery(String query) { waitForElementByElement(searchField); searchField.sendKeys(query); }

Target:
This method is used only in another method, why did you make this encapsulation?
Source:
public void clickEdit() { clickAndWait(editLink); changeToMonoBook(); PageObjectLogging.log("clickEdit", "click on Edit link", true, driver); }

Target:
driver
Source:
public ComparisonExecutor(AliasResolver aliasResolver) { asyncComparisonExecutor = newAsyncComparisonExecutor(); this.aliasResolver = aliasResolver; }

Target:
I would also use the two argument constructor here (keep the default visibility) and provide a factory method that creates the ComparisonExecutor with the "production" executor service.
Source:
public ApplicationStatus getApplicationStatus() { ApplicationStatus applicationStatus = new ApplicationStatus(); DiffViewerStatus status = new DiffViewerStatus(); applicationStatus.setDiffViewerStatus(status); applicationStatus.setConfiguration(getConfiguration()); applicationStatus.setSearchEngineStatus(SearchEngineStatus.create()); applicationStatus.setVersion(ApplicationVersionHolder.INSTANCE.getApplicationVersion()); return applicationStatus; }

Target:
This class has Constructor and getter/setter which are never used.
Source:
private ApiInfo apiInfo() { Collection<VendorExtension> vendorExtensions = new ArrayList<>(); return new ApiInfo( "Oppijan verkkopalvelukokonaisuus / ePerusteet rajapinta", "", "Spring MVC API based on the swagger 2.0 and 1.2 specification", "https://confluence.csc.fi/display/oppija/Rajapinnat+toisen+asteen+ja+perusasteen+toimijoille", null, "EUPL 1.1", "http://ec.europa.eu/idabc/eupl", vendorExtensions); }

Target:
Inline?
Source:
public WebViewPage(WebDriver driver) { super(driver); webViewDriver = (AppiumDriver) (((EventFiringWebDriver) getDriver()).getWrappedDriver()); Set contextNames = webViewDriver.getContextHandles(); contextNames.forEach(System.out::println); webViewContext = contextNames.toArray()[1].toString(); }

Target:
- Please rewrite constructor according to project style guide.
Source:
public static PublicSuffixMatcher load(final InputStream in) throws IOException { Args.notNull(in, "InputStream"); final List<PublicSuffixList> lists = new PublicSuffixListParser().parseByType( new InputStreamReader(in, StandardCharsets.UTF_8)); return new PublicSuffixMatcher(lists); }

Target:
@nielsbasjes Is making this method public really necessary? Do we need to expose this method in the public APIs? Can't it be package private?
Source:
static boolean isWeakCipherSuite(final String cipherSuite) { final String normalizedCipherSuite = cipherSuite.toUpperCase(); for (final Pattern pattern : WEAK_CIPHER_SUITE_PATTERNS) { if (pattern.matcher(normalizedCipherSuite).matches()) { return true; } } return false; }

Target:
@artem-smotrakov Please use `#toUpperCase` with `Locale#ROOT` parameter. Alternatively you might want to use non-case sensitive regex matching now.
Source:
private boolean isValidImport(String part, int executionCount) { try { CompletableFuture<Boolean> validImportFuture = new CompletableFuture<>(); kernel.executeCode("Class.forName(\"" + part + "\")", new Message(), executionCount, seo -> { validImportFuture.complete(!seo.getStatus().equals(EvaluationStatus.ERROR)); }); return validImportFuture.get(); } catch (InterruptedException | ExecutionException e) { return Boolean.FALSE; } }

Target:
There should be a more more direct way of doing this that doesn't use executeCode like this. For example, this will fail with the Clojure kernel.
Source:
private boolean isValidImport(String part, int executionCount) { try { part = part.replace(";",""); CompletableFuture<Boolean> validImportFuture = new CompletableFuture<>(); kernel.executeCode("Class.forName(\"" + part + "\");", new Message(), executionCount, seo -> validImportFuture.complete(!seo.getStatus().equals(EvaluationStatus.ERROR))); return validImportFuture.get(); } catch (InterruptedException | ExecutionException e) { return Boolean.FALSE; } }

Target:
please use the empty cell hack.
Source:
private void handleSetDetails(Message message) { if (isCorrectEvent(message, CommActions.ACTIONDETAILS)) { handleCommEventSync(message, CommActions.ACTIONDETAILS, this::onActionDetails); } LOGGER.warn("Warning: set details handler received non-set details message " + message.toString()); }

Target:
the warning should be inside the conditional.
Source:
protected boolean checkValue(final Object value) { return value instanceof Date; }

Target:
needs to take Dates AND Strings
Source:
public Boolean getDisableKerberos() { return this.disableKerberosPref; }

Target:
is there a reason we have accessors here? the enclosing class can read the members directly. also, "this" is not needed. might be best to just move this class to its own file.
Source:
public void serialize(StringObject value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { synchronized (value) { jgen.writeStartObject(); jgen.writeObjectField("value", value.getText()); jgen.writeEndObject(); } }

Target:
no need to synchronize as value (a StringObject) is immutable.
Source:
public void serialize(TableDisplay value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeObjectField("type", "TableDisplay"); jgen.writeObjectField("columnNames", value.columns); jgen.writeObjectField("values", value.values); jgen.writeEndObject(); }

Target:
if TableDisplay is mutable we should synchronize here.
Source:
private FluentIterable<Event> filterByDateStart(final LocalDateTime dateStart, FluentIterable<Event> results) { return results.filter(new Predicate<Event>() { @Override public boolean apply(@Nullable Event event) { assert event != null; return dateStart == null || event.getDate().isAfter(dateStart) || event.getDate().isEqual(dateStart); } }); }

Target:
@Nullable et après tu fais assert != null?
Source:
public void reserveTicketWhenExists(TicketsInteractor mockedTicketsInteractor) throws RecordNotFoundException, MaximumExceededException, UpdateTicketStateUnauthorizedException { long ticketId = 1; ObjectNode json = Json.newObject(); ArrayNode node = json.putArray(ConstantsManager.TICKET_IDS_FIELD_NAME); node.add(ticketId); when(mockedBody.asJson()).thenReturn(json); Result result = ticketsController.reserve(); assertEquals(Helpers.OK, Helpers.status(result)); verify(mockedTicketsInteractor, times(1)).reserveATicket(ticketId); }

Target:
same here, times(1)
Source:
public TicketSearchCriteria() { states = new ArrayList<>(); quantity = ConstantsManager.TICKET_SEARCH_CRITERIA_INVALID_QUANTITY; }

Target:
pourquoi utiliser une valeur invalid plutot que null
Source:
public Transaction startNewTransaction(User user) { Transaction transaction = new Transaction(user); this.transactionDao.create(transaction); return transaction; }

Target:
il me semble qu'au début de la session on s'était dit que les usages de this on essayait de les limiter au assignations dans le constructeur
Source:
public void persistsOnAdd() { // Arrange DaoPersistenceService persistenceSvc = mock(InMemoryDaoPersistenceService.class); dao = new PersistedDao<TestRecord>(persistenceSvc) {}; // Act dao.create(new TestRecord()); // Assert try { verify(persistenceSvc, times(1)).persist(dao); } catch(Exception ex) { fail("Expected no error in persistence."); } }

Target:
C'est quoi l'avantage d'utiliser `fail` versus ajouter l'exception à la signature. Le test va échouer anyway.
Source:
public void decrementNumberOfTickets(int decrementNumber) throws MaximumExceededException { if(numberOfTickets < decrementNumber) throw new MaximumExceededException(); numberOfTickets -= decrementNumber; }

Target:
La meilleure façon de savoir si on est dans le champ est le jour ou on aura besoin d'injecter des services dans les modèles ahah
Source:
public void addDynamicTemplateData(String key, Object value) { if (dynamicTemplateData == null) { dynamicTemplateData = new HashMap<String,Object>(); dynamicTemplateData.put(key, value); } else { dynamicTemplateData.put(key, value); } }

Target:
Thanks for taking the time to review @dgranahan!
Source:
public void nearbyStationsAddress() throws Exception { nearbyStationsAddress(-34618072, -58436443); System.out.println("\n"); }

Target:
Can you remove this line? No printing to sysout please.
Source:
public HslProvider(String user, String pass) { super(NetworkId.HSL); apiBase = String.format("http://api.reittiopas.fi/hsl/%s/?user=%s&pass=%s", SERVER_VERSION, user, pass); try { parserFactory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); } catch (final XmlPullParserException x) { throw new RuntimeException(x); } }

Target:
Why are username and password part of the API base? My understanding is that they are constant (http://api.reittiopas.fi/hsl/1_2_0/ in this case) and the parameters are appended dynamically. Username and password could be appended in the apiUri() method.
Source:
private static int determineContentStart(String s) { int start = TEXTBLOCK_DELIMITER.length(); // this is the opening delimiter boolean lineTerminator = false; // the content begins after at the first character after the line terminator // of the opening delimiter while (start < s.length() && Character.isWhitespace(s.charAt(start))) { if (s.charAt(start) == '\r' || s.charAt(start) == '\n') { lineTerminator = true; } else if (lineTerminator) { // first character after the line terminator break; } start++; } return start; }

Target:
Does this work with CRLF delimited strings? It looks like it's not going past the LF. Maybe you just need to call this method on the normalized string, and stop caring about CR. Also maybe it would be clearer to just `return start + 1;` here instead of breaking on the next iteration.
Source:
public static void reset() { FACADE.reset(); }

Target:
Maybe, a better solution wrt to visibility would be to move the LanguageMetricsProvider out of ApexHandler, and into this package. ApexMetrics will probably not change for 7.0 (apart from this method), while LanguageMetricsProvider is still experimental and we can remove the new API freely in 7.0
Source:
public TokenEntry(String image, String tokenSrcID, int beginLine) { setImage(image); this.tokenSrcID = tokenSrcID; this.beginLine = beginLine; this.beginColumn = -1; this.endColumn = -1; this.index = TOKEN_COUNT.get().getAndIncrement(); }

Target:
Please call here the other constructor via `this(image, tokenSrcID, beginLine, -1, -1)`. That way, we don't need to duplicate the logic...
Source:
public CppCharStream(JavaccTokenDocument document) { super(document); }

Target:
We probably should internalize our *CharStream impls on master, they should anyway not be used directly
Source:
private void parseSingleRuleNode(RuleSetReferenceId ruleSetReferenceId, RuleSetBuilder ruleSetBuilder, Node ruleNode) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Element ruleElement = (Element) ruleNode; // Stop if we're looking for a particular Rule, and this element is not // it. if (StringUtils.isNotBlank(ruleSetReferenceId.getRuleName()) && !isRuleName(ruleElement, ruleSetReferenceId.getRuleName())) { return; } Rule rule = new RuleFactory().buildRule(ruleElement, resourceLoader); rule.setRuleSetName(ruleSetBuilder.getName()); ruleSetBuilder.addRule(rule); }

Target:
Can you add two constructors in RuleFactory? * RuleFactory() - default constructor for backwards compatibility * RuleFactory(ResourceLoader) - the new one to be used here I think, the resource loader should be a property of the rule factory rather than a method argument for parsing the rule element. In theory, we could reuse the RuleFactory instance for parsing all rules within one ruleset (which we don't do currently).
Source:
public RuleBuilder(String name, String clazz, String language) { this.name = name; this.resourceLoader = new ResourceLoader(); language(language); className(clazz); }

Target:
Please call here just the other constructor: ``` this(name, new ResourceLoader(), clazz, language); ``` No need to duplicated the code here.
Source:
public static Set<Language> getLanguages() { return new LinkedHashSet<>(getInstance().languages.values()); }

Target:
maybe better use `Collections.unmodifiableSet` instead of a new `LinkedHashSet `?
Source:
private static long computeFileChecksum(final File sourceFile) { try ( CheckedInputStream stream = new CheckedInputStream( new BufferedInputStream(Files.newInputStream(sourceFile.toPath())), new Adler32()); ) { // Just read it, the CheckedInputStream will update the checksum on it's own IOUtils.skipFully(stream, sourceFile.length()); return stream.getChecksum().getValue(); } catch (final IOException ignored) { // We don't really care, if it's unreadable // the analysis will fail and report the error on it's own since the checksum won't match } // we couldn't read the file, maybe the file doesn't exist // in any case, we can't use the cache. Returning here the timestamp should make // sure, we see that the file changed every time we analyze it. return System.currentTimeMillis(); }

Target:
this seems unrelated to the rest of the PR, although related to the original report
Source:
public ASTAnnotation getAnnotation(String annotQualifiedName) { List<ASTAnnotation> annotations = getDeclaredAnnotations(); for (ASTAnnotation annotation : annotations) { if (annotation.getType() != null) { // since annotQulifiedName is fully qualified, we can directly compare now if (annotQualifiedName.equals(annotation.getType().getName())) { return annotation; } } else { // note: this alternative might fall back to comparing simple class names. If auxclasspath is not // correct, this might lead to false-positives/false-negatives. ASTName name = annotation.getFirstDescendantOfType(ASTName.class); if (name != null && TypeHelper.isA(name, annotQualifiedName)) { return annotation; } } } return null; }

Target:
why not build this behavior right into `TypeHelper.isA`?
Source:
private Boolean hasUnavailableModifier(final List<SwiftParser.AttributeContext> attributes) { return attributes.stream().anyMatch(atr -> AVAILABLE_UNAVAILABLE.equals(atr.getText())); }

Target:
do we need a boxed primitive here?
Source:
private Boolean shouldIncludeUnavailableModifier(final SwiftParser.CodeBlockContext ctx) { if (ctx == null || ctx.statements() == null) { return false; } final List<SwiftParser.StatementContext> statements = ctx.statements().statement(); return statements.size() == 1 && FATAL_ERROR.equals(statements.get(0).getStart().getText()); }

Target:
do we need a boxed primitive here?
Source:
public String getImage() { return getText(); }

Target:
The image attribute is not supposed to be the text of the node. I'd rather keep it separate (the previous `@Text` attribute was fine). A practical reason for that is in the future, other languages may have a way to get the text of their node, in which case that wouldn't be fetched with `getImage`, for compatibility, but probably with a `getText` method, or `getSourceCode` like in #1728. Also we *may* deprecate or otherwise put `getImage` out of use as soon as 7.0, given its contract is super loose.
Source:
public void testRawStringLiterals() throws IOException { final String code = IOUtils.toString(CPPTokenizerTest.class.getResourceAsStream("cpp/issue-1784.cpp"), StandardCharsets.UTF_8); Tokens tokens = parse(code); System.out.println(tokens.getTokens()); assertTrue(TokenEntry.getEOF() != tokens.getTokens().get(0)); assertEquals(16, tokens.size()); }

Target:
Please remove the System.out here...
Source:
public List<AstProcessingStage<?>> testOnlyGetDependencies(RuleSets ruleSets, LanguageVersion languageVersion) { return getDependencies(ruleSets, languageVersion); }

Target:
rather than have a public test method, consider turning `getDependencies` to package-private, and therefore accessible to the test (same package) but invisible to the outside world
Source:
public static Optional<PrimitiveType> fromToken(String token) { return Optional.ofNullable(LOOKUP.get(token)); }

Target:
I'm not sure about this optional… I believe you should just throw here (equivalent to `Enum.valueOf`)… actually the only use you have in this PR simply calls `.get()` on the optional and have it throw if called illegally…
Source:
ASTExpression getLengthExpression() { return (ASTExpression) jjtGetChild(jjtGetNumChildren() - 1); }

Target:
getLengthExpression, why package private? Should it be public?
Source:
public ASTLambdaParameter(int id) { super(id); }

Target:
The constructors should be package private
Source:
default <T> List<T> findDescendantsOfType(Class<T> targetType) { final List<T> list = new ArrayList<>(); TraversalUtils.findDescendantsOfType(this, targetType, list, false); return list; }

Target:
this implementation seems bogus, you can simply call `return findDescendantsOfType(targetType, false);`
Source:
private void checkSetters(ASTMethodDeclaration node, Object data, String nameOfMethod) { if (!hasIgnoredAnnotation(node)) { ASTResultType resultType = node.getResultType(); if (hasPrefix(nameOfMethod, "set") && !resultType.isVoid()) { addViolationWithMessage(data, node, "Linguistics Antipattern - The setter ''{0}'' should not return any type except void linguistically", new Object[] { nameOfMethod }); } } }

Target:
I'd move this to line 83 (within `visit(ASTMethodDeclaration node, Object data)`), so we ignore all overridden methods and not just setters
Source:
public List<File> findFilesFrom(File dir, FilenameFilter filter, boolean recurse) { this.filter = filter; List<File> files = new ArrayList<>(); scanDirectory(dir, files, recurse); Collections.sort(files, new Comparator<File>() { @Override public int compare(File o1, File o2) { return o1.getPath().compareToIgnoreCase(o2.getPath()); } }); return files; }

Target:
While digging further into this sorting, I found out that `java.io.File` implements Comparable and would sort Files correctly depending on the operating system. So, we could even just say `Collections.sort(files);`. However, we can also change the method `scanDirectory` below instead to do the sorting already: ```java File[] candidates = dir.listFiles(filter); if (candidates == null) { return; } Arrays.sort(candidates); ... ``` Using File instead of String here has the advantage, that we don't need to create new File instances on our own.
Source:
UnsynchronizedStaticFormatterRule(Class<?> formatterClassToCheck) { this.formatterClassToCheck = formatterClassToCheck; }

Target:
using this constructor doesn't use the rule chain... a call to `this();` is probably missing
Source:
protected void setUp() { String[] packages = getClass().getPackage().getName().split("\\."); String categoryName = packages[packages.length - 1]; String language = packages[packages.length - 3]; String rulesetXml = "category/" + language + "/" + categoryName + ".xml"; addRule(rulesetXml, getClass().getSimpleName().replaceFirst("Test$", "")); }

Target:
This is PMD specific, I guess it would probably fail most of the time outside of PMD. Wouldn't it be better to use our own subclass of SimpleAggregatorTst (or RuleTst, since we test a single rule)?
Source:
private List<String> createList(Class[] classArray) { return Arrays.asList(classArray).stream() .filter(files -> files.getSimpleName().startsWith("AST")) .map(m -> m.getSimpleName().substring(("AST").length())) .collect(Collectors.toList()); }

Target:
useless parenthesis around "AST"
Source:
public String getAuxclasspathFiles() { String files = auxclasspathFiles.getValue().stream().map(p -> File.pathSeparator + p.getAbsolutePath()) .collect(Collectors.joining("")); return files; }

Target:
You could use Collectors.joining(File.pathSeparator)
Source:
private static URL[] fileToURL(List<File> files) throws IOException { List<URL> urlList = new ArrayList<>(); for (File f : files) { addFileURLs(urlList, f.toURI().toURL()); } return urlList.toArray(new URL[urlList.size()]); }

Target:
Don't use addFileUrls, just add to your urlList
Source:
public static TimedOperation initThread() { if (!trackTime) { return NOOP_TIMED_OPERATION; } return startOperation(TimedOperationCategory.UNACCOUNTED); }

Target:
None of the callers seem to use the return from this method. Is that okay? Is it needed?
Source:
public String getTypeImage() { if (isTypeInferred()) { return getImage(); } ASTClassOrInterfaceType refType = getFirstDescendantOfType(ASTClassOrInterfaceType.class); if (refType != null) { return refType.getImage(); } return getFirstDescendantOfType(ASTPrimitiveType.class).getImage(); }

Target:
is this ok? Shouldn't we return null / empty string here?
Source:
public void testScopesAreCreated() { parseCode(TEST1); ASTBlock n = acu.findDescendantsOfType(ASTIfStatement.class).get(0) .getFirstDescendantOfType(ASTBlock.class); assertTrue(n.getScope() instanceof LocalScope); }

Target:
This could be a `getFirstDescendantOfType`
Source:
protected Collection<String> defaultSuppressionAnnotations() { Collection<String> defaultValues = new HashSet<>(); defaultValues.add("javax.inject.Inject"); return defaultValues; }

Target:
You may just return `Arrays.asList("javax.inject.Inject")`
Source:
protected Collection<String> defaultSuppressionAnnotations() { Collection defaultValues = new ArrayList<String>(); defaultValues.add("java.lang.Deprecated"); return defaultValues; }

Target:
This is a raw type, please use a parameterized type (`Collection<String>`)
Source:
public void setAnalysisCache(final AnalysisCache cache) { if (cache == null && isAnalysisCacheFunctional()) { analysisCache = new NoopAnalysisCache(); } else { analysisCache = cache; } // the doc says it's a noop if incremental analysis was disabled, // but it's actually the getter that enforces that }

Target:
do we really care?
Source:
static boolean isSystemLevelClass(ASTUserClass node) { List<TypeRef> interfaces = node.getNode().getDefiningType().getCodeUnitDetails().getInterfaceTypeRefs(); boolean hasWhitelistedInterfaces = false; for (TypeRef intObject : interfaces) { if (isWhitelisted(intObject.getNames())) { hasWhitelistedInterfaces = true; break; } } return hasWhitelistedInterfaces; }

Target:
`return true` would be cleaner... or am I missing the point of the rule ?
Source:
private void initXPathRuleQuery() { if (xPathRuleQueryNeedsInitialization()) { final String xpath = getProperty(XPATH_DESCRIPTOR); final String version = getProperty(VERSION_DESCRIPTOR); initRuleQueryBasedOnVersion(version); xpathRuleQuery.setXPath(xpath); xpathRuleQuery.setVersion(version); xpathRuleQuery.setProperties(getPropertiesByPropertyDescriptor()); } }

Target:
This check should be moved out to call-sites (l. 100), which is btw already the case l. 145
Source:
private void initRuleQueryBasedOnVersion(final String version) { if (XPATH_1_0.equals(version)) { xpathRuleQuery = new JaxenXPathRuleQuery(); } else { xpathRuleQuery = new SaxonXPathRuleQuery(); } }

Target:
Maybe use a ternary expression? Up to you
Source:
public Value atomize() throws XPathException { if (value == null) { final Object v = attribute.getValue(); value = SaxonXPathRuleQuery.getAtomicRepresentation(v); } return value; }

Target:
Maybe inline that variable
Source:
private boolean isStringConcat(Node childNode, Node baseNode) { Node currentNode = childNode; // limit to 10 levels for (int i = 0; i < 10 && currentNode != null && currentNode != baseNode; i++) { currentNode = currentNode.jjtGetParent(); if (currentNode instanceof ASTAdditiveExpression) { return true; } } return false; }

Target:
this is rather arbitrary... why the limit? we are always going to be able to get up to the basenode given that the childNode is guaranteed to be a descendant
Source:
public DocumentOperationsApplierForNonOverlappingRegions(final Document document) { this.document = Objects.requireNonNull(document); comparator = new DocumentOperationNonOverlappingRegionsComparator(); operations = new ArrayList<>(); applied = false; }

Target:
there is no reason for this to be an instance field, could be a static final
Source:
XPathEvaluationException(Throwable cause) { super(cause); }

Target:
is package-private the intended visibility? or you just missed the access modifier?
Source:
StyleLayer getLayer(String id) { return layersById.get(id); }

Target:
package-private?
Source:
void dropLayer(String id) { layersById.remove(id); }

Target:
package-private?
Source:
public void initialize(URL location, ResourceBundle resources) { metricResultsListView.setCellFactory(param -> new MetricResultListCell()); scopeHierarchyTreeView.setCellFactory(param -> new ScopeHierarchyTreeCell()); scopeHierarchyTreeView.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal) -> { if (newVal != null && newVal.getValue() instanceof NameDeclaration) { parent.onNameDeclarationSelected((NameDeclaration) newVal.getValue()); } }); }

Target:
In theory, these cell factories can be set directly in fxml: ``` <?import net.sourceforge.pmd.util.fxdesigner.util.controls.MetricResultListCell?> <?import net.sourceforge.pmd.util.fxdesigner.util.controls.ScopeHierarchyTreeCell?> <ListView fx:id="metricResultsListView" styleClass="secondary-panel" BorderPane.alignment="CENTER"> <cellFactory> <MetricResultListCell /> </cellFactory> </ListView> <TreeView fx:id="scopeHierarchyTreeView" styleClass="secondary-panel" BorderPane.alignment="CENTER"> <cellFactory> <ScopeHierarchyTreeCell /> </cellFactory> </TreeView> ```
Source:
public void removeChildAtIndex(final int childIndex) { if (0 <= childIndex && childIndex < jjtGetNumChildren()) { // Remove the child at the given index children = ArrayUtils.remove(children, childIndex); // Update the remaining children indexes for (int i = 0; i < jjtGetNumChildren(); i++) { jjtGetChild(i).jjtSetChildIndex(i); } } }

Target:
This loop can safely start at `childIndex`, since previous indexes should not be affected
Source:
protected Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException { // First, check if the class has already been loaded Class<?> c = findLoadedClass(name); if (c == null) { if (c == null) { try { // checking local c = findClass(name); } catch (final ClassNotFoundException e) { // checking parent // This call to loadClass may eventually call findClass again, in case the parent doesn't find anything. c = super.loadClass(name, resolve); } } } if (resolve) { resolveClass(c); } return c; }

Target:
Nothing harmful, but the null check is done twice.
Source:
public boolean isIntersectionType() { return typeList.size() == 1; }

Target:
I believe this should be `typeList.size() != 1`, isn't it?
Source:
public <T> List<T> getParentsOfType(Class<T> parentType) { List<T> parents = new ArrayList<>(); Node parentNode = jjtGetParent(); while (parentNode != null) { if (parentType.isInstance(parentNode.getClass())) { parents.add((T) parentNode); } parentNode = parentNode.jjtGetParent(); } return parents; }

Target:
This is the cause for the unit test failures (wouldn't have seen it otherwise): It must be `parentType.isInstance(parentNode)` (without the getClass()) - now all the parent nodes have been matched (since every class is a class...).
Source:
public EnumeratedProperty(String theName, String theDescription, Map<String, E> labelsToChoices, E defaultValue, Class<E> valueType, float theUIOrder) { super(theName, theDescription, defaultValue, theUIOrder); this.valueType = valueType; choicesByLabel = Collections.unmodifiableMap(labelsToChoices); labelsByChoice = Collections.unmodifiableMap(CollectionUtil.invertedMapFrom(choicesByLabel)); }

Target:
Can we derive `Class<E>` by looking at one of the label choices, if at least one is always provided? Given these are immutable, a real-world case for an empty enumerations eludes me.
Source:
public Object createNonNullArray() { return new Object @NonNull[0]; }

Target:
`public Object[] createNonNullArray() {` maybe?
Source:
public DataPointGroup aggregate(DataPointGroup dataPointGroup) { if (m_sampling == null) // TODO is this clean? m_sampling = new Sampling(1, TimeUnit.MILLISECONDS); checkNotNull(dataPointGroup); if (m_alignSampling) { m_startTime = alignRangeBoundary(m_startTime); } return (new RangeDataPointAggregator(dataPointGroup, getSubAggregator())); }

Target:
This is unnecessary as the annotation won't let this value be null. We catch this as an api syntax error and return that to the caller.
Source:
public OutputStreamFlushableCommandline( String[] excludedEnvironmentVariables ) { this.excludedEnvironmentVariables = new ConcurrentLinkedDeque<>(); this.addedEnvironmentVariables = new HashSet<>( ); Collections.addAll( this.excludedEnvironmentVariables, excludedEnvironmentVariables ); }

Target:
try to rewrite to `addedEnvironmentVariables = new HashSet<>();` without `this` and space in constructor.
Source:
public synchronized void putAll(Map<?, ?> t) { for (Map.Entry<?, ?> entry : t.entrySet()) { this.put(entry.getKey(), entry.getValue()); } }

Target:
We have different conventions. Please see the spaces around brackets and method parameters, and brackets on new lines. The checkstyle plugin would crash the build. Did you try to run "mvn install -P run-its"? It would take quite long time to complete the build, cca one hour.
Source:
public NullStatisticsReporter() { super( FileUtils.getFile( FileUtils.getTempDirectory(), RandomStringUtils.randomAlphabetic( 24 ) ) ); }

Target:
It would be nice to have protected no-arg constructor of `StatisticsReporter` for these purposes and null variables of `File` and `RunEntryStatisticsMap`, etc. Not necessary to create new objects if unused.