auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private ResolutionApiOutput outputFor(String pid, String crid) { if (pid == null && crid == null) { throw new IllegalArgumentException("Must specify pid or crid"); } if (pid != null && crid != null) { throw new IllegalArgumentException("Must not specify both pid and crid"); } if (pid != null) { return outputFor(VERSION_PID_TYPE, pid, YOUVIEW_CRID_TYPE, mappingStore.getValueFor(canonicalUriFor(pid))); } return outputFor(YOUVIEW_CRID_TYPE, crid, VERSION_PID_TYPE, mappingStore.getKeyFor(crid)); }

Target:
private ResolutionApiOutput outputFor(String pid, String crid) { checkArgument(pid == null && crid == null, "Must specify pid or crid"); checkArgument(pid != null && crid != null, "Must not specify both pid and crid"); if (pid != null) { return outputFor(VERSION_PID_TYPE, pid, YOUVIEW_CRID_TYPE, mappingStore.getValueFor(canonicalUriFor(pid))); } return outputFor(YOUVIEW_CRID_TYPE, crid, VERSION_PID_TYPE, mappingStore.getKeyFor(crid)); }
Source:
void emit(JavaWriter writer) throws IOException; } private void emitCodeForUnderConstruction(JavaWriter writer, VariableElement field, boolean isPrimaryKey, CodeEmitter defaultValueCodeEmitter) throws IOException { writer.beginControlFlow("if (proxyState.isUnderConstruction())"); if (isPrimaryKey) { writer.emitSingleLineComment("default value of the primary key is always ignored."); writer.emitStatement("return"); } else { writer.beginControlFlow("if (!proxyState.getAcceptDefaultValue$realm())") .emitStatement("return") .endControlFlow(); if (Utils.isRealmModel(field)) { } else if (Utils.isRealmList(field)) { writer.beginControlFlow("if (proxyState.getExcludeFields$realm().contains(\"%1$s\"))", field.getSimpleName().toString()) .emitStatement("return") .endControlFlow(); final String modelFqcn = Utils.getGenericTypeQualifiedName(field); writer.beginControlFlow("if (value != null && !value.isManaged())") .emitStatement("final Realm realm = (Realm) proxyState.getRealm$realm()") .emitStatement("final RealmList<%1$s> original = value", modelFqcn) .emitStatement("value = new RealmList<%1$s>()", modelFqcn) .beginControlFlow("for (%1$s item : original)", modelFqcn) .beginControlFlow("if (item == null || RealmObject.isManaged(item))") .emitStatement("value.add(item)") .nextControlFlow("else") .emitStatement("value.add(realm.copyToRealm(item))") .endControlFlow() .endControlFlow() .endControlFlow(); } defaultValueCodeEmitter.emit(writer); } writer.endControlFlow() .emitEmptyLine(); }

Target:
void emit(JavaWriter writer) throws IOException; } private void emitCodeForUnderConstruction(JavaWriter writer, boolean isPrimaryKey, CodeEmitter defaultValueCodeEmitter) throws IOException { writer.beginControlFlow("if (proxyState.isUnderConstruction())"); if (isPrimaryKey) { writer.emitSingleLineComment("default value of the primary key is always ignored."); writer.emitStatement("return"); } else { writer.beginControlFlow("if (!proxyState.getAcceptDefaultValue$realm())") .emitStatement("return") .endControlFlow(); defaultValueCodeEmitter.emit(writer); } writer.endControlFlow(); writer.emitEmptyLine(); }
Source:
public boolean addDnsEntry(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { if (_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Dhcp, getProvider())) { return true; } else { return applyDhcpEntries(network, nic, vm, dest, Service.Dns); } }

Target:
public boolean addDnsEntry(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { if (_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Dhcp, getProvider())) { return true; } return applyDhcpEntries(network, nic, vm, dest, Service.Dns); }
Source:
@Override public void init(ServiceContext ctx) { Ignite ignite = Ignition.localIgnite(); reqQueue = ignite.queue(String.format(INFERENCE_REQ_QUEUE_NAME_PATTERN, suffix), QUEUE_CAPACITY, queueCfg); resQueue = ignite.queue(String.format(INFERENCE_RES_QUEUE_NAME_PATTERN, suffix), QUEUE_CAPACITY, queueCfg); mdl = parser.parse(reader.read()); }

Target:
@Override public void init(ServiceContext ctx) { Ignite ignite = Ignition.localIgnite(); reqQueue = ignite.queue(String.format(INFERENCE_REQUEST_QUEUE_NAME_PATTERN, suffix), QUEUE_CAPACITY, queueCfg); resQueue = ignite.queue(String.format(INFERENCE_RESPONSE_QUEUE_NAME_PATTERN, suffix), QUEUE_CAPACITY, queueCfg); mdl = parser.parse(reader.read()); }
Source:
public CallFilteringResult whenDone(CallFilteringResult result) { for (CallFilter filter : mFilter.getPostFilters()) { synchronized (filter.mLock) { int currIndegree = filter.getIndegree(); currIndegree--; filter.setIndegree(currIndegree); if (currIndegree == 0) { mFiltersQueue.offer(filter); } } } mResults.put(mFilter, result); return result; }

Target:
public CallFilteringResult whenDone(CallFilteringResult result) { mFilter.mResult = result; for (CallFilter filter : mFilter.getPostFilters()) { if (filter.decrementAndGetIndegree() == 0) { mFiltersQueue.offer(filter); } } return result; }
Source:
private List<Artifact> getNewDependencies(List<Dependency> dependencies, List<Dependency> existingDependencies) { List<Artifact> updatedArtifacts = new ArrayList<Artifact>(); for (Dependency dep : dependencies) { boolean newDependency = true; for (Dependency existingDep : existingDependencies) { if (dep.getArtifactId().equals(existingDep.getArtifactId())) { newDependency = false; break; } } if (newDependency) { log.debug("New dependency found: " + dep.getArtifactId()); try { Artifact artifact; artifact = getArtifact(dep.getGroupId(), dep.getArtifactId(), dep.getType(), dep.getVersion()); updatedArtifacts.add(artifact); } catch (MojoExecutionException e) { log.info(e.getMessage()); } } } return updatedArtifacts; }

Target:
private List<Artifact> getNewDependencies(List<Dependency> dependencies, List<Dependency> existingDependencies) { List<Artifact> updatedArtifacts = new ArrayList<Artifact>(); for (Dependency dep : dependencies) { boolean newDependency = true; for (Dependency existingDep : existingDependencies) { if (dep.getArtifactId().equals(existingDep.getArtifactId())) { newDependency = false; break; } } if (newDependency) { log.debug("New dependency found: " + dep.getArtifactId()); try { Artifact artifact = getArtifact(dep.getGroupId(), dep.getArtifactId(), dep.getType(), dep.getVersion()); updatedArtifacts.add(artifact); } catch (MojoExecutionException e) { log.warn(e.getMessage()); } } } return updatedArtifacts; }
Source:
private void testSanitization() throws IOException { ______TS("Test sanitization for edit page"); instructorId = testData.accounts.get("instructor1OfTestingSanitizationCourse").googleId; FeedbackSessionAttributes session = testData.feedbackSessions.get("session1InTestingSanitizationCourse"); courseId = session.getCourseId(); feedbackSessionName = session.getFeedbackSessionName(); feedbackEditPage = getFeedbackEditPage(); feedbackEditPage.verifyHtmlMainContent("/instructorFeedbackEditPageTestingSanitization.html"); ______TS("Test sanitization for copy question modal"); feedbackEditPage.clickCopyButton(); feedbackEditPage.waitForCopyTableToLoad(); feedbackEditPage.verifyHtmlPart(By.id("copyModal"), "/instructorFeedbackCopyQuestionModalTestingSanitization.html"); feedbackEditPage = getFeedbackEditPage(); feedbackEditPage.clickDeleteQuestionLink(1); feedbackEditPage.waitForConfirmationModalAndClickOk(); }

Target:
private void testSanitization() throws IOException { ______TS("Test sanitization for edit page"); instructorId = testData.accounts.get("instructor1OfTestingSanitizationCourse").googleId; FeedbackSessionAttributes session = testData.feedbackSessions.get("session1InTestingSanitizationCourse"); courseId = session.getCourseId(); feedbackSessionName = session.getFeedbackSessionName(); feedbackEditPage = getFeedbackEditPage(); feedbackEditPage.verifyHtmlMainContent("/instructorFeedbackEditPageTestingSanitization.html"); ______TS("Test sanitization for copy question modal"); feedbackEditPage.clickCopyButton(); feedbackEditPage.waitForCopyTableToLoad(); feedbackEditPage.verifyHtmlPart(By.id("copyModal"), "/instructorFeedbackCopyQuestionModalTestingSanitization.html"); }
Source:
public FFmpegProbeResult probe(String mediaPath, @Nullable String userAgent) throws IOException { checkIfFFprobe(); ImmutableList.Builder<String> args = new ImmutableList.Builder<String>(); args.add(path).add("-v", "quiet"); if (userAgent != null) { args.add("-user-agent", userAgent); } args.add("-print_format", "json") .add("-show_error") .add("-show_format") .add("-show_streams") .add("-show_chapters") .add(mediaPath); Process p = runFunc.run(args.build()); try { Reader reader = wrapInReader(p); if (LOG.isDebugEnabled()) { reader = new LoggingFilterReader(reader, LOG); } FFmpegProbeResult result = gson.fromJson(reader, FFmpegProbeResult.class); throwOnError(p); if (result == null) { throw new IllegalStateException("Gson returned null, which shouldn't happen :("); } return result; } finally { if (p != null) { p.destroy(); } } }

Target:
public FFmpegProbeResult probe(String mediaPath, @Nullable String userAgent) throws IOException { checkIfFFprobe(); ImmutableList.Builder<String> args = new ImmutableList.Builder<String>(); args.add(path).add("-v", "quiet"); if (userAgent != null) { args.add("-user-agent", userAgent); } args.add("-print_format", "json") .add("-show_error") .add("-show_format") .add("-show_streams") .add("-show_chapters") .add(mediaPath); Process p = runFunc.run(args.build()); try { Reader reader = wrapInReader(p); if (LOG.isDebugEnabled()) { reader = new LoggingFilterReader(reader, LOG); } FFmpegProbeResult result = gson.fromJson(reader, FFmpegProbeResult.class); throwOnError(p); if (result == null) { throw new IllegalStateException("Gson returned null, which shouldn't happen :("); } return result; } finally { p.destroy(); } }
Source:
private ZapMenuItem getMenuItemHtmlReport() { if (menuItemHtmlReport == null) { menuItemHtmlReport = new ZapMenuItem("menu.report.html.generate"); menuItemHtmlReport.addActionListener((java.awt.event.ActionEvent e) -> { ReportLastScan report = new ReportLastScan(); report.generateReport(getView(), getModel(), ReportLastScan.ReportType.HTML); }); } return menuItemHtmlReport; }

Target:
private ZapMenuItem getMenuItemHtmlReport() { if (menuItemHtmlReport == null) { menuItemHtmlReport = new ZapMenuItem("menu.report.html.generate"); menuItemHtmlReport.addActionListener(e -> new ReportLastScan().generateReport(getView(), getModel(), ReportLastScan.ReportType.HTML)); } return menuItemHtmlReport; }
Source:
public String getPathForHadoop(String dataSource) { return String.format("file://%s/%s", config.getStorageDirectory().getAbsoluteFile(), dataSource); }

Target:
public String getPathForHadoop(String dataSource) { return new File(config.getStorageDirectory().getAbsoluteFile(), dataSource).toURI().toString(); }
Source:
public void stopActiveOutPatientVisits() { SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); SimpleDateFormat formatterExt = new SimpleDateFormat("yyyy-MM-dd"); String formattedDate = formatterExt.format(new Date()) + " " + "00:00:00"; AdministrationService administrationService = Context.getAdministrationService(); String visitTypeUUID =administrationService.getGlobalProperty("ugandaemr.autoCloseVisit.visitTypeUUID"); VisitService visitService = Context.getVisitService(); List activeVisitList = null; activeVisitList = administrationService.executeSQL("select visit.visit_id from visit inner join visit_type on (visit.visit_type_id = visit_type.visit_type_id) where visit_type.uuid='"+visitTypeUUID+"' AND visit.date_stopped IS NULL AND visit.date_started < '" + formattedDate + "'", true); for (Object object : activeVisitList) { ArrayList<Integer> integers = (ArrayList) object; Visit visit = visitService.getVisit(integers.get(0)); try{ visitService.endVisit(visit, OpenmrsUtil.getLastMomentOfDay(visit.getStartDatetime())); }catch (Exception e){ log.error("Failed to auto close visit",e); } } }

Target:
public void stopActiveOutPatientVisits() { SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); SimpleDateFormat formatterExt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String currentDate = formatterExt.format(OpenmrsUtil.firstSecondOfDay(new Date())); AdministrationService administrationService = Context.getAdministrationService(); String visitTypeUUID =administrationService.getGlobalProperty("ugandaemr.autoCloseVisit.visitTypeUUID"); VisitService visitService = Context.getVisitService(); List activeVisitList = null; activeVisitList = administrationService.executeSQL("select visit.visit_id from visit inner join visit_type on (visit.visit_type_id = visit_type.visit_type_id) where visit_type.uuid='"+visitTypeUUID+"' AND visit.date_stopped IS NULL AND visit.date_started < '" + currentDate + "'", true); for (Object object : activeVisitList) { ArrayList<Integer> integers = (ArrayList) object; Visit visit = visitService.getVisit(integers.get(0)); try{ visitService.endVisit(visit, OpenmrsUtil.getLastMomentOfDay(visit.getStartDatetime())); }catch (Exception e){ log.error("Failed to auto close visit",e); } } }
Source:
private Node<Object[]> visit(RelNode rel) { return visit(igniteRel(rel)); }

Target:
private Node<Object[]> visit(RelNode rel) { return visit((IgniteRel) rel); }
Source:
public boolean removeMucClient(String id) { synchronized (syncRoot) { MucClient mucClient = mucClients.remove(id); if (mucClient == null) { logger.info("Can not find MucClient to remove."); return false; } mucClient.stop(); return true; } }

Target:
public boolean removeMucClient(String id) { MucClient mucClient = mucClients.remove(id); if (mucClient == null) { logger.info("Can not find MucClient to remove."); return false; } mucClient.stop(); return true; }
Source:
public void testEntityCopyright() { builder.beginDocument(); builder.entityReference("copy"); builder.characters(" AT"); builder.entityReference("amp"); builder.characters("T 2014"); builder.endDocument(); assertMarkup("&copy; AT&T 2014\n\n"); }

Target:
public void testEntityCopyright() { builder.beginDocument(); builder.entityReference("copy"); builder.characters(" XY"); builder.entityReference("amp"); builder.characters("Z 2014"); builder.endDocument(); assertMarkup("&copy; XY&Z 2014\n\n"); }
Source:
private static FlatMapFunction<Tuple2<AssemblyRegion, SimpleInterval>, VariantContext> callVariantsFromAssemblyRegions( final AuthHolder authHolder, final SAMFileHeader header, final Broadcast<ReferenceMultiSource> referenceBroadcast, final Broadcast<HaplotypeCallerArgumentCollection> hcArgsBroadcast) { return regionAndInterval -> { final ReferenceMultiSourceAdaptor referenceReader = new ReferenceMultiSourceAdaptor(referenceBroadcast.getValue(), authHolder); final HaplotypeCallerEngine hcEngine = new HaplotypeCallerEngine(hcArgsBroadcast.value(), header, referenceReader); final List<VariantContext> variantContexts = hcEngine.callRegion(regionAndInterval._1(), new FeatureContext()); final SimpleInterval shardBoundary = regionAndInterval._2(); return variantContexts.stream().filter(shardBoundary::contains).collect(Collectors.toList()); }; }

Target:
private static FlatMapFunction<Iterator<Tuple2<AssemblyRegion, SimpleInterval>>, VariantContext> callVariantsFromAssemblyRegions( final AuthHolder authHolder, final SAMFileHeader header, final Broadcast<ReferenceMultiSource> referenceBroadcast, final Broadcast<HaplotypeCallerArgumentCollection> hcArgsBroadcast) { return regionAndIntervals -> { final ReferenceMultiSourceAdapter referenceReader = new ReferenceMultiSourceAdapter(referenceBroadcast.getValue(), authHolder); final HaplotypeCallerEngine hcEngine = new HaplotypeCallerEngine(hcArgsBroadcast.value(), header, referenceReader); return iteratorToStream(regionAndIntervals).flatMap(regionToVariants(hcEngine)).iterator(); }; }
Source:
public void setToState(EntityRef entity, CharacterStateEvent state) { LocationComponent location = entity.getComponent(LocationComponent.class); CharacterMovementComponent movementComp = entity.getComponent(CharacterMovementComponent.class); if (location == null || Float.isNaN(location.getWorldPosition().x) || movementComp == null) { return; } location.setWorldPosition(state.getPosition()); location.setWorldRotation(state.getRotation()); entity.saveComponent(location); movementComp.mode = state.getMode(); movementComp.setVelocity(state.getVelocity()); movementComp.grounded = state.isGrounded(); movementComp.footstepDelta = state.getFootstepDelta(); entity.saveComponent(movementComp); setPhysicsLocation(entity, JomlUtil.from(state.getPosition())); Quaternionf rotation = new Quaternionf().rotationYXZ(0f, TeraMath.DEG_TO_RAD * state.getPitch(), 0f); EntityRef gazeEntity = GazeAuthoritySystem.getGazeEntityForCharacter(entity); if (!gazeEntity.equals(entity)) { LocationComponent gazeLocation = gazeEntity.getComponent(LocationComponent.class); gazeLocation.setLocalRotation(JomlUtil.from(rotation)); gazeEntity.saveComponent(gazeLocation); } }

Target:
public void setToState(EntityRef entity, CharacterStateEvent state) { LocationComponent location = entity.getComponent(LocationComponent.class); CharacterMovementComponent movementComp = entity.getComponent(CharacterMovementComponent.class); if (location == null || Float.isNaN(location.getWorldPosition().x) || movementComp == null) { return; } location.setWorldPosition(state.getPosition()); location.setWorldRotation(state.getRotation()); entity.saveComponent(location); movementComp.mode = state.getMode(); movementComp.setVelocity(state.getVelocity()); movementComp.grounded = state.isGrounded(); movementComp.footstepDelta = state.getFootstepDelta(); entity.saveComponent(movementComp); setPhysicsLocation(entity, JomlUtil.from(state.getPosition())); Quaternionf rotation = new Quaternionf().rotationX(TeraMath.DEG_TO_RAD * state.getPitch()); EntityRef gazeEntity = GazeAuthoritySystem.getGazeEntityForCharacter(entity); if (!gazeEntity.equals(entity)) { LocationComponent gazeLocation = gazeEntity.getComponent(LocationComponent.class); gazeLocation.setLocalRotation(JomlUtil.from(rotation)); gazeEntity.saveComponent(gazeLocation); } }
Source:
private static String buildH2JdbcUrl(int embeddedDatabasePort) { return "jdbc:h2:tcp://" + InetAddress.getLoopbackAddress().getHostAddress() + ":" + embeddedDatabasePort + "/sonar"; }

Target:
private static String buildH2JdbcUrl(int embeddedDatabasePort) { InetAddress ip = InetAddress.getLoopbackAddress(); String host; if (ip instanceof Inet6Address) { host = "[" + ip.getHostAddress() + "]"; } else { host = ip.getHostAddress(); } return format("jdbc:h2:tcp://%s:%d/sonar", host, embeddedDatabasePort); }
Source:
public String toString() { return this == Element.BLUE_FIRE ? this.getColor() + "Blue Fire": this.getColor() + this.getName(); }

Target:
public String toString() { return (this == Element.BLUE_FIRE) ? this.getColor() + "Blue Fire": this.getColor() + this.getName(); }
Source:
public Response getApplication(final @PathParam("clientId") String clientId) { checkAccountApiEnabled(); auth.requireOneOf(AccountRoles.MANAGE_ACCOUNT, AccountRoles.VIEW_APPLICATIONS); ClientModel client = realm.getClientByClientId(clientId); if (client == null) { return Cors.add(request, Response.status(Response.Status.NOT_FOUND).entity("No client with clientId: " + clientId + " found.")).build(); } List<String> inUseClients = new LinkedList<>(); if(!session.sessions().getUserSessions(realm, client).isEmpty()) { inUseClients.add(clientId); } List<String> offlineClients = new LinkedList<>(); if(session.sessions().getOfflineSessionsCount(realm, client) > 0) { offlineClients.add(clientId); } return Cors.add(request, Response.ok(modelToRepresentation(client, inUseClients, offlineClients))).build(); }

Target:
public Response getApplication(final @PathParam("clientId") String clientId) { checkAccountApiEnabled(); auth.requireOneOf(AccountRoles.MANAGE_ACCOUNT, AccountRoles.VIEW_APPLICATIONS); ClientModel client = realm.getClientByClientId(clientId); if (client == null || client.isBearerOnly() || client.getBaseUrl() == null) { return Cors.add(request, Response.status(Response.Status.NOT_FOUND).entity("No client with clientId: " + clientId + " found.")).build(); } List<String> inUseClients = new LinkedList<>(); if(!session.sessions().getUserSessions(realm, client).isEmpty()) { inUseClients.add(clientId); } List<String> offlineClients = new LinkedList<>(); if(session.sessions().getOfflineSessionsCount(realm, client) > 0) { offlineClients.add(clientId); } UserConsentModel consentModel = session.users().getConsentByClient(realm, user.getId(), client.getId()); Map<String, UserConsentModel> consentModels = Collections.singletonMap(client.getClientId(), consentModel); return Cors.add(request, Response.ok(modelToRepresentation(client, inUseClients, offlineClients, consentModels))).build(); }
Source:
public void addDestroyAction(UUID registrationId, Callable<Boolean> removeAction) { removeListenerActions.put(registrationId, removeAction); if (destroyed) { callRemoveAction(removeAction); removeDestroyAction(registrationId); } }

Target:
public void addDestroyAction(UUID registrationId, Callable<Boolean> removeAction) { removeListenerActions.put(registrationId, removeAction); if (destroyed) { removeAndCallRemoveAction(registrationId); } }
Source:
protected String buildDocumentDescription(String departmentName) { String documentDescriptionBase = configurationService.getPropertyValueAsString(CuFPKeyConstants.AWS_BILLING_SERVICE_DOCUMENT_DESCRIPTION_FORMAT); String documentDescription = MessageFormat.format(documentDescriptionBase, findMonthName(), departmentName); return StringUtils.substring(documentDescription, 0, 40); }

Target:
protected String buildDocumentDescription(String departmentName) { String documentDescriptionBase = configurationService.getPropertyValueAsString(CuFPKeyConstants.AWS_BILLING_SERVICE_DOCUMENT_DESCRIPTION_FORMAT); String documentDescription = MessageFormat.format(documentDescriptionBase, findMonthName(), findProcessYear(), departmentName); int descriptionMaxLength = dataDictionaryService.getAttributeMaxLength(DocumentHeader.class, KFSPropertyConstants.DOCUMENT_DESCRIPTION); return StringUtils.substring(documentDescription, 0, descriptionMaxLength); }
Source:
private boolean isRetryable(@NonNull Throwable t) { return !(t instanceof IllegalArgumentException || t instanceof UnknownHostException || ThrowableUtil.is404(t)); }

Target:
private boolean isRetryable(@NonNull Throwable t) { return !(t instanceof IllegalArgumentException || ThrowableUtil.is404(t)); }
Source:
private Map<Category, Integer> resolveIntoCategoryEntities(List<WeightedTerm> terms) { Set<String> termStrings = terms.stream() .map(WeightedTerm::getTerm) .collect(Collectors.toSet()); Collection<Category> existingCategories = parentService.hibernateTemplate.execute(session -> { Query query = session.createQuery("FROM Category WHERE path IN (:terms)"); query.setParameterList("terms", termStrings); return query.list(); }); Map<String, Category> existingCategoryMap = Maps.uniqueIndex(existingCategories, Category::getPath); Map<Category, Integer> categories = Maps.newLinkedHashMapWithExpectedSize(terms.size()); for (WeightedTerm term : terms) { Category category = existingCategoryMap.get(term.getTerm()); if (category == null) { category = new Category(); category.setPath(term.getTerm()); } categories.put(category, term.getWeight()); } return categories; }

Target:
private Map<Category, Integer> resolveIntoCategoryEntities(List<WeightedTerm> terms) { Set<String> termStrings = terms.stream() .map(WeightedTerm::getPath) .collect(Collectors.toSet()); Collection<Category> existingCategories = parentService.hibernateTemplate.execute(session -> { Query query = session.createQuery("FROM Category WHERE path IN (:terms)"); query.setParameterList("terms", termStrings); return query.list(); }); Map<String, Category> existingCategoryMap = Maps.uniqueIndex(existingCategories, Category::getPath); Map<Category, Integer> categories = Maps.newLinkedHashMapWithExpectedSize(terms.size()); for (WeightedTerm term : terms) { Category category = existingCategoryMap.get(term.getPath()); if (category == null) { category = new Category(); category.setPath(term.getPath()); parentService.hibernateTemplate.save(category); } categories.put(category, term.getWeight()); } return categories; }
Source:
public void fireEvents(TaskType taskType, long delay, Object entity) throws InterruptedException { final String WaitForLaunch = "WaitForLaunch".intern(); final String PoweringUp = "Powering up".intern(); final String Up = "Up".intern(); final String PoweredDown = "Powering down".intern(); final String Down = "Down".intern(); VM vm = (VM) entity; switch (taskType){ case START_VM: vmUpdateStatus(vm, VM.VMStatus.WaitForLaunch, delay, WaitForLaunch); vmUpdateStatus(vm, VM.VMStatus.PoweringUp, delay, PoweringUp); break; case START_VM_AS_UP: vmUpdateStatus(vm, VM.VMStatus.Up, delay, Up); break; case SHUTDOWN_VM: vmUpdateStatus(vm, VM.VMStatus.PoweredDown, delay, PoweredDown); if (vm != null) { vm.getHost().getRunningVMs().remove(vm.getId()); } vmUpdateStatus(vm, VM.VMStatus.Down, 0, Down); break; default: log.error("Unhandled status detected."); break; } }

Target:
public void fireEvents(TaskType taskType, long delay, Object entity) throws InterruptedException { final String WaitForLaunch = "WaitForLaunch"; final String PoweringUp = "Powering up"; final String Up = "Up"; final String PoweredDown = "Powering down"; final String Down = "Down"; VM vm = (VM) entity; switch (taskType){ case START_VM: vmUpdateStatus(vm, VM.VMStatus.WaitForLaunch, delay, WaitForLaunch, service, false); vmUpdateStatus(vm, VM.VMStatus.PoweringUp, delay, PoweringUp, service, false); break; case START_VM_AS_UP: vmUpdateStatus(vm, VM.VMStatus.Up, delay, Up, service, true); break; case SHUTDOWN_VM: vmUpdateStatus(vm, VM.VMStatus.PoweredDown, delay, PoweredDown, service, false); if (vm != null) { vm.getHost().getRunningVMs().remove(vm.getId()); } vmUpdateStatus(vm, VM.VMStatus.Down, 0, Down, service, true); break; default: log.error("Unhandled status detected."); break; } }
Source:
private void appendBoxedListExpressionItem(final ListSeleniumModel list, final String item) { expandDecisionNavigatorDock(); final WebElement node = waitOperation().until(element(LIST, list.getName())); assertThat(node) .as("Decision table of '" + list.getName() + "'was not present in the list of nodes") .isNotNull(); node.click(); final WebElement editor = getEditor(); for (int i = 0; i < list.getItems().size() - 1; i++) { editor.sendKeys(Keys.ARROW_DOWN); } editor.sendKeys(Keys.CONTROL, Keys.SPACE); final WebElement listEntry = waitOperation().until(element(MENU_ENTRY, "Insert below")); assertThat(listEntry) .as("Entry in context menu not available") .isNotNull(); listEntry.click(); editor.sendKeys(Keys.ARROW_DOWN); editor.sendKeys(Keys.ENTER); getAutocompleteEditor().sendKeys(item, Keys.TAB); collapseDecisionNavigatorDock(); }

Target:
private void appendBoxedListExpressionItem(final ListSeleniumModel list, final String item) { expandDecisionNavigatorDock(); final WebElement node = waitOperation().until(element(LIST, list.getName())); assertThat(node) .as("List expression '" + list.getName() + NOT_PRESENT_IN_NAVIGATOR) .isNotNull(); node.click(); final WebElement editor = getEditor(); for (int i = 0; i < list.getItems().size() - 1; i++) { editor.sendKeys(Keys.ARROW_DOWN); } editor.sendKeys(Keys.CONTROL, Keys.SPACE); final WebElement insertBelow = waitOperation().until(element(MENU_ENTRY, "Insert below")); assertThat(insertBelow) .as("Insert below entry in context menu not available") .isNotNull(); insertBelow.click(); editor.sendKeys(Keys.ARROW_DOWN, Keys.ENTER); getAutocompleteEditor().sendKeys(item, Keys.TAB); collapseDecisionNavigatorDock(); }
Source:
public void testVersionRecordManagerIsInitializedOnRename() { Mockito.reset(versionRecordManager); when(versionRecordManager.getCurrentPath()).thenReturn(observablePath); baseEditor.onRename(); verify(versionRecordManager).init(any(), any(), any()); }

Target:
public void testVersionRecordManagerIsInitializedOnRename() { Mockito.reset(versionRecordManager); when(versionRecordManager.getCurrentPath()).thenReturn(observablePath); baseEditor.onRename(); verify(versionRecordManager).init(any(), eq(observablePath), any()); }
Source:
public static Optional<HiveBucketProperty> getBucketProperty(Map<String, Object> tableProperties) { List<String> bucketedBy = getBucketedBy(tableProperties); List<SortingColumn> sortedBy = getSortedBy(tableProperties); int bucketCount = (Integer) tableProperties.get(BUCKET_COUNT_PROPERTY); if ((bucketedBy.isEmpty()) && (bucketCount == 0)) { if (!sortedBy.isEmpty()) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s may be specified only when %s is specified", SORTED_BY_PROPERTY, BUCKETED_BY_PROPERTY)); } return Optional.empty(); } if (bucketCount < 0) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s must be greater than zero", BUCKET_COUNT_PROPERTY)); } if (bucketCount > 32_000) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s should be no more than 32000", BUCKET_COUNT_PROPERTY)); } if (bucketedBy.isEmpty() || bucketCount == 0) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s and %s must be specified together", BUCKETED_BY_PROPERTY, BUCKET_COUNT_PROPERTY)); } return Optional.of(new HiveBucketProperty(bucketedBy, bucketCount, sortedBy)); }

Target:
public static Optional<HiveBucketProperty> getBucketProperty(Map<String, Object> tableProperties) { List<String> bucketedBy = getBucketedBy(tableProperties); List<SortingColumn> sortedBy = getSortedBy(tableProperties); int bucketCount = (Integer) tableProperties.get(BUCKET_COUNT_PROPERTY); if ((bucketedBy.isEmpty()) && (bucketCount == 0)) { if (!sortedBy.isEmpty()) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s may be specified only when %s is specified", SORTED_BY_PROPERTY, BUCKETED_BY_PROPERTY)); } return Optional.empty(); } if (bucketCount < 0) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s must be greater than zero", BUCKET_COUNT_PROPERTY)); } if (bucketCount > 1_000_000) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s should be no more than 1000000", BUCKET_COUNT_PROPERTY)); } if (bucketedBy.isEmpty() || bucketCount == 0) { throw new PrestoException(INVALID_TABLE_PROPERTY, format("%s and %s must be specified together", BUCKETED_BY_PROPERTY, BUCKET_COUNT_PROPERTY)); } return Optional.of(new HiveBucketProperty(bucketedBy, bucketCount, sortedBy)); }
Source:
public void insertRollups(List<SingleRollupWriteContext> writeContexts) throws IOException { if (writeContexts.size() == 0) { return; } Map<ResultSetFuture, SingleRollupWriteContext> futureLocatorMap = new HashMap<ResultSetFuture, SingleRollupWriteContext>(); Timer.Context ctx = Instrumentation.getWriteTimerContext( writeContexts.get( 0 ).getDestinationCF().getName() ); try { for (SingleRollupWriteContext writeContext : writeContexts) { Rollup rollup = writeContext.getRollup(); Locator locator = writeContext.getLocator(); Granularity granularity = writeContext.getGranularity(); int ttl = getTtl(locator, rollup.getRollupType(), granularity); RollupType rollupType = writeContext.getRollup().getRollupType(); DAbstractMetricIO io = rollupTypeToIO.get(rollupType); if ( io == null ) { throw new InvalidDataException( String.format("insertRollups(locator=%s, granularity=%s): unsupported rollupType=%s", locator, granularity, rollupType.name())); } ResultSetFuture future = io.putAsync(locator, writeContext.getTimestamp(), rollup, writeContext.getGranularity(), ttl); futureLocatorMap.put(future, writeContext); } for (ResultSetFuture future : futureLocatorMap.keySet()) { try { future.getUninterruptibly().all(); } catch (Exception ex) { SingleRollupWriteContext writeContext = futureLocatorMap.get(future); LOG.error(String.format("error writing to locator %s, granularity %s", writeContext.getLocator(), writeContext.getGranularity()), ex); } } } finally { ctx.stop(); } }

Target:
public void insertRollups(List<SingleRollupWriteContext> writeContexts) { if (writeContexts.size() == 0) { return; } Map<ResultSetFuture, SingleRollupWriteContext> futureLocatorMap = new HashMap<ResultSetFuture, SingleRollupWriteContext>(); Timer.Context ctx = Instrumentation.getWriteTimerContext( writeContexts.get( 0 ).getDestinationCF().getName() ); try { for (SingleRollupWriteContext writeContext : writeContexts) { Rollup rollup = writeContext.getRollup(); Locator locator = writeContext.getLocator(); Granularity granularity = writeContext.getGranularity(); int ttl = getTtl(locator, rollup.getRollupType(), granularity); RollupType rollupType = writeContext.getRollup().getRollupType(); DAbstractMetricIO io = getIO( rollupType.name().toLowerCase(), granularity ); ResultSetFuture future = io.putAsync(locator, writeContext.getTimestamp(), rollup, writeContext.getGranularity(), ttl); futureLocatorMap.put(future, writeContext); } for (ResultSetFuture future : futureLocatorMap.keySet()) { try { future.getUninterruptibly().all(); } catch (Exception ex) { Instrumentation.markWriteError(); SingleRollupWriteContext writeContext = futureLocatorMap.get(future); LOG.error(String.format("error writing to locator %s, granularity %s", writeContext.getLocator(), writeContext.getGranularity()), ex); } } } finally { ctx.stop(); } }
Source:
public void vdsNotResponding(final VDS vds, final boolean executeSshSoftFencing) { ExecutionHandler.updateSpecificActionJobCompleted(vds.getId(), VdcActionType.MaintenanceVds, false); ThreadPoolUtil.execute(new Runnable() { @Override public void run() { log.infoFormat("ResourceManager::vdsNotResponding entered for Host {0}, {1}", vds.getId(), vds.getHostName()); boolean sshSoftFencingSuccessful = false; if (executeSshSoftFencing) { VdcReturnValueBase retVal = Backend.getInstance().runInternalAction(VdcActionType.SshSoftFencing, new VdsActionParameters(vds.getId()), ExecutionHandler.createInternalJobContext()); sshSoftFencingSuccessful = retVal.getSucceeded(); } if (!sshSoftFencingSuccessful) { Backend.getInstance().runInternalAction(VdcActionType.VdsNotRespondingTreatment, new FenceVdsActionParameters(vds.getId(), FenceActionType.Restart), ExecutionHandler.createInternalJobContext()); } } }); }

Target:
public void vdsNotResponding(final VDS vds, final boolean executeSshSoftFencing) { ExecutionHandler.updateSpecificActionJobCompleted(vds.getId(), VdcActionType.MaintenanceVds, false); ThreadPoolUtil.execute(new Runnable() { @Override public void run() { log.infoFormat("ResourceManager::vdsNotResponding entered for Host {0}, {1}", vds.getId(), vds.getHostName()); boolean shouldExecRealFencing = true; if (executeSshSoftFencing) { VdcReturnValueBase retVal = Backend.getInstance().runInternalAction(VdcActionType.SshSoftFencing, new VdsActionParameters(vds.getId()), ExecutionHandler.createInternalJobContext()); shouldExecRealFencing = !retVal.getSucceeded(); } if (shouldExecRealFencing) { Backend.getInstance().runInternalAction(VdcActionType.VdsNotRespondingTreatment, new FenceVdsActionParameters(vds.getId(), FenceActionType.Restart), ExecutionHandler.createInternalJobContext()); } } }); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMapView = (MapView) findViewById(R.id.mapView); mCutButton = findViewById(R.id.cutButton); ArcGISMap map = new ArcGISMap(Basemap.createTopographic()); mMapView.setMap(map); final GraphicsOverlay graphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(graphicsOverlay); final Graphic polygonGraphic = new Graphic(createLakeSuperiorPolygon(), new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, 0x220000FF, new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFF0000FF, 2))); graphicsOverlay.getGraphics().add(polygonGraphic); final Graphic polylineGraphic = new Graphic(createBorder(), new SimpleLineSymbol(SimpleLineSymbol.Style.DOT, 0xFFFF0000, 3)); graphicsOverlay.getGraphics().add(polylineGraphic); mMapView.setViewpointGeometryAsync(polygonGraphic.getGeometry()); mCutButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { List<Geometry> parts = GeometryEngine .cut(polygonGraphic.getGeometry(), (Polyline) polylineGraphic.getGeometry()); Graphic canadaSide = new Graphic(parts.get(0), new SimpleFillSymbol(SimpleFillSymbol.Style.BACKWARD_DIAGONAL, 0xFF00FF00, new SimpleLineSymbol(SimpleLineSymbol.Style.NULL, 0xFFFFFFFF, 0))); Graphic usSide = new Graphic(parts.get(1), new SimpleFillSymbol(SimpleFillSymbol.Style.FORWARD_DIAGONAL, 0xFFFFFF00, new SimpleLineSymbol(SimpleLineSymbol.Style.NULL, 0xFFFFFFFF, 0))); graphicsOverlay.getGraphics().addAll(Arrays.asList(canadaSide, usSide)); mCutButton.setEnabled(false); } }); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMapView = findViewById(R.id.mapView); Button cutButton = findViewById(R.id.cutButton); ArcGISMap map = new ArcGISMap(Basemap.createTopographic()); mMapView.setMap(map); final GraphicsOverlay graphicsOverlay = new GraphicsOverlay(); mMapView.getGraphicsOverlays().add(graphicsOverlay); final Graphic polygonGraphic = new Graphic(createLakeSuperiorPolygon(), new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID,0x220000FF, new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, 0xFF0000FF, 2))); graphicsOverlay.getGraphics().add(polygonGraphic); final Graphic polylineGraphic = new Graphic(createBorder(), new SimpleLineSymbol(SimpleLineSymbol.Style.DOT, 0xFFFF0000, 3)); graphicsOverlay.getGraphics().add(polylineGraphic); mMapView.setViewpointGeometryAsync(polygonGraphic.getGeometry()); cutButton.setOnClickListener(v -> { List<Geometry> parts = GeometryEngine .cut(polygonGraphic.getGeometry(), (Polyline) polylineGraphic.getGeometry()); Graphic canadaSide = new Graphic(parts.get(0), new SimpleFillSymbol(SimpleFillSymbol.Style.BACKWARD_DIAGONAL, 0xFF00FF00, new SimpleLineSymbol(SimpleLineSymbol.Style.NULL, 0xFFFFFFFF, 0))); Graphic usSide = new Graphic(parts.get(1), new SimpleFillSymbol(SimpleFillSymbol.Style.FORWARD_DIAGONAL, 0xFFFFFF00, new SimpleLineSymbol(SimpleLineSymbol.Style.NULL, 0xFFFFFFFF, 0))); graphicsOverlay.getGraphics().addAll(Arrays.asList(canadaSide, usSide)); cutButton.setEnabled(false); }); }
Source:
public HttpClientConnectionManager httpClientConnectionManager( IClientConfig config, ApacheHttpClientConnectionManagerFactory connectionManagerFactory) { Integer maxTotalConnections = config.getPropertyAsInteger( CommonClientConfigKey.MaxTotalConnections, DefaultClientConfigImpl.DEFAULT_MAX_TOTAL_CONNECTIONS); Integer maxConnectionsPerHost = config.getPropertyAsInteger( CommonClientConfigKey.MaxConnectionsPerHost, DefaultClientConfigImpl.DEFAULT_MAX_CONNECTIONS_PER_HOST); Integer timerRepeat = config.getPropertyAsInteger( CommonClientConfigKey.ConnectionCleanerRepeatInterval, DefaultClientConfigImpl.DEFAULT_CONNECTION_IDLE_TIMERTASK_REPEAT_IN_MSECS); Integer timeToLive = config.get( CommonClientConfigKey.PoolKeepAliveTime, (int)DefaultClientConfigImpl.DEFAULT_POOL_KEEP_ALIVE_TIME); Object ttlUnitObj = config .getProperty(CommonClientConfigKey.PoolKeepAliveTimeUnits); TimeUnit ttlUnit = DefaultClientConfigImpl.DEFAULT_POOL_KEEP_ALIVE_TIME_UNITS; if (ttlUnitObj instanceof TimeUnit) { ttlUnit = (TimeUnit) ttlUnitObj; } final HttpClientConnectionManager connectionManager = connectionManagerFactory .newConnectionManager(false, maxTotalConnections, maxConnectionsPerHost, (long)timeToLive, ttlUnit, registryBuilder); this.connectionManagerTimer.schedule(new TimerTask() { @Override public void run() { connectionManager.closeExpiredConnections(); } }, 30000, timerRepeat); return connectionManager; }

Target:
public HttpClientConnectionManager httpClientConnectionManager( IClientConfig config, ApacheHttpClientConnectionManagerFactory connectionManagerFactory) { Integer maxTotalConnections = config.getPropertyAsInteger( CommonClientConfigKey.MaxTotalConnections, DefaultClientConfigImpl.DEFAULT_MAX_TOTAL_CONNECTIONS); Integer maxConnectionsPerHost = config.getPropertyAsInteger( CommonClientConfigKey.MaxConnectionsPerHost, DefaultClientConfigImpl.DEFAULT_MAX_CONNECTIONS_PER_HOST); Integer timerRepeat = config.getPropertyAsInteger( CommonClientConfigKey.ConnectionCleanerRepeatInterval, DefaultClientConfigImpl.DEFAULT_CONNECTION_IDLE_TIMERTASK_REPEAT_IN_MSECS); Object timeToLiveObj = config .getProperty(CommonClientConfigKey.PoolKeepAliveTime); Long timeToLive = DefaultClientConfigImpl.DEFAULT_POOL_KEEP_ALIVE_TIME; Object ttlUnitObj = config .getProperty(CommonClientConfigKey.PoolKeepAliveTimeUnits); TimeUnit ttlUnit = DefaultClientConfigImpl.DEFAULT_POOL_KEEP_ALIVE_TIME_UNITS; if (timeToLiveObj instanceof Long) { timeToLive = (Long) timeToLiveObj; } else if (timeToLiveObj instanceof String) { timeToLive = Long.valueOf((String)timeToLiveObj); } if (ttlUnitObj instanceof TimeUnit) { ttlUnit = (TimeUnit) ttlUnitObj; } final HttpClientConnectionManager connectionManager = connectionManagerFactory .newConnectionManager(false, maxTotalConnections, maxConnectionsPerHost, timeToLive, ttlUnit, registryBuilder); this.connectionManagerTimer.schedule(new TimerTask() { @Override public void run() { connectionManager.closeExpiredConnections(); } }, 30000, timerRepeat); return connectionManager; }
Source:
public void testPluginLifeCycle(){ CustomWpsService localWpsServer = new CustomWpsService(); CustomCoreWorkspace customCoreWorkspace = new CustomCoreWorkspace(); Assert.assertNotNull("Unable to create the temporary folder for the custom CoreWorkspace.", customCoreWorkspace.getApplicationFolder()); OrbisGISWpsScriptPlugin plugin = new OrbisGISWpsScriptPlugin(); plugin.setLocalWpsService(localWpsServer); plugin.setCoreWorkspace(new CustomCoreWorkspace()); plugin.activate(); List<File> addScriptList = localWpsServer.getAddScriptList(); File folder = new File(this.getClass().getResource("scripts").getFile()); List<File> resourceGroovyScriptList = getAllGroovyScripts(folder); for(File resourceScript : resourceGroovyScriptList){ boolean isResourceScriptAdd = false; for(File addScript : addScriptList){ if(resourceScript.getName().equals(addScript.getName())){ isResourceScriptAdd = true; } } Assert.assertTrue("The resource file '"+resourceScript.getName()+"' should be add by the plugin.", isResourceScriptAdd); } plugin.deactivate(); Assert.assertTrue("All the scripts should have been removed from the server.", localWpsServer.getAddScriptList().isEmpty()); plugin.unsetCoreWorkspace(null); plugin.unsetInternalWpsClient(null); }

Target:
public void testPluginLifeCycle(){ CustomWpsService localWpsServer = new CustomWpsService(); CustomCoreWorkspace customCoreWorkspace = new CustomCoreWorkspace(); Assert.assertNotNull("Unable to create the temporary folder for the custom CoreWorkspace.", customCoreWorkspace.getApplicationFolder()); OrbisGISWpsScriptPlugin plugin = new OrbisGISWpsScriptPlugin(); plugin.setLocalWpsService(localWpsServer); plugin.setCoreWorkspace(new CustomCoreWorkspace()); plugin.activate(); List<File> addScriptList = localWpsServer.getAddScriptList(); File folder = new File(this.getClass().getResource("scripts").getFile()); List<File> resourceGroovyScriptList = getAllGroovyScripts(folder); for(File resourceScript : resourceGroovyScriptList){ boolean isResourceScriptAdd = false; for(File addScript : addScriptList){ if(resourceScript.getName().equals(addScript.getName())){ isResourceScriptAdd = true; } } Assert.assertTrue("The resource file '"+resourceScript.getName()+"' should be add by the plugin.", isResourceScriptAdd); } plugin.deactivate(); Assert.assertTrue("All the scripts should have been removed from the server.", localWpsServer.getAddScriptList().isEmpty()); plugin.unsetCoreWorkspace(null); plugin.unsetLocalWpsService(null); }
Source:
public void close() { if (closeClient && !client.isClosed()) { try { client.close(); } catch (IOException e) { throw new RuntimeException(e); } } closed = true; }

Target:
public void close() { if (closeClient && !client.isClosed()) { try { client.close(); } catch (IOException e) { logger.warn("Unexpected error on client close", e); } } closed = true; }
Source:
public Optional<PassengerData> fill(DataHolder dataHolder, PassengerData manipulator) { if (dataHolder instanceof net.minecraft.entity.Entity) { manipulator.set(Keys.VEHICLE, (Entity) ((net.minecraft.entity.Entity) dataHolder).ridingEntity); net.minecraft.entity.Entity currentEntity = ((net.minecraft.entity.Entity) dataHolder).ridingEntity; while (currentEntity != null && currentEntity.isRiding()) { currentEntity = currentEntity.ridingEntity; } final Entity baseVehicle = (Entity) currentEntity; manipulator.set(Keys.BASE_VEHICLE, baseVehicle); return Optional.of(manipulator); } return Optional.absent(); }

Target:
public Optional<PassengerData> fill(DataHolder dataHolder, PassengerData manipulator) { if (supports(dataHolder)) { manipulator.set(Keys.VEHICLE, (Entity) ((net.minecraft.entity.Entity) dataHolder).ridingEntity); net.minecraft.entity.Entity currentEntity = ((net.minecraft.entity.Entity) dataHolder).ridingEntity; while (currentEntity != null && currentEntity.isRiding()) { currentEntity = currentEntity.ridingEntity; } final Entity baseVehicle = (Entity) currentEntity; manipulator.set(Keys.BASE_VEHICLE, baseVehicle); return Optional.of(manipulator); } return Optional.absent(); }
Source:
private void checkAndAllocateAppUser(String appUser) { if (appUserToLocalUser.containsKey(appUser)) { return; } LOG.info("Allocating local user for appUser " + appUser); int index = -1; for (int i=0; i<localUserCount; ++i) { if (!allocated.get(i)) { index = i; allocated.set(i, true); break; } } if (index == -1) { String errMsg = "Cannot allocate local users from a pool of " + localUserCount; LOG.error(errMsg); throw new RuntimeException(errMsg); } appUserToLocalUser.put(appUser, new LocalUserInfo(localUserPrefix + index, index)); LOG.info("Allocated local user index " + index + " for appUser " + appUser); }

Target:
private boolean checkAndAllocateAppUser(String appUser) { if (appUserToLocalUser.containsKey(appUser)) { return true; } LOG.info("Allocating local user for appUser " + appUser); int index = localUserIndex(appUser); if (index == -1) { for (int i=0; i<localUserCount; ++i) { if (!allocated.get(i)) { index = i; break; } } } if (index == -1) { String errMsg = "Cannot allocate local users from a pool of " + localUserCount; LOG.error(errMsg); return false; } else { allocated.set(index, true); } appUserToLocalUser.put(appUser, new LocalUserInfo(localUserPrefix + index, index)); LOG.info("Allocated local user index " + index + " for appUser " + appUser); return true; }
Source:
public void showRemoveLanguagesDialog() { if (selectedCodes.size() > 0) { if (selectedCodes.size() < wikipediaLanguages.size() - EMPTY_ITEMS_FORM_SECTION_TEXT) { new AlertDialog.Builder(requireActivity()) .setCancelable(false) .setTitle(R.string.wikipedia_languages_remove_dialog_title) .setMessage(R.string.wikipedia_languages_remove_dialog_content) .setPositiveButton(R.string.wikipedia_languages_remove_dialog_ok, (dialog, i) -> { deleteSelectedLanguages(); finishActionMode(); }) .setNegativeButton(R.string.wikipedia_languages_remove_dialog_cancel, null) .show(); } else { new AlertDialog.Builder(requireActivity()) .setCancelable(false) .setTitle(R.string.wikipedia_languages_remove_warning_dialog_title) .setMessage(R.string.wikipedia_languages_remove_warning_dialog_content) .setPositiveButton(R.string.wikipedia_languages_remove_warning_dialog_ok, null) .show(); } } }

Target:
public void showRemoveLanguagesDialog() { if (selectedCodes.size() > 0) { if (selectedCodes.size() < wikipediaLanguages.size()) { new AlertDialog.Builder(requireActivity()) .setTitle(R.string.wikipedia_languages_remove_dialog_title) .setMessage(R.string.wikipedia_languages_remove_dialog_content) .setPositiveButton(android.R.string.ok, (dialog, i) -> { deleteSelectedLanguages(); finishActionMode(); }) .setNegativeButton(android.R.string.cancel, null) .show(); } else { new AlertDialog.Builder(requireActivity()) .setTitle(R.string.wikipedia_languages_remove_warning_dialog_title) .setMessage(R.string.wikipedia_languages_remove_warning_dialog_content) .setPositiveButton(android.R.string.ok, null) .show(); } } }