auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void expose(T env) throws InternalInfrastructureException { List<CommandImpl> previewUrlCommands = env.getCommands() .stream() .filter(c -> c.getPreviewUrl() != null) .collect(Collectors.toList()); List<ServicePort> portsToProvision = new ArrayList<>(); for (CommandImpl command : previewUrlCommands) { int port = command.getPreviewUrl().getPort(); Optional<Service> foundService = Services.findServiceWithPort(env.getServices().values(), port); if (foundService.isPresent()) { if (!hasMatchingEndpoint(env, foundService.get(), port)) { ServicePort servicePort = Services.findPort(foundService.get(), port) .orElseThrow( () -> new InternalInfrastructureException( String.format( "Port '%d' in service '%s' not found. This is not expected, please report a bug!", port, foundService.get().getMetadata().getName()))); externalServerExposer.expose( env, null, foundService.get().getMetadata().getName(), servicePort, ImmutableMap.of( command.getName(), new ServerConfigImpl( servicePort.getName(), "http", "/", Collections.emptyMap()))); } } else { portsToProvision.add(createServicePort(port)); } } if (!portsToProvision.isEmpty()) { String serverName = generate(SERVER_PREFIX, SERVER_UNIQUE_PART_SIZE) + "-previewUrl"; Service service = new ServerServiceBuilder().withName(serverName).withPorts(portsToProvision).build(); env.getServices().put(serverName, service); portsToProvision.forEach( port -> externalServerExposer.expose( env, null, service.getMetadata().getName(), port, ImmutableMap.of( serverName, new ServerConfigImpl(port.getName(), "http", "/", Collections.emptyMap())))); } }

Target:
public void expose(T env) throws InternalInfrastructureException { List<CommandImpl> previewUrlCommands = env.getCommands() .stream() .filter(c -> c.getPreviewUrl() != null) .collect(Collectors.toList()); List<ServicePort> portsToProvision = new ArrayList<>(); for (CommandImpl command : previewUrlCommands) { int port = command.getPreviewUrl().getPort(); Optional<Service> foundService = Services.findServiceWithPort(env.getServices().values(), port); if (foundService.isPresent()) { if (!hasMatchingEndpoint(env, foundService.get(), port)) { ServicePort servicePort = Services.findPort(foundService.get(), port) .orElseThrow( () -> new InternalInfrastructureException( String.format( "Port '%d' in service '%s' not found. This is not expected, please report a bug!", port, foundService.get().getMetadata().getName()))); String serviceName = foundService.get().getMetadata().getName(); externalServerExposer.expose( env, null, serviceName, serviceName, servicePort, Collections.emptyMap()); } } else { portsToProvision.add(createServicePort(port)); } } if (!portsToProvision.isEmpty()) { String serverName = generate(SERVER_PREFIX, SERVER_UNIQUE_PART_SIZE) + "-previewUrl"; Service service = new ServerServiceBuilder().withName(serverName).withPorts(portsToProvision).build(); env.getServices().put(serverName, service); portsToProvision.forEach( port -> externalServerExposer.expose( env, null, service.getMetadata().getName(), service.getMetadata().getName(), port, Collections.emptyMap())); } }
Source:
public boolean isValid(ILaunchConfiguration launchConfig) { setErrorMessage(null); IPath scriptPath = getScriptPath(); if (scriptPath == null) { setErrorMessage(MessageFormat.format(Messages.SystemTapScriptLaunchConfigurationTab_couldNotFindFile, scriptPathText.getText())); return false; } if (!scriptPath.getFileExtension().equals("stp")) { setErrorMessage(Messages.SystemTapScriptLaunchConfigurationTab_fileNotStp); } return true; }

Target:
public boolean isValid(ILaunchConfiguration launchConfig) { setErrorMessage(null); IPath scriptPath = getScriptPath(); if (scriptPath == null) { setErrorMessage(MessageFormat.format(Messages.SystemTapScriptLaunchConfigurationTab_couldNotFindFile, scriptPathText.getText())); return false; } String extension = scriptPath.getFileExtension(); if (extension == null || !extension.equals("stp")) { setErrorMessage(Messages.SystemTapScriptLaunchConfigurationTab_fileNotStp); return false; } return true; }
Source:
public UserTuneElement build() { if (title != null) { return new UserTuneElement(this); } else { throw new IllegalArgumentException("UserTune should atleast have 'title'"); } }

Target:
public UserTuneElement build() { return new UserTuneElement(this); }
Source:
public LocalApplicationRunner(SamzaApplication app, Config config, MetadataStoreFactory metadataStoreFactory) { this(app, config, getCoordinationUtils(config), metadataStoreFactory); }

Target:
public LocalApplicationRunner(SamzaApplication app, Config config, MetadataStoreFactory metadataStoreFactory) { this(new LocalApplicationRunnerContext(app, config).setMetadataStoreFactory(metadataStoreFactory)); }
Source:
public void setMessageBus(MessageBusSupport messageBus) { messageBus.setIntegrationEvaluationContext(new StandardEvaluationContext()); try { messageBus.afterPropertiesSet(); } catch (Exception e) { e.printStackTrace(); } this.messageBus = messageBus; }

Target:
public void setMessageBus(MessageBusSupport messageBus) { messageBus.setIntegrationEvaluationContext(new StandardEvaluationContext()); try { messageBus.afterPropertiesSet(); } catch (Exception e) { throw new RuntimeException("Failed to initialize message bus", e); } this.messageBus = messageBus; }
Source:
public void testLetTarget() { disableTypeCheck(); testEs6( LINE_JOINER.join( "let X = Polymer({", " is: 'x-element',", "});"), LINE_JOINER.join( " ", "var X = function() {};", "X = Polymer( {is:'x-element'});")); disableTypeCheck(); testEs6( LINE_JOINER.join( "let X = class extends Polymer.Element {", " static get is() { return 'x-element'; }", " static get config() { return { properties: }; }", "};"), LINE_JOINER.join( "let X = class extends Polymer.Element {", " static get is() { return 'x-element'; }", " static get config() { return { properties: }; }", "};")); }

Target:
public void testLetTarget() { disableTypeCheck(); testEs6( LINE_JOINER.join( "let X = Polymer({", " is: 'x-element',", "});"), LINE_JOINER.join( " ", "var X = function() {};", "X = Polymer( {is:'x-element'});")); disableTypeCheck(); testSameEs6( LINE_JOINER.join( "let X = class extends Polymer.Element {", " static get is() { return 'x-element'; }", " static get properties() { return { }; }", "};")); }
Source:
public void deletePerspectives(ArrayList<IPerspectiveDescriptor> perspToDelete) { for (IPerspectiveDescriptor element : perspToDelete) { deletePerspective(element); } }

Target:
public void deletePerspectives(ArrayList<IPerspectiveDescriptor> perspToDelete) { for (IPerspectiveDescriptor descriptor : perspToDelete) { deletePerspective(descriptor); } }
Source:
private void handleByName(Context context, String name) throws Exception { if (name == null || "".equals(name) || DEFAULT_NAME_TOKEN.equals(name)) { context.clientError(404); return; } SortedMap<String, HealthCheck.Result> hcheckResults = new ConcurrentSkipListMap<>(); Optional<HealthCheck> hcheck = context.first(TypeToken.of(HealthCheck.class), hc -> hc.getName().equals(name)); if (!hcheck.isPresent()) { context.clientError(404); return; } try { Promise<HealthCheck.Result> promise = hcheck.get().check(context.getExecution().getControl()); promise.onError(throwable -> { hcheckResults.put(hcheck.get().getName(), HealthCheck.Result.unhealthy(throwable)); context.render(new HealthCheckResults(ImmutableSortedMap.<String, HealthCheck.Result>copyOfSorted(hcheckResults))); }).then(r -> { hcheckResults.put(hcheck.get().getName(), r); context.render(new HealthCheckResults(ImmutableSortedMap.<String, HealthCheck.Result>copyOfSorted(hcheckResults))); }); } catch (Exception ex) { hcheckResults.put(hcheck.get().getName(), HealthCheck.Result.unhealthy(ex)); context.render(new HealthCheckResults(ImmutableSortedMap.<String, HealthCheck.Result>copyOfSorted(hcheckResults))); } }

Target:
private void handleByName(Context context, String name) throws Exception { if (name == null || "".equals(name)) { context.clientError(404); return; } Optional<HealthCheck> hcheck = context.first(TypeToken.of(HealthCheck.class), hc -> { if (hc.getName().equals(name)) { return hc; } else { return null; } }); if (!hcheck.isPresent()) { context.clientError(404); return; } try { Promise<HealthCheck.Result> promise = hcheck.get().check(context.getExecution().getControl()); promise.onError(throwable -> { context.render(new HealthCheckResults(ImmutableSortedMap.<String, HealthCheck.Result>of(hcheck.get().getName(), HealthCheck.Result.unhealthy(throwable)))); }).then(r -> { context.render(new HealthCheckResults(ImmutableSortedMap.<String, HealthCheck.Result>of(hcheck.get().getName(), r))); }); } catch (Exception ex) { context.render(new HealthCheckResults(ImmutableSortedMap.<String, HealthCheck.Result>of(hcheck.get().getName(), HealthCheck.Result.unhealthy(ex)))); } }
Source:
synchronized void waitForCompletion() throws InterruptedException { while (finishCount < count) { wait(); } if (opts.keepalive > 0) { Thread.sleep(opts.keepalive); } eSvc.shutdown(); while (!eSvc.awaitTermination(5L, TimeUnit.SECONDS)) { System.err.println("Failed to close all threads, trying again..."); } for (ResultReporter r : reporters) { r.close(); } try { eSvc.awaitTermination(opts.keepalive, TimeUnit.MILLISECONDS); } finally { try { if (opts.diffable != null) { ResultFileSorter sorter = new ResultFileSorter(opts.diffable); sorter.sortFile(); } if (server != null) { server.stop(); } trf.close(); } catch (Exception e) { e.printStackTrace(); } } }

Target:
synchronized void waitForCompletion() throws InterruptedException { while (finishCount < count) { wait(); } if (opts.keepalive > 0) { Thread.sleep(opts.keepalive); } eSvc.shutdown(); while (!eSvc.awaitTermination(5L, TimeUnit.SECONDS)) { System.err.println("Failed to close all threads, trying again..."); } for (ResultReporter r : reporters) { r.close(); } try { eSvc.awaitTermination(opts.keepalive, TimeUnit.MILLISECONDS); } finally { try { if (server != null) { server.stop(); } trf.close(); } catch (Exception e) { e.printStackTrace(); } } }
Source:
private String perspToString(MPerspective persp) throws IOException { Resource resource = new E4XMIResourceFactory().createResource(null); resource.getContents().add((EObject) modelService.cloneElement(persp, null)); ByteArrayOutputStream output = new ByteArrayOutputStream(); try { resource.save(output, null); } finally { if (output != null) { try { output.close(); } catch (IOException e) { logger.error(e, "Cannot close output stream"); } } } return new String(output.toByteArray(), StandardCharsets.US_ASCII); }

Target:
private String perspToString(MPerspective persp) throws IOException { Resource resource = new E4XMIResourceFactory().createResource(null); resource.getContents().add((EObject) modelService.cloneElement(persp, null)); ByteArrayOutputStream output = new ByteArrayOutputStream(); try { resource.save(output, null); } finally { try { output.close(); } catch (IOException e) { logger.error(e, "Cannot close output stream"); } } resource.getContents().clear(); return new String(output.toByteArray(), ASCII_ENCODING); }
Source:
private GitUser getCommitAuthor(RevCommit commit) { PersonIdent authorIdentity = commit.getAuthorIdent(); GitUser author = createDto(GitUser.class).withName(authorIdentity.getName()) .withEmail(authorIdentity.getEmailAddress()); return author; }

Target:
private GitUser getCommitAuthor(RevCommit commit) { PersonIdent authorIdentity = commit.getAuthorIdent(); return newDto(GitUser.class).withName(authorIdentity.getName()) .withEmail(authorIdentity.getEmailAddress()); }
Source:
protected boolean addedValid(IConfigurationElement element) { IConfigurationElement[] nsURIChildren = element.getChildren(TAG_NS_URI); IConfigurationElement[] resourceURIChildren = element.getChildren(TAG_RESOURCE_URI); Pattern nsURI = null; if (nsURIChildren.length > 0) { nsURI = Pattern.compile(nsURIChildren[0].getAttribute(ATT_VALUE)); } Pattern resourceURI = null; if (resourceURIChildren.length > 0) { resourceURI = Pattern.compile(resourceURIChildren[0].getAttribute(ATT_VALUE)); } String className = element.getAttribute(ATT_CLASS); IPostProcessor.Descriptor descriptor = new PostProcessorDescriptor(element, nsURI, resourceURI); descriptor.setOrdinal(Integer.parseInt(element.getAttribute(ATT_ORDINAL))); StaticItemDescriptor<IPostProcessor.Descriptor> ddescriptor = new StaticItemDescriptor<IPostProcessor.Descriptor>( element.getAttribute(ATT_LABEL), element.getAttribute(ATT_DESCRIPTION), descriptor .getOrdinal(), className, descriptor); IItemDescriptor<Descriptor> previous = registry.add(ddescriptor); if (previous != null) { EMFCompareRCPPlugin.getDefault().log(IStatus.WARNING, "The post processor factory '" + className + "' is registered twice."); } return true; }

Target:
protected boolean addedValid(IConfigurationElement element) { IConfigurationElement[] nsURIChildren = element.getChildren(TAG_NS_URI); IConfigurationElement[] resourceURIChildren = element.getChildren(TAG_RESOURCE_URI); Pattern nsURI = null; if (nsURIChildren.length > 0) { nsURI = Pattern.compile(nsURIChildren[0].getAttribute(ATT_VALUE)); } Pattern resourceURI = null; if (resourceURIChildren.length > 0) { resourceURI = Pattern.compile(resourceURIChildren[0].getAttribute(ATT_VALUE)); } String className = element.getAttribute(ATT_CLASS); IPostProcessor.Descriptor postProcessorDescriptor = new PostProcessorDescriptor(element, nsURI, resourceURI); postProcessorDescriptor.setOrdinal(Integer.parseInt(element.getAttribute(ATT_ORDINAL))); WrapperItemDescriptor<IPostProcessor.Descriptor> postProcessorItemDescriptor = new WrapperItemDescriptor<IPostProcessor.Descriptor>( element.getAttribute(ATT_LABEL), element.getAttribute(ATT_DESCRIPTION), postProcessorDescriptor.getOrdinal(), className, postProcessorDescriptor); IItemDescriptor<Descriptor> previous = registry.add(postProcessorItemDescriptor); if (previous != null) { EMFCompareRCPPlugin.getDefault().log(IStatus.WARNING, "The post processor factory '" + className + "' is registered twice."); } return true; }
Source:
public void onPlayerJoin(PlayerJoinEvent event) { final Player player = event.getPlayer(); if (!PlayerListener19Spigot.isPlayerSpawnLocationEventCalled()) { teleportationService.teleportOnJoin(player); } if (quickCommandsProtectionManager.shouldSaveLogin(player)) { quickCommandsProtectionManager.setLogin(player.getName()); } management.performJoin(player); teleportationService.teleportNewPlayerToFirstSpawn(player); }

Target:
public void onPlayerJoin(PlayerJoinEvent event) { final Player player = event.getPlayer(); if (!PlayerListener19Spigot.isPlayerSpawnLocationEventCalled()) { teleportationService.teleportOnJoin(player); } quickCommandsProtectionManager.processJoin(player); management.performJoin(player); teleportationService.teleportNewPlayerToFirstSpawn(player); }
Source:
public BindAzureBlobMetadataToMultipartRequest(AzureBlobToBlob azureBlob2Blob, BindUserMetadataToHeadersWithPrefix blobBinder) { this.azureBlob2Blob = checkNotNull(azureBlob2Blob, "azureBlob2Blob"); this.blobBinder = checkNotNull(blobBinder, "blobBinder"); }

Target:
BindAzureBlobMetadataToMultipartRequest(AzureBlobToBlob azureBlob2Blob, BindUserMetadataToHeadersWithPrefix blobBinder) { this.azureBlob2Blob = azureBlob2Blob; this.blobBinder = blobBinder; }
Source:
public static BlobProperties buildBlobProperties(Map<String, Object> args) throws RestServiceException { Account account = (Account) args.get(InternalKeys.TARGET_ACCOUNT_KEY); Container container = (Container) args.get(InternalKeys.TARGET_CONTAINER_KEY); Objects.requireNonNull(account, "Target account object has not been injected into rest request"); Objects.requireNonNull(container, "Target container object has not been injected into rest request"); String serviceId = getHeader(args, Headers.SERVICE_ID, true); String contentType = getHeader(args, Headers.AMBRY_CONTENT_TYPE, true); String ownerId = getHeader(args, Headers.OWNER_ID, false); long ttl = Utils.Infinite_Time; String ttlStr = getHeader(args, Headers.TTL, false); if (ttlStr != null) { try { ttl = Long.parseLong(ttlStr); if (ttl < -1) { throw new RestServiceException(Headers.TTL + "[" + ttl + "] is not valid (has to be >= -1)", RestServiceErrorCode.InvalidArgs); } } catch (NumberFormatException e) { throw new RestServiceException(Headers.TTL + "[" + ttlStr + "] could not parsed into a number", RestServiceErrorCode.InvalidArgs); } } return new BlobProperties(-1, serviceId, ownerId, contentType, getIsPrivateSetting(args), ttl, account.getId(), container.getId()); }

Target:
public static BlobProperties buildBlobProperties(Map<String, Object> args) throws RestServiceException { Account account = (Account) args.get(InternalKeys.TARGET_ACCOUNT_KEY); Container container = (Container) args.get(InternalKeys.TARGET_CONTAINER_KEY); String serviceId = getHeader(args, Headers.SERVICE_ID, true); String contentType = getHeader(args, Headers.AMBRY_CONTENT_TYPE, true); String ownerId = getHeader(args, Headers.OWNER_ID, false); long ttl = Utils.Infinite_Time; String ttlStr = getHeader(args, Headers.TTL, false); if (ttlStr != null) { try { ttl = Long.parseLong(ttlStr); if (ttl < -1) { throw new RestServiceException(Headers.TTL + "[" + ttl + "] is not valid (has to be >= -1)", RestServiceErrorCode.InvalidArgs); } } catch (NumberFormatException e) { throw new RestServiceException(Headers.TTL + "[" + ttlStr + "] could not parsed into a number", RestServiceErrorCode.InvalidArgs); } } return new BlobProperties(-1, serviceId, ownerId, contentType, isPrivate(args), ttl, account.getId(), container.getId()); }
Source:
public boolean onLongClick(View view) { switch (view.getId()) { case R.id.from: onAddAddressesToClipboard(mMessage.getFrom()); break; case R.id.to: try { onAddAddressesToClipboard(mMessage.getRecipients(Message.RecipientType.TO)); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Couldn't get recipients address", e); } break; case R.id.cc: try { onAddAddressesToClipboard(mMessage.getRecipients(Message.RecipientType.CC)); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Couldn't get recipients address", e); } break; } return true; }

Target:
public boolean onLongClick(View view) { switch (view.getId()) { case R.id.from: onAddAddressesToClipboard(mMessage.getFrom()); break; case R.id.to: onAddRecipientsToClipboard(Message.RecipientType.TO); break; case R.id.cc: onAddRecipientsToClipboard(Message.RecipientType.CC); break; } return true; }
Source:
protected Object readResolve() { if (containers == null) { containers = new ArrayList<>(); ContainerTemplate containerTemplate = new ContainerTemplate(KubernetesCloud.JNLP_NAME, this.image); containerTemplate.setCommand(command); containerTemplate.setArgs(Strings.isNullOrEmpty(args) ? FALLBACK_ARGUMENTS : args); containerTemplate.setPrivileged(privileged); containerTemplate.setAlwaysPullImage(alwaysPullImage); containerTemplate.setEnvVars(envVars); containerTemplate.setResourceRequestMemory(resourceRequestMemory); containerTemplate.setResourceLimitCpu(resourceLimitCpu); containerTemplate.setResourceLimitMemory(resourceLimitMemory); containerTemplate.setResourceRequestCpu(resourceRequestCpu); containerTemplate.setWorkingDir(remoteFs); containers.add(containerTemplate); } if (podRetention == null) { podRetention = PodRetention.getPodTemplateDefault(); } if (annotations == null) { annotations = new ArrayList<>(); } yaml = Util.fixEmpty(yaml); if (yamls != null) { setYamls(yamls); if (!yamls.isEmpty()) { yaml = yamls.get(0); } yamls = null; } if (showRawYaml == null) { showRawYaml = Boolean.TRUE; } if (yamlMergeStrategy == null) { yamlMergeStrategy = YamlMergeStrategy.defaultStrategy(); } return this; }

Target:
protected Object readResolve() { if (containers == null) { containers = new ArrayList<>(); ContainerTemplate containerTemplate = new ContainerTemplate(KubernetesCloud.JNLP_NAME, this.image); containerTemplate.setCommand(command); containerTemplate.setArgs(Strings.isNullOrEmpty(args) ? FALLBACK_ARGUMENTS : args); containerTemplate.setPrivileged(privileged); containerTemplate.setAlwaysPullImage(alwaysPullImage); containerTemplate.setEnvVars(envVars); containerTemplate.setResourceRequestMemory(resourceRequestMemory); containerTemplate.setResourceLimitCpu(resourceLimitCpu); containerTemplate.setResourceLimitMemory(resourceLimitMemory); containerTemplate.setResourceRequestCpu(resourceRequestCpu); containerTemplate.setWorkingDir(remoteFs); containers.add(containerTemplate); } if (podRetention == null) { podRetention = PodRetention.getPodTemplateDefault(); } if (annotations == null) { annotations = new ArrayList<>(); } yaml = Util.fixEmpty(yaml); if (yamls != null) { setYamls(yamls); if (!yamls.isEmpty()) { if (yamls.size() > 1) { LOGGER.log(Level.WARNING, "Found several persisted YAML fragments in pod template " + name + ". Only the first fragment will be considered, others will be ignored."); } yaml = yamls.get(0); } yamls = null; } if (showRawYaml == null) { showRawYaml = Boolean.TRUE; } if (yamlMergeStrategy == null) { yamlMergeStrategy = YamlMergeStrategy.defaultStrategy(); } return this; }
Source:
public void testNonPartition() throws Exception { prepareTables(false); createTable("source", source.toURI().toString(), false); createTable("sink", sink.toURI().toString(), false); tEnv().executeSql("insert into sink select * from source").await(); CloseableIterator<Row> iter = tEnv().executeSql("select * from sink").collect(); List<String> results = CollectionUtil.iteratorToList(iter).stream() .map(row -> row.getKind().shortString() + "(" + row.toString() + ")") .collect(Collectors.toList()); iter.close(); Assert.assertEquals(EXPECTED, results); }

Target:
public void testNonPartition() throws Exception { prepareTables(false); createTable(false, source.toURI().toString(), false); createTable(true, sink.toURI().toString(), false); tEnv().executeSql("insert into sink select id,name,UPPER(name),description,weight from source").await(); CloseableIterator<Row> iter = tEnv() .executeSql("select id,upper_name,description,weight from sink").collect(); List<String> results = CollectionUtil.iteratorToList(iter).stream() .map(row -> row.getKind().shortString() + "(" + row.toString() + ")") .collect(Collectors.toList()); iter.close(); Assert.assertEquals(EXPECTED, results); }
Source:
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { long endTimeNanos = System.nanoTime() + unit.toNanos(timeout); Counter counter = getActiveChannelCounter(); for (ChannelAndMetrics channelWrapper : channels.get()) { ManagedChannel channel = channelWrapper.channel; if (channel.isTerminated()) { continue; } long awaitTimeNanos = endTimeNanos - System.nanoTime(); if (awaitTimeNanos <= 0) { break; } channel.awaitTermination(awaitTimeNanos, TimeUnit.NANOSECONDS); counter.dec(); } return isTerminated(); }

Target:
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { long endTimeNanos = System.nanoTime() + unit.toNanos(timeout); for (InstrumentedChannel channel : channels.get()) { if (channel.isTerminated()) { continue; } long awaitTimeNanos = endTimeNanos - System.nanoTime(); if (awaitTimeNanos <= 0) { break; } channel.awaitTermination(awaitTimeNanos, TimeUnit.NANOSECONDS); } return isTerminated(); }
Source:
protected boolean checkDisksNotInBackupStorage() { for (Disk disk : getVm().getDiskMap().values()) { StorageDomainStatic destDomain = storageDomainStaticDao.get(disk.getId()); if (destDomain.isBackup()) { return false; } } return true; }

Target:
protected boolean checkDisksNotInBackupStorage() { for (Disk disk : getVm().getDiskMap().values()) { if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { StorageDomainStatic destDomain = storageDomainStaticDao.get(((DiskImage)disk).getStorageIds().get(0)); if (getVm().getDiskMap().values().stream().anyMatch(destDomain.isBackup())) { return false; } } } return true; }
Source:
public void shouldNotSetRemovalTime_HistoricProcessInstancePermissionsDisabled() { testRule.getProcessEngineConfiguration() .setEnableHistoricInstancePermissions(false); String processInstanceId = testRule.process().call().userTask().deploy().start(); Authorization authorization = authorizationService.createNewAuthorization(Authorization.AUTH_TYPE_GRANT); authorization.setResource(Resources.HISTORIC_PROCESS_INSTANCE); authorization.setResourceId(processInstanceId); authorization.setUserId("foo"); authorizationService.saveAuthorization(authorization); testRule.updateHistoryTimeToLive("rootProcess", 5); HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery().rootProcessInstances(); testRule.syncExec( historyService.setRemovalTimeToHistoricProcessInstances() .calculatedRemovalTime() .byQuery(query) .hierarchical() .executeAsync() ); authorization = authorizationService.createAuthorizationQuery() .resourceType(Resources.HISTORIC_PROCESS_INSTANCE) .singleResult(); assertThat(authorization.getRemovalTime()).isNull(); testRule.clearAuthorization(); }

Target:
public void shouldNotSetRemovalTime_HistoricProcessInstancePermissionsDisabled() { testRule.getProcessEngineConfiguration() .setEnableHistoricInstancePermissions(false); String processInstanceId = testRule.process().call().userTask().deploy().start(); Authorization authorization = authorizationService.createNewAuthorization(Authorization.AUTH_TYPE_GRANT); authorization.setResource(Resources.HISTORIC_PROCESS_INSTANCE); authorization.setResourceId(processInstanceId); authorization.setUserId("foo"); authorizationService.saveAuthorization(authorization); testRule.updateHistoryTimeToLive("rootProcess", 5); HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery().rootProcessInstances(); testRule.syncExec( historyService.setRemovalTimeToHistoricProcessInstances() .calculatedRemovalTime() .byQuery(query) .hierarchical() .executeAsync() ); authorization = authorizationService.createAuthorizationQuery() .resourceType(Resources.HISTORIC_PROCESS_INSTANCE) .singleResult(); assertThat(authorization.getRemovalTime()).isNull(); }
Source:
private boolean isNetworkStack(long accountId, long instanceId) { Instance instance = objectManager.findAny(Instance.class, INSTANCE.ID, instanceId); List<? extends Service> services = instanceDao.findServicesFor(instance); if(services.size() > 0) { List<Service> network_services = objectManager.find(Service.class, SERVICE.ACCOUNT_ID, accountId, SERVICE.REMOVED, null, SERVICE.STACK_ID, services.get(0).getStackId(), SERVICE.KIND, ServiceConstants.KIND_NETWORK_DRIVER_SERVICE); if(network_services.size() > 0) { return true; } } return false; }

Target:
private boolean isNetworkStack(long accountId, long instanceId) { List<? extends Service> services = instanceDao.findServicesForInstanceId(instanceId); if(services.size() > 0) { if(services.get(0).getKind().equals(ServiceConstants.KIND_NETWORK_DRIVER_SERVICE)) { return true; } List<Service> network_services = objectManager.find(Service.class, SERVICE.ACCOUNT_ID, accountId, SERVICE.REMOVED, null, SERVICE.STACK_ID, services.get(0).getStackId(), SERVICE.KIND, ServiceConstants.KIND_NETWORK_DRIVER_SERVICE); if(network_services.size() > 0) { return true; } } return false; }
Source:
public void validateDatastreamsUpdate(List<Datastream> datastreams) throws DatastreamValidationException { _log.info("About to validate datastremas update: " + datastreams); try { List<String> connectorTypes = datastreams.stream().map(Datastream::getConnectorName).distinct().collect(Collectors.toList()); if (connectorTypes.size() != 1) { throw new DatastreamValidationException( "Expecting exactly one type of connectors for datastreams update: " + connectorTypes); } String connectorName = connectorTypes.get(0); ConnectorInfo connectorInfo = _connectors.get(connectorName); if (connectorInfo == null) { throw new DatastreamValidationException("Invalid connector: " + connectorName); } connectorInfo.getConnector() .validateUpdateDatastreams(datastreams, _datastreamCache.getAllDatastreams() .stream() .filter(d -> d.getConnectorName().equals(connectorName)) .collect(Collectors.toList())); } catch (Exception e) { _dynamicMetricsManager.createOrUpdateMeter(MODULE, "validateDatastreamsUpdate", NUM_ERRORS, 1); throw e; } }

Target:
public void validateDatastreamsUpdate(List<Datastream> datastreams) throws DatastreamValidationException { _log.info("About to validate datastreams update: " + datastreams); try { List<String> connectorTypes = datastreams.stream().map(Datastream::getConnectorName).distinct().collect(Collectors.toList()); if (connectorTypes.size() != 1) { throw new DatastreamValidationException( "Expecting exactly one type of connectors for datastreams update: " + connectorTypes); } String connectorName = connectorTypes.get(0); ConnectorInfo connectorInfo = _connectors.get(connectorName); if (connectorInfo == null) { throw new DatastreamValidationException("Invalid connector: " + connectorName); } connectorInfo.getConnector() .validateUpdateDatastreams(datastreams, _datastreamCache.getAllDatastreams() .stream() .filter(d -> d.getConnectorName().equals(connectorName)) .collect(Collectors.toList())); } catch (Exception e) { _dynamicMetricsManager.createOrUpdateMeter(MODULE, "validateDatastreamsUpdate", NUM_ERRORS, 1); throw e; } }
Source:
private void registerLeaderElectionService(TimeLockServerConfiguration configuration) { remoteServers = getRemoteServerPaths(configuration); LeaderConfig leaderConfig = getLeaderConfig(configuration); Set<String> paxosSubresourceUris = PaxosTimeLockUriUtils.getLeaderPaxosUris(remoteServers); Leaders.LocalPaxosServices localPaxosServices = Leaders.createInstrumentedLocalServices( leaderConfig, ImmutableRemotePaxosServerSpec.builder() .remoteLeaderUris(remoteServers) .remoteAcceptorUris(paxosSubresourceUris) .remoteLearnerUris(paxosSubresourceUris) .build(), "paxos-leader-election-service"); leaderElectionService = localPaxosServices.leaderElectionService(); environment.jersey().register(localPaxosServices.pingableLeader()); environment.jersey().register(new LeadershipResource( localPaxosServices.ourAcceptor(), localPaxosServices.ourLearner())); }

Target:
private void registerLeaderElectionService(TimeLockServerConfiguration configuration) { remoteServers = getRemoteServerPaths(configuration); LeaderConfig leaderConfig = getLeaderConfig(configuration); Set<String> paxosSubresourceUris = PaxosTimeLockUriUtils.getLeaderPaxosUris(remoteServers); Leaders.LocalPaxosServices localPaxosServices = Leaders.createInstrumentedLocalServices( leaderConfig, ImmutableRemotePaxosServerSpec.builder() .remoteLeaderUris(remoteServers) .remoteAcceptorUris(paxosSubresourceUris) .remoteLearnerUris(paxosSubresourceUris) .build(), "leader-election-service"); leaderElectionService = localPaxosServices.leaderElectionService(); environment.jersey().register(localPaxosServices.pingableLeader()); environment.jersey().register(new LeadershipResource( localPaxosServices.ourAcceptor(), localPaxosServices.ourLearner())); }
Source:
private CollectionStream(String systemName, String streamName, Integer partitionCount) { this.streamName = streamName; this.streamConfig = new HashMap<>(); this.partitions = new HashMap<>(); this.systemName = systemName; streamConfig.put(String.format(STREAM_TO_SYSTEM, this.streamName), systemName); for (int i = 0; i < partitionCount; i++) { partitions.put(i, new ArrayList<>()); } }

Target:
private CollectionStream(String systemName, String streamName, Integer partitionCount) { this(systemName, streamName); Preconditions.checkState(partitionCount > 0); initPartitions = new HashMap<>(); for (int i = 0; i < partitionCount; i++) { initPartitions.put(i, new ArrayList<>()); } }
Source:
protected IDialogSettings getDialogBoundsSettings() { IDialogSettings settings = DebugUIPlugin.getDefault().getDialogSettings(); IDialogSettings section = settings.getSection(SETTINGS_ID); if (section == null) { section = settings.addNewSection(SETTINGS_ID); } return section; }

Target:
private IDialogSettings getDialogBoundsSettings() { IDialogSettings settings = DebugUIPlugin.getDefault().getDialogSettings(); IDialogSettings section = settings.getSection(SETTINGS_ID); if (section == null) { section = settings.addNewSection(SETTINGS_ID); } return section; }
Source:
public @ResponseBody JSONObj get(@PathVariable String wsName, @PathVariable Long id) throws Exception { ImportContext imp = findImport(id); JSONObj result = new JSONObj(); result.put("id", imp.getId()); JSONArr preimport = result.putArray("preimport"); JSONArr imported = result.putArray("imported"); JSONArr pending = result.putArray("pending"); JSONArr failed = result.putArray("failed"); JSONArr ignored = result.putArray("ignored"); for (ImportTask task : imp.getTasks()) { if (imp.getState() == ImportContext.State.PENDING) { preimport.add(task(task)); } else { if (task.getState() == ImportTask.State.COMPLETE) { imported.add(complete(task)); } else { switch(task.getState()) { case NO_BOUNDS: case NO_CRS: pending.add(pending(task)); break; case ERROR: failed.add(failed(task)); break; default: ignored.add(ignored(task)); } } } } return result; }

Target:
public @ResponseBody JSONObj get(@PathVariable String wsName, @PathVariable Long id) throws Exception { ImportContext imp = findImport(id); JSONObj result = new JSONObj(); result.put("id", imp.getId()); JSONArr preimport = result.putArray("preimport"); JSONArr imported = result.putArray("imported"); JSONArr pending = result.putArray("pending"); JSONArr failed = result.putArray("failed"); JSONArr ignored = result.putArray("ignored"); for (ImportTask task : imp.getTasks()) { if (imp.getState() == ImportContext.State.PENDING) { preimport.add(task(task)); } else { switch(task.getState()) { case COMPLETE: imported.add(complete(task)); break; case NO_BOUNDS: case NO_CRS: pending.add(pending(task)); break; case ERROR: failed.add(failed(task)); break; default: ignored.add(ignored(task)); } } } return result; }
Source:
default void checkCanSelectFromTable(ConnectorTransactionHandle transactionHandle, Identity identity, SchemaTableName tableName) { denySelectTable(tableName.toString()); }

Target:
default void checkCanSelectFromTable(ConnectorTransactionHandle transactionHandle, Identity identity, SchemaTableName tableName) { checkCanSelectFromColumns(transactionHandle, identity, tableName, emptySet()); }
Source:
SignatureSignerContext signer() throws SignatureException; SignatureVerifierContext verifier(String kid) throws VerificationException; SignatureVerifierContext verifier(ClientModel client, JWSInput input) throws VerificationException; @Override default void close() { }

Target:
SignatureSignerContext signer() throws SignatureException; SignatureVerifierContext verifier(String kid) throws VerificationException; @Override default void close() { }
Source:
public JavaTypeDefinition getVarargComponentType() { return argTypes.get(argTypes.size() - 1).getComponentType(); }

Target:
public JavaTypeDefinition getVarargComponentType() { if (!isVararg()) { throw new IllegalStateException("Method is not vararg: " + method.toString() + "!"); } return argTypes.get(argTypes.size() - 1).getComponentType(); }
Source:
public void configure(Job job) throws IOException { final Configuration conf = job.getConfiguration(); final Kiji kiji = mTable.getKiji(); conf.set( KijiConfKeys.OUTPUT_KIJI_TABLE_URI, String.format("kiji://%s:%s/%s/%s", conf.get(HConstants.ZOOKEEPER_QUORUM), conf.getInt(HConstants.ZOOKEEPER_CLIENT_PORT, HConstants.DEFAULT_ZOOKEPER_CLIENT_PORT), kiji.getName(), mTable.getName())); job.setOutputFormatClass(NullOutputFormat.class); conf.set(KijiConfKeys.KIJI_TABLE_CONTEXT_CLASS, DirectKijiTableWriterContext.class.getName()); job.setNumReduceTasks(mNumReduceTasks); conf.setBoolean("mapred.map.tasks.speculative.execution", false); }

Target:
public void configure(Job job) throws IOException { final Configuration conf = job.getConfiguration(); final Kiji kiji = mTable.getKiji(); conf.set( KijiConfKeys.OUTPUT_KIJI_TABLE_URI, String.format("kiji://%s:%s/%s/%s", conf.get(HConstants.ZOOKEEPER_QUORUM), conf.getInt(HConstants.ZOOKEEPER_CLIENT_PORT, HConstants.DEFAULT_ZOOKEPER_CLIENT_PORT), kiji.getName(), mTable.getName())); job.setOutputFormatClass(NullOutputFormat.class); conf.setClass( KijiConfKeys.KIJI_TABLE_CONTEXT_CLASS, DirectKijiTableWriterContext.class, KijiTableContext.class); job.setNumReduceTasks(mNumReduceTasks); conf.setBoolean("mapred.map.tasks.speculative.execution", false); }
Source:
private static int getUnsignedIntValue(String bits){ int value = 0; int i = 0; for (int j = bits.length() - 1; j >= 0; j--, i++) { if (bits.charAt(j) == '1') { value += (int) Math.pow(2.0, (double) i); } } return value; }

Target:
private static int getUnsignedIntValue(String bits){ int value = 0; int i = 0; for (int j = bits.length() - 1; j >= 0; j--, i++) { if (bits.charAt(j) == '1') { value += 1 << i; } } return value; }
Source:
public void checkWebJavaPetclinicProjectCommands() { projectExplorer.openItemByPath(WEB_JAVA_PETCLINIC); consoles.executeCommandFromProcessesArea( "db", COMMON_GOAL, "show databases", "information_schema"); consoles.executeCommandFromProcessesArea( "dev-machine", COMMON_GOAL, BUILD_COMMAND, BUILD_SUCCESS); consoles.executeCommandFromProcessesArea( "dev-machine", BUILD_GOAL, BUILD_COMMAND_ITEM.getItem(WEB_JAVA_PETCLINIC), BUILD_SUCCESS); consoles.executeCommandFromProcessesArea( "dev-machine", RUN_GOAL, BUILD_AND_DEPLOY_COMMAND_ITEM.getItem(WEB_JAVA_PETCLINIC), "Server startup in"); consoles.checkWebElementVisibilityAtPreviewPage(By.xpath(" projectExplorer.invokeCommandWithContextMenu( RUN_GOAL, WEB_JAVA_PETCLINIC, STOP_TOMCAT_COMMAND_ITEM.getItem(WEB_JAVA_PETCLINIC), "dev-machine"); consoles.selectProcessInProcessConsoleTreeByName("Terminal"); terminal.typeIntoTerminal("ps ax"); terminal.typeIntoTerminal(ENTER.toString()); terminal.waitExpectedTextNotPresentTerminal("$TOMCAT_HOME/bin/catalina.sh"); consoles.executeCommandFromProcessesArea( "dev-machine", DEBUG_GOAL, DEBUG_COMMAND_ITEM.getItem(WEB_JAVA_PETCLINIC), LISTENING_AT_ADDRESS_8000); }

Target:
public void checkWebJavaPetclinicProjectCommands() { By textOnPreviewPage = By.xpath(" String tomcatIsRunning = "$TOMCAT_HOME/bin/catalina.sh"; projectExplorer.openItemByPath(WEB_JAVA_PROJECT); consoles.executeCommandFromProcessesArea( DB_MACHINE_NAME, COMMON_GOAL, "show databases", "information_schema"); consoles.executeCommandFromProcessesArea( DEV_MACHINE_NAME, COMMON_GOAL, BUILD_COMMAND, BUILD_SUCCESS); consoles.executeCommandFromProcessesArea( DEV_MACHINE_NAME, BUILD_GOAL, BUILD_COMMAND_ITEM.getItem(WEB_JAVA_PROJECT), BUILD_SUCCESS); consoles.executeCommandFromProcessesArea( DEV_MACHINE_NAME, RUN_GOAL, BUILD_AND_DEPLOY_COMMAND_ITEM.getItem(WEB_JAVA_PROJECT), "Server startup in"); consoles.checkWebElementVisibilityAtPreviewPage(textOnPreviewPage); projectExplorer.invokeCommandWithContextMenu( RUN_GOAL, WEB_JAVA_PROJECT, STOP_TOMCAT_COMMAND_ITEM.getItem(WEB_JAVA_PROJECT), DEV_MACHINE_NAME); consoles.selectProcessInProcessConsoleTreeByName("Terminal"); terminal.typeIntoTerminal("ps ax"); terminal.typeIntoTerminal(ENTER.toString()); terminal.waitExpectedTextNotPresentTerminal(tomcatIsRunning); consoles.executeCommandFromProcessesArea( DEV_MACHINE_NAME, DEBUG_GOAL, DEBUG_COMMAND_ITEM.getItem(WEB_JAVA_PROJECT), LISTENING_AT_ADDRESS_8000); }
Source:
public void processOnVmStop(Collection<Guid> vmIds) { for (final Guid vmId : vmIds) { log.infoFormat("process VM {0} that went down", vmId); ThreadPoolUtil.execute(new Runnable() { @Override public void run() { Backend.getInstance().runInternalAction(VdcActionType.ProcessDownVm, new IdParameters(vmId), ExecutionHandler.createInternalJobContext()); } }); } }

Target:
public void processOnVmStop(Collection<Guid> vmIds) { for (final Guid vmId : vmIds) { ThreadPoolUtil.execute(new Runnable() { @Override public void run() { Backend.getInstance().runInternalAction(VdcActionType.ProcessDownVm, new IdParameters(vmId)); } }); } }
Source:
private void handleEvent(SiteNode parent, SiteNode node, EventType eventType) { switch (eventType) { case ADD: publishEvent(SiteMapEventPublisher.SITE_NODE_ADDED_EVENT, node); if (parent == getRoot()) { publishEvent(SiteMapEventPublisher.SITE_ADDED_EVENT, node); } break; case REMOVE: publishEvent(SiteMapEventPublisher.SITE_NODE_REMOVED_EVENT, node); if(parent == getRoot()) { publishEvent(SiteMapEventPublisher.SITE_REMOVED_EVENT, node); System.out.println("Site - Remove"); } } }

Target:
private void handleEvent(SiteNode parent, SiteNode node, EventType eventType) { switch (eventType) { case ADD: publishEvent(SiteMapEventPublisher.SITE_NODE_ADDED_EVENT, node); if (parent == getRoot()) { publishEvent(SiteMapEventPublisher.SITE_ADDED_EVENT, node); } break; case REMOVE: publishEvent(SiteMapEventPublisher.SITE_NODE_REMOVED_EVENT, node); if(parent == getRoot()) { publishEvent(SiteMapEventPublisher.SITE_REMOVED_EVENT, node); } } }
Source:
public static DumpWriter makePredicateDumpWriter(final DumpWriter successorWriter, final PredicatePageFilter filter) { return new ChainingDumpWriter(successorWriter) { boolean showThisPage = true; public void writeStartPage(Page page) throws IOException { showThisPage = filter.test(page); if (showThisPage) writer.writeStartPage(page); } public void writeEndPage() throws IOException { if (showThisPage) writer.writeEndPage(); } public void writeRevision(Revision revision) throws IOException { if (showThisPage) writer.writeRevision(revision); } }; }

Target:
public static DumpWriter makePredicateDumpWriter(final DumpWriter successorWriter, final PredicatePageFilter filter) { return new ChainingDumpWriter(successorWriter) { boolean showThisPage = true; public void writeStartPage(Page page) throws IOException { showThisPage = filter.test(page); if (showThisPage) { writer.writeStartPage(page); } } public void writeEndPage() throws IOException { if (showThisPage) { writer.writeEndPage(); } } public void writeRevision(Revision revision) throws IOException { if (showThisPage) { writer.writeRevision(revision); } } }; }
Source:
public MeasureSpecRenderer() { super("Android MeasureSpec.toString"); }

Target:
public MeasureSpecRenderer() { super("Android MeasureSpec"); }
Source:
public void activate(ComponentContext context) { typeRegistry = new TypeRegistry(); recomputeCallback = () -> typeRegistry.recomputeTypes(); SchemaManagerImpl schemaManager = (SchemaManagerImpl)Framework.getService(SchemaManager.class); schemaManager.registerRecomputeCallback(recomputeCallback); }

Target:
public void activate(ComponentContext context) { typeRegistry = new TypeRegistry(); recomputeCallback = typeRegistry::recomputeTypes; SchemaManagerImpl schemaManager = (SchemaManagerImpl) Framework.getService(SchemaManager.class); schemaManager.registerRecomputeCallback(recomputeCallback); }
Source:
public ActionResult execute() { String blobKey = getNonNullRequestParamValue(Const.ParamsNames.BLOB_KEY); log.info("blob-key given: " + blobKey); return new ImageResult(blobKey); }

Target:
public ActionResult execute() { String blobKey = getNonNullRequestParamValue(Const.ParamsNames.BLOB_KEY); return new ImageResult(blobKey); }
Source:
private void updateData(@NonNull TimeQueryFilter filters, IProgressMonitor monitor) { try (FlowScopeLog scope = new FlowScopeLogBuilder(LOGGER, Level.FINE, "CommonXLineChart:updateData", "numRequests=", fNumRequests).setParentScope(fScope).build()) { ITmfXYDataProvider dataProvider = fXYDataProvider[0]; if (dataProvider == null) { TraceCompassLogUtils.traceInstant(LOGGER, Level.WARNING, "Data provider for this viewer is not available"); return; } boolean isComplete = false; do { try (FlowScopeLog scopeDp = new FlowScopeLogBuilder(LOGGER, Level.FINE, dataProvider.getClass().getName() + ":fetchXY").setParentScope(fScope).build()) { TmfModelResponse<ITmfCommonXAxisModel> response = dataProvider.fetchXY(filters, monitor); ITmfCommonXAxisModel model = response.getModel(); if (model != null) { updateDisplay(model, monitor); } ITmfResponse.Status status = response.getStatus(); if (status == ITmfResponse.Status.COMPLETED) { isComplete = true; } else if (status == ITmfResponse.Status.FAILED || status == ITmfResponse.Status.CANCELLED) { TraceCompassLogUtils.traceInstant(LOGGER, Level.WARNING, response.getStatusMessage()); isComplete = true; } else { try { Thread.sleep(BUILD_UPDATE_TIMEOUT); } catch (InterruptedException e) { TraceCompassLogUtils.traceInstant(LOGGER, Level.INFO, e.getMessage()); } } } } while (!isComplete); } }

Target:
private void updateData(@NonNull TimeQueryFilter filters, IProgressMonitor monitor) { try (FlowScopeLog scope = new FlowScopeLogBuilder(LOGGER, Level.FINE, "CommonXLineChart:updateData", "numRequests=", fNumRequests).setParentScope(fScope).build()) { ITmfXYDataProvider dataProvider = fXYDataProvider[0]; if (dataProvider == null) { TraceCompassLogUtils.traceInstant(LOGGER, Level.WARNING, "Data provider for this viewer is not available"); return; } boolean isComplete = false; do { try (FlowScopeLog scopeDp = new FlowScopeLogBuilder(LOGGER, Level.FINER, dataProvider.getClass().getName() + ":fetchXY").setParentScope(fScope).build()) { TmfModelResponse<ITmfCommonXAxisModel> response = dataProvider.fetchXY(filters, monitor); ITmfCommonXAxisModel model = response.getModel(); if (model != null) { updateDisplay(model, monitor); } ITmfResponse.Status status = response.getStatus(); if (status == ITmfResponse.Status.COMPLETED) { isComplete = true; } else if (status == ITmfResponse.Status.FAILED || status == ITmfResponse.Status.CANCELLED) { TraceCompassLogUtils.traceInstant(LOGGER, Level.WARNING, response.getStatusMessage()); isComplete = true; } else { try { Thread.sleep(BUILD_UPDATE_TIMEOUT); } catch (InterruptedException e) { TraceCompassLogUtils.traceInstant(LOGGER, Level.INFO, e.getMessage()); } } } } while (!isComplete); } }
Source:
public void call(final Subscriber<? super T> subscriber) { subscriber.setProducer(new Producer() { @Override public void request(long n) { if (selection.choice.get() != null) { selection.choice.get().requestMore(n); } for (Observable<? extends T> source : sources) { if (subscriber.isUnsubscribed()) { break; } if (selection.choice.get() != null) { break; } AmbSubscriber<T> ambSubscriber = new AmbSubscriber<T>(n, subscriber, selection); selection.ambSubscribers.add(ambSubscriber); subscriber.add(ambSubscriber); source.unsafeSubscribe(ambSubscriber); } } }); }

Target:
public void call(final Subscriber<? super T> subscriber) { subscriber.add(Subscriptions.create(new Action0() { @Override public void call() { if (selection.choice.get() != null) { selection.choice.get().unsubscribe(); } if(!selection.ambSubscribers.isEmpty()) { for (AmbSubscriber<T> other : selection.ambSubscribers) { other.unsubscribe(); } selection.ambSubscribers.clear(); } } })); subscriber.setProducer(new Producer() { @Override public void request(long n) { if (selection.choice.get() != null) { selection.choice.get().requestMore(n); } else { for (Observable<? extends T> source : sources) { if (subscriber.isUnsubscribed()) { break; } AmbSubscriber<T> ambSubscriber = new AmbSubscriber<T>(n, subscriber, selection); selection.ambSubscribers.add(ambSubscriber); if (selection.choice.get() != null) { selection.unsubscribeOthers(selection.choice.get()); break; } source.unsafeSubscribe(ambSubscriber); } } } }); }
Source:
public void assertChangedResources(String[] expected) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); for (String file : expected) assertTrue(changedResources.contains(root.findMember(file))); assertTrue(changedResources.size() == expected.length); }

Target:
public void assertChangedResources(String[] expected) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); for (String file : expected) assertThat(changedResources, hasItem(root.findMember(file))); assertEquals(changedResources.size(), expected.length); }