auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Setting getSetting(VDomainModelReference domainModelReference, EObject object) throws DatabindingFailedException { final VFeaturePathDomainModelReference featurePathReference = checkAndConvertDMR(domainModelReference); if (object == null) { throw new IllegalArgumentException("The given EObject must not be null."); } EObject currentObject = object; for (final EReference eReference : featurePathReference.getDomainModelEReferencePath()) { currentObject = (EObject) currentObject.eGet(eReference); } return InternalEObject.class.cast(currentObject).eSetting(featurePathReference.getDomainModelEFeature()); }

Target:
public Setting getSetting(VDomainModelReference domainModelReference, EObject object) throws DatabindingFailedException { final VFeaturePathDomainModelReference featurePathReference = checkAndConvertDMR(domainModelReference); EObject currentObject = object; for (final EReference eReference : featurePathReference.getDomainModelEReferencePath()) { currentObject = (EObject) currentObject.eGet(eReference); if (currentObject == null) { throw new DatabindingFailedException("The path is not fully resolved."); } } return InternalEObject.class.cast(currentObject).eSetting(featurePathReference.getDomainModelEFeature()); }
Source:
public void testGetVersion() throws Exception { BugzillaRestClient client = new BugzillaRestClient(actualFixture.location()); assertNotNull(client.getClient()); assertNull(client.getClient().getLoginToken()); BugzillaRestVersion version = client.getVersion(new NullOperationMonitor()); assertTrue("expeccted: " + actualFixture.getVersion() + " actual: " + version.toString(), actualFixture.getVersion().compareTo(version.toString()) == 0); }

Target:
public void testGetVersion() throws Exception { BugzillaRestClient client = new BugzillaRestClient(actualFixture.location()); assertNotNull(client.getClient()); assertNull(client.getClient().getLoginToken()); BugzillaRestVersion version = client.getVersion(new NullOperationMonitor()); assertEquals("expeccted: " + actualFixture.getVersion() + " actual: " + version.toString(), actualFixture.getVersion(), version.toString()); }
Source:
public List<AuditEvent> pollConsumerEvents(PerunSession perunSession, String consumerName) throws InternalErrorException { if (consumerName == null) throw new InternalErrorException("Auditer consumer doesn't exist."); try { if(jdbc.queryForInt("select count(*) from auditer_consumers where name=?", consumerName) != 1) { throw new InternalErrorException("Auditer consumer doesn't exist."); } List<AuditEvent> eventList = new ArrayList<>(); int lastProcessedId = getLastProcessedId(consumerName); int maxId = jdbc.queryForInt("select max(id) from auditer_log"); if (maxId > lastProcessedId) { eventList = jdbc.query("select " + auditMessageMappingSelectQuery + " from auditer_log where id > ? and id <= ? order by id", AUDIT_EVENT_MAPPER, lastProcessedId, maxId); jdbc.update("update auditer_consumers set last_processed_id=?, modified_at=" + Compatibility.getSysdate() + " where name=?", maxId, consumerName); } return eventList; } catch (Exception ex) { throw new InternalErrorException(ex); } }

Target:
public List<AuditEvent> pollConsumerEvents(PerunSession perunSession, String consumerName) throws InternalErrorException { checkAuditerConsumerExists(perunSession, consumerName); try { List<AuditEvent> eventList = new ArrayList<>(); int lastProcessedId = getLastProcessedId(consumerName); int maxId = getLastMessageId(perunSession); if (maxId > lastProcessedId) { eventList = jdbc.query("select " + auditMessageMappingSelectQuery + " from auditer_log where id > ? and id <= ? order by id", AUDIT_EVENT_MAPPER, lastProcessedId, maxId); setLastProcessedId(perunSession, consumerName, maxId); } return eventList; } catch (Exception ex) { throw new InternalErrorException(ex); } }
Source:
private static void refreshPageInCache(String pageIdentifier) throws DotDataException, DotSecurityException { Set<String> inodes = new HashSet<String>(); List<ContentletVersionInfo> infos = APILocator.getVersionableAPI().findContentletVersionInfos(pageIdentifier); for (ContentletVersionInfo versionInfo : infos) { inodes.add(versionInfo.getWorkingInode()); if(versionInfo.getLiveInode() != null){ inodes.add(versionInfo.getLiveInode()); } } List<Contentlet> cons = APILocator.getContentletAPIImpl().findContentlets(Lists.newArrayList(inodes)); for (Contentlet pageContent : cons) { IHTMLPage htmlPage = APILocator.getHTMLPageAssetAPI().fromContentlet(pageContent); PageServices.invalidateAll(htmlPage); } }

Target:
private static void refreshPageInCache(String pageIdentifier) throws DotDataException, DotSecurityException { Set<String> inodes = new HashSet<String>(); List<ContentletVersionInfo> infos = APILocator.getVersionableAPI().findContentletVersionInfos(pageIdentifier); for (ContentletVersionInfo versionInfo : infos) { inodes.add(versionInfo.getWorkingInode()); if(versionInfo.getLiveInode() != null){ inodes.add(versionInfo.getLiveInode()); } } List<Contentlet> contentlets = APILocator.getContentletAPIImpl().findContentlets(Lists.newArrayList(inodes)); for (Contentlet pageContent : contentlets) { IHTMLPage htmlPage = APILocator.getHTMLPageAssetAPI().fromContentlet(pageContent); PageServices.invalidateAll(htmlPage); } }
Source:
private void copyFiles() throws IOException { RemoteIterator<LocatedFileStatus> itr = dataFileSystem.listFiles(dataFileListPath, true); while (itr.hasNext()) { LocatedFileStatus fileStatus = itr.next(); if (shouldExport(fileStatus)) { ReplCopyTask.doCopy(exportRootDataDir, exportFileSystem, fileStatus.getPath(), dataFileSystem, hiveConf); } } }

Target:
private void copyFiles() throws IOException { FileStatus[] fileStatuses = LoadSemanticAnalyzer.matchFilesOrDir(dataFileSystem, dataFileListPath); for (FileStatus fileStatus : fileStatuses) { ReplCopyTask.doCopy(exportRootDataDir, exportFileSystem, fileStatus.getPath(), dataFileSystem, hiveConf); } }
Source:
public void setupTenants() throws Exception { sourceTenants = new ArrayList<>(2); sourceTenants.add("tenant" + tenantNum++); sourceTenants.add("tenant" + tenantNum++); sourceOnlyTenant = sourceTenants.get(0); sourceAndTargetTenant = sourceTenants.get(1); targetOnlyTenant = "tenant" + tenantNum++; upsertData(); split(sourceTableName, 4); split(targetTableName, 2); ensureRegionsOnDifferentServers(sourceTableName); ensureRegionsOnDifferentServers(targetTableName); }

Target:
public void setupTenants() throws Exception { sourceTenants = new ArrayList<>(NUM_TENANTS); sourceTenants.add("tenant" + tenantNum++); sourceTenants.add("tenant" + tenantNum++); sourceOnlyTenant = sourceTenants.get(0); sourceAndTargetTenant = sourceTenants.get(1); targetOnlyTenant = "tenant" + tenantNum++; upsertData(); splitSource(sourceTableName); splitTarget(targetTableName); }
Source:
private NavigableMap<String, Long> collectValidDataSizeByLogSegment(long deleteReferenceTimeInMs, long expirationReferenceTimeInMs) throws StoreException { Set<String> deletedKeys = new HashSet<>(); NavigableMap<String, Long> validSizePerLogSegment = new TreeMap<>(); for (IndexSegment indexSegment : index.getIndexSegments().descendingMap().values()) { List<IndexValue> validIndexValues = getValidIndexValues(indexSegment, deleteReferenceTimeInMs, expirationReferenceTimeInMs, deletedKeys); for (IndexValue value : validIndexValues) { updateMapHelper(validSizePerLogSegment, indexSegment.getLogSegmentName(), value.getSize()); } } return validSizePerLogSegment; }

Target:
private NavigableMap<String, Long> collectValidDataSizeByLogSegment(long deleteReferenceTimeInMs, long expirationReferenceTimeInMs) throws StoreException { Set<StoreKey> deletedKeys = new HashSet<>(); NavigableMap<String, Long> validSizePerLogSegment = new TreeMap<>(); for (IndexSegment indexSegment : index.getIndexSegments().descendingMap().values()) { List<IndexValue> validIndexValues = getValidIndexValues(indexSegment, deleteReferenceTimeInMs, expirationReferenceTimeInMs, deletedKeys); for (IndexValue value : validIndexValues) { updateMapHelper(validSizePerLogSegment, indexSegment.getLogSegmentName(), value.getSize()); } } return validSizePerLogSegment; }
Source:
public static synchronized void createModel(Configuration conf) throws IOException { if(isModelCreated) { LOG.info("Model exists, skipping model creation"); return; } LOG.info("Creating Cosine model"); try { if(!conf.get("scoring.similarity.stopword.file").equals("stopwords.txt.template")) { stopWords = new ArrayList<String>(); String stopWord; BufferedReader br = new BufferedReader(conf.getConfResourceAsReader((conf.get("scoring.similarity.stopword.file")))); while ((stopWord = br.readLine()) != null) { stopWords.add(stopWord); } LOG.info("Loaded custom stopwords from {}",conf.get("scoring.similarity.stopword.file")); } int ngram = conf.getInt("scoring.similarity.ngrams", 1); LOG.info("Value of ngram: "+ngram); String line; StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(conf.getConfResourceAsReader((conf.get("cosine.goldstandard.file")))); while ((line = br.readLine()) != null) { sb.append(line); } DocVector goldStandard = createDocVector(sb.toString(), ngram); if(goldStandard!=null) docVectors.add(goldStandard); else { throw new Exception("Could not create DocVector for goldstandard"); } } catch (Exception e) { LOG.warn("Failed to add to model : {}",conf.get("cosine.goldstandard.file","goldstandard.txt.template"), StringUtils.stringifyException(e)); } if(docVectors.size()>0) { LOG.info("Cosine model creation complete"); isModelCreated = true; } else LOG.info("Cosine model creation failed"); }

Target:
public static synchronized void createModel(Configuration conf) throws IOException { if(isModelCreated) { LOG.info("Model exists, skipping model creation"); return; } LOG.info("Creating Cosine model"); try { if(!conf.get("scoring.similarity.stopword.file").equals("stopwords.txt.template")) { stopWords = new ArrayList<String>(); String stopWord; BufferedReader br = new BufferedReader(conf.getConfResourceAsReader((conf.get("scoring.similarity.stopword.file")))); while ((stopWord = br.readLine()) != null) { stopWords.add(stopWord); } LOG.info("Loaded custom stopwords from {}",conf.get("scoring.similarity.stopword.file")); } int ngram = conf.getInt("scoring.similarity.ngrams", 1); LOG.info("Value of ngram: {}",ngram); String line; StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(conf.getConfResourceAsReader((conf.get("cosine.goldstandard.file")))); while ((line = br.readLine()) != null) { sb.append(line); } DocVector goldStandard = createDocVector(sb.toString(), ngram); if(goldStandard!=null) docVectors.add(goldStandard); else { throw new Exception("Could not create DocVector for goldstandard"); } } catch (Exception e) { LOG.warn("Failed to add to model : {}",conf.get("cosine.goldstandard.file","goldstandard.txt.template"), StringUtils.stringifyException(e)); } if(docVectors.size()>0) { LOG.info("Cosine model creation complete"); isModelCreated = true; } else LOG.info("Cosine model creation failed"); }
Source:
private Version createVersion(ProjectHistory projectHistory, Project projectState, LogMessage logMessage, ACUser user, Version previousVersion) throws ESException { final Version newVersion = VersioningFactory.eINSTANCE.createVersion(); long computedChecksum = ModelUtil.NO_CHECKSUM; try { if (ServerConfiguration.isComputeChecksumOnCommitActive()) { computedChecksum = ModelUtil.computeChecksum(projectState); ModelUtil.logProjectDetails( MessageFormat.format("Checksum compuation during version create: {0}", computedChecksum), user.getName(), projectHistory.getProjectName(), projectHistory.getProjectId().getId(), null, -1); } } catch (final SerializationException exception) { throw new ESException(MessageFormat.format( Messages.VersionSubInterfaceImpl_ChecksumComputationFailed, projectHistory.getProjectName()), exception); } logMessage.setDate(new Date()); logMessage.setAuthor(user.getName()); newVersion.setLogMessage(logMessage); newVersion.setPrimarySpec(Versions.createPRIMARY(previousVersion.getPrimarySpec(), projectHistory.getVersions() .size())); newVersion.getPrimarySpec().setProjectStateChecksum(computedChecksum); newVersion.setNextVersion(null); projectHistory.getVersions().add(newVersion); return newVersion; }

Target:
private Version createVersion(ProjectHistory projectHistory, Project projectState, LogMessage logMessage, ACUser user, Version previousVersion) throws ESException { final Version newVersion = VersioningFactory.eINSTANCE.createVersion(); long computedChecksum = ModelUtil.NO_CHECKSUM; try { if (ServerConfiguration.isComputeChecksumOnCommitActive()) { computedChecksum = ModelUtil.computeChecksum(projectState); ModelUtil.logProjectDetails( MessageFormat.format("Checksum computaion during version create: {0}", computedChecksum), user.getName(), projectHistory.getProjectName(), projectHistory.getProjectId().getId(), null, -1); } } catch (final SerializationException exception) { throw new ESException(MessageFormat.format( Messages.VersionSubInterfaceImpl_ChecksumComputationFailed, projectHistory.getProjectName()), exception); } logMessage.setDate(new Date()); logMessage.setAuthor(user.getName()); newVersion.setLogMessage(logMessage); newVersion.setPrimarySpec(Versions.createPRIMARY(previousVersion.getPrimarySpec(), projectHistory.getVersions() .size())); newVersion.getPrimarySpec().setProjectStateChecksum(computedChecksum); newVersion.setNextVersion(null); projectHistory.getVersions().add(newVersion); return newVersion; }
Source:
public boolean showSearchBox() { if (node.pluginManager != null && node.pluginManager.isPluginLoaded("plugins.Library.Main")) { return true; } else { return false; } }

Target:
public boolean showSearchBox() { return (node.pluginManager != null && node.pluginManager.isPluginLoaded("plugins.Library.Main")); }
Source:
private static List<AliasedNode> extractFromSelect(List<AliasedNode> select, TableRef table, ColumnResolver resolver) throws SQLException { List<AliasedNode> ret = new ArrayList<AliasedNode>(); if (isWildCardSelect(select)) { ret.add(NODE_FACTORY.aliasedNode(null, WildcardParseNode.INSTANCE, select.get(0).getArrayColumnNode())); return ret; } ColumnParseNodeVisitor visitor = new ColumnParseNodeVisitor(resolver); for (AliasedNode node : select) { node.getNode().accept(visitor); ColumnParseNodeVisitor.ContentType type = visitor.getContentType(table); if (type == ColumnParseNodeVisitor.ContentType.SELF_ONLY) { ret.add(node); } else if (type == ColumnParseNodeVisitor.ContentType.COMPLEX) { for (Map.Entry<ColumnRef, ColumnParseNode> entry : visitor.getColumnRefMap().entrySet()) { if (entry.getKey().getTableRef().equals(table)) { ret.add(NODE_FACTORY.aliasedNode(null, entry.getValue())); } } } visitor.reset(); } return ret; }

Target:
private static List<AliasedNode> extractFromSelect(List<AliasedNode> select, TableRef table, ColumnResolver resolver) throws SQLException { List<AliasedNode> ret = new ArrayList<AliasedNode>(); if (isWildCardSelect(select)) { ret.add(NODE_FACTORY.aliasedNode(null, WildcardParseNode.INSTANCE)); return ret; } ColumnParseNodeVisitor visitor = new ColumnParseNodeVisitor(resolver); for (AliasedNode node : select) { node.getNode().accept(visitor); ColumnParseNodeVisitor.ContentType type = visitor.getContentType(table); if (type == ColumnParseNodeVisitor.ContentType.SELF_ONLY) { ret.add(node); } else if (type == ColumnParseNodeVisitor.ContentType.COMPLEX) { for (Map.Entry<ColumnRef, ColumnParseNode> entry : visitor.getColumnRefMap().entrySet()) { if (entry.getKey().getTableRef().equals(table)) { ret.add(NODE_FACTORY.aliasedNode(null, entry.getValue())); } } } visitor.reset(); } return ret; }
Source:
protected boolean InitializeVds() { boolean returnValue = true; if (getVds() == null) { List<VDS> hosts = getVdsDAO().getAllForStoragePoolAndStatus(getStoragePool().getId(), VDSStatus.Up); if (!hosts.isEmpty()) { setVds(hosts.get(new Random().nextInt(hosts.size()))); } if (getVds() == null) { returnValue = false; addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_NO_VDS_IN_POOL); } } return returnValue; }

Target:
protected boolean InitializeVds() { boolean returnValue = true; if (getVds() == null) { List<VDS> hosts = getVdsDAO().getAllForStoragePoolAndStatus(getStoragePool().getId(), VDSStatus.Up); if (!hosts.isEmpty()) { setVds(RandomUtils.instance().pickRandom(hosts)); } if (getVds() == null) { returnValue = false; addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_NO_VDS_IN_POOL); } } return returnValue; }
Source:
public void testJtds() throws Exception { boolean canTestJtds = false; useJtdsDriver = true; try { new SQLServerOutputPluginTest().connect(); canTestJtds = true; String table = "TEST1"; dropTable(table); createTable(table); insertRecord(table); tester.run(convertYml("/sqlserver/yml/test-jtds.yml")); assertTable(1, table); } catch (Throwable t) { System.out.println(t); } finally { useJtdsDriver = false; if (!canTestJtds) { System.out.println("Warning: jTDS driver can't connect to database."); System.out.println("(server = localhost, port = 1433, instance = SQLEXPRESS, database = TESTDB, user = TEST_USER, password = TEST_PW)"); } } }

Target:
public void testJtds() throws Exception { boolean canTestJtds = false; useJtdsDriver = true; try { new SQLServerOutputPluginTest().connect(); canTestJtds = true; } catch (Throwable t) { System.out.println(t); } finally { if (!canTestJtds) { System.out.println("Warning: jTDS driver can't connect to database."); System.out.println("(server = localhost, port = 1433, instance = SQLEXPRESS, database = TESTDB, user = TEST_USER, password = TEST_PW)"); return; } } try { String table = "TEST1"; dropTable(table); createTable(table); insertRecord(table); tester.run(convertYml("/sqlserver/yml/test-jtds.yml")); assertTableJtds(1, table); } finally { useJtdsDriver = false; } }
Source:
protected void handleDownload(HttpServletRequest req, HttpServletResponse resp, String downloadPath, String baseUrl, boolean info) throws IOException { boolean tx = false; DownloadBlobInfo downloadBlobInfo; try { downloadBlobInfo = new DownloadBlobInfo(downloadPath); } catch (IllegalArgumentException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid URL syntax"); return; } try { if (!TransactionHelper.isTransactionActive()) { tx = TransactionHelper.startTransaction(); } String xpath = downloadBlobInfo.xpath; String filename = downloadBlobInfo.filename; DocumentModel doc = getDownloadDocument(downloadBlobInfo.repository, downloadBlobInfo.docId); if (doc == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "No document found"); return; } if (info) { Blob blob = resolveBlob(doc, xpath); if (blob == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "No blob found"); return; } String downloadUrl = baseUrl + getDownloadUrl(doc, xpath, filename); String result = blob.getMimeType() + ':' + URLEncoder.encode(blob.getFilename(), "UTF-8") + ':' + downloadUrl; resp.setContentType("text/plain"); resp.getWriter().write(result); resp.getWriter().flush(); } else { downloadBlob(req, resp, doc, xpath, null, filename, EVENT_NAME); } } catch (NuxeoException e) { if (tx) { TransactionHelper.setTransactionRollbackOnly(); } throw new IOException(e); } finally { if (tx) { TransactionHelper.commitOrRollbackTransaction(); } } }

Target:
protected void handleDownload(HttpServletRequest req, HttpServletResponse resp, String downloadPath, String baseUrl, boolean info) throws IOException { boolean tx = false; DownloadBlobInfo downloadBlobInfo; try { downloadBlobInfo = new DownloadBlobInfo(downloadPath); } catch (IllegalArgumentException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid URL syntax"); return; } try { if (!TransactionHelper.isTransactionActive()) { tx = TransactionHelper.startTransaction(); } String xpath = downloadBlobInfo.xpath; String filename = downloadBlobInfo.filename; DocumentModel doc = getDownloadDocument(downloadBlobInfo.repository, downloadBlobInfo.docId); if (doc == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "No document found"); return; } if (info) { Blob blob = resolveBlob(doc, xpath); if (blob == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "No blob found"); return; } String downloadUrl = baseUrl + getDownloadUrl(doc, xpath, filename); String result = blob.getMimeType() + ':' + URLEncoder.encode(blob.getFilename(), "UTF-8") + ':' + downloadUrl; resp.setContentType("text/plain"); resp.getWriter().write(result); resp.getWriter().flush(); } else { downloadBlob(req, resp, doc, xpath, null, filename, "download"); } } catch (NuxeoException e) { if (tx) { TransactionHelper.setTransactionRollbackOnly(); } throw new IOException(e); } finally { if (tx) { TransactionHelper.commitOrRollbackTransaction(); } } }
Source:
default void executeTask(final KeyFilter<? super K> filter, BiConsumer<? super K, InternalCacheEntry<K, V>> action) throws InterruptedException { iterator().forEachRemaining(ice -> { if (filter == null || filter.accept(ice.getKey())) { action.accept(ice.getKey(), ice); } }); }

Target:
default void executeTask(final KeyFilter<? super K> filter, BiConsumer<? super K, InternalCacheEntry<K, V>> action) throws InterruptedException { forEach(ice -> { if (filter == null || filter.accept(ice.getKey())) { action.accept(ice.getKey(), ice); } }); }
Source:
private static void speedUpDTMManager() { String className = System.getProperty(DTM_MANAGER_DEFAULT_PROP_NAME); if (className == null) { String dtmManagerClassName = null; try { Class<?> XPathContextClass = Class.forName(XPATH_CONTEXT_CLASS_NAME); Method getDTMManager = XPathContextClass.getMethod("getDTMManager"); Object XPathContext = XPathContextClass.newInstance(); Object dtmManager = getDTMManager.invoke(XPathContext); dtmManagerClassName = dtmManager.getClass().getName(); } catch (ClassNotFoundException ex) { } catch (NoSuchMethodException ex) { } catch (InstantiationException ex) { } catch (IllegalAccessException ex) { } catch (IllegalArgumentException ex) { } catch (InvocationTargetException ex) { } if (DTM_MANAGER_IMPL_CLASS_NAME.equals(dtmManagerClassName)) { System.setProperty(DTM_MANAGER_DEFAULT_PROP_NAME, DTM_MANAGER_IMPL_CLASS_NAME); } } }

Target:
private static void speedUpDTMManager() throws Exception { if (System.getProperty(DTM_MANAGER_DEFAULT_PROP_NAME) == null) { Class<?> XPathContextClass = Class.forName(XPATH_CONTEXT_CLASS_NAME); Method getDTMManager = XPathContextClass.getMethod("getDTMManager"); Object XPathContext = XPathContextClass.newInstance(); Object dtmManager = getDTMManager.invoke(XPathContext); if (DTM_MANAGER_IMPL_CLASS_NAME.equals(dtmManager.getClass().getName())) { System.setProperty(DTM_MANAGER_DEFAULT_PROP_NAME, DTM_MANAGER_IMPL_CLASS_NAME); } } }
Source:
public String deploy(String url, String targetName) { String canonicalTargetName = getFilenameContextMapper().convertDeploymentTargetNameToFilename(targetName); String dest = getDeployDir() + "/" + canonicalTargetName; log.info("{} deploying to {}:{}", new Object[]{entity, url, getHostname(), dest}); getMachine().run(String.format("mv -f %s %s.bak > /dev/null 2>&1", dest, dest)); int result = -1; if (url.startsWith("http")) { result = getMachine().run(String.format("wget --no-check-certificate %s -O %s", url, dest)); } else { result = getMachine().copyTo(getResource(url), dest); } log.debug("{} deployed to {}:{}: result {}", new Object[]{entity, url, getHostname(), dest, result}); if (result!=0) log.warn("Problem deploying to {}:{} for {}: result {}", new Object[]{url, getHostname(), dest, entity, result}); return getFilenameContextMapper().convertDeploymentTargetNameToContext(canonicalTargetName); }

Target:
public String deploy(String url, String targetName) { String canonicalTargetName = getFilenameContextMapper().convertDeploymentTargetNameToFilename(targetName); String dest = getDeployDir() + "/" + canonicalTargetName; log.info("{} deploying to {}:{}", new Object[]{entity, url, getHostname(), dest}); getMachine().run(String.format("mv -f %s %s.bak > /dev/null 2>&1", dest, dest)); int result = -1; if (url.toLowerCase().matches("^https?://.*")) { result = getMachine().execCommands("download", ImmutableList.of( CommonCommands.INSTALL_WGET, String.format("wget --no-check-certificate %s -O %s > /dev/null 2>&1", url, dest))); } if (result != 0) { result = getMachine().copyTo(getResource(url), dest); } log.debug("{} deployed to {}:{}: result {}", new Object[]{entity, url, getHostname(), dest, result}); if (result!=0) log.warn("Problem deploying to {}:{} for {}: result {}", new Object[]{url, getHostname(), dest, entity, result}); return getFilenameContextMapper().convertDeploymentTargetNameToContext(canonicalTargetName); }
Source:
public void patchGroupName() throws Exception { context.turnOffAuthorisationSystem(); Group group = GroupBuilder.createGroup(context).withName("Group").build(); context.restoreAuthSystemState(); String token = getAuthToken(admin.getEmail(), password); String requestBody = " [\n" + " {\n" + " \"op\": \"replace\",\n" + " \"path\": \"/name\",\n" + " \"value\": \"new name\"\n" + " }\n" + " ]"; getClient(token) .perform(patch("/api/eperson/groups/" + group.getID()).content(requestBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isOk()); getClient(token) .perform(get("/api/eperson/groups/" + group.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$", Matchers.is( GroupMatcher.matchGroupEntry(group.getID(), "new name")) )); }

Target:
public void patchGroupName() throws Exception { context.turnOffAuthorisationSystem(); Group group = GroupBuilder.createGroup(context).withName("Group").build(); context.restoreAuthSystemState(); String token = getAuthToken(admin.getEmail(), password); List<Operation> ops = new ArrayList<>(); ReplaceOperation replaceOperation = new ReplaceOperation("/name", "new name"); ops.add(replaceOperation); String requestBody = getPatchContent(ops); getClient(token) .perform(patch("/api/eperson/groups/" + group.getID()).content(requestBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isOk()); getClient(token) .perform(get("/api/eperson/groups/" + group.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$", Matchers.is( GroupMatcher.matchGroupEntry(group.getID(), "new name")) )); }
Source:
public void configure(ResourceInfo resourceInfo, FeatureContext context) { final AnnotatedMethod am = new AnnotatedMethod(resourceInfo.getResourceMethod()); final Annotation[][] parameterAnnotations = am.getParameterAnnotations(); final Class<?>[] parameterTypes = am.getParameterTypes(); for (int i = 0; i < parameterAnnotations.length; i++) { for (final Annotation annotation : parameterAnnotations[i]) { if (annotation instanceof Auth && parameterTypes[i].equals(Optional.class) && authFilter != null) { context.register(new WebApplicationExceptionCatchingFilter(authFilter)); return; } else if (annotation instanceof Auth) { registerAuthFilter(context); return; } } } final boolean annotationOnClass = (resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class) != null) || (resourceInfo.getResourceClass().getAnnotation(PermitAll.class) != null); final boolean annotationOnMethod = am.isAnnotationPresent(RolesAllowed.class) || am.isAnnotationPresent(DenyAll.class) || am.isAnnotationPresent(PermitAll.class); if (annotationOnClass || annotationOnMethod) { registerAuthFilter(context); } }

Target:
public void configure(ResourceInfo resourceInfo, FeatureContext context) { final AnnotatedMethod am = new AnnotatedMethod(resourceInfo.getResourceMethod()); final Annotation[][] parameterAnnotations = am.getParameterAnnotations(); final Class<?>[] parameterTypes = am.getParameterTypes(); for (int i = 0; i < parameterAnnotations.length; i++) { for (final Annotation annotation : parameterAnnotations[i]) { if (annotation instanceof Auth) { if (parameterTypes[i].equals(Optional.class) && authFilter != null) { context.register(new WebApplicationExceptionCatchingFilter(authFilter)); return; } else { registerAuthFilter(context); return; } } } } final boolean annotationOnClass = (resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class) != null) || (resourceInfo.getResourceClass().getAnnotation(PermitAll.class) != null); final boolean annotationOnMethod = am.isAnnotationPresent(RolesAllowed.class) || am.isAnnotationPresent(DenyAll.class) || am.isAnnotationPresent(PermitAll.class); if (annotationOnClass || annotationOnMethod) { registerAuthFilter(context); } }
Source:
protected KualiDecimal calculateTotalAmountForCashAdvanceLinesReferencedByRegularLines( List<ConcurStandardAccountingExtractDetailLine> regularDetailLines) { return regularDetailLines.stream() .map(ConcurStandardAccountingExtractDetailLine::getReportEntryId) .distinct() .map(cashAdvanceLinesByReportEntryId::get) .filter((cashAdvanceLine) -> cashAdvanceLine != null) .map(ConcurStandardAccountingExtractDetailLine::getJournalAmount) .reduce(KualiDecimal.ZERO, KualiDecimal::add); }

Target:
protected KualiDecimal calculateTotalAmountForCashAdvanceLinesReferencedByRegularLines( List<ConcurStandardAccountingExtractDetailLine> regularDetailLines) { if (cashAdvanceLinesByReportEntryId.isEmpty()) { return KualiDecimal.ZERO; } String[] reportEntryIds = regularDetailLines.stream() .map(ConcurStandardAccountingExtractDetailLine::getReportEntryId) .distinct() .toArray(String[]::new); List<ConcurStandardAccountingExtractDetailLine> cashAdvanceLines = new ArrayList<>(reportEntryIds.length); for (String reportEntryId : reportEntryIds) { ConcurStandardAccountingExtractDetailLine cashAdvanceLine = cashAdvanceLinesByReportEntryId.get(reportEntryId); if (cashAdvanceLine != null) { cashAdvanceLines.add(cashAdvanceLine); } } if (cashAdvanceLines.isEmpty()) { return KualiDecimal.ZERO; } else { return calculateTotalAmountForLines(cashAdvanceLines); } }
Source:
protected Set<PropertyKey> PopulateParticipantKeys(HelixDataAccessor accessor, Map<String, LiveInstance> liveInstanceMap) { Set<PropertyKey> participantStateKeys = new HashSet<>(); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); Set<String> restrictedKeys = new HashSet<>(); if (accessor.getProperty(accessor.keyBuilder().customizedStateAggregationConfig()) != null) { restrictedKeys = new HashSet<>( accessor.getProperty(accessor.keyBuilder().customizedStateAggregationConfig()).getRecord() .getListFields().get( CustomizedStateAggregationConfig.CustomizedStateAggregationProperty.AGGREGATION_ENABLED_TYPES .name())); } for (String instanceName : liveInstanceMap.keySet()) { for (String customizedStateType : restrictedKeys) { accessor.getChildNames(keyBuilder.customizedStates(instanceName, customizedStateType)) .stream().forEach(resourceName -> participantStateKeys .add(keyBuilder.customizedState(instanceName, customizedStateType, resourceName))); } } return participantStateKeys; }

Target:
protected Set<PropertyKey> PopulateParticipantKeys(HelixDataAccessor accessor, Map<String, LiveInstance> liveInstanceMap) { Set<PropertyKey> participantStateKeys = new HashSet<>(); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); for (String instanceName : liveInstanceMap.keySet()) { for (String customizedStateType : _aggregationEnabledTypes) { accessor.getChildNames(keyBuilder.customizedStates(instanceName, customizedStateType)) .stream().forEach(resourceName -> participantStateKeys .add(keyBuilder.customizedState(instanceName, customizedStateType, resourceName))); } } return participantStateKeys; }
Source:
public @ServiceState.RilRadioTechnology int getCsCallRadioTech() { int vrat = ServiceState.RIL_RADIO_TECHNOLOGY_UNKNOWN; if (mSST != null) { int vrs = mSST.mSS.getVoiceRegState(); vrat = mSST.mSS.getRilVoiceRadioTechnology(); logd("getCsCallRadioTech, current vrs=" + vrs + ", vrat=" + vrat); if (vrs != ServiceState.STATE_IN_SERVICE || ArrayUtils.contains(VOICE_PS_CALL_RADIO_TECHNOLOGY, vrat)) { vrat = ServiceState.RIL_RADIO_TECHNOLOGY_UNKNOWN; } } logd("getCsCallRadioTech, result vrat=" + vrat); return vrat; }

Target:
public @ServiceState.RilRadioTechnology int getCsCallRadioTech() { int calcVrat = ServiceState.RIL_RADIO_TECHNOLOGY_UNKNOWN; if (mSST != null) { calcVrat = getCsCallRadioTech(mSST.mSS.getVoiceRegState(), mSST.mSS.getRilVoiceRadioTechnology()); } return calcVrat; }
Source:
public AssertsNearCache<K, V> expectNearPreemptiveRemove(K key, AssertsNearCache<K, V>... affected) { if (nearCacheMode.invalidated()) { MockRemoveEvent preemptiveRemove = pollEvent(events); assertEquals(key, preemptiveRemove.key); } expectNoNearEvents(); return this; }

Target:
public AssertsNearCache<K, V> expectNearPreemptiveRemove(K key, AssertsNearCache<K, V>... affected) { MockRemoveEvent preemptiveRemove = pollEvent(events); assertEquals(key, preemptiveRemove.key); expectNoNearEvents(); return this; }
Source:
public int read(byte[] b, int off, int len) throws IOException { prepare(); int p = off; int n = 0; while (true) { if (len <= buf.remaining()) { buf.get(b, off, len); return n + len; } int r = buf.remaining(); buf.get(b, p, r); n += r; p += r; buf.rewind(); position += buf.capacity(); int nr = os.read(position, buf); if (nr < 0) { buf.limit(0); return n > 0 ? n : -1; } buf.flip(); } }

Target:
public int read(byte[] b, int off, int len) throws IOException { int cnt = 0; while (0 < len) { if (!buf.hasRemaining()) { buf.rewind(); int nr = os.read(position, buf); if (nr < 0) { buf.position(buf.remaining()); break; } position += nr; buf.flip(); } int n = Math.min(len, buf.remaining()); buf.get(b, off, n); off += n; len -= n; cnt += n; } if (cnt == 0 && len > 0) return -1; return cnt; }
Source:
private void initiateMocks() { int[] activeSlots = fusionVersion.aliveSlots(); accessors = new IndexAccessor[INSTANCE_COUNT]; Arrays.fill( accessors, IndexAccessor.EMPTY ); aliveAccessors = new IndexAccessor[activeSlots.length]; for ( int i = 0; i < activeSlots.length; i++ ) { IndexAccessor mock = mock( IndexAccessor.class ); aliveAccessors[i] = mock; switch ( activeSlots[i] ) { case STRING: accessors[STRING] = mock; break; case NUMBER: accessors[NUMBER] = mock; break; case SPATIAL: accessors[SPATIAL] = mock; break; case TEMPORAL: accessors[TEMPORAL] = mock; break; case LUCENE: accessors[LUCENE] = mock; break; default: throw new RuntimeException(); } } fusionIndexAccessor = new FusionIndexAccessor( fusionVersion.slotSelector(), new Selector<>( accessors ), indexId, mock( SchemaIndexDescriptor.class ), dropAction ); }

Target:
private void initiateMocks() { int[] activeSlots = fusionVersion.aliveSlots(); accessors = new IndexAccessor[INSTANCE_COUNT]; Arrays.fill( accessors, IndexAccessor.EMPTY ); aliveAccessors = new IndexAccessor[activeSlots.length]; for ( int i = 0; i < activeSlots.length; i++ ) { IndexAccessor mock = mock( IndexAccessor.class ); aliveAccessors[i] = mock; switch ( activeSlots[i] ) { case STRING: accessors[STRING] = mock; break; case NUMBER: accessors[NUMBER] = mock; break; case SPATIAL: accessors[SPATIAL] = mock; break; case TEMPORAL: accessors[TEMPORAL] = mock; break; case LUCENE: accessors[LUCENE] = mock; break; default: throw new RuntimeException(); } } fusionIndexAccessor = new FusionIndexAccessor( fusionVersion.slotSelector(), new InstanceSelector<>( accessors ), indexId, mock( SchemaIndexDescriptor.class ), dropAction ); }
Source:
protected void onInit() throws Exception { super.onInit(); if (this.topicProcessor instanceof BeanFactoryAware && getBeanFactory() != null) { ((BeanFactoryAware) this.topicProcessor).setBeanFactory(getBeanFactory()); } if (this.qosProcessor instanceof BeanFactoryAware && getBeanFactory() != null) { ((BeanFactoryAware) this.qosProcessor).setBeanFactory(getBeanFactory()); } if (this.retainedProcessor instanceof BeanFactoryAware && getBeanFactory() != null) { ((BeanFactoryAware) this.retainedProcessor).setBeanFactory(getBeanFactory()); } if (this.converter == null) { DefaultPahoMessageConverter mConverter = new DefaultPahoMessageConverter( m -> { if (this.qosProcessor == null) { return MqttMessageConverter.defaultQosFunction(this.defaultQos).apply(m); } else { Integer result = this.qosProcessor.processMessage(m); if (result == null) { return this.defaultQos; } else { return result; } } }, m -> { if (this.retainedProcessor == null) { return MqttMessageConverter.defaultRetainedFunction(this.defaultRetained).apply(m); } else { Boolean result = this.retainedProcessor.processMessage(m); if (result == null) { return this.defaultRetained; } else { return result; } } }); if (getBeanFactory() != null) { mConverter.setBeanFactory(getBeanFactory()); } this.converter = mConverter; } }

Target:
protected void onInit() throws Exception { super.onInit(); if (this.topicProcessor instanceof BeanFactoryAware && getBeanFactory() != null) { ((BeanFactoryAware) this.topicProcessor).setBeanFactory(getBeanFactory()); } if (this.qosProcessor instanceof BeanFactoryAware && getBeanFactory() != null) { ((BeanFactoryAware) this.qosProcessor).setBeanFactory(getBeanFactory()); } if (this.retainedProcessor instanceof BeanFactoryAware && getBeanFactory() != null) { ((BeanFactoryAware) this.retainedProcessor).setBeanFactory(getBeanFactory()); } if (this.converter == null) { DefaultPahoMessageConverter defaultConverter = new DefaultPahoMessageConverter(this.defaultQos, this.qosProcessor, this.defaultRetained, this.retainedProcessor); if (getBeanFactory() != null) { defaultConverter.setBeanFactory(getBeanFactory()); } this.converter = defaultConverter; } }
Source:
public String get(@NonNull String key) { try { storageLock.lock(); if (_storage == null) { throw new RuntimeException(EXCEPTION_STORAGE); } return _storage.get(key); } finally { storageLock.unlock(); } }

Target:
public @Nullable String get(@NonNull String key) { storageLock.lock(); try { if (storage == null) { throw new IllegalStateException(EXCEPTION_STORAGE); } return storage.get(key); } finally { storageLock.unlock(); } }
Source:
public void initVertex() { super.initVertex(); if (maxBFSIteration == -1) { maxBFSIteration = 10; END_BFS)); } if (maxTraversalLength == -1) { maxTraversalLength = 10; } if (source == "") { source = "AAT"; } if (destination == "") { destination = "AGA"; } if (commonReadId == -1) { commonReadId = 1; } if (outgoingMsg == null) outgoingMsg = new BFSTraverseMessage(); if (fakeVertex == null) { fakeVertex = new VKmer(); } }

Target:
public void initVertex() { super.initVertex(); if (maxBFSIteration == -1) { maxBFSIteration = Integer.parseInt(getContext().getConfiguration().get(NUM_STEP_SIMULATION_END_BFS)); } if (maxTraversalLength == -1) { maxTraversalLength = Integer.parseInt(getContext().getConfiguration().get(MAX_TRAVERSAL_LENGTH)); } if (source == "") { source = getContext().getConfiguration().get(SOURCE); } if (destination == "") { destination = getContext().getConfiguration().get(DESTINATION); } if (commonReadId == -1) { commonReadId = Long.parseLong(getContext().getConfiguration().get(COMMOND_READID)); } if (outgoingMsg == null) outgoingMsg = new BFSTraverseMessage(); if (fakeVertex == null) { fakeVertex = new VKmer(); } }
Source:
public CrashDetails(String crashIdentifier, Throwable throwable, String managedExceptionString, Boolean isManagedException) { this(crashIdentifier); final Writer stackTraceResult = new StringWriter(); final PrintWriter printWriter = new BoundedPrintWriter(stackTraceResult, CRASH_FILE_STACKTRACE_MAX_SIZE); isXamarinException = true; setFormat(FIELD_FORMAT_VALUE); if (isManagedException) { printWriter.print(FIELD_XAMARIN_CAUSED_BY); throwable.printStackTrace(printWriter); } else { if (!TextUtils.isEmpty(managedExceptionString)) { PrintWriter javaExceptionWriter = new BoundedPrintWriter(stackTraceResult, CRASH_FILE_STACKTRACE_MAX_SIZE / 2); throwable.printStackTrace(javaExceptionWriter); printWriter.print(FIELD_XAMARIN_CAUSED_BY); PrintWriter managedExceptionWriter = new BoundedPrintWriter(stackTraceResult, CRASH_FILE_STACKTRACE_MAX_SIZE / 2); managedExceptionWriter.print(managedExceptionString); } else { throwable.printStackTrace(printWriter); } } throwableStackTrace = stackTraceResult.toString(); }

Target:
public CrashDetails(String crashIdentifier, Throwable throwable, String managedExceptionString, Boolean isManagedException) { this(crashIdentifier); final int xamarinCausedByHeaderLength = FIELD_XAMARIN_CAUSED_BY.length(); final Writer stackTraceResult = new StringWriter(); final Writer boundedWriter = new BoundedPrintWriter(stackTraceResult, CRASH_FILE_STACKTRACE_SIZE + xamarinCausedByHeaderLength); final PrintWriter printWriter = new PrintWriter(boundedWriter); isXamarinException = true; setFormat(FIELD_FORMAT_VALUE); if (isManagedException) { printWriter.print(FIELD_XAMARIN_CAUSED_BY); throwable.printStackTrace(printWriter); } else { if (!TextUtils.isEmpty(managedExceptionString)) { Writer javaExceptionWriter = new BoundedPrintWriter(printWriter, CRASH_FILE_STACKTRACE_SIZE / 2); throwable.printStackTrace(new PrintWriter(javaExceptionWriter)); printWriter.print(FIELD_XAMARIN_CAUSED_BY); Writer managedExceptionWriter = new BoundedPrintWriter(printWriter, CRASH_FILE_STACKTRACE_SIZE / 2); PrintWriter managedExceptionPrintWriter = new PrintWriter(managedExceptionWriter); managedExceptionPrintWriter.print(managedExceptionString); } else { throwable.printStackTrace(printWriter); } } throwableStackTrace = stackTraceResult.toString(); }
Source:
private void prepareActions(ActionManager actionManager, DependencyResolverAction dependencyResolverAction, GetEffectivePomAction getEffectivePomAction, ReimportMavenDependenciesAction reimportMavenDependenciesAction) { actionManager.registerAction("getEffectivePom", getEffectivePomAction); actionManager.registerAction("reimportMavenDependenciesAction", reimportMavenDependenciesAction); DefaultActionGroup assistantGroup = (DefaultActionGroup)actionManager.getAction(GROUP_ASSISTANT); assistantGroup.add(getEffectivePomAction, Constraints.LAST); DefaultActionGroup mavenContextMenuGroup = new DefaultActionGroup("Maven", true, actionManager); actionManager.registerAction("mavenContextMenu", mavenContextMenuGroup); mavenContextMenuGroup.getTemplatePresentation().setSVGResource(resources.maven()); DefaultActionGroup mainContextMenuGroup = (DefaultActionGroup)actionManager.getAction("resourceOperation"); mainContextMenuGroup.addSeparator(); mainContextMenuGroup.add(mavenContextMenuGroup, Constraints.LAST); mavenContextMenuGroup.add(reimportMavenDependenciesAction); mavenContextMenuGroup.addSeparator(); final DefaultActionGroup rightStatusPanelGroup = (DefaultActionGroup)actionManager.getAction(GROUP_RIGHT_STATUS_PANEL); rightStatusPanelGroup.add(dependencyResolverAction); }

Target:
private void prepareActions(ActionManager actionManager, DependencyResolverAction dependencyResolverAction, GetEffectivePomAction getEffectivePomAction, ReimportMavenDependenciesAction reimportMavenDependenciesAction) { actionManager.registerAction("getEffectivePom", getEffectivePomAction); actionManager.registerAction("reimportMavenDependenciesAction", reimportMavenDependenciesAction); DefaultActionGroup assistantGroup = (DefaultActionGroup)actionManager.getAction(GROUP_ASSISTANT); assistantGroup.add(getEffectivePomAction, Constraints.LAST); DefaultActionGroup mavenContextMenuGroup = new DefaultActionGroup(MAVEN_GROUP_CONTEXT_MENU_NAME, true, actionManager); actionManager.registerAction(MAVEN_GROUP_CONTEXT_MENU_ID, mavenContextMenuGroup); mavenContextMenuGroup.getTemplatePresentation().setSVGResource(resources.maven()); DefaultActionGroup mainContextMenuGroup = (DefaultActionGroup)actionManager.getAction("resourceOperation"); mainContextMenuGroup.addSeparator(); mainContextMenuGroup.add(mavenContextMenuGroup, Constraints.LAST); mavenContextMenuGroup.add(reimportMavenDependenciesAction); mavenContextMenuGroup.addSeparator(); final DefaultActionGroup rightStatusPanelGroup = (DefaultActionGroup)actionManager.getAction(GROUP_RIGHT_STATUS_PANEL); rightStatusPanelGroup.add(dependencyResolverAction); }
Source:
public void testCommentTenMinutesLimit() { when(user.getModhash()).thenReturn(MODHASH); when(user.getCookie()).thenReturn(COOKIE); when(restClient.post("thing_id=" + "fullname" + "&text=" + "text" + "&uh=" + user.getModhash(), ApiEndpointUtils.COMMENT, user.getCookie())) .thenReturn(responseTenMinutesLimit); ByteArrayOutputStream errorOutput = new ByteArrayOutputStream(); System.setErr(new PrintStream(errorOutput)); boolean res = submitAction.comment("fullname", "text"); assertEquals(errorOutput.toString().contains("User submission failed: You need to wait before posting again"), true); assertFalse(res); }

Target:
public void testCommentTenMinutesLimit() { when(user.getModhash()).thenReturn(MODHASH); when(user.getCookie()).thenReturn(COOKIE); when(restClient.post("thing_id=" + "fullname" + "&text=" + "text" + "&uh=" + user.getModhash(), ApiEndpointUtils.COMMENT, user.getCookie())) .thenReturn(responseTenMinutesLimit); ByteArrayOutputStream errorOutput = new ByteArrayOutputStream(); System.setErr(new PrintStream(errorOutput)); boolean res = submitAction.comment("fullname", "text"); assertTrue(errorOutput.toString().contains("User submission failed: You need to wait before posting again")); assertFalse(res); }
Source:
public void testGetForStoragePool() { StorageDomain result = dao.getForStoragePool(existingDomain.getId(), Guid.createGuidFromString("6d849ebf-755f-4552-ad09-9a090cda105d")); assertGetResult(result); }

Target:
public void testGetForStoragePool() { StorageDomain result = dao.getForStoragePool(existingDomain.getId(),new Guid("6d849ebf-755f-4552-ad09-9a090cda105d")); assertGetResult(result); }
Source:
public void test_isDescendant() { Tree tree = PHPParserBuilder.createParser().parse("<?= for(;;) ?>"); StatementTree statementTree = ((CompilationUnitTree) tree).script().statements().get(0); assertThat(isDescendant(statementTree, tree)).isTrue(); assertThat(isDescendant(tree, statementTree)).isFalse(); }

Target:
public void test_isDescendant() { Tree tree = PHPParserBuilder.createParser().parse("<?= for(;;) ?>"); StatementTree statementTree = ((CompilationUnitTree) tree).script().statements().get(0); assertThat(isDescendant(statementTree, tree)).isTrue(); assertThat(isDescendant(tree, statementTree)).isFalse(); assertThat(isDescendant(tree, tree)).isTrue(); assertThat(isDescendant(statementTree, statementTree)).isTrue(); }