auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void notPossibleToLogInWhenUsernameFieldBlank() throws InterruptedException { LoginPage loginPage = new LoginPage(driver).get(); loginPage.logUserIn("", Configuration.getCredentials().password10); //we must wait some seconds to make sure button is activated Thread.sleep(1000); Assertion.assertTrue(loginPage.isSubmitButtonDisabled()); }

Target:
public void notPossibleToLogInWhenUsernameFieldBlank() throws InterruptedException { LoginPage loginPage = new LoginPage(driver).get(); loginPage.logUserIn("", Configuration.getCredentials().password10); Assertion.assertTrue(loginPage.isSubmitButtonDisabled(2)); }
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:
public int getNumberOfResultTemplates() { switchToIFrame(); try { if (resultTemplates.isEmpty()) { return 0; } else { return resultTemplates.size(); } } finally { PageObjectLogging.log( "getNumberOfResultTemplates", "Number of result templates found: " + resultTemplates.size(), true ); switchOutOfIFrame(); } }
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:
public ArticlePageObject savePage() { switchToIFrame(); waitForElementInViewPort(editSummary); waitForElementClickableByElement(publishButton); publishButton.click(); PageObjectLogging.log("savePage", "The 2nd Publish Button is clicked", true); switchOutOfIFrame(); return new ArticlePageObject(driver); }
Source:
public String getAssociatedArticleImageSrc() { waitForElementByElement(associatedArticleImage); String imageSrc = articleImageUrl.getAttribute("src"); System.out.println(imageSrc); return imageSrc; }

Target:
public String getAssociatedArticleImageSrc() { waitForElementByElement(associatedArticleImage); return articleImageUrl.getAttribute("src"); }
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:
public void verifyUndoSucceeded() { waitForElementByElement(notification); String notificationMsg = notification.getText(); Assertion.assertEquals(notificationMsg, "This page has been restored."); PageObjectLogging.log("verifyUndoSucceeded", "able to undo a swapped video", true); }
Source:
public String getLastEditHistoryDevice() { return editHistoriesDevice.get(0).getText(); }

Target:
private String getLastEditHistoryDevice() { return editHistoriesDevice.get(0).getText(); }
Source:
public void waitForTooYoungErrorMsg() { waitForElementByElement(tooYoungError); Assertion.assertTrue(tooYoungError.isDisplayed()); PageObjectLogging.log("typeInBirthDate ", "BirthDate field selected", true, driver); }

Target:
public void waitForTooYoungErrorMsg() { waitForElementByElement(tooYoungError); Assertion.assertTrue(tooYoungError.isDisplayed()); PageObjectLogging.log("typeInBirthDate ", "BirthDate field selected", true); }
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:
private ApiInfo apiInfo() { 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", new ArrayList<>()); }
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:
static boolean isWeakCipherSuite(final String cipherSuite) { for (final Pattern pattern : WEAK_CIPHER_SUITE_PATTERNS) { if (pattern.matcher(cipherSuite).matches()) { return true; } } return false; }
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:
private boolean isValidImport(String part, int executionCount) { try { CompletableFuture<Boolean> validImportFuture = new CompletableFuture<>(); kernel.executeCode("", new Message(), executionCount, seo -> validImportFuture.complete(!seo.getStatus().equals(EvaluationStatus.ERROR))); return validImportFuture.get(); } catch (InterruptedException | ExecutionException e) { return Boolean.FALSE; } }
Source:
protected boolean checkValue(final Object value) { return value instanceof Date; }

Target:
protected boolean checkValue(final Object value) { return value instanceof Date || value instanceof String; }
Source:
public Boolean getDisableKerberos() { return this.disableKerberosPref; }

Target:
Boolean getDisableKerberos() { return this.disableKerberosPref; }
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:
public void serialize(StringObject value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeObjectField("value", value.getText()); jgen.writeEndObject(); }
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:
public void serialize(TableDisplay value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { synchronized (value) { jgen.writeStartObject(); jgen.writeObjectField("type", "TableDisplay"); jgen.writeObjectField("columnNames", value.columns); jgen.writeObjectField("values", value.values); jgen.writeEndObject(); } }
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:
private FluentIterable<Event> filterByDateStart(final LocalDateTime dateStart, FluentIterable<Event> results) { return results.filter(new Predicate<Event>() { @Override public boolean apply(@Nullable Event event) { return event != null && (dateStart == null || event.getDate().isAfter(dateStart) || event.getDate().isEqual(dateStart)); } }); }
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:
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).reserveATicket(ticketId); }
Source:
public TicketSearchCriteria() { states = new ArrayList<>(); quantity = ConstantsManager.TICKET_SEARCH_CRITERIA_INVALID_QUANTITY; }

Target:
public TicketSearchCriteria() { states = new ArrayList<>(); quantity = null; }
Source:
public Transaction startNewTransaction(User user) { Transaction transaction = new Transaction(user); this.transactionDao.create(transaction); return transaction; }

Target:
public Transaction startNewTransaction(User user) { Transaction transaction = new Transaction(user); transactionDao.create(transaction); return transaction; }
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:
public void persistsOnAdd() throws IOException { // Arrange DaoPersistenceService persistenceSvc = mock(InMemoryDaoPersistenceService.class); dao = new PersistedDao<TestRecord>(persistenceSvc) {}; // Act dao.create(new TestRecord()); // Assert verify(persistenceSvc, times(1)).persist(dao); }
Source:
public void decrementNumberOfTickets(int decrementNumber) throws MaximumExceededException { if(numberOfTickets < decrementNumber) throw new MaximumExceededException(); numberOfTickets -= decrementNumber; }

Target:
public synchronized void decrementNumberOfTickets(int decrementNumber) throws MaximumExceededException { if (numberOfTickets < decrementNumber) throw new MaximumExceededException(); numberOfTickets -= decrementNumber; }
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:
public HslProvider(String user, String pass) { super(NetworkId.HSL); this.user = user; this.pass = pass; try { parserFactory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); } catch (final XmlPullParserException x) { throw new RuntimeException(x); } }
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:
private static int determineContentStart(String s) { int start = TEXTBLOCK_DELIMITER.length(); // this is the opening delimiter // 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) == '\n') { return start + 1; } start++; } return start; }
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:
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(resourceLoader).buildRule(ruleElement); rule.setRuleSetName(ruleSetBuilder.getName()); ruleSetBuilder.addRule(rule); }
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:
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 } return 0; }
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:
public ASTAnnotation getAnnotation(String annotQualifiedName) { List<ASTAnnotation> annotations = getDeclaredAnnotations(); for (ASTAnnotation annotation : annotations) { ASTName name = annotation.getFirstDescendantOfType(ASTName.class); if (name != null && TypeHelper.isA(name, annotQualifiedName)) { return annotation; } } return null; }
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:
protected void setUp() { // empty, to be overridden. }
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:
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()); }
Source:
public String getAuxclasspathFiles() { String files = auxclasspathFiles.getValue().stream().map(p -> File.pathSeparator + p.getAbsolutePath()) .collect(Collectors.joining("")); return files; }

Target:
public String getAuxclasspathFiles() { return auxclasspathFiles.getValue().stream().map(p -> p.getAbsolutePath()).collect(Collectors.joining(File.pathSeparator)); }
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:
public void setAnalysisCache(final AnalysisCache cache) { // the doc says it's a noop if incremental analysis was disabled, // but it's actually the getter that enforces that this.analysisCache = cache == null ? new NoopAnalysisCache() : cache; }
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:
private boolean isStringConcat(Node childNode, Node baseNode) { Node currentNode = childNode; while (currentNode != baseNode) { currentNode = currentNode.jjtGetParent(); if (currentNode instanceof ASTAdditiveExpression) { return true; } } return false; }
Source:
StyleLayer getLayer(String id) { return layersById.get(id); }

Target:
public StyleLayer getLayer(String id) { return layersById.get(id); }
Source:
void dropLayer(String id) { layersById.remove(id); }

Target:
public void dropLayer(String id) { layersById.remove(id); }
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:
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 & left-shifted children indexes for (int i = childIndex; i < jjtGetNumChildren(); i++) { jjtGetChild(i).jjtSetChildIndex(i); } } }
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:
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) { 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; }
Source:
public Object createNonNullArray() { return new Object @NonNull[0]; }

Target:
public Object[] createNonNullArray() { return new Object @NonNull[0]; }
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:
public DataPointGroup aggregate(DataPointGroup dataPointGroup) { checkNotNull(dataPointGroup); if (m_alignSampling) m_startTime = alignRangeBoundary(m_startTime); return (new RangeDataPointAggregator(dataPointGroup, getSubAggregator())); }
Source:
public MockSCMSource build() { MockSCMSource source = controller == null ? new MockSCMSource(controllerId, repository, traits()) : new MockSCMSource(controller, repository, traits()); if (id != null) { source.setId(id()); } return source; }

Target:
public MockSCMSource build() { MockSCMSource source = controller == null ? new MockSCMSource(controllerId, repository, traits()) : new MockSCMSource(controller, repository, traits()); source.setId(id()); return source; }
Source:
public <T extends Action> T getAction(@NonNull Class<T> type) { // TODO should be deleted but old versions of blue ocean api rely on this return ChangeRequestAction.class.equals(type) ? (T)new ChangeRequestAction(){} : null; }

Target:
public <T extends Action> T getAction(@NonNull Class<T> type) { // TODO should be deleted but old versions of blue ocean api call this method return null; }
Source:
protected void onPostExecute(String result) { a.setProgressBarIndeterminateVisibility(false); if(result != null && result.length() > 0) { Toast.makeText(a, result, Toast.LENGTH_LONG).show(); } if (operation == RESTORE_OPERATION || operation == BACKUP_OPERATION || operation == CLEAR_TILES_OPERATION) { a.reloadLocalIndexes(); } else { a.newDownloadIndexes(); } getMyApplication().getPoiHelper().readPoiTypesFromMapAsync(); }

Target:
protected void onPostExecute(String result) { a.setProgressBarIndeterminateVisibility(false); if(result != null && result.length() > 0) { Toast.makeText(a, result, Toast.LENGTH_LONG).show(); } if (operation == RESTORE_OPERATION || operation == BACKUP_OPERATION || operation == CLEAR_TILES_OPERATION) { a.reloadLocalIndexes(); } else { a.newDownloadIndexes(); } }
Source:
public void setLocationFromService(net.osmand.Location location, boolean continuous) { if (locationSimulation.isRouteAnimating()) { return; } if (location != null) { notifyGpsLocationRecovered(); } // if continuous notify about lost location if (continuous) { scheduleCheckIfGpsLost(location); } app.getSavingTrackHelper().updateLocation(location, app.getLocationProvider().heading); OsmandPlugin.updateLocationPlugins(location); app.getRoutingHelper().updateLocation(location); app.getWaypointHelper().locationChanged(location); }

Target:
public void setLocationFromService(net.osmand.Location location, boolean continuous) { if (locationSimulation.isRouteAnimating()) { return; } if (location != null) { notifyGpsLocationRecovered(); } // if continuous notify about lost location if (continuous) { scheduleCheckIfGpsLost(location); } app.getSavingTrackHelper().updateLocation(location, heading); OsmandPlugin.updateLocationPlugins(location); app.getRoutingHelper().updateLocation(location); app.getWaypointHelper().locationChanged(location); }
Source:
public Set<String> getSelectedPoiFilters() { Set<String> result = new LinkedHashSet<>(); String filtersId = SELECTED_POI_FILTER_FOR_MAP.get(); if (filtersId != null) Collections.addAll(result, filtersId.split(",")); return result; }

Target:
public Set<String> getSelectedPoiFilters() { Set<String> result = new LinkedHashSet<>(); String filtersId = SELECTED_POI_FILTER_FOR_MAP.get(); if (filtersId != null) { Collections.addAll(result, filtersId.split(",")); } return result; }
Source:
public boolean checkMeasurementPointSize(int radius){ //check if proposed change to measurement point display size is within defined range if(radius <= maxMeasurementPointRadius && radius >= minMeasurementPointRadius){ return true; }else{ return false; } }

Target:
public boolean checkMeasurementPointSize(int radius){ //check if proposed change to measurement point display size is within defined range return radius <= maxMeasurementPointRadius && radius >= minMeasurementPointRadius; }
Source:
public static boolean sleep(SleepCondition conn, int timeout, int minimumTimeout) { long start = System.currentTimeMillis(); if(!sleep(conn, timeout)) return false; long t; if((t = System.currentTimeMillis() - start) < minimumTimeout) { Time.sleep((int)(minimumTimeout - t)); } return true; }

Target:
public static boolean sleep(SleepCondition conn, int timeout, int minimumTimeout) { long start = System.currentTimeMillis(); if(!sleep(conn, timeout)) { return false; } long t; if((t = System.currentTimeMillis() - start) < minimumTimeout) { Time.sleep((int)(minimumTimeout - t)); } return true; }
Source:
public void getExperimentAsUser(final String userId, final String problemId, final String sessionInfo, final MultiConnectionManager internalConnections) throws DatabaseAccessException { LOG.info("Getting experiment for user: {}", userId); LOG.info("Problem: {}", problemId); SubmissionManager.mongoGetExperiment(getInstance().database, userId, problemId, sessionInfo, internalConnections); }

Target:
public void getExperimentAsUser(final String userId, final String problemId, final String sessionInfo, final MultiConnectionManager internalConnections) throws DatabaseAccessException { LOG.debug("Getting experiment for user: {}", userId); LOG.info("Problem: {}", problemId); SubmissionManager.mongoGetExperiment(getInstance().database, userId, problemId, sessionInfo, internalConnections); }
Source:
private int checkGPS() { LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE); service.addGpsStatusListener(this); short gpsStatus = 0; boolean enabled = service .isProviderEnabled(LocationManager.GPS_PROVIDER); if (!enabled) gpsStatus = MainScreenActivity.GPS_NOT_ENABLED; else if (isConnected && (mLastRecordedLocation == null || mLastRecordedLocation .getAccuracy() > MyLocationListener.REQUIRED_ACCURACY)) gpsStatus = MainScreenActivity.NO_GPS_SIGNAL; else gpsStatus = MainScreenActivity.GPS_WORKING; Database db = new Database(this); return gpsStatus; }

Target:
private int checkGPS() { LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE); service.addGpsStatusListener(this); short gpsStatus = 0; boolean enabled = service .isProviderEnabled(LocationManager.GPS_PROVIDER); if (!enabled) { gpsStatus = MainScreenActivity.GPS_NOT_ENABLED; } else if (isConnected && (mLastRecordedLocation == null || mLastRecordedLocation .getAccuracy() > MyLocationListener.REQUIRED_ACCURACY)) { gpsStatus = MainScreenActivity.NO_GPS_SIGNAL; } else { gpsStatus = MainScreenActivity.GPS_WORKING; } return gpsStatus; }
Source:
private List<SingleRun> readfromDB() { Database db = new Database(this); List<SingleRun> runs; runs = db.getAllRuns(); SingleRun[] run_data = new SingleRun[0]; return runs; }

Target:
private List<SingleRun> readfromDB() { Database db = new Database(this); List<SingleRun> runs; runs = db.getAllRuns(); return runs; }
Source:
public <T> Gauge<T> gauge(String name, Gauge<T> gauge) { checkNotNullOrEmpty(name); checkNotNull(gauge); // Unfortunately register doesn't call getOrAdd (probably a bug in metrics), and instead goes through // a code path that throws an exception if this metric already exists. String fullName = name(name); Gauge<T> metric = (Gauge<T>) _metrics.get(fullName); if (metric == null) { metric = _registry.register(fullName, gauge); } return metric; }

Target:
public synchronized <T> Gauge<T> gauge(String name, Gauge<T> gauge) { checkNotNullOrEmpty(name); checkNotNull(gauge); // Unfortunately register doesn't call getOrAdd (probably a bug in metrics), and instead goes through // a code path that throws an exception if this metric already exists. String fullName = name(name); Gauge<T> metric = (Gauge<T>) _metrics.get(fullName); if (metric == null) { metric = _registry.register(fullName, gauge); } return metric; }
Source:
public boolean check(Map<String, Object> info) throws Exception { return BlueOceanHook.isBOPlugin(info) || DeclarativePipelineHook.isDPPlugin(info) || StructsHook.isStructsPlugin(info) || HaHook.isHaPlugin(info); }

Target:
public boolean check(Map<String, Object> info) throws Exception { return BlueOceanHook.isBOPlugin(info) || DeclarativePipelineHook.isDPPlugin(info) || StructsHook.isStructsPlugin(info); }
Source:
public Map<String, String> getShellEnvironment() { MutableMap<String, String> result = MutableMap.copyOf(super.getShellEnvironment()); // how to change epmd port, according to // http://serverfault.com/questions/582787/how-to-change-listening-interface-of-rabbitmqs-epmd-port-4369 result.put("ERL_EPMD_PORT", "" + getEntity().getEpmdListenerPort()); return result; }

Target:
public Map<String, String> getShellEnvironment() { MutableMap<String, String> result = MutableMap.copyOf(super.getShellEnvironment()); // how to change epmd port, according to // http://serverfault.com/questions/582787/how-to-change-listening-interface-of-rabbitmqs-epmd-port-4369 result.put("ERL_EPMD_PORT", "" + Integer.toString(getEntity().getEpmdListenerPort())); return result; }
Source:
public static File mkdirs(File dir) { if (dir.isDirectory()) return dir; boolean success = dir.mkdirs(); if (!success) { // A race condition can cause dir.mkdirs() to return false if the dir has been created on a separate thread // since the initial check above if (dir.isDirectory()) return dir; throw Exceptions.propagate(new IOException("Failed to create directory " + dir + (dir.isFile() ? "(is file)" : ""))); } return dir; }

Target:
public static File mkdirs(File dir) { dir.mkdirs(); if (dir.isDirectory()) { return dir; } throw Exceptions.propagate(new IOException("Failed to create directory " + dir + (dir.isFile() ? "(is file)" : ""))); }
Source:
public MachineDetails getMachineDetails() { MachineDetails details = machineDetails; if (details == null) { // Or could just load and store several times Tasks.setBlockingDetails("Waiting for machine details"); synchronized (machineDetailsLock) { details = machineDetails; if (details == null) { machineDetails = details = BasicMachineDetails.forSshMachineLocation(this); } } Tasks.resetBlockingDetails(); } return details; }

Target:
public MachineDetails getMachineDetails() { MachineDetails details = machineDetails; if (details == null) { // Or could just load and store several times Tasks.setBlockingDetails("Waiting for machine details"); try { synchronized (machineDetailsLock) { details = machineDetails; if (details == null) { machineDetails = details = BasicMachineDetails.forSshMachineLocation(this); } } } finally { Tasks.resetBlockingDetails(); } } return details; }
Source:
public void reloadBrooklynProperties() { log.info("Reloading brooklyn properties from " + builder); BrooklynProperties properties = builder.build(); configMap = properties; if (brooklynAdditionalProperties != null) { log.info("Reloading additional brooklyn properties from " + brooklynAdditionalProperties); configMap.addFromMap(brooklynAdditionalProperties); } this.downloadsManager = BasicDownloadsManager.newDefault(configMap); // Force reload of location registry this.locationRegistry = null; // Notify listeners that properties have been reloaded for (PropertiesReloadListener listener : reloadListeners) { if (listener != null) listener.reloaded(); } }

Target:
public void reloadBrooklynProperties() { log.info("Reloading brooklyn properties from " + builder); BrooklynProperties properties = builder.build(); configMap = properties; if (brooklynAdditionalProperties != null) { log.info("Reloading additional brooklyn properties from " + brooklynAdditionalProperties); configMap.addFromMap(brooklynAdditionalProperties); } this.downloadsManager = BasicDownloadsManager.newDefault(configMap); // Force reload of location registry this.locationRegistry = null; // Notify listeners that properties have been reloaded for (PropertiesReloadListener listener : reloadListeners) { listener.reloaded(); } }
Source:
public static Throwable getError(Task<?> t) { if (t==null) return null; if (!t.isDone()) return null; if (t.isCancelled()) return new CancellationException(); try { t.get(); return null; } catch (Throwable error) { Exceptions.propagateIfFatal(error); return error; } }

Target:
public static Throwable getError(Task<?> t) { if (t==null) return null; if (!t.isDone()) return null; if (t.isCancelled()) return new CancellationException(); try { t.get(); return null; } catch (Throwable error) { // do not propagate as we are pretty much guaranteed above that it wasn't this // thread which originally threw the error return error; } }
Source:
public Map<String, String> getShellEnvironment() { Map<String, String> orig = super.getShellEnvironment(); String kafkaJmxOpts = orig.remove("JAVA_OPTS"); if (Strings.isBlank(kafkaJmxOpts)) kafkaJmxOpts = " "; // FIXME - this is required to prevent jmxremote being setup in bin/kafka-run-class.sh return MutableMap.<String, String>builder() .putAll(orig) .putIfNotNull("KAFKA_JMX_OPTS", kafkaJmxOpts) .build(); }

Target:
public Map<String, String> getShellEnvironment() { Map<String, String> orig = super.getShellEnvironment(); String kafkaJmxOpts = orig.remove("JAVA_OPTS"); return MutableMap.<String, String>builder() .putAll(orig) .putIfNotNull("KAFKA_JMX_OPTS", kafkaJmxOpts) .build(); }
Source:
public MachineSet ensureExists(int count, ReusableMachineTemplate template) { MachineSet current; synchronized (this) { current = all(matching(template)); } if (current.size() >= count) return current; //have to create more MachineSet moreNeeded = create(count-current.size(), template); return current.added(moreNeeded); }

Target:
public MachineSet ensureExists(int count, ReusableMachineTemplate template) { MachineSet current; current = all(matching(template)); if (current.size() >= count) return current; //have to create more MachineSet moreNeeded = create(count-current.size(), template); return current.added(moreNeeded); }
Source:
public void close() { try { if (channel != null) { channel.close(); } } catch (final IOException e) { // NOPMD // ignore } finally { channel = null; isClosed = true; } }

Target:
public void close() { try { if (channel != null) { channel.close(); } } catch (IOException e) { // NOPMD // ignore } finally { channel = null; isClosed = true; } }
Source:
public static synchronized CacheManager get(AlluxioConfiguration conf) throws IOException { // TODO(feng): support multiple cache managers if (sCacheManager == null) { try { sCacheManager = Optional.of(create(conf)); } catch (IOException e) { sCacheManager = Optional.empty(); throw e; } } return sCacheManager.orElse(null); }

Target:
public static synchronized CacheManager get(AlluxioConfiguration conf) throws IOException { // TODO(feng): support multiple cache managers if (sCacheManager == null) { sCacheManager = create(conf); } return sCacheManager; }
Source:
public BackupLeaderRole(CoreMasterContext masterContext) { super(masterContext); LOG.info("Creating backup-leader role."); // Store state lock manager pausing state change when necessary. mStateLockManager = masterContext.getStateLockManager(); // Read properties. mStateLockTimeout = ServerConfiguration.getMs(PropertyKey.MASTER_SHELL_BACKUP_STATE_LOCK_TIMEOUT); mBackupAbandonTimeout = ServerConfiguration.getMs(PropertyKey.MASTER_BACKUP_ABANDON_TIMEOUT); }

Target:
public BackupLeaderRole(CoreMasterContext masterContext) { super(masterContext); LOG.info("Creating backup-leader role."); // Store state lock manager pausing state change when necessary. mStateLockManager = masterContext.getStateLockManager(); // Read properties. mBackupAbandonTimeout = ServerConfiguration.getMs(PropertyKey.MASTER_BACKUP_ABANDON_TIMEOUT); }
Source:
public void seek(long position) throws IOException { if (position < mPos || position - mPos > MOVEMENT_LIMIT) { mSequentialReadCount = 0; } else { ((Seekable) in).seek(position); } mPos = position; }

Target:
public void seek(long position) throws IOException { if (position < mPos || position - mPos > MOVEMENT_LIMIT) { mSequentialReadCount = 0; } mPos = position; }
Source:
public int read() throws IOException { byte[] buffer = new byte[1]; int bytesRead = ((FSDataInputStream) in).read(mPos, buffer, 0, buffer.length); if (bytesRead > 0) { mPos += bytesRead; return BufferUtils.byteToInt(buffer[0]); } Preconditions.checkArgument(bytesRead != 0, "Expected a non-zero value if end of stream has not been reached"); return bytesRead; }

Target:
public int read() throws IOException { byte[] buffer = new byte[1]; int bytesRead = read(buffer); if (bytesRead > 0) { return BufferUtils.byteToInt(buffer[0]); } Preconditions.checkArgument(bytesRead != 0, "Expected a non-zero value if end of stream has not been reached"); return bytesRead; }
Source:
public ScpCommand(String remoteHost, String fromFile, String toFile, boolean isDir) { super(new String[]{}); String template = "scp %s %s:%s localhost:%s"; if (isDir) { template = "scp -r %s %s:%s localhost:%s"; } // copy from hostname to local mCommand = new String[]{"bash", "-c", String.format(template, ShellUtils.COMMON_SSH_OPTS, remoteHost, fromFile, toFile) }; mHostName = remoteHost; }

Target:
public ScpCommand(String remoteHost, String fromFile, String toFile, boolean isDir) { super(new String[]{"bash", "-c", String.format(isDir ? "scp -r %s %s:%s localhost:%s" : "scp %s %s:%s localhost:%s", ShellUtils.COMMON_SSH_OPTS, remoteHost, fromFile, toFile) }); mHostName = remoteHost; }
Source:
public boolean shutdown() { // Stop accepting new connections. mServer.shutdown(); // Close resources that potentially owns active streams. try { mCloser.close(); } catch (IOException e) { LOG.warn("Failed to close resources during shutdown.", e); // Do nothing. } // Force shutdown remaining calls. mServer.shutdownNow(); // Wait until server terminates. try { return mServer.awaitTermination(mServerShutdownTimeoutMs, TimeUnit.MILLISECONDS); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); return false; } }

Target:
public boolean shutdown() { // Stop accepting new connections. mServer.shutdown(); // Close resources that potentially owns active streams. try { mCloser.close(); } catch (IOException e) { LOG.error("Failed to close resources during shutdown.", e); // Do nothing. } // Force shutdown remaining calls. mServer.shutdownNow(); // Wait until server terminates. try { return mServer.awaitTermination(mServerShutdownTimeoutMs, TimeUnit.MILLISECONDS); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); return false; } }
Source:
private void enforceResumeJournals() { try { mJournalSystem.resume(); } catch (IOException e) { ProcessUtils.fatalError(LOG, e, "Failed to resume journals."); } }

Target:
private void enforceResumeJournals() { try { mJournalSystem.resume(); } catch (Throwable e) { ProcessUtils.fatalError(LOG, e, "Failed to resume journals."); } }
Source:
public void suspend() throws IOException { try (LockResource stateLock = new LockResource(mStateLock)) { Preconditions.checkState(!mSuspended, "Already suspended"); LOG.info("Suspending state machine."); mSuspended = true; LOG.info("Suspended state machine at sequence: {}", mLastAppliedSequence); } }

Target:
public void suspend() throws IOException { try (LockResource stateLock = new LockResource(mStateLock)) { Preconditions.checkState(!mSuspended, "Already suspended"); mSuspended = true; LOG.info("Suspended state machine at sequence: {}", mLastAppliedSequence); } }
Source:
public void start(Boolean isLeader) throws IOException { super.start(isLeader); mTransformManager.startHeartbeat(getExecutorService(), mMasterContext.getUserState()); }

Target:
public void start(Boolean isLeader) throws IOException { super.start(isLeader); if (isLeader) { mTransformManager.start(getExecutorService(), mMasterContext.getUserState()); } }
Source:
public boolean processJournalEntry(Journal.JournalEntry entry) { if (entry.hasAttachDb()) { apply(entry.getAttachDb()); return true; } else if (entry.hasAddTable()) { Database db = mDBs.get(entry.getAddTable().getDbName()); return db.processJournalEntry(entry); } else if (entry.hasDetachDb()) { apply(entry.getDetachDb()); } return false; }

Target:
public boolean processJournalEntry(Journal.JournalEntry entry) { if (entry.hasAttachDb()) { apply(entry.getAttachDb()); return true; } else if (entry.hasAddTable()) { Database db = mDBs.get(entry.getAddTable().getDbName()); return db.processJournalEntry(entry); } else if (entry.hasDetachDb()) { apply(entry.getDetachDb()); return true; } return false; }
Source:
public int run(CommandLine cl) throws AlluxioStatusException { String[] args = cl.getArgs(); String dbName = args[0]; String dbType = args[1]; Properties p = cl.getOptionProperties(OPTION_OPTION.getOpt()); mClient.attachDatabase(dbName, dbType, Maps.fromProperties(p)); System.out.println(String.format("Attached database %s (type: %s)", dbName, dbType)); return 0; }

Target:
public int run(CommandLine cl) throws AlluxioStatusException { String[] args = cl.getArgs(); String dbName = args[0]; String dbType = args[1]; Properties p = cl.getOptionProperties(OPTION_OPTION.getOpt()); mClient.attachDatabase(dbName, dbType, Maps.fromProperties(p)); return 0; }
Source:
public AlluxioURI reverseResolve(AlluxioURI ufspath) throws IOException, AlluxioException { checkUri(ufspath); return rpc(client -> { AlluxioURI path = client.reverseResolve(ufspath); LOG.debug("Reverse resolved to {}", ufspath.getPath(), path.getPath()); return path; }); }

Target:
public AlluxioURI reverseResolve(AlluxioURI ufspath) throws IOException, AlluxioException { return rpc(client -> { AlluxioURI path = client.reverseResolve(ufspath); LOG.debug("Reverse resolved to {}", ufspath.getPath(), path.getPath()); return path; }); }
Source:
public List<alluxio.grpc.catalog.Partition> readTable(String dbName, String tableName, Constraint constraint) throws IOException { Table table = getTable(dbName, tableName); List<Partition> partitions = table.getPartitions(); // TODO(david): implement partition pruning List<alluxio.grpc.catalog.Partition> returnList = partitions.stream().map(Partition::toProto).collect(Collectors.toList()); return returnList; }

Target:
public List<alluxio.grpc.catalog.Partition> readTable(String dbName, String tableName, Constraint constraint) throws IOException { Table table = getTable(dbName, tableName); List<Partition> partitions = table.getPartitions(); // TODO(david): implement partition pruning return partitions.stream().map(Partition::toProto).collect(Collectors.toList()); }
Source:
public boolean isRootListable() { try { return getObjectListingChunkForPath("", true) != null; } catch (Exception e) { LOG.debug("Unable to list root of bucket {}:", super.mUri.toString(), e.getMessage()); return false; } }

Target:
public boolean isRootListable() { try { return getObjectListingChunkForPath("", true) != null; } catch (Exception e) { LOG.debug("Unable to list root of bucket {}:", super.mUri.toString(), e); return false; } }
Source:
public synchronized void updateTasks(List<TaskInfo> taskInfoList) { synchronized (mJobInfo) { for (TaskInfo taskInfo : taskInfoList) { mJobInfo.setTaskInfo(taskInfo.getTaskId(), taskInfo); } updateStatus(); } }

Target:
public void updateTasks(List<TaskInfo> taskInfoList) { synchronized (mJobInfo) { for (TaskInfo taskInfo : taskInfoList) { mJobInfo.setTaskInfo(taskInfo.getTaskId(), taskInfo); } updateStatus(); } }
Source:
public synchronized void failTasksForWorker(long workerId) { Integer taskId = mWorkerIdToTaskId.get(workerId); if (taskId == null) { return; } TaskInfo taskInfo = mJobInfo.getTaskInfo(taskId); if (taskInfo.getStatus().isFinished()) { return; } synchronized (mJobInfo) { if (!mJobInfo.getStatus().isFinished()) { taskInfo.setStatus(Status.FAILED); taskInfo.setErrorMessage("Job worker was lost before the task could complete"); updateStatus(); } } }

Target:
public void failTasksForWorker(long workerId) { synchronized (mJobInfo) { Integer taskId = mWorkerIdToTaskId.get(workerId); if (taskId == null) { return; } TaskInfo taskInfo = mJobInfo.getTaskInfo(taskId); if (taskInfo.getStatus().isFinished()) { return; } if (!mJobInfo.getStatus().isFinished()) { taskInfo.setStatus(Status.FAILED); taskInfo.setErrorMessage("Job worker was lost before the task could complete"); updateStatus(); } } }
Source:
private void shutdownManagedChannel(ManagedChannel managedChannel, long shutdownTimeoutMs) { managedChannel.shutdown(); try { managedChannel.awaitTermination(shutdownTimeoutMs, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // Allow thread to exit. } finally { managedChannel.shutdownNow(); } Verify.verify(managedChannel.isShutdown()); }

Target:
private void shutdownManagedChannel(ManagedChannel managedChannel, long shutdownTimeoutMs) { managedChannel.shutdown(); try { managedChannel.awaitTermination(shutdownTimeoutMs, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // Allow thread to exit. } finally { managedChannel.shutdownNow(); } }
Source:
private String getTransportPath(AlluxioURI uri) { if (uri.hasScheme()) { return uri.toString(); } else { return uri.getPath(); } }

Target:
private static String getTransportPath(AlluxioURI uri) { if (uri.hasScheme()) { return uri.toString(); } else { // Scheme-less URIs are assumed to be Alluxio paths // and getPath() is used to avoid string conversion. return uri.getPath(); } }
Source:
public Options getOptions() { return new Options() .addOption(FORCE_OPTION) .addOption(LIST_DIR_AS_FILE_OPTION) .addOption(LIST_HUMAN_READABLE_OPTION) .addOption(LIST_PINNED_FILES_OPTION) .addOption(TIMESTAMP_OPTION) .addOption(RECURSIVE_OPTION) .addOption(REVERSE_SORT_OPTION) .addOption(SORT_OPTION); }

Target:
public Options getOptions() { return new Options() .addOption(FORCE_OPTION) .addOption(LIST_DIR_AS_FILE_OPTION) .addOption(LIST_HUMAN_READABLE_OPTION) .addOption(LIST_PINNED_FILES_OPTION) .addOption(RECURSIVE_OPTION) .addOption(REVERSE_SORT_OPTION) .addOption(SORT_OPTION) .addOption(TIMESTAMP_OPTION); }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof IdentityObject)) { // If it isn't an instance of an identity object, compare our internal pointer with the arg // A form of "auto unboxing" when performing comparisons return mObj == o; } try { IdentityObject<T> other = (IdentityObject<T>) o; return mObj == other.mObj; } catch (ClassCastException e) { return false; } }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof IdentityObject)) { return false; } try { IdentityObject<T> other = (IdentityObject<T>) o; return mObj == other.mObj; } catch (ClassCastException e) { return false; } }
Source:
public synchronized JournalContext createJournalContext() throws UnavailableException { if (mState != State.PRIMARY) { // We throw UnavailableException here so that clients will retry with the next primary master. throw new UnavailableException("Failed to write to journal: journal is in state " + mState); } AsyncJournalWriter writer = mAsyncWriter; if (writer == null) { throw new UnavailableException("Failed to write to journal: journal is shutdown."); } return new MasterJournalContext(writer); }

Target:
public synchronized JournalContext createJournalContext() throws UnavailableException { if (mState != State.PRIMARY) { // We throw UnavailableException here so that clients will retry with the next primary master. throw new UnavailableException("Failed to write to journal: journal is in state " + mState); } return new MasterJournalContext(mAsyncWriter); }