auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void any_class_should_be_actual_alias_to_isA() { mock.simpleMethod(new ArrayList()); verify(mock).simpleMethod(isA(List.class)); verify(mock).simpleMethod(any(List.class)); mock.simpleMethod((String) null); try { verify(mock).simpleMethod(isA(String.class)); } catch (AssertionError ignored) { try { verify(mock).simpleMethod(any(String.class)); } catch (AssertionError ignored2) { return; } } fail(); }

Target:
public void any_class_should_be_actual_alias_to_isA() { mock.simpleMethod(new ArrayList()); verify(mock).simpleMethod(isA(List.class)); verify(mock).simpleMethod(any(List.class)); mock.simpleMethod((String) null); assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() { verify(mock).simpleMethod(isA(String.class)); } }).isInstanceOf(ArgumentsAreDifferent.class); assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() { verify(mock).simpleMethod(any(String.class)); } }).isInstanceOf(ArgumentsAreDifferent.class); }
Source:
private void adjustQuestionNumbers(int oldQuestionNumber, int newQuestionNumber, List<FeedbackQuestionAttributes> questions) { try { if (oldQuestionNumber > newQuestionNumber && oldQuestionNumber >= 1) { for (int i = oldQuestionNumber - 1; i >= newQuestionNumber; i--) { FeedbackQuestionAttributes question = questions.get(i - 1); question.questionNumber += 1; updateFeedbackQuestionWithoutResponseRateUpdate(question); } } else if (oldQuestionNumber < newQuestionNumber && oldQuestionNumber < questions.size()) { for (int i = oldQuestionNumber + 1; i <= newQuestionNumber; i++) { FeedbackQuestionAttributes question = questions.get(i - 1); question.questionNumber -= 1; updateFeedbackQuestionWithoutResponseRateUpdate(question); } } } catch (InvalidParametersException e) { Assumption.fail("Invalid question."); } catch (EntityDoesNotExistException e) { Assumption.fail("Question disappeared."); } }

Target:
private void adjustQuestionNumbers(int oldQuestionNumber, int newQuestionNumber, List<FeedbackQuestionAttributes> questions) { if (oldQuestionNumber > newQuestionNumber && oldQuestionNumber >= 1) { for (int i = oldQuestionNumber - 1; i >= newQuestionNumber; i--) { FeedbackQuestionAttributes question = questions.get(i - 1); question.questionNumber += 1; updateFeedbackQuestionWithoutResponseRateUpdate(question); } } else if (oldQuestionNumber < newQuestionNumber && oldQuestionNumber < questions.size()) { for (int i = oldQuestionNumber + 1; i <= newQuestionNumber; i++) { FeedbackQuestionAttributes question = questions.get(i - 1); question.questionNumber -= 1; updateFeedbackQuestionWithoutResponseRateUpdate(question); } } }
Source:
public List<Trip> getTripsForDate (String stop_id, LocalDate date) { List<String> tripIds = stats.getTripsForDate(date).stream() .map(trip -> trip.trip_id) .collect(Collectors.toList()); return feed.getStopTimesForStop(stop_id).stream() .map(t -> feed.trips.get(t.b.a)) .filter(t -> tripIds.contains(t.trip_id)) .collect(Collectors.toList()); }

Target:
public List<Trip> getTripsForDate (String stop_id, LocalDate date) { List<String> tripIds = stats.getTripsForDate(date).stream() .map(trip -> trip.trip_id) .collect(Collectors.toList()); return feed.getDistinctTripsForStop(stop_id).stream() .filter(t -> tripIds.contains(t.trip_id)) .collect(Collectors.toList()); }
Source:
public void run() { boolean performAction = MessageDialog.openConfirm(form.getShell(), UIText.DiscardChangesAction_confirmActionTitle, UIText.DiscardChangesAction_confirmActionMessage); if (!performAction) return ; String[] files = getSelectedFiles(selection); replaceWith(files, headRevision); Repository repository = currentRepository; if (repository != null) { IndexDiffCacheEntry indexDiffCacheForRepository = org.eclipse.egit.core.Activator .getDefault().getIndexDiffCache() .getIndexDiffCacheEntry(repository); if (indexDiffCacheForRepository != null) { indexDiffCacheForRepository .refreshFiles(Arrays.asList(files)); } } }

Target:
public void run() { boolean performAction = MessageDialog.openConfirm(form.getShell(), UIText.DiscardChangesAction_confirmActionTitle, UIText.DiscardChangesAction_confirmActionMessage); if (!performAction) { return; } List<String> files = new ArrayList<>(); List<String> inaccessibleFiles = new ArrayList<>(); getSelectedFiles(files, inaccessibleFiles); replaceWith(files, inaccessibleFiles); }
Source:
public Description getDescription() { Description description = Description.createSuiteDescription( getTestClass().getJavaClass(), getName(), getRunnerAnnotations() ); for (T child : getFilteredChildren()) { description.addChild(describeChild(child)); } return description; }

Target:
public Description getDescription() { Class<?> clazz = getTestClass().getJavaClass(); Description description; if (clazz == null || !clazz.getName().equals(getName())) { description = Description.createSuiteDescription(getName(), getRunnerAnnotations()); } else { description = Description.createSuiteDescription(clazz, getRunnerAnnotations()); } for (T child : getFilteredChildren()) { description.addChild(describeChild(child)); } return description; }
Source:
public BasicNettyOrigin(String name, String vip, Registry registry) { this.name = name; this.vip = vip; this.registry = registry; this.config = setupClientConfig(name); this.clientChannelManager = new DefaultClientChannelManager(name, vip, config, registry); this.clientChannelManager.init(); this.requestAttemptFactory = new NettyRequestAttemptFactory(); this.concurrentRequests = new AtomicInteger(0); this.concurrencyMax = new CachedDynamicIntProperty("zuul.origin." + name + ".concurrency.max.requests", 200); this.concurrencyProtectionEnabled = new CachedDynamicBooleanProperty("zuul.origin." + name + ".concurrency.protect.enabled", true); }

Target:
public BasicNettyOrigin(String name, String vip, Registry registry) { this.name = name; this.vip = vip; this.registry = registry; this.config = setupClientConfig(name); this.clientChannelManager = new DefaultClientChannelManager(name, vip, config, registry); this.clientChannelManager.init(); this.requestAttemptFactory = new NettyRequestAttemptFactory(); this.concurrentRequests = SpectatorUtils.newGauge("zuul.origin.concurrent.requests", name, new AtomicInteger(0)); this.rejectedRequests = SpectatorUtils.newCounter("zuul.origin.rejected.requests", name); this.concurrencyMax = new CachedDynamicIntProperty("zuul.origin." + name + ".concurrency.max.requests", 200); this.concurrencyProtectionEnabled = new CachedDynamicBooleanProperty("zuul.origin." + name + ".concurrency.protect.enabled", true); }
Source:
public void loadModule(String name) throws IOException, ScriptException { Resource resource = null; if ("underscore".equals(name)) { resource = this.assetSource.getClasspathAsset("/META-INF/assets/tapestry5/underscore-1.8.3.js").getResource(); } else { resource = this.moduleManager.findResourceForModule(name); } if (resource == null) { throw new RuntimeException("Could not load module / resource not found for module: " + name); } StreamableResource streamableResource = this.srs.getStreamableResource(resource, StreamableResourceProcessing.COMPRESSION_DISABLED, this.tracker); try (InputStream is = streamableResource.openStream()) { log.debug("Evaluating in nashorn javascript engine", resource.getFile()); this.engine.eval(IOUtils.toString(is), this.bindings); log.debug("Finished evaluating in nashorn javascript engine", resource.getFile()); } }

Target:
public void loadModule(String name) throws IOException, ScriptException { Resource resource = this.moduleManager.findResourceForModule(name); if (resource == null) { throw new RuntimeException("Could not load module / resource not found for module: " + name); } StreamableResource streamableResource = this.srs.getStreamableResource(resource, StreamableResourceProcessing.COMPRESSION_DISABLED, this.tracker); try (InputStream is = streamableResource.openStream()) { log.debug("Evaluating in nashorn javascript engine", resource.getFile()); this.engine.eval(IOUtils.toString(is, Charset.forName("UTF-8"))); log.debug("Finished evaluating in nashorn javascript engine", resource.getFile()); } }
Source:
public void execution2() throws Exception { withProduct(client(), product -> { final String slug = product.getMasterData().getStaged().getSlug().get(Locale.ENGLISH); final ProductProjectionQuery normalSphereRequest = ProductProjectionQuery.ofStaged() .withPredicates(m -> m.slug().locale(Locale.ENGLISH).is(slug)) .plusExpansionPaths(m -> m.productType()); final JsonNodeSphereRequest jsonNodeSphereRequest = JsonNodeSphereRequest.of(normalSphereRequest); assertThat(normalSphereRequest.httpRequestIntent()) .as("a JsonNodeSphereRequest creates the same request to the platform, but differes in the response") .isEqualTo(jsonNodeSphereRequest.httpRequestIntent()); final PagedQueryResult<ProductProjection> productProjectionPagedSearchResult = client().executeBlocking(normalSphereRequest); final JsonNode jsonNode = client().executeBlocking(jsonNodeSphereRequest); assertThat(jsonNode.get("results").get(0).get("productType").get("obj").get("description").asText()) .as("the expansion paths are honored") .isEqualTo("a 'T' shaped cloth"); }); }

Target:
public void execution2() throws Exception { withProduct(client(), product -> { final String slug = product.getMasterData().getStaged().getSlug().get(Locale.ENGLISH); final ProductProjectionQuery normalSphereRequest = ProductProjectionQuery.ofStaged() .withPredicates(m -> m.slug().locale(Locale.ENGLISH).is(slug)) .plusExpansionPaths(m -> m.productType()); final JsonNodeSphereRequest jsonNodeSphereRequest = JsonNodeSphereRequest.of(normalSphereRequest); assertThat(normalSphereRequest.httpRequestIntent()) .as("a JsonNodeSphereRequest creates the same request to the platform, but differs in the response") .isEqualTo(jsonNodeSphereRequest.httpRequestIntent()); final PagedQueryResult<ProductProjection> productProjectionPagedSearchResult = client().executeBlocking(normalSphereRequest); final JsonNode jsonNode = client().executeBlocking(jsonNodeSphereRequest); assertThat(jsonNode.get("results").get(0).get("productType").get("obj").get("description").asText()) .as("the expansion paths are honored") .isEqualTo("a 'T' shaped cloth"); }); }
Source:
public static Map<String, String> headersToMap(Map<String, List<String>> headers) { List<String>a = new ArrayList<String>(); Map<String, String> map = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); for (String name : headers.keySet()) { map.put(name, join(headers.get(name), ", ")); } return map; }

Target:
public static Map<String, String> headersToMap(Map<String, List<String>> headers) { Map<String, String> map = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); for (String name : headers.keySet()) { map.put(name, join(headers.get(name), ", ")); } return map; }
Source:
public void createControl(Composite parent) { final Composite composite = getCompositeProvider().createUI(parent); if (getCompositeProvider().getViewer() instanceof TreeViewer) { final TreeViewer tv = (TreeViewer) getCompositeProvider().getViewer(); tv.expandToLevel(2); } getCompositeProvider().getViewer().addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { updatePageStatus(); } }); getCompositeProvider().getViewer().addDoubleClickListener(new IDoubleClickListener() { @Override public void doubleClick(DoubleClickEvent event) { if (isPageComplete() && performFinish()) { ((WizardDialog) getContainer()).close(); } } }); setPageComplete(false); updatePageStatus(); setControl(composite); }

Target:
public void createControl(Composite parent) { final Composite composite = getCompositeProvider().createUI(parent); if (getCompositeProvider().getViewer() instanceof TreeViewer) { final TreeViewer tv = (TreeViewer) getCompositeProvider().getViewer(); tv.expandToLevel(2); } getCompositeProvider().getViewer().addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { updatePageStatus(); } }); getCompositeProvider().getViewer().addDoubleClickListener(new IDoubleClickListener() { @Override public void doubleClick(DoubleClickEvent event) { if (isPageComplete() && performFinish()) { ((WizardDialog) getContainer()).close(); } } }); updatePageStatus(); setControl(composite); }
Source:
public <F> void testEmptyTemporaryFileSuffixCannotBeNull() throws Exception { SessionFactory<F> sf = mock(SessionFactory.class); Session<F> session = mock(Session.class); when(sf.getSession()).thenReturn(session); ExpressionParser parser = new SpelExpressionParser(); FileTransferringMessageHandler<F> handler = new FileTransferringMessageHandler<F>(sf); handler.setBeanFactory(mock(BeanFactory.class)); handler.setRemoteDirectoryExpressionString("headers['path']"); handler.setTemporaryFileSuffix(null); handler.onInit(); }

Target:
public <F> void testEmptyTemporaryFileSuffixCannotBeNull() throws Exception { SessionFactory<F> sf = mock(SessionFactory.class); Session<F> session = mock(Session.class); when(sf.getSession()).thenReturn(session); FileTransferringMessageHandler<F> handler = new FileTransferringMessageHandler<F>(sf); handler.setBeanFactory(mock(BeanFactory.class)); handler.setRemoteDirectoryExpressionString("headers['path']"); handler.setTemporaryFileSuffix(null); handler.onInit(); }
Source:
public JobId submit(File workflowFile, Map<String, String> variables) throws NotConnectedRestException, PermissionRestException, SubmissionClosedRestException, JobCreationRestException { try { Job job = createJobObject(workflowFile, variables); JobId jobId = scheduler.submit(job); File visualizationFile = new File(PortalConfiguration.jobIdToPath(jobId.value()) + ".html"); Files.deleteIfExists(visualizationFile.toPath()); FileUtils.write(new File(visualizationFile.getAbsolutePath()), job.getVisualization(), StandardCharsets.UTF_8); return jobId; } catch (NotConnectedException e) { throw new NotConnectedRestException(e); } catch (PermissionException e) { throw new PermissionRestException(e); } catch (SubmissionClosedException e) { throw new SubmissionClosedRestException(e); } catch (JobCreationException e) { throw new JobCreationRestException(e); } catch (Exception e) { logger.warn("Unexpected error when submitting job", e); throw new JobCreationRestException(e); } }

Target:
public JobId submit(File workflowFile, Map<String, String> variables) throws NotConnectedRestException, PermissionRestException, SubmissionClosedRestException, JobCreationRestException { try { Job job = createJobObject(workflowFile, variables); JobId jobId = scheduler.submit(job); String visualization = job.getVisualization(); if (visualization != null && !visualization.isEmpty()) { File visualizationFile = new File(PortalConfiguration.jobIdToPath(jobId.value()) + ".html"); Files.deleteIfExists(visualizationFile.toPath()); FileUtils.write(new File(visualizationFile.getAbsolutePath()), job.getVisualization(), Charset.forName(FILE_ENCODING)); } return jobId; } catch (NotConnectedException e) { throw new NotConnectedRestException(e); } catch (PermissionException e) { throw new PermissionRestException(e); } catch (SubmissionClosedException e) { throw new SubmissionClosedRestException(e); } catch (JobCreationException e) { throw new JobCreationRestException(e); } catch (Exception e) { logger.warn("Unexpected error when submitting job", e); throw new JobCreationRestException(e); } }
Source:
public void visitNode(Tree tree) { Symbol.TypeSymbol symbol = ((ClassTree) tree).symbol(); if (symbol.owner().isTypeSymbol() && symbol.isStatic()) { addIssue(tree, "Remove this redundant \"static\" qualifier."); } }

Target:
public void visitNode(Tree tree) { if (isStatic((ClassTree) tree)) { addIssue(tree, "Remove this redundant \"static\" qualifier."); } }
Source:
public ClusterFeatures list() { ClusterFeatures features = new ClusterFeatures(); Set<SupportedAdditionalClusterFeature> addlFeatures = getOptionalEntity(Set.class, QueryType.GetClusterFeaturesByClusterId, new IdQueryParameters(asGuid(clusterId)), clusterId, false); if (addlFeatures != null) { for (SupportedAdditionalClusterFeature entity : addlFeatures) { if (entity.isEnabled()) { features.getClusterFeatures().add(addLinks(ClusterFeaturesMapper.map(entity.getFeature(), null))); } } } return features; }

Target:
public ClusterFeatures list() { ClusterFeatures features = new ClusterFeatures(); Set<SupportedAdditionalClusterFeature> addlFeatures = getOptionalEntity(Set.class, QueryType.GetClusterFeaturesByClusterId, new IdQueryParameters(asGuid(clusterId)), clusterId, false); if (addlFeatures != null) { for (SupportedAdditionalClusterFeature entity : addlFeatures) { if (entity.isEnabled()) { features.getClusterFeatures().add(addLinks(map(entity.getFeature(), null))); } } } return features; }
Source:
protected void validateCredentials(final UsernamePasswordCredentials credentials, final OAuthRegisteredService registeredService, final WebContext context) { val token = credentials.getPassword(); LOGGER.trace("Received refresh token for authentication", token); val refreshToken = getTicketRegistry().getTicket(token, OAuth20RefreshToken.class); if (refreshToken == null || refreshToken.isExpired() || !StringUtils.equals(refreshToken.getClientId(), credentials.getUsername())) { LOGGER.error("Provided refresh token is either not found in the ticket registry or has expired or not related with the client provided"); throw new CredentialsException("Invalid token: " + token); } }

Target:
protected void validateCredentials(final UsernamePasswordCredentials credentials, final OAuthRegisteredService registeredService, final WebContext context) { val token = credentials.getPassword(); LOGGER.trace("Received refresh token for authentication", token); val refreshToken = getTicketRegistry().getTicket(token, OAuth20RefreshToken.class); val clientId = credentials.getUsername(); if (refreshToken == null || refreshToken.isExpired() || !StringUtils.equals(refreshToken.getClientId(), clientId)) { LOGGER.error("Provided refresh token is either not found in the ticket registry, has expired or is not related to the client [{}]", token, clientId); throw new CredentialsException("Invalid token: " + token); } }
Source:
private void persistBloomFilter() throws StoreException { try { CrcOutputStream crcStream = new CrcOutputStream(new FileOutputStream(bloomFile)); DataOutputStream stream = new DataOutputStream(crcStream); FilterFactory.serialize(bloomFilter, stream); long crcValue = crcStream.getValue(); stream.writeLong(crcValue); stream.close(); } catch (IOException e) { if (e.getClass() == IOException.class && e.getMessage().equals(StoreException.IO_ERROR_STR)) { throw new StoreException("IO error while trying to persist bloom filter", e, StoreErrorCodes.IOError); } else { throw new StoreException("Unknown error while trying to persist bloom filter", e, StoreErrorCodes.Unknown_Error); } } }

Target:
private void persistBloomFilter() throws StoreException { try { CrcOutputStream crcStream = new CrcOutputStream(new FileOutputStream(bloomFile)); DataOutputStream stream = new DataOutputStream(crcStream); FilterFactory.serialize(bloomFilter, stream); long crcValue = crcStream.getValue(); stream.writeLong(crcValue); stream.close(); } catch (IOException e) { StoreErrorCodes errorCode = e.getMessage().equals(StoreException.IO_ERROR_STR) ? StoreErrorCodes.IOError : StoreErrorCodes.Unknown_Error; throw new StoreException(errorCode.toString() + " while trying to persist bloom filter", e, errorCode); } }
Source:
Exception onConferenceCallStarted(Call jvbConferenceCall) { this.jvbCall = jvbConferenceCall; this.chatRoom = super.jvbConference.getJvbRoom(); if(!service.isConfiguredProperly()) { logger.warn("TranscriptionService is not properly set"); sendMessageToRoom("Transcriber is not properly configured. " + "Contact the host and let him now! I will now leave"); jvbConference.stop(); } jvbConferenceCall.setConference(new MediaAwareCallConference() { @Override public MediaDevice getDefaultDevice(MediaType mediaType, MediaUseCase useCase) { if(MediaType.AUDIO.equals(mediaType)) { return transcriber.getMediaDevice(); } return super.getDefaultDevice(mediaType, useCase); } }); addInitialMembers(); transcriber.start(); sendMessageToRoom("Started transcription!"); logger.debug("TranscriptionGatewaySession started transcribing"); return null; }

Target:
Exception onConferenceCallStarted(Call jvbConferenceCall) { this.jvbCall = jvbConferenceCall; this.chatRoom = super.jvbConference.getJvbRoom(); if(!service.isConfiguredProperly()) { logger.warn("TranscriptionService is not properly configured"); sendMessageToRoom("Transcriber is not properly " + "configured. Contact the service administrators and let them " + "know! I will now leave."); jvbConference.stop(); return null; } jvbConferenceCall.setConference(new MediaAwareCallConference() { @Override public MediaDevice getDefaultDevice(MediaType mediaType, MediaUseCase useCase) { if(MediaType.AUDIO.equals(mediaType)) { return transcriber.getMediaDevice(); } return super.getDefaultDevice(mediaType, useCase); } }); addInitialMembers(); transcriber.start(); sendMessageToRoom("Started transcription!"); logger.debug("TranscriptionGatewaySession started transcribing"); return null; }
Source:
private boolean saveVendorMaintenanceDocument(MaintenanceDocument vendorMaintenceDoc, PaymentWorksNewVendorRequestsBatchReportData reportData, PaymentWorksVendor pmwVendor) { GlobalVariables.getMessageMap().clearErrorMessages(); LOG.info("saveVendorMaintenanceDocument: vendorMaintenceDoc validate save business rules."); boolean documentSaved = false; try { getDocumentService().saveDocument(vendorMaintenceDoc); LOG.info("saveVendorMaintenanceDocument: vendorMaintenceDoc saved."); documentSaved = true; } catch (WorkflowException we) { List<String> edocCreateErrors = getPaymentWorksBatchUtilityService().convertReportDataValidationErrors(GlobalVariables.getMessageMap().getErrorMessages()); captureKfsProcessingErrorsForVendor(pmwVendor, reportData, edocCreateErrors); LOG.error("saveVendorMaintenanceDocument: eDoc saving error(s): " + edocCreateErrors.toString()); LOG.error("saveVendorMaintenanceDocument: eDoc saving exception caught: " + we.getMessage()); } finally { GlobalVariables.getMessageMap().clearErrorMessages(); } return documentSaved; }

Target:
private boolean saveVendorMaintenanceDocument(MaintenanceDocument vendorMaintenceDoc, PaymentWorksNewVendorRequestsBatchReportData reportData, PaymentWorksVendor pmwVendor) { return kfsVendorMaintenceDocumentActionProcessed(vendorMaintenceDoc, reportData, pmwVendor, DocumentAction.SAVE); }
Source:
public MqttClient getMqttSinkClient(final String brokerURI) throws MqttException, IOException { this.publisherLock.lock(); final List<MqttClient> mqttClientList = mqttPublisherMap.get(brokerURI); if (mqttClientList == null) { mqttPublisherMap.putIfAbsent(brokerURI, new ArrayList<>()); final MqttClient client = new MqttClient(brokerURI, MQTT_PUBLISHER_ID_PREFIX + brokerURI + "_0"); final MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setMaxInflight(maxInflightMqttEventNum); client.connect(connectOptions); mqttPublisherMap.get(brokerURI).add(client); publisherSinkNumMap.put(client, 1); this.publisherLock.unlock(); return client; } else { final MqttClient clientCandidate = mqttClientList.get(mqttClientList.size() - 1); final int sinkNum = publisherSinkNumMap.get(clientCandidate); if (sinkNum < maxMqttSinkNumPerClient) { publisherSinkNumMap.replace(clientCandidate, sinkNum + 1); this.publisherLock.unlock(); return clientCandidate; } else { final MqttClient newClientCandidate = new MqttClient(brokerURI, MQTTSharedResource.MQTT_PUBLISHER_ID_PREFIX + brokerURI + "_" + mqttClientList.size()); final MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setMaxInflight(maxInflightMqttEventNum); newClientCandidate.connect(connectOptions); mqttClientList.add(newClientCandidate); publisherSinkNumMap.put(newClientCandidate, 1); this.publisherLock.unlock(); return newClientCandidate; } } }

Target:
public MqttClient getMqttSinkClient(final String brokerURI) throws MqttException, IOException { this.publisherLock.lock(); final List<MqttClient> mqttClientList = mqttPublisherMap.get(brokerURI); if (mqttClientList == null) { mqttPublisherMap.put(brokerURI, new ArrayList<>()); final MqttClient client = createSinkClient(brokerURI, mqttPublisherMap.get(brokerURI)); this.publisherLock.unlock(); return client; } else { final MqttClient clientCandidate = mqttClientList.get(mqttClientList.size() - 1); final int sinkNum = publisherSinkNumMap.get(clientCandidate); if (sinkNum < maxMqttSinkNumPerClient) { publisherSinkNumMap.replace(clientCandidate, sinkNum + 1); this.publisherLock.unlock(); return clientCandidate; } else { final MqttClient newClientCandidate = createSinkClient(brokerURI, mqttClientList); this.publisherLock.unlock(); return newClientCandidate; } } }
Source:
Map<String, String> parseGroupingKey(final String groupingKeyConfig) { if (!groupingKeyConfig.isEmpty()) { Map<String, String> groupingKey = new HashMap<>(); String[] kvs = groupingKeyConfig.split(";"); for (String kv : kvs) { int idx = kv.indexOf("="); if (idx < 0) { LOG.warn("Invalid prometheusPushGateway groupingKey:" + kv + ", will be ignored"); continue; } String labelKey = kv.substring(0, idx); String labelValue = kv.substring(idx + 1); if (StringUtils.isEmpty(labelKey) || StringUtils.isEmpty(labelValue)) { LOG.warn("Invalid groupingKey labelKey:" + labelKey + ", labelValue:" + labelValue + " must not be empty"); continue; } groupingKey.put(labelKey, labelValue); } return groupingKey; } return Collections.emptyMap(); }

Target:
Map<String, String> parseGroupingKey(final String groupingKeyConfig) { if (!groupingKeyConfig.isEmpty()) { Map<String, String> groupingKey = new HashMap<>(); String[] kvs = groupingKeyConfig.split(";"); for (String kv : kvs) { int idx = kv.indexOf("="); if (idx < 0) { LOG.warn("Invalid prometheusPushGateway groupingKey:{}, will be ignored", kv); continue; } String labelKey = kv.substring(0, idx); String labelValue = kv.substring(idx + 1); if (StringUtils.isEmpty(labelKey) || StringUtils.isEmpty(labelValue)) { LOG.warn("Invalid groupingKey labelKey:{}, labelValue:{} must not be empty", labelKey, labelValue); continue; } groupingKey.put(labelKey, labelValue); } return groupingKey; } return Collections.emptyMap(); }
Source:
private void writeData(PartitionIterable partitions) throws SemanticException { try { if (tableSpec.tableHandle.isPartitioned()) { if (partitions == null) { throw new IllegalStateException("partitions cannot be null for partitionTable :" + tableSpec.getTableName().getTable()); } new PartitionExport(paths, partitions, distCpDoAsUser, conf, mmCtx).write(replicationSpec); } else { List<Path> dataPathList = Utils.getDataPathList(tableSpec.tableHandle.getDataLocation(), replicationSpec, conf); if (!replicationSpec.isLazy()) { new FileOperations(dataPathList, paths.dataExportDir(), distCpDoAsUser, conf, mmCtx).export(); } } } catch (Exception e) { throw new SemanticException(e.getMessage(), e); } }

Target:
private void writeData(PartitionIterable partitions) throws SemanticException { try { if (tableSpec.tableHandle.isPartitioned()) { if (partitions == null) { throw new IllegalStateException("partitions cannot be null for partitionTable :" + tableSpec.getTableName().getTable()); } new PartitionExport(paths, partitions, distCpDoAsUser, conf, mmCtx).write(replicationSpec); } else { List<Path> dataPathList = Utils.getDataPathList(tableSpec.tableHandle.getDataLocation(), replicationSpec, conf); new FileOperations(dataPathList, paths.dataExportDir(), distCpDoAsUser, conf, mmCtx) .export(replicationSpec); } } catch (Exception e) { throw new SemanticException(e.getMessage(), e); } }
Source:
public void testTextWrapBoundariesUpdatesOnSetSize() { tested.setSize(10, 10); verify(textDecorator).setTextBoundaries(any()); }

Target:
public void testTextWrapBoundariesUpdatesOnSetSize() { tested.setSize(10, 10); verify(textDecorator).setTextBoundaries(PATH.getBoundingBox()); }
Source:
private SampleIdentity createParentIdentity(DetailedSample sample) throws IOException, MisoNamingException, SQLException { log.debug("Creating a new Identity to use as a parent."); List<SampleClass> identityClasses = sampleClassService.listByCategory(SampleIdentity.CATEGORY_NAME); if (identityClasses.size() != 1) { throw new IllegalStateException("Found more or less than one SampleClass of category " + SampleIdentity.CATEGORY_NAME + ". Cannot choose which to use as root sample class."); } SampleClass rootSampleClass = identityClasses.get(0); String internalName = sample.getProject().getShortName() + "_"; String number = sampleNumberPerProjectService.nextNumber(sample.getProject(), internalName); internalName += number; if (sample.getProject().getShortName() == null) { throw new NullPointerException("Project shortname required to generate Identity alias"); } SampleIdentity shellParent = (SampleIdentity) sample.getParent(); confirmExternalNameUniqueForProjectIfRequired(shellParent.getExternalName(), sample); Sample identitySample = new IdentityBuilder().project(sample.getProject()) .sampleType(sample.getSampleType()).scientificName(sample.getScientificName()).name(generateTemporaryName()) .alias(internalName).rootSampleClass(rootSampleClass).volume(0D).externalName(shellParent.getExternalName()) .donorSex(shellParent.getDonorSex()).build(); setChangeDetails(identitySample); return (SampleIdentity) save(identitySample, true); }

Target:
private SampleIdentity createParentIdentity(DetailedSample sample) throws IOException, MisoNamingException, SQLException { log.debug("Creating a new Identity to use as a parent."); List<SampleClass> identityClasses = sampleClassService.listByCategory(SampleIdentity.CATEGORY_NAME); if (identityClasses.size() != 1) { throw new IllegalStateException("Found more or less than one SampleClass of category " + SampleIdentity.CATEGORY_NAME + ". Cannot choose which to use as root sample class."); } SampleClass rootSampleClass = identityClasses.get(0); if (sample.getProject().getShortName() == null) { throw new NullPointerException("Project shortname required to generate Identity alias"); } String internalName = sample.getProject().getShortName() + "_"; String number = sampleNumberPerProjectService.nextNumber(sample.getProject(), internalName); internalName += number; SampleIdentity shellParent = (SampleIdentity) sample.getParent(); confirmExternalNameUniqueForProjectIfRequired(shellParent.getExternalName(), sample); Sample identitySample = new IdentityBuilder().project(sample.getProject()) .sampleType(sample.getSampleType()).scientificName(sample.getScientificName()).name(generateTemporaryName()) .alias(internalName).rootSampleClass(rootSampleClass).volume(0D).externalName(shellParent.getExternalName()) .donorSex(shellParent.getDonorSex()).build(); setChangeDetails(identitySample); return (SampleIdentity) save(identitySample, true); }
Source:
protected void commonInitialize() { super.commonInitialize(); getModel().getIsStateless().getEntityChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { if (getModel().getTemplateWithVersion() == null || getModel().getTemplateWithVersion().getItems() == null || getModel().getTemplateWithVersion().getSelectedItem() == null) { return; } List<VmTemplate> baseTemplates = new ArrayList<>(); for (TemplateWithVersion templateWithVersion : getModel().getTemplateWithVersion().getItems()) { if (templateWithVersion.isLatest()) { continue; } baseTemplates.add(templateWithVersion.getBaseTemplate()); } TemplateWithVersion selectedItemTemplateWithVersion = getModel().getTemplateWithVersion().getSelectedItem(); VmTemplate selectedTemplateWithVersion = selectedItemTemplateWithVersion.getTemplateVersion(); if (selectedTemplateWithVersion == null) { return; } Guid selectedId = selectedTemplateWithVersion.getId(); updateStatelessFlag = false; initTemplateWithVersion(baseTemplates, selectedId, selectedItemTemplateWithVersion.isLatest(), getModel().getIsStateless().getEntity()); } }); }

Target:
protected void commonInitialize() { super.commonInitialize(); getModel().getIsStateless().getEntityChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { if (getModel().getTemplateWithVersion() == null || getModel().getTemplateWithVersion().getItems() == null || getModel().getTemplateWithVersion().getSelectedItem() == null) { return; } List<VmTemplate> baseTemplates = new ArrayList<>(); for (TemplateWithVersion templateWithVersion : getModel().getTemplateWithVersion().getItems()) { if (templateWithVersion.isLatest() || templateWithVersion.getTemplateVersion() == null) { continue; } baseTemplates.add(templateWithVersion.getTemplateVersion()); } TemplateWithVersion selectedItemTemplateWithVersion = getModel().getTemplateWithVersion().getSelectedItem(); VmTemplate selectedTemplateWithVersion = selectedItemTemplateWithVersion.getTemplateVersion(); if (selectedTemplateWithVersion == null) { return; } Guid selectedId = selectedTemplateWithVersion.getId(); updateStatelessFlag = false; initTemplateWithVersion(baseTemplates, selectedId, selectedItemTemplateWithVersion.isLatest(), getModel().getIsStateless().getEntity()); } }); }
Source:
private void addTakeToDb() { ProjectDatabaseHelper db = new ProjectDatabaseHelper(this); ProjectPatternMatcher ppm = mProject.getPatternMatcher(); ppm.match(mNewRecording.getFile()); db.addTake( ppm.getTakeInfo(), mNewRecording.getFile().getName(), mNewRecording.getMetadata().getModeSlug(), mNewRecording.getFile().lastModified(), 0, mUser.getId() ); if(chunkPlugin != null) { ProjectProgress pp = new ProjectProgress(mProject, db, chunkPlugin.getChapters()); pp.updateProjectProgress(); } db.close(); }

Target:
private void addTakeToDb() { ProjectPatternMatcher ppm = mProject.getPatternMatcher(); ppm.match(mNewRecording.getFile()); db.addTake( ppm.getTakeInfo(), mNewRecording.getFile().getName(), mNewRecording.getMetadata().getModeSlug(), mNewRecording.getFile().lastModified(), 0, mUser.getId() ); if(projectProgress != null) { projectProgress.updateProjectProgress(); } }
Source:
private static void createTables(SchemaDao dao) { dao.createTableDistributions(); dao.createTableTables(); dao.createTableColumns(); dao.createTableViews(); dao.createTableNodes(); dao.createTableShards(); dao.createTableShardNodes(); dao.createTableExternalBatches(); dao.createTableTransactions(); dao.createTableCreatedShards(); dao.createTableDeletedShards(); dao.createTableBuckets(); dao.createTableShardOrganizerJobs(); try { dao.alterTableTables(); dao.alterTableShards(); } catch (Exception e) { log.info("alter table failed: s%", e); } }

Target:
private static void createTables(SchemaDao dao) { dao.createTableDistributions(); dao.createTableTables(); dao.createTableColumns(); dao.createTableViews(); dao.createTableNodes(); dao.createTableShards(); dao.createTableShardNodes(); dao.createTableExternalBatches(); dao.createTableTransactions(); dao.createTableCreatedShards(); dao.createTableDeletedShards(); dao.createTableBuckets(); dao.createTableShardOrganizerJobs(); alterTable(dao::alterTableTablesWithDeltaDelete); alterTable(dao::alterTableTablesWithDeltaCount); alterTable(dao::alterTableShardsWithIsDelta); alterTable(dao::alterTableShardsWithDeltaUuid); }
Source:
private synchronized void writeCurrentBufferToService() throws IOException { outputStreamStatistics.writeCurrentBuffer(); if (bufferIndex == 0) { return; } final byte[] bytes = buffer; final int bytesLength = bufferIndex; outputStreamStatistics.bytesToUpload(bytesLength); buffer = byteBufferPool.getBuffer(false, bufferSize).array(); bufferIndex = 0; final long offset = position; position += bytesLength; if (threadExecutor.getQueue().size() >= maxConcurrentRequestCount * 2) { long start = System.currentTimeMillis(); waitForTaskToComplete(); outputStreamStatistics.timeSpentTaskWait(start, System.currentTimeMillis()); } final Future<Void> job = completionService.submit(new Callable<Void>() { @Override public Void call() throws Exception { AbfsPerfTracker tracker = client.getAbfsPerfTracker(); try (AbfsPerfInfo perfInfo = new AbfsPerfInfo(tracker, "writeCurrentBufferToService", "append")) { AbfsRestOperation op = client.append(path, offset, bytes, 0, bytesLength); perfInfo.registerResult(op.getResult()); byteBufferPool.putBuffer(ByteBuffer.wrap(bytes)); perfInfo.registerSuccess(true); return null; } } }); if (job.isCancelled()) { outputStreamStatistics.uploadFailed(bytesLength); } else { outputStreamStatistics.uploadSuccessful(bytesLength); } writeOperations.add(new WriteOperation(job, offset, bytesLength)); shrinkWriteOperationQueue(); }

Target:
private synchronized void writeCurrentBufferToService() throws IOException { if (bufferIndex == 0) { return; } outputStreamStatistics.writeCurrentBuffer(); final byte[] bytes = buffer; final int bytesLength = bufferIndex; outputStreamStatistics.bytesToUpload(bytesLength); buffer = byteBufferPool.getBuffer(false, bufferSize).array(); bufferIndex = 0; final long offset = position; position += bytesLength; if (threadExecutor.getQueue().size() >= maxConcurrentRequestCount * 2) { long start = System.currentTimeMillis(); waitForTaskToComplete(); outputStreamStatistics.timeSpentTaskWait(start, System.currentTimeMillis()); } final Future<Void> job = completionService.submit(new Callable<Void>() { @Override public Void call() throws Exception { AbfsPerfTracker tracker = client.getAbfsPerfTracker(); try (AbfsPerfInfo perfInfo = new AbfsPerfInfo(tracker, "writeCurrentBufferToService", "append")) { AbfsRestOperation op = client.append(path, offset, bytes, 0, bytesLength); perfInfo.registerResult(op.getResult()); byteBufferPool.putBuffer(ByteBuffer.wrap(bytes)); perfInfo.registerSuccess(true); return null; } } }); if (job.isCancelled()) { outputStreamStatistics.uploadFailed(bytesLength); } else { outputStreamStatistics.uploadSuccessful(bytesLength); } writeOperations.add(new WriteOperation(job, offset, bytesLength)); shrinkWriteOperationQueue(); }
Source:
public void calculateAgeAdjustedRawValue(Context context){ double adjust_for = AGE_ADJUSTMENT_TIME - time_since_sensor_started; if (adjust_for > 0 && !CollectionServiceStarter.isLimitter(context)) { age_adjusted_raw_value = ((AGE_ADJUSTMENT_FACTOR * (adjust_for / AGE_ADJUSTMENT_TIME)) * raw_data) + raw_data; Log.i(TAG, "calculateAgeAdjustedRawValue: RAW VALUE ADJUSTMENT FROM:" + raw_data + " TO: " + age_adjusted_raw_value); } else { age_adjusted_raw_value = raw_data; } }

Target:
public void calculateAgeAdjustedRawValue(Context context){ double adjust_for = AGE_ADJUSTMENT_TIME - time_since_sensor_started; if (adjust_for <= 0 || CollectionServiceStarter.isLimitter(context)) { age_adjusted_raw_value = raw_data; } else { age_adjusted_raw_value = ((AGE_ADJUSTMENT_FACTOR * (adjust_for / AGE_ADJUSTMENT_TIME)) * raw_data) + raw_data; Log.i(TAG, "calculateAgeAdjustedRawValue: RAW VALUE ADJUSTMENT FROM:" + raw_data + " TO: " + age_adjusted_raw_value); } }
Source:
public void shouldStoreAndLoadStrings() throws Exception { try ( StringCollisionValues values = new StringCollisionValues( factory, 100_000 ); ) { long[] offsets = new long[100]; String[] strings = new String[offsets.length]; for ( int i = 0; i < offsets.length; i++ ) { String string = random.string(); offsets[i] = values.add( string ); strings[i] = string; } for ( int i = 0; i < offsets.length; i++ ) { assertEquals( strings[i], values.get( offsets[i] ) ); } } }

Target:
public void shouldStoreAndLoadStrings() throws Exception { try ( StringCollisionValues values = new StringCollisionValues( factory, 10_000 ); ) { long[] offsets = new long[100]; String[] strings = new String[offsets.length]; for ( int i = 0; i < offsets.length; i++ ) { String string = random.string(); offsets[i] = values.add( string ); strings[i] = string; } for ( int i = 0; i < offsets.length; i++ ) { assertEquals( strings[i], values.get( offsets[i] ) ); } } }
Source:
public void aboutToBeShown() { super.aboutToBeShown(); this.getController().onNewLabel(new IConsumer<String>() { @Override public void apply(String value) { if (!label.isDisposed() && !(label.getText() != null && label.getText().equals(value))) { label.setText(Objects.firstNonNull(value, "")); } AbstractEEFWidgetLifecycleManager.this.setLabelFontStyle(); } }); this.getController().onNewHelp(new IConsumer<String>() { @Override public void apply(String value) { if (help != null && !help.isDisposed() && !(help.getText() != null && help.getText().equals(value))) { help.setToolTipText(Objects.firstNonNull(value, "No description available")); } } }); }

Target:
public void aboutToBeShown() { super.aboutToBeShown(); this.getController().onNewLabel(new IConsumer<String>() { @Override public void apply(String value) { if (!label.isDisposed() && !(label.getText() != null && label.getText().equals(value))) { label.setText(Objects.firstNonNull(value, "")); } AbstractEEFWidgetLifecycleManager.this.setLabelFontStyle(); } }); this.getController().onNewHelp(new IConsumer<String>() { @Override public void apply(String value) { if (help != null && !help.isDisposed() && !(help.getText() != null && help.getText().equals(value))) { help.setToolTipText(Objects.firstNonNull(value, Messages.AbstractEEFWidgetLifecycleManager_noDescriptionAvailable)); } } }); }
Source:
private FunctionCheckedException<CassandraClient, Void, TException> truncationFunction( Collection<TableReference> tablesToTruncate) { return new FunctionCheckedException<CassandraClient, Void, TException>() { @Override public Void apply(CassandraClient client) throws TException { for (TableReference tableRef : tablesToTruncate) { queryRunner.run(client, tableRef, () -> { client.truncate(CassandraKeyValueServiceImpl.internalTableName(tableRef)); return true; }); } return null; } @Override public String toString() { return "truncateTables(" + tablesToTruncate.size() + " tables)"; } }; }

Target:
private FunctionCheckedException<CassandraClient, Void, TException> truncationFunction( Collection<TableReference> tablesToTruncate) { return new FunctionCheckedException<CassandraClient, Void, TException>() { @Override public Void apply(CassandraClient client) throws TException { for (TableReference tableRef : tablesToTruncate) { queryRunner.run(client, tableRef, () -> { client.truncate(CassandraKeyValueServiceImpl.internalTableName(tableRef)); return true; }); } return null; } @Override public String toString() { return "truncateTables(" + tablesToTruncate + ")"; } }; }
Source:
public void startingAndroidAppWithCapabilitiesOnlyTest(){ File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "ApiDemos-debug.apk"); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.APPIUM); AndroidDriver<MobileElement> driver = null; try { driver = new AndroidDriver<>(capabilities); Capabilities caps = driver.getCapabilities(); Assert.assertEquals(true, caps.getCapability(MobileCapabilityType.AUTOMATION_NAME).equals(AutomationName.APPIUM)); Assert.assertEquals(true, caps.getCapability(MobileCapabilityType.PLATFORM_NAME).equals(MobilePlatform.ANDROID)); Assert.assertNotEquals(null, caps.getCapability(MobileCapabilityType.DEVICE_NAME)); Assert.assertEquals(true, caps.getCapability(MobileCapabilityType.APP).equals(app.getAbsolutePath())); } finally { if (driver != null) driver.quit(); } }

Target:
public void startingAndroidAppWithCapabilitiesOnlyTest(){ File appDir = new File("src/test/java/io/appium/java_client"); File app = new File(appDir, "ApiDemos-debug.apk"); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator"); capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath()); capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.APPIUM); AndroidDriver<MobileElement> driver = new AndroidDriver<>(capabilities);; try { Capabilities caps = driver.getCapabilities(); assertEquals(true, caps.getCapability(MobileCapabilityType.AUTOMATION_NAME).equals(AutomationName.APPIUM)); assertEquals(true, caps.getCapability(MobileCapabilityType.PLATFORM_NAME).equals(MobilePlatform.ANDROID)); assertNotEquals(null, caps.getCapability(MobileCapabilityType.DEVICE_NAME)); assertEquals(true, caps.getCapability(MobileCapabilityType.APP).equals(app.getAbsolutePath())); } finally { driver.quit(); } }
Source:
public static void onBlockRandomTick(World worldIn, BlockPos pos, IBlockState state, Random random) { if(BlockEvent.RandomTickEvent.RandomBlockTickEventRegistry.isEventRegistredForBlock(state.getBlock())) { BlockEvent.RandomTickEvent rte = new BlockEvent.RandomTickEvent(worldIn, pos, state); MinecraftForge.EVENT_BUS.post(rte); if(!rte.isCanceled()) { state.getBlock().randomTick(worldIn, pos, state, random); BlockEvent.RandomTickEvent.Post post = new BlockEvent.RandomTickEvent.Post(worldIn, pos, state); MinecraftForge.EVENT_BUS.post(post); } else { if(!(rte.getState() == state)) { if(!worldIn.isRemote) { worldIn.setBlockState(pos, rte.getState(), 3); } } } } else state.getBlock().randomTick(worldIn, pos, state, random); }

Target:
public static void onBlockRandomTick(World worldIn, BlockPos pos, IBlockState state, Random random) { if(BlockEvent.RandomTickEvent.RandomBlockTickEventRegistry.isBlockRegistred(state.getBlock())) { BlockEvent.RandomTickEvent rte = new BlockEvent.RandomTickEvent(worldIn, pos, state); MinecraftForge.EVENT_BUS.post(rte); if(!rte.isCanceled()) { state.getBlock().randomTick(worldIn, pos, state, random); BlockEvent.RandomTickEvent.Post post = new BlockEvent.RandomTickEvent.Post(worldIn, pos, state); MinecraftForge.EVENT_BUS.post(post); } else { if(rte.getState() != state) { if(!worldIn.isRemote) { worldIn.setBlockState(pos, rte.getState(), 3); } } } } else state.getBlock().randomTick(worldIn, pos, state, random); }
Source:
private void doMediaIdsSelected(ArrayList<Long> mediaIds, @NonNull PhotoPickerMediaSource source) { if (mBrowserType == MediaBrowserType.FEATURED_IMAGE_PICKER && mediaIds != null && mediaIds.size() == 1) { mFeaturedImageHelper.trackFeaturedImageEvent( FeaturedImageHelper.TrackableEvent.IMAGE_PICKED, mLocalPostId ); Intent data = new Intent() .putExtra(EXTRA_MEDIA_ID, mediaIds.get(0)) .putExtra(EXTRA_MEDIA_SOURCE, source.name()); setResult(RESULT_OK, data); finish(); } else { Intent data = new Intent() .putExtra(MediaBrowserActivity.RESULT_IDS, ListUtils.toLongArray(mediaIds)) .putExtra(EXTRA_MEDIA_SOURCE, source.name()); setResult(RESULT_OK, data); finish(); } }

Target:
private void doMediaIdsSelected(ArrayList<Long> mediaIds, @NonNull PhotoPickerMediaSource source) { if (mediaIds != null && mediaIds.size() == 1) { if (mBrowserType == MediaBrowserType.FEATURED_IMAGE_PICKER) { mFeaturedImageHelper.trackFeaturedImageEvent( FeaturedImageHelper.TrackableEvent.IMAGE_PICKED, mLocalPostId ); Intent data = new Intent() .putExtra(EXTRA_MEDIA_ID, mediaIds.get(0)) .putExtra(EXTRA_MEDIA_SOURCE, source.name()); setResult(RESULT_OK, data); finish(); } else { Intent data = new Intent() .putExtra(MediaBrowserActivity.RESULT_IDS, ListUtils.toLongArray(mediaIds)) .putExtra(EXTRA_MEDIA_SOURCE, source.name()); setResult(RESULT_OK, data); finish(); } } else { throw new IllegalArgumentException("call to doMediaIdsSelected with null or empty mediaIds array"); } }
Source:
public Page getOutput() { if (pageBuilder.isFull()) { Page output = pageBuilder.build(); pageBuilder.reset(); return output; } if (pendingInput != null) { processInput(pendingInput); updateMemoryUsage(); return null; } if (finishing) { if (previousRow != null) { evaluateAggregatesToPageBuilder(previousRow, 0); previousRow = null; } Page output = null; if (!pageBuilder.isEmpty()) { output = pageBuilder.build(); } pageBuilder.reset(); return output; } return null; }

Target:
public Page getOutput() { if (!outputPages.isEmpty()) { return outputPages.removeFirst(); } return null; }