auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private int distToInt(double distance) { if (distance < 0) throw new IllegalArgumentException("Distance cannot be negative: " + distance); if (distance > MAX_DIST) { distance = MAX_DIST; // throw new IllegalArgumentException("Distance too large leading to overflowed integer (#435): " + distance + " "); } int integ = Math.round((float) (distance * INT_DIST_FACTOR)); assert integ >= 0 : "distance out of range"; return integ; }

Target:
private int distToInt(double distance) { if (distance < 0) throw new IllegalArgumentException("Distance cannot be negative: " + distance); if (distance > MAX_DIST) { distance = MAX_DIST; } int integ = (int) Math.round(distance * INT_DIST_FACTOR); assert integ >= 0 : "distance out of range"; return integ; }
Source:
public void addTurnInfo(int fromEdge, int viaNode, int toEdge, long turnFlags) { // no need to store turn information if (turnFlags == EMPTY_FLAGS) { return; } BiFunction<Long, Long, Long> overwriteFunc = (oldFlags, newFlags) -> { return newFlags; }; setAndMergeTurnInfo(fromEdge, viaNode, toEdge, turnFlags, overwriteFunc); }

Target:
public void addTurnInfo(int fromEdge, int viaNode, int toEdge, long turnFlags) { setAndMergeTurnInfo(fromEdge, viaNode, toEdge, turnFlags, false, false); }
Source:
public void readGraph() throws IOException { // TODO why 1000? graphStorage.create(1000); processJunctions(); processRoads(); }

Target:
public void readGraph() { graphStorage.create(1000); processJunctions(); processRoads(); }
Source:
private boolean loadDataFromSession() { HttpSession session = getHttpSession(); Object data = session.getAttribute(SESSION_KEY); if ((data != null) && (data instanceof ReportSessionData)) { ReportSessionData reportSessionData = (ReportSessionData) data; currentUser = reportSessionData.currentUser; dateFrom = reportSessionData.dateFrom; dateFromFormated = DateTimeConverterUtil.dateToString(dateFrom); dateTo = reportSessionData.dateTo; dateToFormated = DateTimeConverterUtil.dateToString(dateTo); return true; } else { return false; } }

Target:
private boolean loadDataFromSession() { HttpSession session = getHttpSession(); Object data = session.getAttribute(SESSION_KEY); if (!(data instanceof ReportSessionData)) { return false; } ReportSessionData reportSessionData = (ReportSessionData) data; currentUser = reportSessionData.currentUser; dateFrom = reportSessionData.dateFrom; dateFromFormated = DateTimeConverterUtil.dateToString(dateFrom); dateTo = reportSessionData.dateTo; dateToFormated = DateTimeConverterUtil.dateToString(dateTo); return true; }
Source:
public Workbook strictParseWorkbook(final File file, final String programUUID) throws WorkbookParserException { final WorkbookParser parser = new WorkbookParser(this.maxRowLimit); final OntologyDataManagerImpl ontology = new OntologyDataManagerImpl(this.getSessionProvider()); final GermplasmDataManager germplasmDataManager = new GermplasmDataManagerImpl(this.getSessionProvider()); // partially parse the file to parse the description sheet only at first return this.strictParseWorkbook(file, parser, parser.parseFile(file, true), ontology, germplasmDataManager, programUUID); }

Target:
public Workbook strictParseWorkbook(final File file, final String programUUID) throws WorkbookParserException { final WorkbookParser parser = new WorkbookParser(this.maxRowLimit); // partially parse the file to parse the description sheet only at first return this.strictParseWorkbook(file, parser, parser.parseFile(file, true), programUUID); }
Source:
protected void initTiffParser() { super.initTiffParser(); // older .scn files require color correction // newer files from Versa systems do not if (handler != null) { Image i = handler.imageMap.get(0); tiffParser.setYCbCrCorrection(!"versa".equalsIgnoreCase(i.devModel) && !"leica scn400".equalsIgnoreCase(i.devModel); } }

Target:
protected void initTiffParser() { super.initTiffParser(); // older .scn files require color correction // newer files from Versa systems do not if (handler != null) { Image i = handler.imageMap.get(0); tiffParser.setYCbCrCorrection(!("versa".equalsIgnoreCase(i.devModel) || "leica scn400".equalsIgnoreCase(i.devModel))); } }
Source:
public static void setupServer(boolean updateable, SecurityHandler sh) { // Clean datasets. dsgTesting = DatasetGraphFactory.createTxnMem(); server = FusekiEmbeddedServer.create() .add(datasetPath(), dsgTesting) .setPort(port()) .setSecurityHandler(sh) .build() .start(); }

Target:
public static void setupServer(boolean updateable, SecurityHandler sh) { setupServer(updateable, sh, DatasetGraphFactory.createTxnMem()); }
Source:
@Test public void testExhaustionClosesSourceIterator() { iterator.setCallback(new Callback() { @Override public void call() { /* do nothing */ } }); Context context = new Context() ; ExecutionContext ec = new ExecutionContext(context, (Graph) null, (DatasetGraph) null, (OpExecutorFactory) null); QueryIterSort qis = new QueryIterSort(iterator, comparator, ec); while (qis.hasNext()) qis.next(); assertTrue("source iterator should have been closed", iterator.isClosed()); }

Target:
public void testExhaustionClosesSourceIterator() { iterator.setCallback(() -> {}); Context context = new Context() ; ExecutionContext ec = new ExecutionContext(context, (Graph) null, (DatasetGraph) null, (OpExecutorFactory) null); QueryIterSort qis = new QueryIterSort(iterator, comparator, ec); while (qis.hasNext()) qis.next(); assertTrue("source iterator should have been closed", iterator.isClosed()); }
Source:
public void isolation_01() { // Start a read transaction on another thread. // The transaction has begin() by the time threadTxnRead // returns but the action of the ThreadTxn is not triggered // until other.run() is called. DatasetGraph dsg = create() ; ThreadAction other = ThreadTxn.threadTxnRead(dsg, ()-> { long x = Iter.count(dsg.find()) ; Assert.assertEquals(0, x) ; }) ; dsg.begin(WRITE) ; dsg.add(q1) ; dsg.commit() ; dsg.end() ; other.run() ; }

Target:
public void isolation_01() { // Start a read transaction on another thread. // The transaction has begin() by the time threadTxnRead // returns but the action of the ThreadTxn is not triggered // until other.run() is called. DatasetGraph dsg = create() ; ThreadAction other = ThreadTxn.threadTxnRead(dsg, ()-> Assert.assertTrue(dsg.isEmpty()) ) ; dsg.begin(WRITE) ; dsg.add(q1) ; dsg.commit() ; dsg.end() ; other.run() ; }
Source:
private static boolean isVariableThatCanEscape(Symbol symb) { List<Usage> usages = symb.usages(); if (usages.size() > 2) { // Check whether there are any usages except assignments and `is`-comparisons. // (Assignments override, they don't let the reference escape. Comparisons with `is` also don't let it escape, // because they only compare, they don't copy the reference anywhere.) return usages.stream().anyMatch(u -> !u.isBindingUsage() && TreeUtils.firstAncestorOfKind(u.tree(), Tree.Kind.IS) == null); } else { // Only original assignment and usage within comparison itself, ignore return false; } }

Target:
private static boolean isVariableThatCanEscape(Symbol symb) { List<Usage> usages = symb.usages(); if (usages.size() > 2) { // Check whether there are any usages except assignments and `is`-comparisons. // (Assignments override, they don't let the reference escape. Comparisons with `is` also don't let it escape, // because they only compare, they don't copy the reference anywhere.) return usages.stream().anyMatch(u -> !u.isBindingUsage() && TreeUtils.firstAncestorOfKind(u.tree(), Tree.Kind.IS) == null); } // Must be definition and usage within <code>is</code>-comparison itself. return false; }
Source:
private static boolean isUsageInClassBody(Usage usage, ClassDef classDef) { if (usage.kind() == Usage.Kind.FUNC_DECLARATION) { return false; } Tree tree = usage.tree(); return classDef.equals(TreeUtils.firstAncestorOfKind(tree, Tree.Kind.CLASSDEF)) && TreeUtils.firstAncestorOfKind(tree, Tree.Kind.FUNCDEF) == null; }

Target:
private static boolean isUsageInClassBody(Usage usage, ClassDef classDef) { // We want all usages that are not function declarations and their closes parent is the class definition return usage.kind() != Usage.Kind.FUNC_DECLARATION && classDef.equals(TreeUtils.firstAncestorOfKind(usage.tree(), Tree.Kind.CLASSDEF, Tree.Kind.FUNCDEF)); }
Source:
private boolean argumentInheritsFromBaseException(Argument argument) { if (!argument.is(Tree.Kind.REGULAR_ARGUMENT)) { // Need type inference to assess further return true; } Expression expression = ((RegularArgument) argument).expression(); if (expression.is(Tree.Kind.NAME) || expression.is(Tree.Kind.QUALIFIED_EXPR)) { return inheritsFromBaseException(((HasSymbol) expression).symbol()); } return true; }

Target:
private boolean argumentInheritsFromBaseException(Argument argument) { if (!argument.is(Tree.Kind.REGULAR_ARGUMENT)) { // Need type inference to assess further return true; } Expression expression = ((RegularArgument) argument).expression(); if (expression instanceof HasSymbol) { return inheritsFromBaseException(((HasSymbol) expression).symbol()); } return true; }
Source:
public void scan(@Nullable Tree element) { if (element != null) { currentElement = element; List<SubscriptionContextImpl> elementConsumers = consumers.getOrDefault(element.getKind(), Collections.emptyList()); for (SubscriptionContextImpl consumer : elementConsumers) { consumer.execute(); } } super.scan(element); }

Target:
public void scan(@Nullable Tree element) { if (element != null) { currentElement = element; consumers.getOrDefault(element.getKind(), Collections.emptyList()).forEach(SubscriptionContextImpl::execute); } super.scan(element); }
Source:
public void function_declaration(){ setRootRule(PythonGrammar.FUNCDEF); assertThat(p).matches("def fun()->'Returns some value': pass"); assertThat(p).matches("def fun(count:'Number of smth'=1, value:'Value of smth', type:Type): pass"); assertThat(p).matches("async def fun(): pass"); setRootRule(PythonGrammar.LAMBDEF); assertThat(p).matches("lambda x: x"); assertThat(p).notMatches("lambda x:Type: x"); }

Target:
public void function_declaration(){ setRootRule(PythonGrammar.FUNCDEF); assertThat(p).matches("def fun()->'Returns some value': pass"); assertThat(p).matches("def fun(count:'Number of smth'=1, value:'Value of smth', type:Type): pass"); setRootRule(PythonGrammar.LAMBDEF); assertThat(p).matches("lambda x: x"); assertThat(p).notMatches("lambda x:Type: x"); }
Source:
public String getStoriesIdJsonStringInSprint() throws JSONException { return new ConvertSprintBacklog().getStoriesIdJsonStringInSprint( mSprintBacklogLogic.getStoriesSortedByIdInSprint()); }

Target:
public String getStoriesIdJsonStringInSprint() throws JSONException { return ConvertSprintBacklog.getStoriesIdJsonStringInSprint( mSprintBacklogLogic.getStoriesSortedByIdInSprint()); }
Source:
public String getTasksIdJsonStringInStory(long storyId) throws JSONException { ArrayList<TaskObject> tasks = mSprintBacklogMapper.getStory(storyId).getTasks(); return new ConvertSprintBacklog().getTasksIdJsonStringInStory(storyId, tasks); }

Target:
public String getTasksIdJsonStringInStory(long storyId) throws JSONException { ArrayList<TaskObject> tasks = mSprintBacklogMapper.getStory(storyId).getTasks(); return ConvertSprintBacklog.getTasksIdJsonStringInStory(storyId, tasks); }
Source:
public String getSprintBacklogJsonString() throws JSONException { SprintObject sprint = mSprintBacklogMapper.getSprint(); return new ConvertSprintBacklog().getSprintBacklogJsonString(sprint); }

Target:
public String getSprintBacklogJsonString() throws JSONException { SprintObject sprint = mSprintBacklogMapper.getSprint(); return ConvertSprintBacklog.getSprintBacklogJsonString(sprint); }
Source:
public String getTasksJsonString(ArrayList<TaskObject> tasks) throws JSONException { JSONObject tasksJsonString = new JSONObject(); JSONArray tasksJsonArray = new JSONArray(); if (tasks == null) return ""; for (TaskObject task : tasks) { JSONObject taskJson = new JSONObject(getTaskJsonString(task)); tasksJsonArray.put(taskJson); } tasksJsonString.put(SprintBacklogUtil.TAG_TASKS, tasksJsonArray); return tasksJsonString.toString(); }

Target:
static public String getTasksJsonString(ArrayList<TaskObject> tasks) throws JSONException { JSONObject tasksJsonString = new JSONObject(); JSONArray tasksJsonArray = new JSONArray(); if (tasks == null) return ""; for (TaskObject task : tasks) { JSONObject taskJson = new JSONObject(getTaskJsonString(task)); tasksJsonArray.put(taskJson); } tasksJsonString.put(SprintBacklogUtil.TAG_TASKS, tasksJsonArray); return tasksJsonString.toString(); }
Source:
public void openConnect() { getControl().connect(); mNoteService = new MantisNoteService(getControl(), getConfig()); mIssueService = new MantisIssueService(getControl(), getConfig()); mAttachFileService = new MantisAttachFileService(getControl(), getConfig()); }

Target:
public void openConnect() { getControl().connect(); mNoteService = new MantisNoteService(getControl(), getConfig()); mIssueService = new MantisIssueService(getControl(), getConfig()); }
Source:
private void initialize(long projectId) { UserSession userSession = new UserSession(super.getAccount()); mProjectHelper = new ProjectHelper(); mProject = mProjectHelper.getProject(projectId); IProject iProject = new ProjectMapper().getProjectByID(mProject.getName()); mSprintBacklogHelper = new SprintBacklogHelper(iProject, userSession); mProductBacklogHelper = new ProductBacklogHelper(userSession, iProject); }

Target:
private void initialize(long projectId) { UserSession userSession = new UserSession(super.getAccount()); mProjectHelper = new ProjectHelper(); mProject = mProjectHelper.getProject(projectId); IProject project = new ProjectMapper().getProjectByID(mProject.getName()); mSprintBacklogHelper = new SprintBacklogHelper(project, userSession); mProductBacklogHelper = new ProductBacklogHelper(userSession, project); }
Source:
public IssueBacklog(IProject project, IUserSession userSession) { // 有些地方還是只能使用IProject 所以過度期使用此段程式碼 ezScrum v1.8 m_project = new ProjectObject(); m_project.setNickName(project.getName()); // m_project = project; m_userSession = userSession; // 初始Config設定 m_config = new Configuration(m_userSession); }

Target:
public IssueBacklog(IProject project, IUserSession userSession) { // 有些地方還是只能使用IProject 所以過度期使用此段程式碼 ezScrum v1.8 m_project = new ProjectObject(project.getName()); // m_project = project; m_userSession = userSession; // 初始Config設定 m_config = new Configuration(m_userSession); }
Source:
public void write(byte[] data, int offset, int len) { if(!this.running) { return; } //Send audio data requestObserver.onNext(StreamingRecognizeRequest.newBuilder().setAudioContent(ByteString.copyFrom(data)).build()); }

Target:
public void write(byte[] data, int offset, int len) { if(!this.running.get()) { return; } //Send audio data requestObserver.onNext(StreamingRecognizeRequest.newBuilder().setAudioContent(ByteString.copyFrom(data, offset, len)).build()); }
Source:
public DelegatingResourceDescription getUpdatableProperties() throws ResourceDoesNotSupportOperationException { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("name"); description.addProperty("description"); description.addProperty("identifierType"); return description; }

Target:
public DelegatingResourceDescription getUpdatableProperties() throws ResourceDoesNotSupportOperationException { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("name"); description.addProperty("description"); return description; }
Source:
SlackService getSlackService(final String baseUrl, final String teamDomain, final String authTokenCredentialId, final boolean botUser, final String roomId, final Item item) { final String populatedToken = CredentialsObtainer.getTokenToUse(authTokenCredentialId, item,null ); if (populatedToken != null) { return new StandardSlackService( new StandardSlackServiceBuilder() .withBaseUrl(baseUrl) .withTeamDomain(teamDomain) .withBotUser(botUser) .withRoomId(roomId) .withPopulatedToken(populatedToken) ); } else { throw new NoSuchElementException("Could not obtain credentials with credential id: " + authTokenCredentialId); } }

Target:
SlackService getSlackService(final String baseUrl, final String teamDomain, final String authTokenCredentialId, final boolean botUser, final String roomId, final Item item) { final String populatedToken = CredentialsObtainer.getTokenToUse(authTokenCredentialId, item,null ); if (populatedToken != null) { return new StandardSlackService( StandardSlackService.builder() .withBaseUrl(baseUrl) .withTeamDomain(teamDomain) .withBotUser(botUser) .withRoomId(roomId) .withPopulatedToken(populatedToken) ); } else { throw new NoSuchElementException("Could not obtain credentials with credential id: " + authTokenCredentialId); } }
Source:
public SlackResponse(String slackResponseString) { if (StringUtils.isEmpty(slackResponseString)) { JSONObject result = new JSONObject(slackResponseString); channelId = result.getString("channel"); ts = result.getString("ts"); } }

Target:
public SlackResponse(String slackResponseString) { if (!StringUtils.isEmpty(slackResponseString)) { JSONObject result = new JSONObject(slackResponseString); channelId = result.getString("channel"); ts = result.getString("ts"); } }
Source:
public Person somePerson() { return new Person(); }

Target:
private static Person somePerson() { return new Person(); }
Source:
public void newPersonForwardsToViewIfValidationFails() throws Exception { doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Errors errors = (Errors) invocation.getArgument(1); errors.rejectValue("email", "invalid.email"); return null; } }).when(validator).validate(any(), any()); perform(post("/web/person")).andExpect(view().name("person/person_form")); }

Target:
public void newPersonForwardsToViewIfValidationFails() throws Exception { doAnswer(invocation -> { Errors errors = invocation.getArgument(1); errors.rejectValue("email", "invalid.email"); return null; }).when(validator).validate(any(), any()); perform(post("/web/person")).andExpect(view().name("person/person_form")); }
Source:
public void editPersonFormForUnknownIdThrowsUnknownPersonException() throws Exception { assertThatThrownBy(() -> perform(get("/web/person/" + UNKNOWN_PERSON_ID + "/edit")) ).hasCauseInstanceOf(UnknownPersonException.class); }

Target:
public void editPersonFormForUnknownIdThrowsUnknownPersonException() { assertThatThrownBy(() -> perform(get("/web/person/" + UNKNOWN_PERSON_ID + "/edit")) ).hasCauseInstanceOf(UnknownPersonException.class); }
Source:
public void editPersonForwardsToViewIfValidationFails() throws Exception { doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Errors errors = (Errors) invocation.getArgument(1); errors.rejectValue("email", "invalid.email"); return null; } }).when(validator).validate(any(), any()); perform(post("/web/person/" + PERSON_ID + "/edit")).andExpect(view().name("person/person_form")); }

Target:
public void editPersonForwardsToViewIfValidationFails() throws Exception { doAnswer(invocation -> { Errors errors = invocation.getArgument(1); errors.rejectValue("email", "invalid.email"); return null; }).when(validator).validate(any(), any()); perform(post("/web/person/" + PERSON_ID + "/edit")).andExpect(view().name("person/person_form")); }
Source:
private static Person personWithId(int personId) { Person person = new Person(); person.setId(PERSON_ID); return person; }

Target:
private static Person personWithId(int personId) { Person person = new Person(); person.setId(personId); return person; }
Source:
public void showPersonInformationUsesGivenYear() throws Exception { when(personService.getPersonByID(PERSON_ID)).thenReturn(Optional.of(person)); when(departmentService.isSignedInUserAllowedToAccessPersonData(person, person)).thenReturn(true); when(settingsService.getSettings()).thenReturn(settingsWithFederalState(FederalState.BADEN_WUERTTEMBERG)); perform(get("/web/person/" + PERSON_ID).param(ControllerConstants.YEAR_ATTRIBUTE, "1985")) .andExpect(model().attribute(ControllerConstants.YEAR_ATTRIBUTE,1985)); }

Target:
public void showPersonInformationUsesGivenYear() throws Exception { when(personService.getPersonByID(PERSON_ID)).thenReturn(Optional.of(person)); when(departmentService.isSignedInUserAllowedToAccessPersonData(person, person)).thenReturn(true); when(settingsService.getSettings()).thenReturn(settingsWithFederalState(BADEN_WUERTTEMBERG)); perform(get("/web/person/" + PERSON_ID).param(YEAR_ATTRIBUTE, "1985")) .andExpect(model().attribute(YEAR_ATTRIBUTE,1985)); }
Source:
public void showPersonWithActiveTrueForUserWithRoleBossCallsCorrectService() throws Exception { when(personService.getSignedInUser()).thenReturn(personWithRole(Role.BOSS)); perform(get("/web/person").param("active", "true")); verify(personService).getActivePersons(); }

Target:
public void showPersonWithActiveTrueForUserWithRoleBossCallsCorrectService() throws Exception { when(personService.getSignedInUser()).thenReturn(personWithRole(BOSS)); perform(get("/web/person").param("active", "true")); verify(personService).getActivePersons(); }
Source:
private DayLength getExpectedWorktimeFor(Person person, LocalDate currentDay) { Optional<WorkingTime> workingTimeOrNot = workingTimeService.getByPersonAndValidityDateEqualsOrMinorDate(person, currentDay); if (workingTimeOrNot.isEmpty()) { throw new FreeTimeAbsenceException("Person " + person + " does not have workingTime configured"); } WorkingTime workingTime = workingTimeOrNot.get(); return workingTime.getDayLengthForWeekDay(currentDay.getDayOfWeek().getValue()); }

Target:
private DayLength getExpectedWorktimeFor(Person person, LocalDate currentDay) { Optional<WorkingTime> workingTimeOrNot = workingTimeService.getByPersonAndValidityDateEqualsOrMinorDate(person, currentDay); if (!workingTimeOrNot.isPresent()) { throw new FreeTimeAbsenceException("Person " + person + " does not have workingTime configured"); } WorkingTime workingTime = workingTimeOrNot.get(); return workingTime.getDayLengthForWeekDay(currentDay.getDayOfWeek().getValue()); }
Source:
BigDecimal calculatePresenceRatio() { BigDecimal absenceRatio = BigDecimal.ZERO; for (TimedAbsence absenceSpan : absencesList) { absenceRatio = absenceRatio.add(absenceSpan.getRatio()); } BigDecimal presenceRatio = BigDecimal.ONE.subtract(absenceRatio); boolean negativePresenceRatio = presenceRatio.compareTo(BigDecimal.ZERO) < 0; if (negativePresenceRatio) { presenceRatio = BigDecimal.ZERO; } return presenceRatio; }

Target:
BigDecimal calculatePresenceRatio() { BigDecimal presenceRatio = BigDecimal.ONE; for (TimedAbsence absenceSpan : absencesList) { presenceRatio = presenceRatio.subtract(absenceSpan.getRatio()); } boolean negativePresenceRatio = presenceRatio.compareTo(BigDecimal.ZERO) < 0; if (negativePresenceRatio) { presenceRatio = BigDecimal.ZERO; } return presenceRatio; }
Source:
public String[] cutUri (URI uri) throws NullPointerException, IllegalArgumentException { String path = uri.getPath(); String[] result = path.split("/"); if (result.length < 2) { throw new IllegalArgumentException("there is neither ContainerName nor BlobName in the URI path"); } for (int i = 1; i < result.length; i++){ if (result[i] == null) { throw new NullPointerException("one of the path parameters is null"); } } return result; }

Target:
public String[] cutUri(URI uri) throws IllegalArgumentException { String path = uri.getPath(); String[] result = path.split("/"); if (result.length < 2) { throw new IllegalArgumentException("there is neither ContainerName nor BlobName in the URI path"); } return result; }
Source:
public void setup() { super.setup(); virtualGuestApi = api.getVirtualGuestApi(); datacenter = Iterables.get(api.getDatacenterApi().listDatacenters(), 0); assertNull(datacenter, "Datacenter must not be null"); }

Target:
public void setup() { super.setup(); virtualGuestApi = api.getVirtualGuestApi(); datacenter = Iterables.get(api.getDatacenterApi().listDatacenters(), 0); assertNotNull(datacenter, "Datacenter must not be null"); }
Source:
String buildJson(String notes) { return json.toJson(ImmutableMap.of("parameters", ImmutableList.of(ImmutableMap.of("notes", notes)))); }

Target:
private String buildJson(String notes) { return json.toJson(ImmutableMap.of("parameters", ImmutableList.of(ImmutableMap.of("notes", notes)))); }
Source:
NotesToJson(Json json) { this.json = checkNotNull(json, "json"); }

Target:
NotesToJson(Json json) { this.json = json; }
Source:
public URI apply(Object from) { if (!(from instanceof String)) { throw new AssertionError("you must specify a region, as a String argument"); } Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); checkState(!regionToEndpoint.isEmpty(), "no region name to endpoint mappings configured!"); checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); }

Target:
public URI apply(Object from) { Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); checkState(!regionToEndpoint.isEmpty(), "no region name to endpoint mappings configured!"); checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); }
Source:
public void testReboot() throws Exception { Set<? extends NodeMetadata> rebootNodes = client.rebootNodesMatching(inGroup(group)); for (ComputeMetadata node : rebootNodes) { assert node.getProviderId() != null : node; assert node.getLocation() != null : node; assertEquals(node.getType(), ComputeType.NODE); } // validation testGet(); }

Target:
public void testReboot() throws Exception { Set<? extends NodeMetadata> rebootNodes = client.rebootNodesMatching(inGroup(group)); for (ComputeMetadata node : rebootNodes){ assertNotNull(node); assert node.getProviderId() != null : node; assert node.getLocation() != null : node; } // validation testGet(); }
Source:
private Image findImageWithId(Set<? extends Image> images) { // Try to find the image in the cache and fallback to the GetImageStrategy // see https://issues.apache.org/jira/browse/JCLOUDS-570 Optional<? extends Image> image = tryFind(images, idPredicate); if (image.isPresent()) { return image.get(); } logger.warn("Image %s not found in the image cache. Trying to get it from the provider...", imageId); // Note that this will generate make a call to the provider instead of using a cache, but // this will be executed rarely, only when an image is not present in the image list but // it actually exists in the provider. It shouldn't be an expensive call so using a cache just for // this corner case is overkill. Image imageFromProvider = getImageStrategy.getImage(imageId); if (imageFromProvider == null) { throwNoSuchElementExceptionAfterLoggingImageIds(format("%s not found", idPredicate), images); } // Register the just found image in the image cache, so subsequent uses of the TemplateBuilder and // the ComptueService find it. this.images.registerImage(imageFromProvider); return imageFromProvider; }

Target:
private Image findImageWithId(Set<? extends Image> images) { // Try to find the image in the cache and fallback to the GetImageStrategy // see https://issues.apache.org/jira/browse/JCLOUDS-570 Optional<? extends Image> image = tryFind(images, idPredicate); if (image.isPresent()) { return image.get(); } logger.info("Image %s not found in the image cache. Trying to get it from the provider...", imageId); // Note that this will generate make a call to the provider instead of using a cache, but // this will be executed rarely, only when an image is not present in the image list but // it actually exists in the provider. It shouldn't be an expensive call so using a cache just for // this corner case is overkill. Image imageFromProvider = getImageStrategy.getImage(imageId); if (imageFromProvider == null) { throwNoSuchElementExceptionAfterLoggingImageIds(format("%s not found", idPredicate), images); } // Register the just found image in the image cache, so subsequent uses of the TemplateBuilder and // the ComptueService find it. this.images.registerImage(imageFromProvider); return imageFromProvider; }
Source:
protected String imageIdForZone(String zoneId) { ImageApi imageApi = api.getImageApiForZone(zoneId); return Iterables.getFirst(imageApi.list().concat(), null).getId(); }

Target:
protected String imageIdForZone(String zoneId) { ImageApi imageApi = api.getImageApiForZone(zoneId); // Get the first image from the list as it tends to be "lighter" and faster to start return Iterables.get(imageApi.list().concat(), 0).getId(); }
Source:
public DeployVirtualMachineOptions apply(CloudStackTemplateOptions templateOptions, Map<String, Network> networks, String zoneId, DeployVirtualMachineOptions options) { // both security groups and networks are optional, and CloudStack will // use the zone/user's default network/security group if none given if (templateOptions.getSecurityGroupIds().size() > 0) { options.securityGroupIds(templateOptions.getSecurityGroupIds()); } if (templateOptions.getNetworks().size() > 0) { options.networkIds(templateOptions.getNetworks()); } return options; }

Target:
public DeployVirtualMachineOptions apply(CloudStackTemplateOptions templateOptions, Map<String, Network> networks, String zoneId, DeployVirtualMachineOptions options) { // both security groups and networks are optional, and CloudStack will // use the zone/user's default network/security group if none given if (!templateOptions.getSecurityGroupIds().isEmpty()) { options.securityGroupIds(templateOptions.getSecurityGroupIds()); } if (!templateOptions.getNetworks().isEmpty()) { options.networkIds(templateOptions.getNetworks()); } return options; }
Source:
protected void tearDownContext() { if (nodes != null) { client.destroyNodesMatching(inGroup(group)); } super.tearDownContext(); }

Target:
protected void tearDownContext() { try { if (nodes != null) { client.destroyNodesMatching(inGroup(group)); } } catch (Exception e) { } super.tearDownContext(); }
Source:
protected Builder() { id("softlayer") .name("SoftLayer") .apiMetadata(new SoftLayerApiMetadata()) .homepage(URI.create("http://www.softlayer.com")) .console(URI.create("https://manage.softlayer.com")) .iso3166Codes("SG","US-CA","US-TX","US-VA","US-WA","US-TX", "NL") .endpoint("https://api.softlayer.com/rest") .defaultProperties(SoftLayerProviderMetadata.defaultProperties()); }

Target:
protected Builder() { id("softlayer") .name("SoftLayer") .apiMetadata(new SoftLayerApiMetadata()) .homepage(URI.create("http://www.softlayer.com")) .console(URI.create("https://manage.softlayer.com")) .iso3166Codes("SG","US-CA","US-TX","US-VA","US-WA","US-TX") .endpoint("https://api.softlayer.com/rest") .defaultProperties(SoftLayerProviderMetadata.defaultProperties()); }
Source:
public void testId() { ProductItemPrice price = ProductItemPrice.builder().id(1234).build(); ProductItem item = ProductItem.builder().id(5678).prices(price).build(); assertEquals("Expected the ID of the ProductItemPrice to be returned", "1234",imageId().apply(item)); }

Target:
public void testId() { ProductItemPrice price = ProductItemPrice.builder().id(1234).build(); ProductItem item = ProductItem.builder().id(5678).prices(price).build(); assertEquals(imageId().apply(item), "1234", "Expected the ID of the ProductItemPrice to be returned"); }
Source:
public static Function<ProductItem, String> imageId() { return new Function<ProductItem, String>() { @Override public String apply(ProductItem productItem) { checkNotNull(productItem, "productItem"); ProductItemPrice price = ProductItems.price().apply(productItem); checkNotNull(price, "price"); return String.valueOf(price.getId()); } }; }

Target:
public static Function<ProductItem, String> imageId() { return new Function<ProductItem, String>() { @Override public String apply(ProductItem productItem) { checkNotNull(productItem, "productItem"); ProductItemPrice price = ProductItems.price().apply(productItem); return String.valueOf(checkNotNull(price, "price").getId()); } }; }
Source:
protected Supplier<URI> provideStorageUrl(RegionIdToURISupplier.Factory factory, @ApiVersion String apiVersion, @Named(LocationConstants.PROPERTY_REGION) String region) { //Get the URI's keyed by their region name Supplier<Map<String, Supplier<URI>>> endpointsSupplier = factory.createForApiTypeAndVersion(ServiceType.OBJECT_STORE, apiVersion); //Pick the matching region name (if any) otherwise just return an arbitrary URL if no region name is set //NOTE: The region string should never be null (it can be empty) if this object was instantiated via guice // as it pulls these named strings from a Properties object. That being said, there's no real reason we // should treat a null string differently to an empty string. if (!Strings.isNullOrEmpty(region)) { return getValueInMapOrNull(endpointsSupplier, region); } else { return getLastValueInMap(endpointsSupplier); } }

Target:
protected Supplier<URI> provideStorageUrl(RegionIdToURISupplier.Factory factory, @ApiVersion String apiVersion, @Named(LocationConstants.PROPERTY_REGION) String region) { //Get the URI's keyed by their region name Supplier<Map<String, Supplier<URI>>> endpointsSupplier = factory.createForApiTypeAndVersion(ServiceType.OBJECT_STORE, apiVersion); //Pick the matching region name (if any) otherwise just return an arbitrary URL if no region name is set //NOTE: The region string should never be null (it can be empty) if this object was instantiated via guice // as it pulls these named strings from a Properties object. if (region.isEmpty()) { return getLastValueInMap(endpointsSupplier); } else { return getValueInMapOrNull(endpointsSupplier, region); } }
Source:
public <T extends View> T onErrorUse(Class<T> view) { if (!hasErrors()) { return new MockResult(proxifier).use(view); //ignore anything, no errors occurred } result.include("errors", getErrors()); outjector.outjectRequestMap(); logger.debug("there are errors on result: {}", messages.handleErrors()); return viewsFactory.instanceFor(view, messages.handleErrors()); }

Target:
public <T extends View> T onErrorUse(Class<T> view) { if (!hasErrors()) { return new MockResult(proxifier).use(view); //ignore anything, no errors occurred } result.include("errors", getErrors()); outjector.outjectRequestMap(); logger.debug("there are errors on result: {}", getErrors()); return viewsFactory.instanceFor(view, messages.handleErrors()); }
Source:
public XMLSerialization indented() { indented = environment.get(ENVIRONMENT_INDENTED_KEY, "true").equalsIgnoreCase("true"); return this; }

Target:
public XMLSerialization indented() { indented = true; return this; }
Source:
public LocaleBasedPrimitiveDoubleConverter() { }

Target:
public LocaleBasedPrimitiveDoubleConverter() { this(null); }
Source:
public static <T> Response<T> success(int code, @Nullable T body) { if (code < 200 || code >= 300) throw new IllegalArgumentException("code < 200 or >= 300: " + code); return success(body, new okhttp3.Response.Builder() // .code(code) .message("Response.success()") .protocol(Protocol.HTTP_1_1) .request(new Request.Builder().url("http://localhost/").build()) .build()); }

Target:
public static <T> Response<T> success(int code, @Nullable T body) { if (code < 200 || code >= 300) { throw new IllegalArgumentException("code < 200 or >= 300: " + code); } return success(body, new okhttp3.Response.Builder() // .code(code) .message("Response.success()") .protocol(Protocol.HTTP_1_1) .request(new Request.Builder().url("http://localhost/").build()) .build()); }
Source:
@Override public <R> Observable<Result<R>> adapt(Call<R> call, Retrofit retrofit) { return Observable.create(new CallOnSubscribe<>(call, retrofit)) // .onErrorReturn(new Func1<Throwable, Result<R>>() { @Override public Result<R> call(Throwable throwable) { return Result.error(throwable); } }); }

Target:
@Override public <R> Observable<Result<R>> adapt(Call<R> call, Retrofit retrofit) { return Observable.create(new CallOnSubscribe<>(call, retrofit)); }
Source:
public static <T> Call<T> response(final Response<T> response) { return new Call<T>() { @Override public Response<T> execute() throws IOException { return response; } @Override public void enqueue(Callback<T> callback) { callback.onResponse(response); } @Override public void cancel() { } @SuppressWarnings("CloneDoesntCallSuperClone") // Immutable object. @Override public Call<T> clone() { return response(response); } }; }

Target:
public static <T> Call<T> response(final Response<T> response) { return new Call<T>() { @Override public Response<T> execute() throws IOException { return response; } @Override public void enqueue(Callback<T> callback) { callback.onResponse(response); } @Override public void cancel() { } @SuppressWarnings("CloneDoesntCallSuperClone") // Immutable object. @Override public Call<T> clone() { return this; } }; }
Source:
public void onAttach(Activity activity) { super.onAttach(activity); // Initialize Baidu Map library com.baidu.mapapi.SDKInitializer.initialize(getActivity().getApplicationContext()); mDpApp = (DroidPlannerApp) activity.getApplication(); }

Target:
public void onAttach(Activity activity) { super.onAttach(activity); // Initialize Baidu Map library com.baidu.mapapi.SDKInitializer.initialize(activity.getApplicationContext()); mDpApp = (DroidPlannerApp) activity.getApplication(); }
Source:
private static String findRootPath(File extFile) { File currPath = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { currPath = extFile; try { while (Environment.isExternalStorageRemovable(currPath.getParentFile())) { currPath = currPath.getParentFile(); } } catch (IllegalArgumentException e) { //swallow return currPath.getAbsolutePath(); } } return currPath.getAbsolutePath(); }

Target:
private static String findRootPath(File extFile) { if (extFile == null) { return null; } File currPath = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { currPath = extFile; try { while (Environment.isExternalStorageRemovable(currPath.getParentFile())) { currPath = currPath.getParentFile(); } } catch (IllegalArgumentException e) { //swallow return currPath.getAbsolutePath(); } } return currPath.getAbsolutePath(); }
Source:
public CharSequence[][] getHelpItems() { return new CharSequence[][] { { getResources().getString(R.string.help_item_description) }, { "https://www.youtube.com/watch?v=btsk7bzn-9Q" } }; }

Target:
public CharSequence[][] getHelpItems() { return new CharSequence[][] { { getString(R.string.help_item_description) }, { "https://www.youtube.com/watch?v=btsk7bzn-9Q" } }; }
Source:
private boolean containsAll(final NullnessAnnotation... search) { Boolean result = null; if (this.annotations.isEmpty()) { // an empty list of annotations can never contain all result = false; } else { for (final NullnessAnnotation obj : search) { if (!this.annotations.contains(obj)) { result = false; break; } } } if (result == null) { result = true; } return result; }

Target:
private boolean containsAll(final NullnessAnnotation... search) { boolean result = true; if (this.annotations.isEmpty()) { // an empty list of annotations can never contain all result = false; } else { for (final NullnessAnnotation obj : search) { if (!this.annotations.contains(obj)) { result = false; break; } } } return result; }
Source:
private boolean containsAny(final NullnessAnnotation... search) { Boolean result = null; if (this.annotations.isEmpty()) { result = false; } else { for (final NullnessAnnotation obj : search) { if (this.annotations.contains(obj)) { result = true; break; } } } if (result == null) { result = false; } return result; }

Target:
private boolean containsAny(final NullnessAnnotation... search) { boolean result = false; if (!this.annotations.isEmpty()) { for (final NullnessAnnotation obj : search) { if (this.annotations.contains(obj)) { result = true; break; } } } return result; }
Source:
public boolean contains(int num) { final boolean lowerLimitCheckPassed = lowerLimit == null || num >= lowerLimit; final boolean upperLimitCheckPassed = upperLimit == null || num <= upperLimit; return lowerLimitCheckPassed && upperLimitCheckPassed; }

Target:
public boolean contains(int num) { return num >= lowerLimit && num <= upperLimit; }
Source:
protected boolean isClassEnumeration(DetailAST aAST) { return hasMembers(aAST, mExcludes); }

Target:
private boolean isClassEnumeration(DetailAST aAST) { return hasMembers(aAST, mExcludes); }
Source:
public boolean hasPrivilege(UserPrivilege.Keys privilege) { //System.out.println("3 - hasPrivilege() " + privilege + " : " + this.privileges.containsKey(privilege)); if (this.privileges.containsKey(privilege)) { return this.privileges.get(privilege).getValue(); } return false; }

Target:
public synchronized boolean hasPrivilege(UserPrivilege.Keys privilege) { if (this.privileges.containsKey(privilege)) { return this.privileges.get(privilege).getValue(); } return false; }
Source:
public void run() { ISarosSession session = sessionManager.getSession(); JID jid = getSelectedJID(); if (session != null || jid == null) { return; } // TODO: Currently only Saros/S is known to have a working JoinSessionRequestHandler, // remove this once the situation changes / change this to it's own feature. if (!discoveryManager.isFeatureSupported(jid, SarosConstants.NAMESPACE_SERVER)) { return; } transmitter.sendPacketExtension( jid, JoinSessionRequestExtension.PROVIDER.create(new JoinSessionRequestExtension())); }

Target:
public void run() { ISarosSession session = sessionManager.getSession(); JID jid = getSelectedJID(); if (session != null || jid == null) { return; } transmitter.sendPacketExtension( jid, JoinSessionRequestExtension.PROVIDER.create(new JoinSessionRequestExtension())); }
Source:
private List<IRecord> create(BrowserAction action) { List<IRecord> records = new LinkedList<IRecord>(); // since the library fabric.js (used in the html whiteboard) does not // support parent hierarchies this function will always add the new // element to the root element ElementRecord parent = sxe.getDocumentRecord().getRoot(); ElementRecord newElement = parent.createNewElementRecord(null, action.getElementType()); newElement.setRid(action.getID()); records.add(newElement); records.addAll(setAttributes(newElement, action.getAttributes())); return records; }

Target:
private List<IRecord> create(BrowserAction action) { List<IRecord> records = new ArrayList<IRecord>(); // since the library fabric.js (used in the html whiteboard) does not // support parent hierarchies this function will always add the new // element to the root element ElementRecord parent = sxe.getDocumentRecord().getRoot(); ElementRecord newElement = parent.createNewElementRecord(null, action.getElementType()); newElement.setRid(action.getID()); records.add(newElement); records.addAll(setAttributes(newElement, action.getAttributes())); return records; }
Source:
public void testCompareBasic() throws Exception { // Test on all available basic repos to ensure that the output is identical. for (AvailableGitTestRepo testRepo : AvailableGitTestRepo.values()) { if (testRepo == AvailableGitTestRepo.GIT_COMMIT_ID) { continue; } mavenSandbox.withParentProject("my-basic-project", "jar").withNoChildProject().withGitRepoInParent(testRepo).create(); MavenProject targetProject = mavenSandbox.getParentProject(); verifyNativeAndJGit(testRepo, targetProject, DEFAULT_FORMAT_STRING); } }

Target:
public void testCompareBasic() throws Exception { // Test on all available basic repos to ensure that the output is identical. for (AvailableGitTestRepo testRepo : AvailableGitTestRepo.values()) { if (testRepo != AvailableGitTestRepo.GIT_COMMIT_ID) { mavenSandbox.withParentProject("my-basic-project", "jar").withNoChildProject().withGitRepoInParent(testRepo).create(); MavenProject targetProject = mavenSandbox.getParentProject(); verifyNativeAndJGit(testRepo, targetProject, DEFAULT_FORMAT_STRING); } } }
Source:
public void setConfigurable(boolean configurable) { if (configurable) { this.configurable = configurable; } }

Target:
public void setConfigurable(boolean configurable) { this.configurable = configurable; }
Source:
public void setLevel(Level newLevel) throws SecurityException { // We have to propagate our level to an internal data structure in the superclass super.setLevel(newLevel); LogContext.checkAccess(); loggerNode.setLevel(newLevel); }

Target:
public void setLevel(Level newLevel) throws SecurityException { LogContext.checkAccess(); // We have to propagate our level to an internal data structure in the superclass super.setLevel(newLevel); loggerNode.setLevel(newLevel); }
Source:
public static void dropFunctions(final PrintWriter writer, final PgDiffArguments arguments, final PgSchema oldSchema, final PgSchema newSchema, final SearchPathHelper searchPathHelper) { if (oldSchema == null) { return; } // Drop functions that exist no more for (final PgFunction oldFunction : oldSchema.getFunctions()) { if (!newSchema.containsFunction(oldFunction.getSignature())) { searchPathHelper.outputSearchPath(writer); writer.println(); writer.println(oldFunction.getDropSQL(arguments)); } } }

Target:
public static void dropFunctions(final PrintWriter writer, final PgDiffArguments arguments, final PgSchema oldSchema, final PgSchema newSchema, final SearchPathHelper searchPathHelper) { if (oldSchema == null) { return; } // Drop functions that exist no more for (final PgFunction oldFunction : oldSchema.getFunctions()) { if (!newSchema.containsFunction(oldFunction.getSignature())) { searchPathHelper.outputSearchPath(writer); writer.println(); writer.println(oldFunction.getDropSQL()); } } }
Source:
public void testPhoneHomeParameterCreator() { PhoneHomeParameterCreator phoneHomeParameterCreator = new PhoneHomeParameterCreator(); phoneHomeParameterCreator.addParam("1", "hazelcast"); phoneHomeParameterCreator.addParam("2", "phonehome"); Map<String, String> map = phoneHomeParameterCreator.getParameters(); assertEquals("?1=hazelcast&2=phonehome", phoneHomeParameterCreator.build()); assertNotNull(map); assertEquals(ImmutableMap.of("1", "hazelcast", "2", "phonehome"), map); assertNull(map.get("3")); }

Target:
public void testPhoneHomeParameterCreator() { PhoneHomeParameterCreator phoneHomeParameterCreator = new PhoneHomeParameterCreator(); phoneHomeParameterCreator.addParam("1", "hazelcast"); phoneHomeParameterCreator.addParam("2", "phonehome"); Map<String, String> map = phoneHomeParameterCreator.getParameters(); assertEquals("?1=hazelcast&2=phonehome", phoneHomeParameterCreator.build()); assertEquals(ImmutableMap.of("1", "hazelcast", "2", "phonehome"), map); }
Source:
public PhoneHomeParameterCreator createParameters() { PhoneHomeParameterCreator parameterCreator = new PhoneHomeParameterCreator(); MetricsCollector[] metricsCollectorArray = new MetricsCollector[]{new BuildInfoCollector(), new ClusterInfoCollector(), new ClientInfoCollector(), new MapInfoCollector(), new OSInfoCollector()}; List<MetricsCollector> metricsCollectorList = Arrays.asList(metricsCollectorArray); metricsCollectorList.forEach((metricsCollector -> parameterCreator. addMap(metricsCollector.computeMetrics(hazelcastNode)))); return parameterCreator; }

Target:
public PhoneHomeParameterCreator createParameters() { PhoneHomeParameterCreator parameterCreator = new PhoneHomeParameterCreator(); metricsCollectorList.forEach((metricsCollector -> parameterCreator. addMap(metricsCollector.computeMetrics(hazelcastNode)))); return parameterCreator; }
Source:
public boolean schedule() { // If the fragment is already scheduled, we do not need to do anything else, because executor will re-check queue state // before exiting. if (scheduled.get()) { return false; } // Otherwise we schedule the fragment into the worker pool. boolean res = scheduled.compareAndSet(false, true); if (res) { fragmentPool.submit(this); } return res; }

Target:
public boolean schedule() { boolean res = !scheduled.get() && scheduled.compareAndSet(false, true); if (res) { submit(); } return res; }
Source:
public Entry(int coreId, AffinityLock lock) { this.coreId = coreId; this.lock = lock; }

Target:
private Entry(int coreId, AffinityLock lock) { this.coreId = coreId; this.lock = lock; }