auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void setup() { mockSystemProducer = new MockCoordinatorStreamSystemFactory.MockSystemProducer("source"); ScheduledExecutorService mockExecutorService = Mockito.mock(ScheduledExecutorService.class); Mockito.when(mockExecutorService.scheduleWithFixedDelay(Mockito.argThat(new ArgumentMatcher<Runnable>() { @Override public boolean matches(Object argument) { Runnable runnable = (Runnable) argument; try { runnable.run(); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } return true; } }), Mockito.anyLong(), Mockito.anyLong(), Mockito.eq(TimeUnit.SECONDS))) .thenReturn(Mockito.mock(ScheduledFuture.class)); this.diagnosticsManager = new DiagnosticsManager(jobName, jobId, containerModels, containerMb, containerNumCores, numStoresWithChangelog, "0", executionEnvContainerId, taskClassVersion, samzaVersion, hostname, diagnosticsSystemStream, mockSystemProducer, Duration.ofSeconds(1), mockExecutorService); }

Target:
public void setup() { mockSystemProducer = new MockSystemProducer(); ScheduledExecutorService mockExecutorService = Mockito.mock(ScheduledExecutorService.class); Mockito.when(mockExecutorService.scheduleWithFixedDelay(Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.eq(TimeUnit.SECONDS))).thenAnswer(invocation -> { ((Runnable) invocation.getArguments()[0]).run(); return Mockito.mock(ScheduledFuture.class); }); this.diagnosticsManager = new DiagnosticsManager(jobName, jobId, containerModels, containerMb, containerNumCores, numStoresWithChangelog, "0", executionEnvContainerId, taskClassVersion, samzaVersion, hostname, diagnosticsSystemStream, mockSystemProducer, Duration.ofSeconds(1), mockExecutorService); exceptionEventList.forEach( diagnosticsExceptionEvent -> this.diagnosticsManager.addExceptionEvent(diagnosticsExceptionEvent)); this.diagnosticsManager.addProcessorStopEvent("0", executionEnvContainerId, hostname, 101); }
Source:
public void dispose() { if (fTableViewer != null) { fTableViewer.getTable().dispose(); } if (fTablePopupMenuManager != null) { fTablePopupMenuManager.dispose(); } super.dispose(); }

Target:
public void dispose() { if (fTableViewer != null) { fTableViewer.getControl().dispose(); } if (fTablePopupMenuManager != null) { fTablePopupMenuManager.dispose(); } super.dispose(); }
Source:
public Tenant getTenantByDomain(String domain) throws TenantMgtException { TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager(); Tenant tenant; try { int tenantID = tenantManager.getTenantId(domain); tenant = (Tenant) tenantManager.getTenant(tenantID); if (tenant == null) { throw new TenantManagementClientException(ERROR_CODE_DOMAIN_NOT_FOUND.getCode(), String.format(ERROR_CODE_DOMAIN_NOT_FOUND.getMessage(), domain)); } } catch (org.wso2.carbon.user.api.UserStoreException e) { throw new TenantManagementServerException("Error while getting the tenant.", e); } return tenant; }

Target:
public Tenant getTenantByDomain(String domain) throws TenantMgtException { TenantManager tenantManager = TenantMgtServiceComponent.getTenantManager(); Tenant tenant; try { int tenantID = tenantManager.getTenantId(domain); tenant = (Tenant) tenantManager.getTenant(tenantID); if (tenant == null) { throw new TenantManagementClientException(ERROR_CODE_DOMAIN_NOT_FOUND.getCode(), String.format(ERROR_CODE_DOMAIN_NOT_FOUND.getMessage(), domain)); } } catch (org.wso2.carbon.user.api.UserStoreException e) { throw new TenantManagementServerException("Error while getting the tenant - " + domain, e); } return tenant; }
Source:
public void headers() throws Exception { WebClient wc = r.createWebClient() .withThrowExceptionOnFailingStatusCode(false); r.getInstance().setSlaveAgentPort(-1); Page p = wc.goTo("tcpSlaveAgentListener"); assertThat(p.getWebResponse().getStatusCode(), equalTo(404)); r.getInstance().setSlaveAgentPort(0); p = wc.goTo("tcpSlaveAgentListener", "text/plain"); assertThat(p.getWebResponse().getStatusCode(), equalTo(200)); assertThat(p.getWebResponse().getResponseHeaderValue("X-Instance-Identity"), notNullValue()); }

Target:
public void headers() throws Exception { WebClient wc = r.createWebClient() .withThrowExceptionOnFailingStatusCode(false); r.getInstance().setSlaveAgentPort(-1); wc.assertFails("tcpSlaveAgentListener", HttpURLConnection.HTTP_NOT_FOUND); r.getInstance().setSlaveAgentPort(0); Page p = wc.goTo("tcpSlaveAgentListener", "text/plain"); assertEquals(HttpURLConnection.HTTP_OK, p.getWebResponse().getStatusCode()); assertThat(p.getWebResponse().getResponseHeaderValue("X-Instance-Identity"), notNullValue()); }
Source:
private String loadVersion() { String version = "unknown"; try { Class clz = getClass(); String className = clz.getSimpleName() + ".class"; String classPath = clz.getResource(className).toString(); if (classPath.startsWith("jar")) { String manifestPath = classPath.substring(0, classPath.lastIndexOf('!') + 1) + "/META-INF/MANIFEST.MF"; Manifest manifest = new Manifest(new URL(manifestPath).openStream()); Attributes attributes = manifest.getMainAttributes(); String value = attributes.getValue("Implementation-Version"); if (StringUtils.hasText(value)) { version = value; } } } catch (Exception e) { System.out.println("Could not determine version of Spring XD via manifest"); e.printStackTrace(); } return version; }

Target:
private String loadVersion() { String version = "unknown"; try { Class clz = getClass(); String className = clz.getSimpleName() + ".class"; String classPath = clz.getResource(className).toString(); if (classPath.startsWith("jar")) { String manifestPath = classPath.substring(0, classPath.lastIndexOf('!') + 1) + "/META-INF/MANIFEST.MF"; Manifest manifest = new Manifest(new URL(manifestPath).openStream()); Attributes attributes = manifest.getMainAttributes(); String value = attributes.getValue("Implementation-Version"); if (StringUtils.hasText(value)) { version = value.replaceAll("BUILD-SNAPSHOT", "SNAP").replaceAll("-RELEASE", ""); } } } catch (Exception e) { System.out.println("Could not determine version of Spring XD via manifest"); e.printStackTrace(); } return version; }
Source:
wbFromDMN(final String description) { if (description == null) { return new Description(""); } else { return new Description(description); } }

Target:
public static Description wbFromDMN(final String description) { if (description == null) { return new Description(""); } else { return new Description(description); } }
Source:
private static Iterable<HivePartitionMetadata> createPartitionMetadataWithOfflinePartitions() throws RuntimeException { return new Iterable<HivePartitionMetadata>() { @Override public Iterator<HivePartitionMetadata> iterator() { return new AbstractIterator<HivePartitionMetadata>() { private int position; private List<HivePartitionMetadata> hivePartitionMetadatas = ImmutableList.of( new HivePartitionMetadata( new HivePartition(new SchemaTableName("testSchema", "table_name"), ImmutableList.of()), Optional.empty(), ImmutableMap.of()), new HivePartitionMetadata( new HivePartition(new SchemaTableName("schemaWithOfflinePartitions", "table_name"), ImmutableList.of()), Optional.empty(), ImmutableMap.of())); protected HivePartitionMetadata computeNext() { if (hivePartitionMetadatas.get(position).getHivePartition().getTableName().getSchemaName().equalsIgnoreCase("schemaWithOfflinePartitions")) { throw new RuntimeException("OFFLINE"); } position++; if (position < hivePartitionMetadatas.size()) { return hivePartitionMetadatas.get(position); } return endOfData(); } }; } }; }

Target:
private static Iterable<HivePartitionMetadata> createPartitionMetadataWithOfflinePartitions() throws RuntimeException { return () -> new AbstractIterator<HivePartitionMetadata>() { private int position = -1; @Override protected HivePartitionMetadata computeNext() { position++; switch (position) { case 0: return new HivePartitionMetadata( new HivePartition(new SchemaTableName("testSchema", "table_name"), ImmutableList.of()), Optional.empty(), ImmutableMap.of()); case 1: throw new RuntimeException("OFFLINE"); default: return endOfData(); } } }; }
Source:
private boolean containsAnyParent(TreeItem item, Collection<TreeItem> items) { TreeItem parent = item.getParentItem(); while (parent != null) { if (items.contains(parent)) { return true; } parent = item.getParentItem(); } return false; }

Target:
private boolean containsAnyParent(TreeItem item, Collection<TreeItem> items) { TreeItem parent = item.getParentItem(); while (parent != null) { if (items.contains(parent)) { return true; } parent = parent.getParentItem(); } return false; }
Source:
public static void setRegion(final String region) { Twilio.region = region; }

Target:
public static void setRegion(final String region) { if (!region.equals(Twilio.region)) { Twilio.invalidate(); } Twilio.region = region; }
Source:
private Tag next() throws LimitExceededException{ if (iterator != null) { while (iterator.hasNext()) { final Tag tag = iterator.next(); if (Verbs.isVerb(tag)) { if (current != null && current.hasChildren()) { final List<Tag> children = current.children(); if (children.contains(tag)) { continue; } } if (tag.name().equals("Gather") && tag.hasAttribute(GatherAttributes.ATTRIBUTE_HINTS) && !StringUtils.isEmpty(tag.attribute(GatherAttributes.ATTRIBUTE_HINTS).value())) { String hotWords = tag.attribute(GatherAttributes.ATTRIBUTE_HINTS).value(); List<String> hintList = Arrays.asList(hotWords.split(",")); if (hintList.size() > 50) { throw new LimitExceededException("HotWords limit exceeded. There are more than 50 phrases"); } for (String hint : hintList) { if (hint.length() > 100) { throw new LimitExceededException("HotWords limit exceeded. Hint with more than 100 characters found"); } } } current = tag; return current; } } } else { if(logger.isInfoEnabled()){ logger.info("iterator is null"); } } return null; }

Target:
private Tag next() throws LimitExceededException{ if (iterator != null) { while (iterator.hasNext()) { final Tag tag = iterator.next(); if (Verbs.isVerb(tag)) { if (current != null && current.hasChildren()) { final List<Tag> children = current.children(); if (children.contains(tag)) { continue; } } if (tag.name().equals(Verbs.gather) && tag.hasAttribute(GatherAttributes.ATTRIBUTE_HINTS) && !StringUtils.isEmpty(tag.attribute(GatherAttributes.ATTRIBUTE_HINTS).value())) { String hotWords = tag.attribute(GatherAttributes.ATTRIBUTE_HINTS).value(); List<String> hintList = Arrays.asList(hotWords.split(",")); if (hintList.size() > 50) { throw new LimitExceededException("HotWords limit exceeded. There are more than 50 phrases"); } for (String hint : hintList) { if (hint.length() > 100) { throw new LimitExceededException("HotWords limit exceeded. Hint with more than 100 characters found"); } } } current = tag; return current; } } } else { if(logger.isInfoEnabled()){ logger.info("iterator is null"); } } return null; }
Source:
public ModelAndView newStudy(ModelMap model) throws IOException { User user = securityManager.getUserByLoginName(SecurityContextHolder.getContext().getAuthentication().getName()); Study study = new StudyImpl(user); authorizationManager.throwIfNotWritable(study); return setupForm(study, user, "New Study", model); }

Target:
public ModelAndView newStudy(ModelMap model) throws IOException { User user = authorizationManager.getCurrentUser(); Study study = new StudyImpl(user); authorizationManager.throwIfNotWritable(study); return setupForm(study, user, "New Study", model); }
Source:
public void stop(BundleContext context_p) throws Exception { __plugin = null; if(_adapterFactory != null) _adapterFactory.dispose(); super.stop(context_p); }

Target:
public void stop(BundleContext context_p) throws Exception { __plugin = null; if(_adapterFactory != null){ _adapterFactory.dispose(); _adapterFactory = null; } super.stop(context_p); }
Source:
public String getPropertiesAsJson(String namespace) { Map<String, String> props = getProperties(namespace); List<String> sortedKeys = props.keySet().stream().sorted().collect(Collectors.toList()); StringBuilder sb = new StringBuilder("{\n"); for (int i = 0; i < sortedKeys.size(); i++) { String key = sortedKeys.get(i); sb.append('\t').append('"').append(key).append("\": \"").append(props.get(key)).append('"'); if (i < sortedKeys.size() - 1) { sb.append(','); } sb.append('\n'); } sb.append('}'); return sb.toString(); }

Target:
public String getPropertiesAsJson(String namespace) throws IOException { return mapper.writeValueAsString(getProperties(namespace)); }
Source:
private IStorageModel preparePosixStorageForEdit(StorageDomain storage) { final PosixStorageModel model = getPosixModelByStorage(storage); model.setRole(storage.getStorageDomainType()); boolean isPathEditable = isPathEditable(storage); model.getPath().setIsChangable(isPathEditable); if (model.getType().equals(StorageType.POSIXFS)) { model.getVfsType().setIsChangable(isPathEditable); } else { model.getVfsType().setIsChangable(false); } model.getMountOptions().setIsChangable(isPathEditable); AsyncDataProvider.getInstance().getStorageConnectionById(new AsyncQuery(null, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { StorageServerConnections connection = (StorageServerConnections) returnValue; model.getPath().setEntity(connection.getconnection()); model.getVfsType().setEntity(connection.getVfsType()); model.getMountOptions().setEntity(connection.getMountOptions()); } }), storage.getStorage(), true); return model; }

Target:
private IStorageModel preparePosixStorageForEdit(StorageDomain storage) { final PosixStorageModel model = getPosixModelByStorage(storage); model.setRole(storage.getStorageDomainType()); boolean isPathEditable = isPathEditable(storage); model.getPath().setIsChangable(isPathEditable); model.setVfsChangeability(isPathEditable); model.getMountOptions().setIsChangable(isPathEditable); AsyncDataProvider.getInstance().getStorageConnectionById(new AsyncQuery(null, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { StorageServerConnections connection = (StorageServerConnections) returnValue; model.getPath().setEntity(connection.getconnection()); model.getVfsType().setEntity(connection.getVfsType()); model.getMountOptions().setEntity(connection.getMountOptions()); } }), storage.getStorage(), true); return model; }
Source:
void resumeCompaction() throws InterruptedException, IOException, StoreException { if (srcIndex == null) { throw new IllegalStateException("Compactor has not been started"); } else if (compactionLog == null) { throw new IllegalStateException("There is no compaction to resume"); } runningLatch = new CountDownLatch(1); while (isActive && !compactionLog.getCompactionPhase().equals(CompactionLog.Phase.DONE)) { CompactionLog.Phase phase = compactionLog.getCompactionPhase(); switch (phase) { case PREPARE: compactionLog.markCopyStart(); case COPY: copy(); if (isActive) { compactionLog.markCommitStart(); commit(false); compactionLog.markCleanupStart(); waitTillRefCountZero(); cleanup(false); compactionLog.markCycleComplete(); } break; default: throw new IllegalStateException("Illegal compaction phase: " + phase); } } endCompaction(); runningLatch.countDown(); }

Target:
void resumeCompaction() throws StoreException { if (srcIndex == null) { throw new IllegalStateException("Compactor has not been initialized"); } else if (compactionLog == null) { throw new IllegalStateException("There is no compaction to resume"); } runningLatch = new CountDownLatch(1); try { while (isActive && !compactionLog.getCompactionPhase().equals(CompactionLog.Phase.DONE)) { CompactionLog.Phase phase = compactionLog.getCompactionPhase(); switch (phase) { case PREPARE: compactionLog.markCopyStart(); case COPY: copy(); if (isActive) { compactionLog.markCommitStart(); commit(false); compactionLog.markCleanupStart(); waitTillRefCountZero(); cleanup(false); compactionLog.markCycleComplete(); } break; default: throw new IllegalStateException("Illegal compaction phase: " + phase); } } endCompaction(); } catch (InterruptedException | IOException e) { throw new StoreException("Exception during compaction", e, StoreErrorCodes.Unknown_Error); } finally { runningLatch.countDown(); } }
Source:
public static Block mask(Block sourceBlock, int[] ids) { if (sourceBlock instanceof DictionaryBlock) { DictionaryBlock dictionaryBlock = (DictionaryBlock) sourceBlock; int[] directIds = new int[ids.length]; for (int i = 0; i < ids.length; i++) { directIds[i] = dictionaryBlock.getId(ids[i]); } ids = directIds; sourceBlock = dictionaryBlock.getDictionary(); } return new DictionaryBlock(ids.length, sourceBlock, ids); }

Target:
public static Block mask(Block sourceBlock, int[] ids) { if (sourceBlock instanceof DictionaryBlock) { DictionaryBlock dictionaryBlock = (DictionaryBlock) sourceBlock; int[] directIds = new int[ids.length]; for (int i = 0; i < ids.length; i++) { directIds[i] = dictionaryBlock.getId(ids[i]); } return new DictionaryBlock(directIds.length, dictionaryBlock.getDictionary(), directIds); } return new DictionaryBlock(ids.length, sourceBlock, ids); }
Source:
protected boolean set(final VanishableBridge dataHolder, final Map<Key<?>, Object> keyValues) { if (dataHolder instanceof Entity && ((Entity) dataHolder).world.isRemote) { return false; } final boolean invis = (Boolean) keyValues.get(Keys.INVISIBLE); final boolean collision = (Boolean) keyValues.get(Keys.VANISH_IGNORES_COLLISION); final boolean untargetable = (Boolean) keyValues.get(Keys.VANISH_PREVENTS_TARGETING); final boolean vanish = (Boolean) keyValues.get(Keys.VANISH); dataHolder.bridge$setInvisible(invis); dataHolder.bridge$setVanished(vanish); dataHolder.bridge$setUncollideable(collision); dataHolder.bridge$setUntargetable(untargetable); return true; }

Target:
protected boolean set(final VanishableBridge dataHolder, final Map<Key<?>, Object> keyValues) { if (dataHolder instanceof Entity && ((Entity) dataHolder).world.isRemote) { return false; } final boolean invis = (Boolean) keyValues.get(Keys.INVISIBLE); final boolean collision = (Boolean) keyValues.get(Keys.VANISH_IGNORES_COLLISION); final boolean untargetable = (Boolean) keyValues.get(Keys.VANISH_PREVENTS_TARGETING); final boolean vanish = (Boolean) keyValues.get(Keys.VANISH); dataHolder.bridge$setInvisible(invis); dataHolder.bridge$setVanished(vanish); dataHolder.bridge$setUncollideable(vanish && collision); dataHolder.bridge$setUntargetable(vanish && untargetable); return true; }
Source:
public void close() { try { mCompressedStream.close(); } catch (IOException ioe) { throw(new RuntimeIOException("Close error in CSI compressed stream: " + ioe)); } }

Target:
public void close() { if (mCompressedStream == null) { throw new SAMException("Null input stream."); } try { mCompressedStream.close(); } catch (IOException ioe) { throw(new RuntimeIOException("Close error in CSI compressed stream: " + ioe)); } }
Source:
private boolean isJsonLdMIME(Request request) { String accept = request.getHttpRequest().getHeader(HttpHeaders.ACCEPT); if (accept != null && accept.contains(JSONLDGetFeatureResponse.MIME)) return true; else if (request.getKvp().get("f") != null && request.getKvp().get("f").equals(JSONLDGetFeatureResponse.MIME)) return true; else return false; }

Target:
private boolean isJsonLdMIME(Request request) { String accept = request.getHttpRequest().getHeader(HttpHeaders.ACCEPT); if (request.getKvp().get("f") != null && request.getKvp().get("f").equals(JSONLDGetFeatureResponse.MIME)) return true; else if (accept != null && accept.contains(JSONLDGetFeatureResponse.MIME)) return true; else return false; }
Source:
private void traverseStacks(Stacks stacks, ArrayList<DownloadRuntime> list, IProgressMonitor monitor) { List<org.jboss.jdf.stacks.model.Runtime> runtimes = stacks.getAvailableRuntimes(); Iterator<org.jboss.jdf.stacks.model.Runtime> i = runtimes.iterator(); org.jboss.jdf.stacks.model.Runtime workingRT = null; monitor.beginTask(Messages.CreateDownloadRuntimes, runtimes.size() * 100); while(i.hasNext()) { workingRT = i.next(); String wtpRT = workingRT.getLabels().getProperty(LABEL_WTP_RUNTIME); String dlUrl = workingRT.getDownloadUrl(); if( wtpRT != null ) { String fileSize = workingRT.getLabels().getProperty(LABEL_FILE_SIZE); String license = workingRT.getLicense(); String id = workingRT.getId(); String legacyId = getLegacyId(id); String effectiveId = legacyId == null ? id : legacyId; String name = workingRT.getName(); String version = workingRT.getVersion(); DownloadRuntime dr = new DownloadRuntime(effectiveId, name, version, dlUrl); dr.setHumanUrl(workingRT.getUrl()); dr.setLicenseURL(license); dr.setSize(fileSize); dr.setProperty(PROP_WTP_RUNTIME, wtpRT); dr.setProperty(LABEL_RUNTIME_CATEGORY, workingRT.getLabels().getProperty(LABEL_RUNTIME_CATEGORY)); dr.setProperty(LABEL_RUNTIME_TYPE, workingRT.getLabels().getProperty(LABEL_RUNTIME_TYPE)); if( legacyId != null ) dr.setProperty(DownloadRuntime.PROPERTY_ALTERNATE_ID, id); list.add(dr); } monitor.worked(100); } monitor.done(); }

Target:
private void traverseStacks(Stacks stacks, ArrayList<DownloadRuntime> list, IProgressMonitor monitor) { List<org.jboss.jdf.stacks.model.Runtime> runtimes = stacks.getAvailableRuntimes(); Iterator<org.jboss.jdf.stacks.model.Runtime> i = runtimes.iterator(); org.jboss.jdf.stacks.model.Runtime workingRT = null; monitor.beginTask(Messages.CreateDownloadRuntimes, runtimes.size() * 100); while(i.hasNext()) { workingRT = i.next(); String wtpRT = workingRT.getLabels().getProperty(LABEL_WTP_RUNTIME); if( wtpRT != null ) { String fileSize = workingRT.getLabels().getProperty(LABEL_FILE_SIZE); String license = workingRT.getLicense(); String dlUrl = workingRT.getDownloadUrl(); String id = workingRT.getId(); String legacyId = getLegacyId(id); String effectiveId = legacyId == null ? id : legacyId; String name = workingRT.getName(); String version = workingRT.getVersion(); DownloadRuntime dr = new DownloadRuntime(effectiveId, name, version, dlUrl); dr.setHumanUrl(workingRT.getUrl()); dr.setLicenseURL(license); dr.setSize(fileSize); dr.setProperty(PROP_WTP_RUNTIME, wtpRT); dr.setProperty(LABEL_RUNTIME_CATEGORY, workingRT.getLabels().getProperty(LABEL_RUNTIME_CATEGORY)); dr.setProperty(LABEL_RUNTIME_TYPE, workingRT.getLabels().getProperty(LABEL_RUNTIME_TYPE)); if( legacyId != null ) dr.setProperty(DownloadRuntime.PROPERTY_ALTERNATE_ID, id); list.add(dr); } monitor.worked(100); } monitor.done(); }
Source:
protected List<ExecutorDetails> orderExecutors( TopologyDetails td, Collection<ExecutorDetails> unassignedExecutors) { Boolean orderByProximity = (Boolean) td.getConf() .getOrDefault(Config.TOPOLOGY_RAS_SCHEDULE_EXECUTORS_BY_PROXIMITY_NEEDS, false); if (!orderByProximity) { return orderExecutorsDefault(td, unassignedExecutors); } else { LOG.info("{} is set to true", Config.TOPOLOGY_RAS_SCHEDULE_EXECUTORS_BY_PROXIMITY_NEEDS); return orderExecutorsByProximityNeeds(td, unassignedExecutors); } }

Target:
protected List<ExecutorDetails> orderExecutors( TopologyDetails td, Collection<ExecutorDetails> unassignedExecutors) { Boolean orderByProximity = ObjectReader.getBoolean( td.getConf().get(Config.TOPOLOGY_RAS_ORDER_EXECUTORS_BY_PROXIMITY_NEEDS), false); if (!orderByProximity) { return orderExecutorsDefault(td, unassignedExecutors); } else { LOG.info("{} is set to true", Config.TOPOLOGY_RAS_ORDER_EXECUTORS_BY_PROXIMITY_NEEDS); return orderExecutorsByProximityNeeds(td, unassignedExecutors); } }
Source:
public void processExpires() { log.debug("Processing expired sessions"); Query<Key> query = Query.newKeyQueryBuilder().setKind(sessionKind) .setFilter(PropertyFilter.le(SessionMetadata.EXPIRATION_TIME.getValue(), System.currentTimeMillis())) .build(); QueryResults<Key> keys = datastore.run(query); Stream<Key> toDelete = Streams.stream(keys) .parallel() .flatMap(key -> Streams.stream(datastore.run(Query.newKeyQueryBuilder() .setKind(sessionKind) .setFilter(PropertyFilter.hasAncestor(newKey(key.getName()))) .build()))); datastore.delete(toDelete.toArray(Key[]::new)); }

Target:
public void processExpires() { log.debug("Processing expired sessions"); Query<Key> query = Query.newKeyQueryBuilder().setKind(sessionKind) .setFilter(PropertyFilter.le(SessionMetadata.EXPIRATION_TIME, clock.millis())) .build(); QueryResults<Key> keys = datastore.run(query); Stream<Key> toDelete = Streams.stream(keys) .parallel() .flatMap(key -> Streams.stream(datastore.run(Query.newKeyQueryBuilder() .setKind(sessionKind) .setFilter(PropertyFilter.hasAncestor(newKey(key.getName()))) .build()))); datastore.delete(toDelete.toArray(Key[]::new)); }
Source:
private static String getObjectName(MemberExpressionTree dme) { if (dme.object() != null) { if (dme.object().is(Tree.Kind.DOT_MEMBER_EXPRESSION)) { DotMemberExpressionTree d2 = (DotMemberExpressionTree) dme.object(); return d2.property().name(); } else { return CheckUtils.asString(dme.object()); } } return ""; }

Target:
private static String getObjectName(MemberExpressionTree dme) { if (dme.object().is(Tree.Kind.DOT_MEMBER_EXPRESSION)) { DotMemberExpressionTree d2 = (DotMemberExpressionTree) dme.object(); return d2.property().name(); } else { return CheckUtils.asString(dme.object()); } }
Source:
public EndpointsByRange build() { Map<Range<Token>, EndpointsForRange> map = Collections.unmodifiableMap( new HashMap<>( Maps.transformValues(this.map, EndpointsForRange.Builder::build))); return new EndpointsByRange(map); }

Target:
public EndpointsByRange build() { return new EndpointsByRange( ImmutableMap.copyOf( Maps.transformValues(this.map, EndpointsForRange.Builder::build))); }
Source:
private static boolean shouldCreateMyHandler(PsiElement element) { if (element instanceof LeafPsiElement) { LeafPsiElement leaf = (LeafPsiElement)element; return leaf.getElementType() == GoTypes.RETURN || leaf.getElementType() == GoTypes.FUNC || isPanicCall(leaf); } else { return false; } }

Target:
private static boolean shouldCreateMyHandler(PsiElement element) { if (element instanceof LeafPsiElement) { LeafPsiElement leaf = (LeafPsiElement)element; return leaf.getElementType() == GoTypes.RETURN || leaf.getElementType() == GoTypes.FUNC || isPanicCall(leaf); } return false; }
Source:
public ResourceGroupStateInfo getStateInfo() { synchronized (root) { return new ResourceGroupStateInfo( id, getState(), DataSize.succinctBytes(softMemoryLimitBytes), DataSize.succinctBytes(cachedMemoryUsageBytes), maxRunningQueries, maxQueuedQueries, runningTimeLimit, queuedTimeLimit, getAggregatedRunningQueriesInfo(), queuedQueries.size() + descendantQueuedQueries, subGroups.values().stream() .map(subGroup -> new ResourceGroupInfo( subGroup.getId(), new DataSize(softMemoryLimitBytes, BYTE), maxRunningQueries, runningTimeLimit, maxQueuedQueries, queuedTimeLimit, getState(), eligibleSubGroups.size(), new DataSize(cachedMemoryUsageBytes, BYTE), runningQueries.size() + descendantRunningQueries, queuedQueries.size() + descendantQueuedQueries)) .collect(toImmutableList())); } }

Target:
public ResourceGroupStateInfo getStateInfo() { synchronized (root) { return new ResourceGroupStateInfo( id, getState(), DataSize.succinctBytes(softMemoryLimitBytes), DataSize.succinctBytes(cachedMemoryUsageBytes), maxRunningQueries, maxQueuedQueries, runningTimeLimit, queuedTimeLimit, getAggregatedRunningQueriesInfo(), queuedQueries.size() + descendantQueuedQueries, subGroups.values().stream() .map(subGroup -> new ResourceGroupInfo( subGroup.getId(), DataSize.succinctBytes(softMemoryLimitBytes), maxRunningQueries, runningTimeLimit, maxQueuedQueries, queuedTimeLimit, getState(), eligibleSubGroups.size(), DataSize.succinctBytes(cachedMemoryUsageBytes), runningQueries.size() + descendantRunningQueries, queuedQueries.size() + descendantQueuedQueries)) .collect(toImmutableList())); } }
Source:
public void ensureColumnPresent(Column<T, ?> column, String headerText, boolean present, String width) { if (present) { if (getColumnIndex(column) == -1) { if (width == null) { addColumnWithHtmlHeader(column, headerText); } else { addColumnWithHtmlHeader(column, headerText, width); } } } else if (!present && getColumnIndex(column) != -1) { removeColumn(column); } }

Target:
public void ensureColumnPresent(Column<T, ?> column, String headerText, boolean present, String width) { boolean columnPresent = getColumnIndex(column) != -1; if (present && !columnPresent) { if (width == null) { addColumnWithHtmlHeader(column, headerText); } else { addColumnWithHtmlHeader(column, headerText, width); } } else if (!present && columnPresent) { removeColumn(column); } }
Source:
public ConsoleProfileFinished(String id, Location location, Profile profile, String title) { this.setId(id); this.setLocation(location); this.setProfile(profile); this.setTitle(title); }

Target:
public ConsoleProfileFinished(String id, Location location, Profile profile, String title) { Objects.requireNonNull(id, "id is require"); Objects.requireNonNull(location, "location is require"); Objects.requireNonNull(profile, "profile is require"); this.id = id; this.location = location; this.profile = profile; this.title = title; }
Source:
public void stop() { if (!state.compareAndSet(State.STARTED, State.STOPPING)) { throw new IllegalStateException(String.format("Expected state [%s] found [%s]", State.STARTED, state.get())); } try { runCallbacks(); } finally { state.compareAndSet(State.STOPPING, State.STOPPED); } }

Target:
public void stop() { if (!state.compareAndSet(State.STARTED, State.STOPPING)) { State current = state.waitForTransition(State.STOPPING, State.STOPPED, SHUTDOWN_WAIT_TIMEOUT); if (current != State.STOPPED) { throw new IllegalStateException(String.format("Expected state [%s] found [%s]", State.STARTED, current)); } return; } try { runCallbacks(); } finally { state.compareAndSet(State.STOPPING, State.STOPPED); } }
Source:
void shouldBeAbleToUpdateRoles(String acceptHeader) { final String username = "test-user"; final String newPassword = "password"; UserDto user = new UserDto(); user.setEnabled(true); user.setUsername(username); user.setPassword(newPassword); user.setSecurityTokenKey("some-security-token"); user.setRoles(ImmutableSet.of(SystemRole.UI_MANAGER.name())); userService.save(user); UserForm admin = buildUser(username, newPassword); User updatedUser = retrieveUserByName(admin.getUsername()); assertThat(SetUtils.isEqualSet(updatedUser.getRoles() .stream() .map(UserRole::getUserRole) .collect(Collectors.toSet()), ImmutableSet.of(SystemRole.UI_MANAGER.name()))).isTrue(); admin.setRoles(ImmutableSet.of("ADMIN")); mockMvc.contentType(MediaType.APPLICATION_JSON_VALUE) .accept(acceptHeader) .body(admin) .when() .put(getContextBaseUrl() + "/{username}", username) .peek() .then() .statusCode(HttpStatus.OK.value()) .body(containsString(SUCCESSFUL_UPDATE_USER)) .extract() .asString(); updatedUser = retrieveUserByName(admin.getUsername()); assertThat(SetUtils.isEqualSet(updatedUser.getRoles() .stream() .map(UserRole::getUserRole) .collect(Collectors.toSet()), ImmutableSet.of("ADMIN"))).isTrue(); admin.setRoles(ImmutableSet.of(SystemRole.UI_MANAGER.name())); mockMvc.contentType(MediaType.APPLICATION_JSON_VALUE) .accept(acceptHeader) .body(admin) .when() .put(getContextBaseUrl() + "/{username}", username) .then() .statusCode(HttpStatus.OK.value()); }

Target:
void shouldBeAbleToUpdateRoles(String acceptHeader) { final String username = "test-user"; final String newPassword = "password"; UserDto user = new UserDto(); user.setEnabled(true); user.setUsername(username); user.setPassword(newPassword); user.setSecurityTokenKey("some-security-token"); user.setRoles(ImmutableSet.of(SystemRole.UI_MANAGER.name())); userService.save(user); UserForm admin = buildUser(username, newPassword); User updatedUser = retrieveUserByName(admin.getUsername()); assertThat(SetUtils.isEqualSet(updatedUser.getRoles() .stream() .map(SecurityRole::getRoleName) .collect(Collectors.toSet()), ImmutableSet.of(SystemRole.UI_MANAGER.name()))).isTrue(); admin.setRoles(ImmutableSet.of("ADMIN")); mockMvc.contentType(MediaType.APPLICATION_JSON_VALUE) .accept(acceptHeader) .body(admin) .when() .put(getContextBaseUrl() + "/{username}", username) .peek() .then() .statusCode(HttpStatus.OK.value()) .body(containsString(SUCCESSFUL_UPDATE_USER)) .extract() .asString(); updatedUser = retrieveUserByName(admin.getUsername()); assertThat(SetUtils.isEqualSet(updatedUser.getRoles() .stream() .map(SecurityRole::getRoleName) .collect(Collectors.toSet()), ImmutableSet.of("ADMIN"))).isTrue(); admin.setRoles(ImmutableSet.of(SystemRole.UI_MANAGER.name())); mockMvc.contentType(MediaType.APPLICATION_JSON_VALUE) .accept(acceptHeader) .body(admin) .when() .put(getContextBaseUrl() + "/{username}", username) .then() .statusCode(HttpStatus.OK.value()); }
Source:
private void validateMetadata(Map<String,List<String>> metadata, String key, String mapping) { BeanPropertyBindingResult errors = new BeanPropertyBindingResult(key, "contentSettings.metadata"); Pattern regex = Pattern.compile("[a-z0-9_]+"); if (StringUtils.isBlank(key) || StringUtils.isBlank(mapping) || !regex.matcher(key).matches()) { errors.reject("3", null, "contentsettings.metadata.invalid"); throw new ValidationGenericException(errors); } for(String value : mapping.split(",")) { if (!regex.matcher(value).matches()) { errors.reject("3", null, "contentsettings.metadata.invalid"); throw new ValidationGenericException(errors); } } if (metadata.containsKey(key)) { errors.reject("4", null, "contentsettings.metadata.duplicate"); throw new ValidationConflictException(errors); } }

Target:
public void validateMetadata(Map<String,List<String>> metadata, String key, String mapping) { BeanPropertyBindingResult errors = new BeanPropertyBindingResult(key, "contentSettings.metadata"); Pattern regex = Pattern.compile("[a-z0-9_]+"); if (StringUtils.isBlank(key) || StringUtils.isBlank(mapping) || !regex.matcher(key).matches()) { errors.reject("3", null, "contentsettings.metadata.invalid"); throw new ValidationGenericException(errors); } for(String value : mapping.split(",")) { if (!regex.matcher(value.trim()).matches()) { errors.reject("3", null, "contentsettings.metadata.invalid"); throw new ValidationGenericException(errors); } } if (metadata.containsKey(key)) { errors.reject("4", null, "contentsettings.metadata.duplicate"); throw new ValidationConflictException(errors); } }
Source:
public void enterIdentifier(SwiftParser.IdentifierContext ctx) { String constantName = ctx.getText(); ParserRuleContext constantDecContext = ConstantDecHelper.getConstantDeclaration(ctx); Location location = ListenerUtil.getContextStartLocation(ctx); if (ConstantDecHelper.isGlobal(constantDecContext) || ConstantDecHelper.insideClass(constantDecContext) || ConstantDecHelper.insideStruct(constantDecContext)) { if (!CharFormatUtil.isUpperCamelCase(constantName) && !CharFormatUtil.startsWithAcronym(constantName) && !CharFormatUtil.isLowerCamelCase(constantName)) { printer.error(Rules.CONSTANT_NAMING, Messages.GLOBAL + Messages.CONSTANT + Messages.GLOBAL_CONSTANT_NAMING, location); } } else { if (!CharFormatUtil.startsWithAcronym(constantName) && !CharFormatUtil.isLowerCamelCase(constantName)) { printer.error(Rules.CONSTANT_NAMING, Messages.CONSTANT + Messages.LOWER_CAMEL_CASE, location); } } }

Target:
public void enterIdentifier(SwiftParser.IdentifierContext ctx) { String constantName = ctx.getText(); ParserRuleContext constantDecContext = ConstantDecHelper.getConstantDeclaration(ctx); Location location = ListenerUtil.getContextStartLocation(ctx); if (ConstantDecHelper.isGlobal(constantDecContext) || ConstantDecHelper.insideClass(constantDecContext) || ConstantDecHelper.insideStruct(constantDecContext)) { if (!CharFormatUtil.isUpperCamelCase(constantName) && !CharFormatUtil.isLowerCamelCaseOrAcronym(constantName)) { printer.error(Rules.CONSTANT_NAMING, Messages.GLOBAL + Messages.CONSTANT + Messages.GLOBAL_CONSTANT_NAMING, location); } } else { if (!CharFormatUtil.isLowerCamelCaseOrAcronym(constantName)) { printer.error(Rules.CONSTANT_NAMING, Messages.CONSTANT + Messages.LOWER_CAMEL_CASE, location); } } }
Source:
public FilePath createTempDir(final String prefix, final String suffix) throws IOException, InterruptedException { try { return new FilePath(this,act(new SecureFileCallable<String>() { private static final long serialVersionUID = 1L; public String invoke(File dir, VirtualChannel channel) throws IOException { File f = File.createTempFile(prefix, suffix, dir); f.delete(); Files.createTempDirectory(f.toPath(), null); return f.getName(); } })); } catch (IOException e) { throw new IOException("Failed to create a temp directory on "+remote,e); } }

Target:
public FilePath createTempDir(final String prefix, final String suffix) throws IOException, InterruptedException { try { return new FilePath(this,act(new SecureFileCallable<String>() { private static final long serialVersionUID = 1L; public String invoke(File dir, VirtualChannel channel) throws IOException { File f = File.createTempFile(prefix, suffix, dir); f.delete(); f.mkdir(); return f.getName(); } })); } catch (IOException e) { throw new IOException("Failed to create a temp directory on "+remote,e); } }
Source:
public void assertPrettyIdentical(String source) { Assertions.assertEquals(new GherkinPrettyFormatter().format(GherkinParser.parse(source)), source); }

Target:
void assertPrettyIdentical(String source) { Messages.GherkinDocument gherkinDocument = GherkinParser.parse(source); Assertions.assertEquals(new GherkinPrettyFormatter().format(gherkinDocument), source); }
Source:
public LogCommand all() throws IOException { Map<String, Ref> refs = getRepository().getRefDatabase().getRefs( Constants.R_REFS); for (Ref ref : refs.values()) { ObjectId objectId = ref.getPeeledObjectId(); if (objectId == null) objectId = ref.getObjectId(); add(objectId); } return this; }

Target:
public LogCommand all() throws IOException { for (Ref ref : getRepository().getAllRefs().values()) { ObjectId objectId = ref.getPeeledObjectId(); if (objectId == null) objectId = ref.getObjectId(); add(objectId); } return this; }
Source:
protected BeanDefinitionBuilder buildBeanDefinition(Element element, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ReactorPublishSubscribeChannel.class); String s = element.getAttribute("dispatcher"); if (!StringUtils.hasText(s)) { builder.addConstructorArgValue(new ReactorProcessorMessageDispatcher()); } else { builder.addConstructorArgReference(s); } return builder; }

Target:
protected BeanDefinitionBuilder buildBeanDefinition(Element element, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ReactorPublishSubscribeChannel.class); String dispatcherBeanName = element.getAttribute("dispatcher"); if (!StringUtils.hasText(dispatcherBeanName)) { builder.addConstructorArgValue(new ReactorProcessorMessageDispatcher()); } else { builder.addConstructorArgReference(dispatcherBeanName); } return builder; }
Source:
public void addChild(TimeGraphEntry entry) { if (!(entry instanceof ResourcesEntry)) { throw new IllegalArgumentException(); } ResourcesEntry rEntry = (ResourcesEntry) entry; int index; for (index = 0; index < getChildren().size(); index++) { ResourcesEntry other = (ResourcesEntry) getChildren().get(index); if (rEntry.compareTo(other) < 0) { break; } } entry.setParent(this); getChildren().add(index, entry); }

Target:
public void addChild(TimeGraphEntry entry) { if (!(entry instanceof ResourcesEntry)) { throw new IllegalArgumentException(); } ResourcesEntry rEntry = (ResourcesEntry) entry; int index; for (index = 0; index < getChildren().size(); index++) { ResourcesEntry other = (ResourcesEntry) getChildren().get(index); if (rEntry.compareTo(other) < 0) { break; } } rEntry.setParent(this); getChildren().add(index, rEntry); }
Source:
public Client createWithDropwizardClient(PaymentGatewayName gateway, GatewayOperation operation, MetricRegistry metricRegistry) { JerseyClientBuilder defaultClientBuilder = new JerseyClientBuilder(environment) .using(new ApacheConnectorProvider()) .using(conf.getClientConfiguration()) .withProperty(READ_TIMEOUT, (int) getReadTimeout(operation, gateway) .orElse(conf.getCustomJerseyClient().getReadTimeout()).toMilliseconds()) .withProperty(CONNECTION_MANAGER, createConnectionManager( gateway.getName(), operation.getConfigKey(), metricRegistry)); if (System.getProperty(PROXY_HOST_PROPERTY) != null && System.getProperty(PROXY_PORT_PROPERTY) != null) { defaultClientBuilder.withProperty(ClientProperties.PROXY_URI, format("http://%s:%s", System.getProperty(PROXY_HOST_PROPERTY), System.getProperty(PROXY_PORT_PROPERTY)) ); } Client client = defaultClientBuilder.build(gateway.getName()); client.register(RestClientLoggingFilter.class); if (conf.isXrayEnabled()) client.register(XRayHttpClientFilter.class); return client; }

Target:
public Client createWithDropwizardClient(PaymentGatewayName gateway, GatewayOperation operation, MetricRegistry metricRegistry) { return createWithDropwizardClient(gateway, getReadTimeout(operation, gateway), operation.getConfigKey(), metricRegistry); }
Source:
public <T> AsyncFuture<T> apply( Function<ClusterNode.Group, AsyncFuture<T>> function, BiFunction<T, List<QueryTrace>, T> handleRetryTraceFn ) { final Iterator<ClusterNode.Group> it = groups.iterator(); if (!it.hasNext()) { return async.failed(new RuntimeException("No groups available")); } final RetryPolicy parent = RetryPolicy.timed(30000, RetryPolicy.exponential(100, 5000)); final RetryPolicy iteratorPolicy = clockSource -> { final RetryPolicy.Instance p = parent.apply(clockSource); return () -> { if (it.hasNext()) { return p.next(); } return new RetryPolicy.Decision(false, 0); }; }; return async .retryUntilResolved(() -> { final ClusterNode.Group next = it.next(); return function.apply(next).catchFailed(throwable -> { reporter.reportClusterNodeRPCError(); throw new RuntimeNodeException(next.toString(), throwable.getMessage(), throwable); }).catchCancelled(ignore -> { reporter.reportClusterNodeRPCCancellation(); throw new RuntimeNodeException(next.toString(), "Operation cancelled"); }); }, iteratorPolicy) .directTransform(retryResult -> handleRetryTraceFn.apply(retryResult.getResult(), queryTracesFromRetries(retryResult.getErrors(), retryResult.getBackoffTimings()))); }

Target:
public <T> AsyncFuture<T> apply( Function<ClusterNode.Group, AsyncFuture<T>> function, BiFunction<T, List<QueryTrace>, T> handleRetryTraceFn ) { final Iterator<ClusterNode.Group> it = groups.iterator(); if (!it.hasNext()) { return async.failed(new RuntimeException("No groups available")); } final RetryPolicy parent = RetryPolicy.timed(30000, RetryPolicy.exponential(100, 5000)); final RetryPolicy iteratorPolicy = clockSource -> { final RetryPolicy.Instance p = parent.apply(clockSource); return () -> { if (it.hasNext()) { return p.next(); } return new RetryPolicy.Decision(false, 0); }; }; return async .retryUntilResolved(() -> { final ClusterNode.Group next = it.next(); return function.apply(next).catchFailed(throwable -> { reporter.reportClusterNodeRpcError(); throw new RuntimeNodeException(next.toString(), throwable.getMessage(), throwable); }).catchCancelled(ignore -> { reporter.reportClusterNodeRpcCancellation(); throw new RuntimeNodeException(next.toString(), "Operation cancelled"); }); }, iteratorPolicy) .directTransform(retryResult -> handleRetryTraceFn.apply(retryResult.getResult(), queryTracesFromRetries(retryResult.getErrors(), retryResult.getBackoffTimings()))); }
Source:
private void onEvent(final Set<Method> onEventMethods, final Object sink, final Object payload, final IEvent<?> event) { try { for (Method method : onEventMethods) { OnEvent onEvent = method.getAnnotation(OnEvent.class); if (isPayloadApplicableToHandler(onEvent, payload)) { method.invoke(sink, payload); if (onEvent.stop()) { event.stop(); break; } } } } catch (InvocationTargetException e) { throw new IllegalStateException("Failed to invoke @OnEvent method", e); } catch (IllegalAccessException e) { throw new IllegalStateException("Failed to invoke @OnEvent method", e); } }

Target:
private void onEvent(final Set<Method> onEventMethods, final Object sink, final Object payload, final IEvent<?> event) { try { for (Method method : onEventMethods) { if (canCallListenerInterface(sink, method)) { OnEvent onEvent = method.getAnnotation(OnEvent.class); if (isPayloadApplicableToHandler(onEvent, payload)) { Object result = method.invoke(sink, payload); if (result instanceof Visit<?>) { Visit<?> visit = (Visit<?>) result; if (visit.isDontGoDeeper()) { event.dontBroadcastDeeper(); } else if (visit.isStopped()) { event.stop(); break; } } else if (onEvent.stop()) { event.stop(); break; } } } } } catch (InvocationTargetException e) { throw new IllegalStateException("Failed to invoke @OnEvent method", e); } catch (IllegalAccessException e) { throw new IllegalStateException("Failed to invoke @OnEvent method", e); } }
Source:
public List<RepoImage> getUserRequestForStorageDomainRepoFileList(Guid storageDomainId, ImageFileType imageType, boolean forceRefresh) { List<RepoImage> repoList; if (!isStorageDomainValid(storageDomainId, imageType, forceRefresh)) { throw new VdcBLLException(VdcBllErrors.GetIsoListError); } repoList = getCachedIsoListByDomainId(storageDomainId, imageType); return repoList; }

Target:
public List<RepoImage> getUserRequestForStorageDomainRepoFileList(Guid storageDomainId, ImageFileType imageType, boolean forceRefresh) { if (!isStorageDomainValid(storageDomainId, imageType, forceRefresh)) { throw new VdcBLLException(VdcBllErrors.GetIsoListError); } return getCachedIsoListByDomainId(storageDomainId, imageType); }
Source:
public void testSelectTagAndPlay() { checkIfSpinnerOnBrickAtPositionShowsString(R.id.brick_when_nfc_spinner, nfcBrickPosition, R.string.brick_when_nfc_default_all); clickSpinnerValueOnBrick(R.id.brick_when_nfc_spinner, nfcBrickPosition, R.string.test_tag_name_1); onView(withId(R.id.button_play)) .perform(click()); Script script = ProjectManager.getInstance().getCurrentScene().getSpriteList().get(0).getScript(0); assertEquals("tag not set", ((WhenNfcBrick) script.getScriptBrick()).getNfcTag().getNfcTagName(), tagDataList.get(0).getNfcTagName()); pressBack(); pressBack(); checkIfSpinnerOnBrickAtPositionShowsString(R.id.brick_when_nfc_spinner, nfcBrickPosition, R.string.test_tag_name_1); clickSpinnerValueOnBrick(R.id.brick_when_nfc_spinner, nfcBrickPosition, R.string.test_tag_name_2); onView(withId(R.id.button_play)) .perform(click()); script = ProjectManager.getInstance().getCurrentScene().getSpriteList().get(0).getScript(0); assertEquals("tag not set", ((WhenNfcBrick) script.getScriptBrick()).getNfcTag().getNfcTagName(), tagDataList.get(1).getNfcTagName()); pressBack(); pressBack(); checkIfSpinnerOnBrickAtPositionShowsString(R.id.brick_when_nfc_spinner, nfcBrickPosition, R.string .test_tag_name_2); }

Target:
public void testSelectTagAndPlay() { checkIfSpinnerOnBrickAtPositionShowsString(R.id.brick_when_nfc_spinner, nfcBrickPosition, R.string.brick_when_nfc_default_all); clickSpinnerValueOnBrick(R.id.brick_when_nfc_spinner, nfcBrickPosition, R.string.test_tag_name_1); onView(withId(R.id.button_play)) .perform(click()); assertEquals("Tag not set", ((WhenNfcBrick) scriptUnderTest.getScriptBrick()).getNfcTag().getNfcTagName(), tagDataList.get(0).getNfcTagName()); pressBack(); pressBack(); checkIfSpinnerOnBrickAtPositionShowsString(R.id.brick_when_nfc_spinner, nfcBrickPosition, R.string.test_tag_name_1); clickSpinnerValueOnBrick(R.id.brick_when_nfc_spinner, nfcBrickPosition, R.string.test_tag_name_2); onView(withId(R.id.button_play)) .perform(click()); assertEquals("tag not set", ((WhenNfcBrick) scriptUnderTest.getScriptBrick()).getNfcTag().getNfcTagName(), tagDataList.get(1).getNfcTagName()); pressBack(); pressBack(); checkIfSpinnerOnBrickAtPositionShowsString(R.id.brick_when_nfc_spinner, nfcBrickPosition, R.string .test_tag_name_2); }