auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>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()); } } <START> List<Contentlet> cons = APILocator.getContentletAPIImpl().findContentlets(Lists.newArrayList(inodes)); <END> for (Contentlet pageContent : cons) { IHTMLPage htmlPage = APILocator.getHTMLPageAssetAPI().fromContentlet(pageContent); PageServices.invalidateAll(htmlPage); } }</code><technical_language>rename contenlets contentList</technical_language>

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:
<code>private void copyFiles() throws IOException { RemoteIterator<LocatedFileStatus> itr = dataFileSystem.listFiles(dataFileListPath, true); while (itr.hasNext()) { LocatedFileStatus fileStatus = itr.next(); if (shouldExport(fileStatus)) { <START> ReplCopyTask.doCopy(exportRootDataDir, exportFileSystem, fileStatus.getPath(), dataFileSystem, hiveConf); <END> } } }</code><technical_language>If data copy is lazy (need copy actual files), do in execution phase. This is analyze phase light-weight</technical_language>

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:
<code>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); <START> ensureRegionsOnDifferentServers(sourceTableName); <END> ensureRegionsOnDifferentServers(targetTableName); }</code><technical_language>method assumes regions, 4 regions for table. If I understand correctly, split table evenly 20 rows of 2 tenants assigning 2 region servers. implementation is working in manner</technical_language>

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:
<code>private NavigableMap<String, Long> collectValidDataSizeByLogSegment(long deleteReferenceTimeInMs, long expirationReferenceTimeInMs) throws StoreException { <START> Set<String> deletedKeys = new HashSet<>(); <END> 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; }</code><technical_language>reason this Set<StoreKey></technical_language>

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:
<code>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); <START> LOG.info("Value of ngram: "+ngram); <END> 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"); }</code><technical_language>Please correct effficient slf4j code notation e.g. LOG.info("Value of ngram: ", ngram);</technical_language>

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:
<code>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( <START> MessageFormat.format("Checksum compuation during version create: {0}", computedChecksum), END> 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; }</code><technical_language>typo: computation</technical_language>

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:
<code>public boolean showSearchBox() { <START> if (node.pluginManager != null && <END> node.pluginManager.isPluginLoaded("plugins.Library.Main")) { return true; } else { return false; } }</code><technical_language>if (a) return true else return false? kidding me? :)</technical_language>

Target:
public boolean showSearchBox() { return (node.pluginManager != null && node.pluginManager.isPluginLoaded("plugins.Library.Main")); }
Source:
<code>private static List<AliasedNode> extractFromSelect(List<AliasedNode> select, TableRef table, ColumnResolver resolver) throws SQLException { List<AliasedNode> ret = new ArrayList<AliasedNode>(); if (isWildCardSelect(select)) { <START> ret.add(NODE_FACTORY.aliasedNode(null, WildcardParseNode.INSTANCE, select.get(0).getArrayColumnNode())); <END> 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; }</code><technical_language>need for of this special casing</technical_language>

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:
<code>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()))); <START> } <END> if (getVds() == null) { returnValue = false; addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_NO_VDS_IN_POOL); } } return returnValue; }</code><technical_language>replace this RandomUtils.instance().pickRandom(hosts) - more elegant easy understand</technical_language>

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:
<code>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); <START> } catch (Throwable t) { <END> 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)"); } } }</code><technical_language>test succeed if tester.run assertTable throws exception. catch exception thrown in new SQLServerOutputPluginTest().connect()</technical_language>

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:
<code>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 { <START> downloadBlob(req, resp, doc, xpath, null, filename, EVENT_NAME); <END> } } catch (NuxeoException e) { if (tx) { TransactionHelper.setTransactionRollbackOnly(); } throw new IOException(e); } finally { if (tx) { TransactionHelper.commitOrRollbackTransaction(); } } }</code><technical_language>EVENT_NAME either</technical_language>

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:
<code>default void executeTask(final KeyFilter<? super K> filter, BiConsumer<? super K, InternalCacheEntry<K, V>> action) throws InterruptedException { <START> iterator().forEachRemaining(ice -> { <END> if (filter == null || filter.accept(ice.getKey())) { action.accept(ice.getKey(), ice); } }); }</code><technical_language>forEach too, gaining a lambda</technical_language>

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:
<code>private static void speedUpDTMManager() { <START> String className = System.getProperty(DTM_MANAGER_DEFAULT_PROP_NAME); <END> 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); } } }</code><technical_language>Inline</technical_language>

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:
<code>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; <START> if (url.startsWith("http")) { <END> 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); }</code><technical_language>getResource() method some fancy (unexpected?) for dealing file class-path references URLs. if passed in "http-example.war" classpath relative path valid, previously worked. strict starting "http", is "http://" "https://". a variant of CommonCommands.downloadUrlAs(...). existing variants good enough easy refactor that, download commands execute installing/deploying consistent. For example, installing curl wget - wget installed machine</technical_language>

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:
<code>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" <START> + " ]"; <END> 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")) )); }</code><technical_language>need manually hardcode JSON request. a getPatchContent() method generate this for you. another replace example another IT: <LINK_0></technical_language>

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:
<code>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]) { <START> if (annotation instanceof Auth && parameterTypes[i].equals(Optional.class) && authFilter != null) { <END> 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); } }</code><technical_language>I guess check annotation's type time: java if (annotation instanceof Auth) { // Optional auth requires a concrete AuthFilter provided. if (parameterTypes[i].equals(Optional.class) && authFilter != null) { context.register(new WebApplicationExceptionCatchingFilter(authFilter)); return; } else { registerAuthFilter(context); return; } }</technical_language>

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:
<code>protected KualiDecimal calculateTotalAmountForCashAdvanceLinesReferencedByRegularLines( List<ConcurStandardAccountingExtractDetailLine> regularDetailLines) { <START> return regularDetailLines.stream() <END> .map(ConcurStandardAccountingExtractDetailLine::getReportEntryId) .distinct() .map(cashAdvanceLinesByReportEntryId::get) .filter((cashAdvanceLine) -> cashAdvanceLine != null) .map(ConcurStandardAccountingExtractDetailLine::getJournalAmount) .reduce(KualiDecimal.ZERO, KualiDecimal::add); }</code><technical_language>this statement refactored for clarity? creation of some named variables help</technical_language>

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:
<code>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<>(); <START> if (accessor.getProperty(accessor.keyBuilder().customizedStateAggregationConfig()) != null) { <END> 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; }</code><technical_language>getProperty() real ZK traffic. get assign a local var</technical_language>

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:
<code>public @ServiceState.RilRadioTechnology int getCsCallRadioTech() { int vrat = ServiceState.RIL_RADIO_TECHNOLOGY_UNKNOWN; if (mSST != null) { <START> int vrs = mSST.mSS.getVoiceRegState(); vrat = mSST.mSS.getRilVoiceRadioTechnology(); <END> 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; }</code><technical_language>sending reg state voice technology in EVENT_VRS_OR_RAT_CHANGED message. here</technical_language>

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:
<code>public AssertsNearCache<K, V> expectNearPreemptiveRemove(K key, AssertsNearCache<K, V>... affected) { <START> if (nearCacheMode.invalidated()) { <END> MockRemoveEvent preemptiveRemove = pollEvent(events); assertEquals(key, preemptiveRemove.key); } expectNoNearEvents(); return this; }</code><technical_language>eager cache anymore..</technical_language>

Target:
public AssertsNearCache<K, V> expectNearPreemptiveRemove(K key, AssertsNearCache<K, V>... affected) { MockRemoveEvent preemptiveRemove = pollEvent(events); assertEquals(key, preemptiveRemove.key); expectNoNearEvents(); return this; }
Source:
<code>public int read(byte[] b, int off, int len) throws IOException { prepare(); int p = off; int n = 0; while (true) { if (len <= buf.remaining()) { <START> buf.get(b, off, len); <END> 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(); } }</code><technical_language>p here, len adjusted loop this len - n. This sort of bug is I modify arguments this is JGit warning policy in Eclipse. enabled warning in project settings is a bit paranoid in functions follow actively hurts readability of code</technical_language>

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:
<code>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 ), <START> dropAction ); <END> }</code><technical_language>live lines</technical_language>

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:
<code>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) { <START> DefaultPahoMessageConverter mConverter = new DefaultPahoMessageConverter( <END> 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; } }</code><technical_language>is reason of this variable? for single-threaded bean initialization. //NOSONAR then? :smile:</technical_language>

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:
<code>public String get(@NonNull String key) { try { <START> storageLock.lock(); <END> if (_storage == null) { throw new RuntimeException(EXCEPTION_STORAGE); } return _storage.get(key); } finally { storageLock.unlock(); } }</code><technical_language>of try block</technical_language>

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:
<code>public void initVertex() { super.initVertex(); if (maxBFSIteration == -1) { <START> maxBFSIteration = 10; END_BFS)); <END> } 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(); } }</code><technical_language>need change hard code ? previous parser is better</technical_language>

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:
<code>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)) { <START> PrintWriter javaExceptionWriter = new BoundedPrintWriter(stackTraceResult, CRASH_FILE_STACKTRACE_MAX_SIZE / 2); <END> 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(); }</code><technical_language>new BoundedPrintWriter(~stackTraceResult~ **printWriter** Currently, counter in printWriter is properly</technical_language>

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:
<code>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); <START> actionManager.registerAction("mavenContextMenu", mavenContextMenuGroup); <END> 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); }</code><technical_language>action a constant</technical_language>

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:
<code>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"); <START> assertEquals(errorOutput.toString().contains("User submission failed: You need to wait before posting again"), true); <END> assertFalse(res); }</code><technical_language>assertTrue() replaced</technical_language>

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:
<code>public void testGetForStoragePool() { <START> StorageDomain result = dao.getForStoragePool(existingDomain.getId(), Guid.createGuidFromString("6d849ebf-755f-4552-ad09-9a090cda105d")); <END> assertGetResult(result); }</code><technical_language>new Guid(String) - this literal null</technical_language>

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

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(); }