auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void oveflowMissingBackpressureExceptionDelayed() { TestSubscriber<Integer> ts = TestSubscriber.create(0); PublishSubject<Integer> ps = PublishSubject.create(); OperatorPublish.create(ps, new Func1<Observable<Integer>, Observable<Integer>>() { @Override public Observable<Integer> call(Observable<Integer> o) { return o; } }, true).unsafeSubscribe(ts); for (int i = 0; i < RxRingBuffer.SIZE * 2; i++) { ps.onNext(i); } ts.requestMore(RxRingBuffer.SIZE); <START> ts.assertValueCount(128); <END> ts.assertError(MissingBackpressureException.class); ts.assertNotCompleted(); Assert.assertEquals("Queue full?!", ts.getOnErrorEvents().get(0).getMessage()); Assert.assertFalse("Source has subscribers?", ps.hasObservers()); }</code><technical_language>RxRingBuffer.SIZE here</technical_language>

Target:
public void oveflowMissingBackpressureExceptionDelayed() { TestSubscriber<Integer> ts = TestSubscriber.create(0); PublishSubject<Integer> ps = PublishSubject.create(); OperatorPublish.create(ps, new Func1<Observable<Integer>, Observable<Integer>>() { @Override public Observable<Integer> call(Observable<Integer> o) { return o; } }, true).unsafeSubscribe(ts); for (int i = 0; i < RxRingBuffer.SIZE * 2; i++) { ps.onNext(i); } ts.requestMore(RxRingBuffer.SIZE); ts.assertValueCount(RxRingBuffer.SIZE); ts.assertError(MissingBackpressureException.class); ts.assertNotCompleted(); Assert.assertEquals("Queue full?!", ts.getOnErrorEvents().get(0).getMessage()); Assert.assertFalse("Source has subscribers?", ps.hasObservers()); }
Source:
<code>public void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException { <START> rsp.setStatus(HttpURLConnection.HTTP_UNAVAILABLE); <END> req.getView(this,"index.jelly").forward(req,rsp); }</code><technical_language>503, I missing</technical_language>

Target:
public void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException { rsp.setStatus(SC_SERVICE_UNAVAILABLE); req.getView(this,"index.jelly").forward(req,rsp); }
Source:
<code>public void setUp() throws Exception { IIntroPart intro = PlatformUI.getWorkbench().getIntroManager().getIntro(); if (intro != null) { PlatformUI.getWorkbench().getIntroManager().closeIntro(intro); } editor = (AbstractTextEditor) PlatformUI.getWorkbench().getActiveWorkbenchWindow() <START> .getActivePage().openEditor(new FileEditorInput(file), "org.eclipse.ui.genericeditor.GenericEditor"); <END> }</code><technical_language>In theory this result in a NPE, getActiveWorkbenchWindow, getActivePage openEditor return null if is relevant for this test</technical_language>

Target:
public void setUp() throws Exception { GenericEditorTestUtils.closeIntro(); editor = (AbstractTextEditor) PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getActivePage().openEditor(new FileEditorInput(GenericEditorTestUtils.getFile()), "org.eclipse.ui.genericeditor.GenericEditor"); }
Source:
<code>private DataStore findSnapshotImageStore(SnapshotInfo snapshot) { Boolean fullSnapshot = true; <START> Object payload = snapshot.getFullBackup(); <END> if (payload != null) { fullSnapshot = (Boolean)payload; } if (fullSnapshot) { return dataStoreMgr.getImageStore(snapshot.getDataCenterId()); } else { SnapshotInfo parentSnapshot = snapshot.getParent(); SnapshotDataStoreVO parentSnapshotOnBackupStore = null; if (parentSnapshot != null) { parentSnapshotOnBackupStore = _snapshotStoreDao.findBySnapshot(parentSnapshot.getId(), DataStoreRole.Image); } if (parentSnapshotOnBackupStore == null) { return dataStoreMgr.getImageStore(snapshot.getDataCenterId()); } return dataStoreMgr.getDataStore(parentSnapshotOnBackupStore.getDataStoreId(), parentSnapshotOnBackupStore.getRole()); } }</code><technical_language>If 'full backup' is a boolean, store type object</technical_language>

Target:
private DataStore findSnapshotImageStore(SnapshotInfo snapshot) { Boolean fullSnapshot = true; Boolean snapshotFullBackup = snapshot.getFullBackup(); if (snapshotFullBackup != null) { fullSnapshot = snapshotFullBackup; } if (fullSnapshot) { return dataStoreMgr.getImageStore(snapshot.getDataCenterId()); } else { SnapshotInfo parentSnapshot = snapshot.getParent(); SnapshotDataStoreVO parentSnapshotOnBackupStore = null; if (parentSnapshot != null) { parentSnapshotOnBackupStore = _snapshotStoreDao.findBySnapshot(parentSnapshot.getId(), DataStoreRole.Image); } if (parentSnapshotOnBackupStore == null) { return dataStoreMgr.getImageStore(snapshot.getDataCenterId()); } return dataStoreMgr.getDataStore(parentSnapshotOnBackupStore.getDataStoreId(), parentSnapshotOnBackupStore.getRole()); } }
Source:
<code>public void execute() throws MojoExecutionException, MojoFailureException { String jsonContents = null; File jsonFile; JsonObject jsonObject; String baseDir = null; try { baseDir = project.getBasedir() .getCanonicalPath() .toString(); } catch (IOException e) { getLog().error("Could not find base directory for package.json", e); } if (baseDir != null) { String[] fileList = getListOfPackageJsonFiles(baseDir, FILE_NAME); for (String filepath : fileList) { jsonFile = Paths.get(baseDir, File.separator, filepath).toFile(); try { <START> jsonContents = FileUtils.readFileToString(jsonFile, (Charset) null); <END> } catch (IOException e) { getLog().error("Could not find file", e); } JsonReader jsonReader = Json.createReader(new StringReader(jsonContents)); jsonObject = jsonReader.readObject(); checkJsonForRangeSymbols(jsonObject.getJsonObject("devDependencies"), jsonFile); checkJsonForRangeSymbols(jsonObject.getJsonObject("dependencies"), jsonFile); } } }</code><technical_language>This rewritten standard library if want remove another external dependency. I suggest converting a String need InputStream for JsonReader. Reader jsonReader = Files.newBufferedReader(Paths.get(baseDir, File.separator, filepath)))</technical_language>

Target:
public void execute() throws MojoExecutionException, MojoFailureException { String jsonContents; File jsonFile; boolean hasRangeChars = false; JsonObject jsonObject; String baseDir = null; try { baseDir = project.getBasedir() .getCanonicalPath(); } catch (IOException e) { getLog().error("Could not find base directory", e); } if (baseDir != null) { String[] fileList = getListOfPackageJsonFiles(baseDir, FILE_NAME); for (String filepath : fileList) { jsonFile = Paths.get(baseDir, File.separator, filepath) .toFile(); try { jsonContents = FileUtils.readFileToString(jsonFile, (Charset) null); JsonReader jsonReader = Json.createReader(new StringReader(jsonContents)); jsonObject = jsonReader.readObject(); hasRangeChars |= hasRangeChars(jsonObject.getJsonObject("devDependencies"), jsonFile.toString()); hasRangeChars |= hasRangeChars(jsonObject.getJsonObject("dependencies"), jsonFile.toString()); } catch (IOException e) { getLog().error("Could not find file", e); } } if (hasRangeChars) { throw new MojoFailureException(MOJO_EXCEPTION_MESSAGE); } } }
Source:
<code>public void testInlineLinkWithTitle() { <START> String html = parseToHtml("This is [ an example ](<LINK_0> \"Title\") inline link."); <END> TestUtil.println("HTML: " + html); String expectedHtml = "<p>This is <a href=\"<LINK_0>\" title=\"Title\">an example</a> inline link.</p>\n"; assertEquals(expectedHtml, html); }</code><technical_language>If follow this markup/expectedHtml pattern, consider refactoring a method takes markup expectedHtml parameters</technical_language>

Target:
public void testInlineLinkWithTitle() { String markup = "This is [ an example ](<LINK_0> \"Title\") inline link."; String expectedHtml = "<p>This is <a href=\"<LINK_0>\" title=\"Title\">an example</a> inline link.</p>\n"; parseAndAssert(markup, expectedHtml); }
Source:
<code>private Promise<Map<LinearRange, SnippetResult>> loadMatches(SearchResult element) { Map<LinearRange, SnippetResult> snippets = cache.get(element.getUri()); if (snippets != null) { return promiseProvider.resolve(snippets); } List<LinearRange> ranges = new ArrayList<>(); collectMatchRanges(element, ranges); SnippetParameters params = new org.eclipse.che.api.languageserver.shared.dto.DtoClientImpls.SnippetParametersDto( new SnippetParameters(element.getUri(), ranges)); return textDocumentService .getSnippets(params) .then( (List<SnippetResult> results) -> { Map<LinearRange, SnippetResult> snippets2 = new HashMap<>(); cache.put(element.getUri(), snippets2); results.forEach( result -> { snippets2.put(result.getLinearRange(), result); }); <START> return snippets2; <END> }); }</code><technical_language>I kind of names numeric suffix</technical_language>

Target:
private Promise<Map<LinearRange, SnippetResult>> loadMatches(SearchResult element) { Map<LinearRange, SnippetResult> snippets = cache.get(element.getUri()); if (snippets != null) { return promiseProvider.resolve(snippets); } List<LinearRange> ranges = new ArrayList<>(); collectMatchRanges(element, ranges); SnippetParameters params = new org.eclipse.che.api.languageserver.shared.dto.DtoClientImpls.SnippetParametersDto( new SnippetParameters(element.getUri(), ranges)); return textDocumentService .getSnippets(params) .then( (List<SnippetResult> results) -> { Map<LinearRange, SnippetResult> snippetMap = new HashMap<>(); cache.put(element.getUri(), snippets); results.forEach( result -> { snippetMap.put(result.getLinearRange(), result); }); return snippetMap; }); }
Source:
<code>private List<List<String>> parseCSVColumns(String source, int rows) { List<List<String>> columns = new ArrayList<List<String>>(); ByteArrayInputStream inputStream = new ByteArrayInputStream(source.getBytes()); CsvParser csvParser = new CsvParser(inputStream); for (int i = 0; i <= rows; ++i) { <START> if (!csvParser.hasNext()) { END> break; } List<String> row = csvParser.next(); for (int j = 0; j < row.size(); ++j) { if (columns.size() <= j) { columns.add(new ArrayList<String>()); } columns.get(j).add(row.get(j)); } } return columns; }</code><technical_language>combine this for loop conditional && removing negation</technical_language>

Target:
private List<List<String>> parseCSVColumns(String source, int rows) { List<List<String>> columns = new ArrayList<List<String>>(); ByteArrayInputStream inputStream = new ByteArrayInputStream(source.getBytes()); CsvParser csvParser = new CsvParser(inputStream); for (int i = 0; i <= rows && csvParser.hasNext(); ++i) { List<String> row = csvParser.next(); for (int j = 0; j < row.size(); ++j) { if (columns.size() <= j) { columns.add(new ArrayList<String>()); } columns.get(j).add(row.get(j)); } } return columns; }
Source:
<code>public void testOnlyConsiderRenditionUpToDateIfBlobsArePutInTransientStore() { checkInitialRendition(true); RenditionDefinition renditionDefinition = new RenditionDefinition(); renditionDefinition.setName(LAZY_AUTOMATION); AutomationLazyRenditionProvider lazyRenditionProvider = new AutomationLazyRenditionProvider(); String renditionKey = lazyRenditionProvider.buildRenditionKey(doc, renditionDefinition); TransientStore transientStore = transientStoreService.getStore(CACHE_NAME); String tsSourceDocumentModificationDate = (String) transientStore.getParameter(renditionKey, SOURCE_DOCUMENT_MODIFICATION_DATE_KEY); checkStaleRendition(true, false); String key; do { key = (String) transientStore.getParameter(renditionKey, SOURCE_DOCUMENT_MODIFICATION_DATE_KEY); <START> } while (tsSourceDocumentModificationDate.equals(key)); <END> checkUpToDateRendition(true); }</code><technical_language>long this typically take? add a 1ms sleep in loop avoid hogging CPU</technical_language>

Target:
public void testOnlyConsiderRenditionUpToDateIfBlobsArePutInTransientStore() throws InterruptedException { checkInitialRendition(true); RenditionDefinition renditionDefinition = new RenditionDefinition(); renditionDefinition.setName(LAZY_AUTOMATION); AutomationLazyRenditionProvider lazyRenditionProvider = new AutomationLazyRenditionProvider(); String renditionKey = lazyRenditionProvider.buildRenditionKey(doc, renditionDefinition); TransientStore transientStore = transientStoreService.getStore(CACHE_NAME); String tsSourceDocumentModificationDate = (String) transientStore.getParameter(renditionKey, SOURCE_DOCUMENT_MODIFICATION_DATE_KEY); checkStaleRendition(true, false); await().until(() -> !tsSourceDocumentModificationDate.equals( transientStore.getParameter(renditionKey, SOURCE_DOCUMENT_MODIFICATION_DATE_KEY))); checkUpToDateRendition(true); }
Source:
<code>public void requestResults( String query, Searcher searcher ) { String queryNormalized = StringNormalizer.normalize( query ); queryNormalized = queryNormalized.replaceAll("-", " "); FuzzyScore fuzzyScore = new FuzzyScore(); FuzzyScore.MatchInfo matchInfo = new FuzzyScore.MatchInfo(); for (ContactsPojo pojo : pojos) { boolean match = fuzzyScore.match( queryNormalized, pojo.nameNormalized, matchInfo ); pojo.relevance = matchInfo.score; <START> if ( match && !matchInfo.matchedIndices.isEmpty() ) <END> { List<Pair<Integer, Integer>> positions = matchInfo.getMatchedSequences(); try { pojo.setDisplayNameHighlightRegion( positions ); } catch( Exception e ) { StringBuilder sb = new StringBuilder(); for( Pair p : positions ) sb.append( "<" ) .append( p.first ) .append( "," ) .append( p.second ) .append( ">" ); Log.e( "TBog", sb.toString(), e ); pojo.setDisplayNameHighlightRegion( 0, pojo.nameNormalized.length() ); } } if ( !pojo.nickname.isEmpty() ) { if( fuzzyScore.match( queryNormalized, pojo.nickname, matchInfo ) ) { if( !match || (matchInfo.score > pojo.relevance) ) { match = true; pojo.relevance = matchInfo.score; pojo.displayName = pojo.name + " <small>({" + pojo.nickname + "})</small>"; } } } if ( !match && queryNormalized.length() > 2 ) { if( fuzzyScore.match( queryNormalized, pojo.phoneSimplified, matchInfo ) ) { match = true; pojo.relevance = matchInfo.score; pojo.setDisplayNameHighlightRegion(0, 0); } } if( match ) { if( !searcher.addResult( pojo ) ) return; } } }</code><technical_language>match, matchedIndices empty</technical_language>

Target:
public void requestResults( String query, Searcher searcher ) { StringNormalizer.Result queryNormalized = StringNormalizer.normalizeWithResult( query, false ); queryNormalized = queryNormalized.replaceAll(Character.codePointAt("-", 0), Character.codePointAt(" ", 0)); FuzzyScore fuzzyScore = new FuzzyScore( queryNormalized.codePoints ); FuzzyScore.MatchInfo matchInfo = new FuzzyScore.MatchInfo(); for (ContactsPojo pojo : pojos) { boolean match = fuzzyScore.match( pojo.normalizedName.codePoints, matchInfo ); pojo.relevance = matchInfo.score; if ( match ) { List<Pair<Integer, Integer>> positions = matchInfo.getMatchedSequences(); try { pojo.setDisplayNameHighlightRegion( positions ); } catch( Exception e ) { pojo.setDisplayNameHighlightRegion( 0, pojo.normalizedName.length() ); } } if ( !pojo.nickname.isEmpty() ) { if( fuzzyScore.match( pojo.nickname, matchInfo ) ) { if( !match || (matchInfo.score > pojo.relevance) ) { match = true; pojo.relevance = matchInfo.score; pojo.displayName = pojo.getName() + " <small>({" + pojo.nickname + "})</small>"; } } } if ( !match && queryNormalized.length() > 2 ) { if( fuzzyScore.match( pojo.phoneSimplified, matchInfo ) ) { match = true; pojo.relevance = matchInfo.score; pojo.setDisplayNameHighlightRegion(0, 0); } } if( match ) { if( !searcher.addResult( pojo ) ) return; } } }
Source:
<code>private static Optional<String> getNpcDisplayNameFromTag(ItemStack stack) { <START> if (stack.hasTagCompound() && stack.getTagCompound().hasKey(NPC_STORED_DATA_TAG) && stack.getTagCompound().getCompoundTag(NPC_STORED_DATA_TAG).hasKey("name")) { return Optional.of(stack.getTagCompound().getCompoundTag(NPC_STORED_DATA_TAG).getString("name")); <END> } else return Optional.empty(); }</code><technical_language>sense define a new variable for stack.getTagCompound() (let's "tag") shorten code more readable</technical_language>

Target:
private static Optional<String> getNpcDisplayNameFromTag(ItemStack stack) { if (stack.hasTagCompound()) { NBTTagCompound tag = stack.getTagCompound(); if (tag.hasKey(NPC_STORED_DATA_TAG) && tag.getCompoundTag(NPC_STORED_DATA_TAG).hasKey("name")) { return Optional.of(tag.getCompoundTag(NPC_STORED_DATA_TAG).getString("name")); } } return Optional.empty(); }
Source:
<code>private Promise workItemIconLoader(final WorkItemDefinition wid) { Console.log("RUNING MY CODE MAN"); final String iconUri = wid.getIconDefinition().getUri(); log("Loading icon for URI [" + iconUri + "]"); if (nonEmpty(iconUri)) { return resourceContentService .get(iconUri, ResourceContentOptions.binary()) .then(iconData -> { log("Content for icon = [" + iconData + "]"); if (nonEmpty(iconData)) { wid.getIconDefinition().setIconData(iconDataUri(iconUri, iconData)); } <START> return promises.resolve(DEFAULT_ICON_DATA); <END> }).catch_(error -> { log("Not able to load icon for URI " + iconUri); return Promise.resolve(DEFAULT_ICON_DATA); }); } return promises.resolve(DEFAULT_ICON_DATA); }</code><technical_language>I this is correct, implications final result... I mean, if exist some iconData, set model object, sholud return content a result for promise, it? I mean, actually, setting right iconData object model, work, if this API promise result, obtain default iconData, instead of actual one, it</technical_language>

Target:
private Promise workItemIconLoader(final WorkItemDefinition wid) { final String iconUri = wid.getIconDefinition().getUri(); log("Loading icon for URI [" + iconUri + "]"); if (nonEmpty(iconUri)) { return resourceContentService .get(iconUri, ResourceContentOptions.binary()) .then(iconData -> { log("Content for icon = [" + iconData + "]"); if (nonEmpty(iconData)) { if (!isIconDataUri(iconData)) { iconData = iconDataUri(iconUri, iconData); } wid.getIconDefinition().setIconData(iconData); } return promises.resolve(); }).catch_(error -> { log("Not able to load icon for URI " + iconUri); return Promise.resolve(""); }); } return promises.resolve(); }
Source:
<code>private void fillImplicationsWithUMLSubsets(ReferenceChange diff) { EReference reference = diff.getReference(); for (EObject ref : UMLCompareUtil.getNonUnionSupersetReferences(reference)) { <START> EReference superSet = (EReference)ref; <END> Comparison comparison = diff.getMatch().getComparison(); for (Diff superSetDiff : diff.getMatch().getComparison().getDifferences(superSet)) { if (superSetDiff instanceof ReferenceChange && ((ReferenceChange)superSetDiff).getReference() == superSet && ((ReferenceChange)superSetDiff).getValue() == diff.getValue()) { if (isAdd(comparison, diff) && isAdd(comparison, superSetDiff)) { diff.getImplies().add(superSetDiff); } else if (isDelete(diff) && isDelete(superSetDiff)) { diff.getImpliedBy().add(superSetDiff); } } } } }</code><technical_language>Do unchecked casts</technical_language>

Target:
private void fillImplicationsWithUMLSubsets(ReferenceChange diff) { EReference reference = diff.getReference(); for (EReference superSet : UMLCompareUtil.getNonUnionSupersetReferences(reference)) { Comparison comparison = diff.getMatch().getComparison(); for (Diff superSetDiff : comparison.getDifferences(superSet)) { if (superSetDiff instanceof ReferenceChange && ((ReferenceChange)superSetDiff).getReference() == superSet && ((ReferenceChange)superSetDiff).getValue() == diff.getValue()) { if (isAddOrSetDiff(diff) && isAddOrSetDiff(superSetDiff)) { diff.getImplies().add(superSetDiff); } else if (isDeleteOrUnsetDiff(diff) && isDeleteOrUnsetDiff(superSetDiff)) { diff.getImpliedBy().add(superSetDiff); } } } } }
Source:
<code>protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { TaggedValuePointable arg = args[0]; if (!(arg.getTag() == ValueTag.SEQUENCE_TAG || arg.getTag() == ValueTag.OBJECT_TAG)) { throw new SystemException(ErrorCode.FORG0006); } TaggedValuePointable tempTvp = ppool.takeOne(TaggedValuePointable.class); TaggedValuePointable tempValue = ppool.takeOne(TaggedValuePointable.class); try { abvs.reset(); ob.reset(abvs); tvps.clear(); if (arg.getTag() == ValueTag.SEQUENCE_TAG) { arg.getValue(sp); for (int i = 0; i < sp.getEntryCount(); ++i) { <START> op = (ObjectPointable) ObjectPointable.FACTORY.createPointable(); <END> sp.getEntry(i, tempTvp); tempTvp.getValue(op); op.getKeys(tempTvp); addPairs(tempTvp, tempValue); } } else { op = (ObjectPointable) ObjectPointable.FACTORY.createPointable(); arg.getValue(op); addPairs(tempTvp, tempValue); } ob.finish(); result.set(abvs); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001, e); } finally { ppool.giveBack(tempTvp); for (TaggedValuePointable pointable : tvps) { ppool.giveBack(pointable); } } }</code><technical_language>Add a check item is object</technical_language>

Target:
protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { TaggedValuePointable arg = args[0]; if (!(arg.getTag() == ValueTag.SEQUENCE_TAG || arg.getTag() == ValueTag.OBJECT_TAG)) { throw new SystemException(ErrorCode.FORG0006); } TaggedValuePointable tempTvp = ppool.takeOne(TaggedValuePointable.class); TaggedValuePointable tempValue = ppool.takeOne(TaggedValuePointable.class); try { abvs.reset(); ob.reset(abvs); tvps.clear(); if (arg.getTag() == ValueTag.SEQUENCE_TAG) { arg.getValue(sp); for (int i = 0; i < sp.getEntryCount(); ++i) { op = (ObjectPointable) ObjectPointable.FACTORY.createPointable(); sp.getEntry(i, tempTvp); tempTvp.getValue(op); op.getKeys(tempTvp); addPairs(tempTvp, tempValue); } } else if (arg.getTag() == ValueTag.OBJECT_TAG) { op = (ObjectPointable) ObjectPointable.FACTORY.createPointable(); arg.getValue(op); addPairs(tempTvp, tempValue); } ob.finish(); result.set(abvs); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001, e); } finally { ppool.giveBack(tempTvp); for (TaggedValuePointable pointable : tvps) { ppool.giveBack(pointable); } } }
Source:
<code>public void checkSpecificAccessControl() { String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); String studentEmail = getRequestParamValue(Const.ParamsNames.STUDENT_EMAIL); if (studentEmail != null && courseId != null) { StudentAttributes student = logic.getStudentForEmail(courseId, studentEmail); if (student == null) { throw new UnauthorizedAccessException(UNAUTHORIZED_ACCESS); } <START> <END> gateKeeper.verifyAccessibleForCurrentUserAsInstructorOrTeamMemberOrAdmin(logic.getAccount(userInfo.id), courseId, student.getSection(), student.getEmail()); } }</code><technical_language>This UnauthorizedAccessException me, 404 instead</technical_language>

Target:
public void checkSpecificAccessControl() { String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); String studentEmail = getRequestParamValue(Const.ParamsNames.STUDENT_EMAIL); if (studentEmail == null || courseId == null) { if (!userInfo.isStudent) { throw new UnauthorizedAccessException(UNAUTHORIZED_ACCESS); } } else { StudentAttributes student = logic.getStudentForEmail(courseId, studentEmail); if (student == null) { throw new UnauthorizedAccessException(UNAUTHORIZED_ACCESS); } gateKeeper.verifyAccessibleForCurrentUserAsInstructorOrTeamMemberOrAdmin(userInfo.id, courseId, student.getSection(), student.getEmail()); } }
Source:
<code>public UserDTO updateUser(UUID id, UserDTO userResource) { User originalUserEntity = getEntityByID(id); <START> if (originalUserEntity.isCreatedOnBuddyRequest()) <END> { throw new YonaException("User is created on buddy request, use other method"); } return handleUserUpdate(userResource, originalUserEntity); }</code><technical_language>Replace 4 lines assert originalUserEntity.isCreatedOnBuddyRequest()</technical_language>

Target:
public UserDTO updateUser(UUID id, UserDTO userResource) { User originalUserEntity = getEntityByID(id); if (originalUserEntity.isCreatedOnBuddyRequest()) { throw new IllegalArgumentException("User is created on buddy request, use other method"); } return UserDTO.createInstanceWithPrivateData(User.getRepository().save(userResource.updateUser(originalUserEntity))); }
Source:
<code>public AgentRegistryImpl(Set<Agent> agents) throws IOException { this.agents = new HashMap<>(agents.size()); <START> agents.forEach(a -> this.agents.put(a.getId(), a)); <END> }</code><technical_language>is declared 2 equal agents. If of equals hashcode multibinder throw error. If multibinder is declared support of duplicates throw exception. If equals hashcode is overridden overridden in a ways duplicate agent override previous one</technical_language>

Target:
public AgentRegistryImpl(Set<Agent> agents) throws IllegalArgumentException { this.agents = new HashMap<>(agents.size()); for (Agent agent : agents) { AgentKeyImpl key = new AgentKeyImpl(agent); Agent registeredAgent = this.agents.put(key, agent); if (registeredAgent != null) { throw new IllegalArgumentException(format("Agent with key %s has been registered already.", key)); } } }
Source:
<code>public static Collection<DimensionSpec> extractionsToRewrite(GroupByQuery query) { return Collections2.filter( query.getDimensions(), new Predicate<DimensionSpec>() { @Override public boolean apply(@Nullable DimensionSpec input) { <START> return input != null <END> && input.getExtractionFn() != null && ExtractionFn.ExtractionType.ONE_TO_ONE.equals( input.getExtractionFn().getExtractionType() ); } } ); }</code><technical_language>I removed null dimensions specs, no</technical_language>

Target:
public static Collection<DimensionSpec> extractionsToRewrite(GroupByQuery query) { return Collections2.filter( query.getDimensions(), new Predicate<DimensionSpec>() { @Override public boolean apply(DimensionSpec input) { return input.getExtractionFn() != null && ExtractionFn.ExtractionType.ONE_TO_ONE.equals( input.getExtractionFn().getExtractionType() ); } } ); }
Source:
<code>public void testGetRequirements() { try { File xmlValidFile = TmfXmlTestFiles.VALID_FILE.getFile(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document document; document = factory.newDocumentBuilder().parse(xmlValidFile); <START> NodeList stateProviders = document.getElementsByTagName(TmfXmlStrings.STATE_PROVIDER); <END> Node stateProvider = null; for (int i = 0; i < stateProviders.getLength(); i++) { stateProvider = stateProviders.item(i); String id = stateProvider.getAttributes().getNamedItem(TmfXmlStrings.ID).getNodeValue(); if (id != null && id.equals(SS_MODULE)) { break; } } assertNotNull(stateProvider); assertEquals(SS_MODULE, stateProvider.getAttributes().getNamedItem(TmfXmlStrings.ID).getNodeValue()); TmfAnalysisRequirement eventRequirement = null; for (TmfAnalysisRequirement req : fModule.getAnalysisRequirements()) { if (req.getType().equalsIgnoreCase(TmfXmlStrings.TYPE_EVENT_NAME)) { eventRequirement = req; } } assertNotNull(eventRequirement); NodeList eventHandlers = ((Element) stateProvider).getElementsByTagName(TmfXmlStrings.EVENT_HANDLER); int eventCount = 0; for (int i = 0; i < eventHandlers.getLength(); i++) { Node eventHandler = eventHandlers.item(i); String eventName = eventHandler.getAttributes().getNamedItem(TmfXmlStrings.TYPE_EVENT_NAME).getNodeValue(); assertTrue(eventRequirement.getValues().contains(eventName)); eventCount++; } assertEquals(eventCount, eventRequirement.getValues().size()); } catch (SAXException | IOException | ParserConfigurationException e) { fail(e.getMessage()); } }</code><technical_language>utility method XmlUtils: Element getElementInFile(String filePath, @NonNull String elementType, @NonNull String elementId), save 10 lines here. stateProvider casted Element already</technical_language>

Target:
public void testGetRequirements() { TmfAnalysisRequirement eventRequirement = null; for (TmfAnalysisRequirement req : fModule.getAnalysisRequirements()) { if (req.getType().equalsIgnoreCase(TmfXmlStrings.TYPE_EVENT_NAME)) { eventRequirement = req; } } assertNotNull(eventRequirement); assertEquals(13, eventRequirement.getValues().size()); Element stateProvider = XmlUtils.getElementInFile(TmfXmlTestFiles.VALID_FILE.getPath(), TmfXmlStrings.STATE_PROVIDER, SS_MODULE); assertNotNull(stateProvider); List<Element> eventHandlers = XmlUtils.getChildElements(stateProvider, TmfXmlStrings.EVENT_HANDLER); assertEquals(13, eventHandlers.size()); for (Element eventHandler : eventHandlers) { String eventName = eventHandler.getAttributes().getNamedItem(TmfXmlStrings.TYPE_EVENT_NAME).getNodeValue(); assertTrue(eventRequirement.getValues().contains(eventName)); } }
Source:
<code>protected Control createDialogArea(Composite parent) { Composite dlgArea = (Composite) super.createDialogArea(parent); Composite composite = new Composite(dlgArea, SWT.NONE); GridLayout layout = new GridLayout(); composite.setLayout(layout); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); composite.setLayoutData(gd); createStatesGroup(composite); setTitle(Messages.TmfTimeLegend_LEGEND); setDialogHelpAvailable(false); setHelpAvailable(false); composite.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { fResourceManager.dispose(); <START> } <END> }); return composite; }</code><technical_language>lambda</technical_language>

Target:
protected Control createDialogArea(Composite parent) { Composite dlgArea = (Composite) super.createDialogArea(parent); Composite composite = new Composite(dlgArea, SWT.NONE); GridLayout layout = new GridLayout(); composite.setLayout(layout); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); composite.setLayoutData(gd); createStatesGroup(composite); setTitle(Messages.TmfTimeLegend_LEGEND); setDialogHelpAvailable(false); setHelpAvailable(false); composite.addDisposeListener((e) -> { fResourceManager.dispose(); }); return composite; }
Source:
<code>public void onClick(View view) { int id = view.getId(); String owner = mRepository.getOwner().getLogin(); String name = mRepository.getName(); Intent intent = null; Context c = getActivity(); switch (id) { case R.id.cell_pull_requests: intent = IssueListActivity.makeIntent(c, owner, name, true); break; case R.id.tv_contributors_label: intent = ContributorListActivity.makeIntent(c, owner, name); break; case R.id.tv_collaborators_label: intent = CollaboratorListActivity.makeIntent(c, owner, name); break; case R.id.cell_issues: intent = IssueListActivity.makeIntent(c, owner, name); break; case R.id.cell_stargazers: intent = WatcherListActivity.makeIntent(c, owner, name); break; case R.id.cell_forks: intent = ForkListActivity.makeIntent(c, owner, name); break; case R.id.tv_wiki_label: intent = WikiListActivity.makeIntent(c, owner, name, null); break; case R.id.tv_downloads_label: intent = DownloadsActivity.makeIntent(c, owner, name); break; case R.id.tv_releases_label: intent = ReleaseListActivity.makeIntent(c, owner, name); break; default: if (view.getTag() instanceof Repository) intent = RepositoryActivity.makeIntent(c, (Repository) view.getTag()); <START> break; <END> } if (intent != null) { startActivity(intent); } }</code><technical_language>This change is unrelated</technical_language>

Target:
public void onClick(View view) { int id = view.getId(); String owner = mRepository.getOwner().getLogin(); String name = mRepository.getName(); Intent intent = null; if (id == R.id.cell_pull_requests) { intent = IssueListActivity.makeIntent(getActivity(), owner, name, true); } else if (id == R.id.tv_contributors_label) { intent = ContributorListActivity.makeIntent(getActivity(), owner, name); } else if (id == R.id.tv_collaborators_label) { intent = CollaboratorListActivity.makeIntent(getActivity(), owner, name); } else if (id == R.id.cell_issues) { intent = IssueListActivity.makeIntent(getActivity(), owner, name); } else if (id == R.id.cell_stargazers) { intent = WatcherListActivity.makeIntent(getActivity(), owner, name); } else if (id == R.id.cell_forks) { intent = ForkListActivity.makeIntent(getActivity(), owner, name); } else if (id == R.id.tv_wiki_label) { intent = WikiListActivity.makeIntent(getActivity(), owner, name, null); } else if (id == R.id.tv_downloads_label) { intent = DownloadsActivity.makeIntent(getActivity(), owner, name); } else if (id == R.id.tv_releases_label) { intent = ReleaseListActivity.makeIntent(getActivity(), owner, name); } else if (view.getTag() instanceof Repository) { intent = RepositoryActivity.makeIntent(getActivity(), (Repository) view.getTag()); } if (intent != null) { startActivity(intent); } }
Source:
<code>private void addFullyLinkArchiveVariables(CcToolchainVariables.Builder builder) { builder.addStringVariable( FULLY_LINKED_ARCHIVE_PATH_VARIABLE_NAME, fullyLinkArchive.getExecPathString()); <START> ImmutableSet<Artifact> ccLibs = new ImmutableSet.Builder() .addAll(objcProvider.getCcLibraries()) .build(); <END> Predicate<Artifact> isNotCcLib = library -> !ccLibs.contains(library); Iterable<Artifact> objcLibraries = Iterables.filter(objcProvider.getObjcLibraries(), isNotCcLib); builder.addStringSequenceVariable( OBJC_LIBRARY_EXEC_PATHS_VARIABLE_NAME, Artifact.toExecPaths(objcLibraries)); builder.addStringSequenceVariable( CC_LIBRARY_EXEC_PATHS_VARIABLE_NAME, Artifact.toExecPaths(objcProvider.getCcLibraries())); builder.addStringSequenceVariable( IMPORTED_LIBRARY_EXEC_PATHS_VARIABLE_NAME, Artifact.toExecPaths(objcProvider.get(IMPORTED_LIBRARY).toList())); }</code><technical_language>suggestion ImmutableSet<Artifact> ccLibs = ImmutableSet.copyOf(objcProvider.getCcLibraries());</technical_language>

Target:
private void addFullyLinkArchiveVariables(CcToolchainVariables.Builder builder) { builder.addStringVariable( FULLY_LINKED_ARCHIVE_PATH_VARIABLE_NAME, fullyLinkArchive.getExecPathString()); ImmutableSet<Artifact> ccLibs = ImmutableSet.copyOf(objcProvider.getCcLibraries()); Predicate<Artifact> isNotCcLib = library -> !ccLibs.contains(library); Iterable<Artifact> objcLibraries = Iterables.filter(objcProvider.getObjcLibraries(), isNotCcLib); builder.addStringSequenceVariable( OBJC_LIBRARY_EXEC_PATHS_VARIABLE_NAME, Artifact.toExecPaths(objcLibraries)); builder.addStringSequenceVariable( CC_LIBRARY_EXEC_PATHS_VARIABLE_NAME, Artifact.toExecPaths(objcProvider.getCcLibraries())); builder.addStringSequenceVariable( IMPORTED_LIBRARY_EXEC_PATHS_VARIABLE_NAME, Artifact.toExecPaths(objcProvider.get(IMPORTED_LIBRARY).toList())); }
Source:
<code>public void testWithFileWithoutParent() throws Exception { final DefaultConfiguration moduleConfig = createModuleConfig(JavadocPackageCheck.class); final File fileWithoutParent = spy(new File(getPath("annotation" + File.separator + "package-info.java"))); when(fileWithoutParent.getParent()).thenReturn(null); when(fileWithoutParent.getParentFile()).thenReturn(null); final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; verify(createChecker(moduleConfig), new File[] {fileWithoutParent}, <START> getPath("annotation" <END> + File.separator + "package-info.java"), expected); }</code><technical_language>need spy here</technical_language>

Target:
public void testWithFileWithoutParent() throws Exception { final DefaultConfiguration moduleConfig = createModuleConfig(JavadocPackageCheck.class); final File fileWithoutParent = spy(new File(getPath("noparentfile" + File.separator + "package-info.java"))); when(fileWithoutParent.getParent()).thenReturn(null); when(fileWithoutParent.getParentFile()).thenReturn(null); final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; verify(createChecker(moduleConfig), new File[] {fileWithoutParent}, getPath("annotation" + File.separator + "package-info.java"), expected); }
Source:
<code>private void pullImage(DockerTemplate dockerTemplate) throws IOException { final String imageName = dockerTemplate.getDockerTemplateBase().getImage(); List<Image> images = getClient().listImagesCmd().exec(); NameParser.ReposTag repostag = NameParser.parseRepositoryTag(imageName); final String fullImageName = repostag.repos + ":" + (repostag.tag.isEmpty() ? "latest" : repostag.tag); boolean imageExists = Iterables.any(images, new Predicate<Image>() { @Override public boolean apply(Image image) { return Arrays.asList(image.getRepoTags()).contains(fullImageName); } }); boolean pull = imageExists ? dockerTemplate.getPullStrategy().pullIfExists(imageName) : dockerTemplate.getPullStrategy().pullIfNotExists(imageName); if (pull) { LOGGER.info("Pulling image '{}' {}. This may take awhile...", imageName, imageExists ? "again" : "since one was not found"); long startTime = System.currentTimeMillis(); try { getClient().pullImageCmd(imageName).exec(new PullImageResultCallback()).awaitSuccess(); long pullTime = System.currentTimeMillis() - startTime; LOGGER.info("Finished pulling image '{}', took ms", imageName, pullTime); <START> } <END> catch (DockerClientException e) { LOGGER.error("Error while pulling image '{}'", imageName, e); } } }</code><technical_language>} catch (...) {</technical_language>

Target:
private void pullImage(DockerTemplate dockerTemplate) throws IOException { final String imageName = dockerTemplate.getDockerTemplateBase().getImage(); List<Image> images = getClient().listImagesCmd().exec(); NameParser.ReposTag repostag = NameParser.parseRepositoryTag(imageName); final String fullImageName = repostag.repos + ":" + (repostag.tag.isEmpty() ? "latest" : repostag.tag); boolean imageExists = Iterables.any(images, new Predicate<Image>() { @Override public boolean apply(Image image) { return Arrays.asList(image.getRepoTags()).contains(fullImageName); } }); boolean pull = imageExists ? dockerTemplate.getPullStrategy().pullIfExists(imageName) : dockerTemplate.getPullStrategy().pullIfNotExists(imageName); if (pull) { LOGGER.info("Pulling image '{}' {}. This may take awhile...", imageName, imageExists ? "again" : "since one was not found"); long startTime = System.currentTimeMillis(); getClient().pullImageCmd(imageName).exec(new PullImageResultCallback()).awaitSuccess(); long pullTime = System.currentTimeMillis() - startTime; LOGGER.info("Finished pulling image '{}', took ms", imageName, pullTime); } }
Source:
<code>private static IndexMetadata build(ColumnMetadata column, Map<String, String> indexColumns) { if (indexColumns.isEmpty()) return null; String type = indexColumns.get(INDEX_TYPE); if (type == null) return null; <START> if (!indexColumns.containsKey(INDEX_OPTIONS)) <END> return new IndexMetadata(column, indexColumns.get(INDEX_NAME)); String indexOptionsCol = indexColumns.get(INDEX_OPTIONS); if (indexOptionsCol == null || indexOptionsCol.isEmpty() || indexOptionsCol.equals("null")) return new IndexMetadata(column, indexColumns.get(INDEX_NAME)); else { Map<String, String> indexOptions = SimpleJSONParser.parseStringMap(indexOptionsCol); return new IndexMetadata(column, indexColumns.get(INDEX_NAME), indexOptions); } }</code><technical_language>I need this if block anymore</technical_language>

Target:
private static IndexMetadata build(ColumnMetadata column, Map<String, String> indexColumns) { if (indexColumns.isEmpty()) return null; String type = indexColumns.get(INDEX_TYPE); if (type == null) return null; String indexOptionsCol = indexColumns.get(INDEX_OPTIONS); if (indexOptionsCol == null || indexOptionsCol.isEmpty() || indexOptionsCol.equals("null")) return new IndexMetadata(column, indexColumns.get(INDEX_NAME)); else { Map<String, String> indexOptions = SimpleJSONParser.parseStringMap(indexOptionsCol); return new IndexMetadata(column, indexColumns.get(INDEX_NAME), indexOptions); } }
Source:
<code>public void onReceive(Iterable<EventData> events) { if (events != null) { events.forEach(event -> { <START> byte[] decryptedBody = event.getBytes(); <END> if (serde != null) { decryptedBody = serde.fromBytes(decryptedBody); } EventDataWrapper wrappedEvent = new EventDataWrapper(event, decryptedBody); try { updateMetrics(event); put(ssp, new IncomingMessageEnvelope(ssp, event.getSystemProperties().getOffset(), event.getSystemProperties().getPartitionKey(), wrappedEvent)); } catch (Exception e) { String msg = String.format("Exception while adding the event from ssp %s to dispatch queue.", ssp); LOG.error(msg, e); throw new SamzaException(msg, e); } }); } }</code><technical_language>Remove references encryption de-cryption everywhere? orthogonal record payloadss</technical_language>

Target:
public void onReceive(Iterable<EventData> events) { if (events != null) { events.forEach(event -> { byte[] eventDataBody = event.getBytes(); if (interceptor != null) { eventDataBody = interceptor.intercept(eventDataBody); } String offset = event.getSystemProperties().getOffset(); Object partitionKey = event.getSystemProperties().getPartitionKey(); try { updateMetrics(event); put(ssp, new EventHubIncomingMessageEnvelope(ssp, offset, partitionKey, eventDataBody, event)); } catch (InterruptedException e) { String msg = String.format("Interrupted while adding the event from ssp %s to dispatch queue.", ssp); LOG.error(msg, e); throw new SamzaException(msg, e); } streamPartitionOffsets.put(ssp, offset); }); } }
Source:
<code>private static void updateNetwrokDetailsInInterface(VDS vds, Map<String, Integer> currVlans, Map<String, Integer> networkVlans, XmlRpcStruct network, network net, String ifaceName) { VdsNetworkInterface iface = null; for (VdsNetworkInterface tempInterface : vds.getInterfaces()) { if (tempInterface.getName().equals(ifaceName)) { iface = tempInterface; break; } } if (iface != null) { iface.setNetworkName(net.getname()); if (currVlans.containsKey(iface.getName())) { networkVlans.put(net.getname(), currVlans.get(iface.getName())); } iface.setAddress(net.getaddr()); <START> iface.setBridged(true); <END> if (StringHelper.EqOp(iface.getNetworkName(), NetworkUtils.getEngineNetwork())) { iface.setType(iface.getType() | VdsInterfaceType.Management.getValue()); } iface.setSubnet(net.getsubnet()); iface.setGateway(net.getgateway()); java.util.Map networkConfigAsMap = (java.util.Map) ((network.getItem("cfg") instanceof java.util.Map) ? network .getItem("cfg") : null); XmlRpcStruct networkConfig = networkConfigAsMap == null ? null : new XmlRpcStruct( networkConfigAsMap); AddBootProtocol(networkConfig, iface); } }</code><technical_language>This detected actual provided VDSM, bridgeless well</technical_language>

Target:
private static void updateNetwrokDetailsInInterface(VDS vds, Map<String, Integer> currVlans, Map<String, Integer> networkVlans, XmlRpcStruct network, network net, String ifaceName) { VdsNetworkInterface iface = null; for (VdsNetworkInterface tempInterface : vds.getInterfaces()) { if (tempInterface.getName().equals(ifaceName)) { iface = tempInterface; break; } } if (iface != null) { iface.setNetworkName(net.getname()); if (currVlans.containsKey(iface.getName())) { networkVlans.put(net.getname(), currVlans.get(iface.getName())); } iface.setAddress(net.getaddr()); boolean bridged = false; if (network.getItem("bridged") != null) { bridged = Boolean.parseBoolean(network.getItem("bridged").toString()); } iface.setBridged(bridged); if (StringHelper.EqOp(iface.getNetworkName(), NetworkUtils.getEngineNetwork())) { iface.setType(iface.getType() | VdsInterfaceType.Management.getValue()); } iface.setSubnet(net.getsubnet()); iface.setGateway(net.getgateway()); Map<String, Object> networkConfigAsMap = (Map<String, Object>) ((network.getItem("cfg") instanceof Map) ? network.getItem("cfg") : null); XmlRpcStruct networkConfig = networkConfigAsMap == null ? null : new XmlRpcStruct( networkConfigAsMap); AddBootProtocol(networkConfig, iface); } }
Source:
<code>public Entry getEntryFromTuple(YailList tuple) { try { String xValue = tuple.getString(0); String yValue = tuple.getString(1); try { float y = Float.parseFloat(yValue); return new PieEntry(y, xValue); } catch (NumberFormatException e) { } } catch (Exception e) { } <START> return null; <END> }</code><technical_language>Returning null for sorts of pain of callers checking for this. exception bubble stack code proceed if is wrong</technical_language>

Target:
public Entry getEntryFromTuple(YailList tuple) { try { String xValue = tuple.getString(0); String yValue = tuple.getString(1); try { float y = Float.parseFloat(yValue); return new PieEntry(y, xValue); } catch (NumberFormatException e) { this.view.getForm().dispatchErrorOccurredEvent(this.view.chartComponent, "GetEntryFromTuple", ErrorMessages.ERROR_INVALID_CHART_ENTRY_VALUES, xValue, yValue); } } catch (NullPointerException e) { this.view.getForm().dispatchErrorOccurredEvent(this.view.chartComponent, "GetEntryFromTuple", ErrorMessages.ERROR_NULL_CHART_ENTRY_VALUES); } catch (IndexOutOfBoundsException e) { this.view.getForm().dispatchErrorOccurredEvent(this.view.chartComponent, "GetEntryFromTuple", ErrorMessages.ERROR_INSUFFICIENT_CHART_ENTRY_VALUES, getTupleSize(), tuple.size()); } return null; }
Source:
<code>private void updateColumnNamesInSetQuery(SetOperatorNode setOperatorNode, String columnName, int columnPosition) throws StandardException { ResultColumn rc; <START> boolean replacementDone = false; <END> if (setOperatorNode.getLeftResultSet() instanceof SetOperatorNode) { updateColumnNamesInSetQuery((SetOperatorNode)setOperatorNode.getLeftResultSet(), columnName, columnPosition); } else { rc = setOperatorNode.getLeftResultSet().getResultColumns().elementAt(columnPosition); rc.setName(columnName); } if (setOperatorNode.getRightResultSet() instanceof SetOperatorNode) updateColumnNamesInSetQuery((SetOperatorNode)setOperatorNode.getRightResultSet(), columnName, columnPosition); else { rc = setOperatorNode.getRightResultSet().getResultColumns().elementAt(columnPosition); rc.setName(columnName); } rc = setOperatorNode.getResultColumns().elementAt(columnPosition);; rc.setName(columnName); ColumnReference columnReference = (ColumnReference) getNodeFactory().getNode( C_NodeTypes.COLUMN_REFERENCE, columnName, null, getContextManager()); rc.setExpression(columnReference); }</code><technical_language>This flag is anywhere. Remove</technical_language>

Target:
private void updateColumnNamesInSetQuery(SetOperatorNode setOperatorNode, String columnName, int columnPosition) throws StandardException { ResultColumn rc; if (setOperatorNode.getLeftResultSet() instanceof SetOperatorNode) { updateColumnNamesInSetQuery((SetOperatorNode)setOperatorNode.getLeftResultSet(), columnName, columnPosition); } else { rc = setOperatorNode.getLeftResultSet().getResultColumns().elementAt(columnPosition); rc.setName(columnName); } if (setOperatorNode.getRightResultSet() instanceof SetOperatorNode) updateColumnNamesInSetQuery((SetOperatorNode)setOperatorNode.getRightResultSet(), columnName, columnPosition); else { rc = setOperatorNode.getRightResultSet().getResultColumns().elementAt(columnPosition); rc.setName(columnName); } rc = setOperatorNode.getResultColumns().elementAt(columnPosition); rc.setName(columnName); ColumnReference columnReference = (ColumnReference) getNodeFactory().getNode( C_NodeTypes.COLUMN_REFERENCE, columnName, null, getContextManager()); rc.setExpression(columnReference); }
Source:
<code>public static PrefixMapping calcInUsePrefixMapping(Graph graph, PrefixMapping prefixMapping) { Map<String, String> pmap = prefixMapping.getNsPrefixMap() ; Trie<String> trie = new Trie<>() ; pmap.forEach((prefix,uri)-> trie.add(uri, prefix)) ; Iterator<Triple> iter = graph.find(null, null, null) ; Set<String> inUse = new HashSet<>() ; Consumer<Node> process = (node)->{ if ( ! node.isURI() ) return ; String uri = node.getURI() ; List<String> hits = trie.partialSearch(uri) ; <START> if ( hits == null || hits.isEmpty() ) <END> return ; inUse.addAll(hits) ; } ; while(iter.hasNext()) { Triple triple = iter.next() ; process.accept(triple.getSubject()) ; process.accept(triple.getPredicate()) ; process.accept(triple.getObject()) ; if ( pmap.size() == inUse.size() ) break ; } if ( pmap.size() == inUse.size() ) return prefixMapping ; PrefixMapping pmap2 = new PrefixMappingImpl() ; inUse.forEach((prefix)-> pmap2.setNsPrefix(prefix, prefixMapping.getNsPrefixURI(prefix)) ) ; return pmap2 ; }</code><technical_language>I partialSearch returns null, harmless leave check here</technical_language>

Target:
public static PrefixMapping calcInUsePrefixMapping(Graph graph, PrefixMapping prefixMapping) { Map<String, String> pmap = prefixMapping.getNsPrefixMap() ; Trie<String> trie = new Trie<>() ; pmap.forEach((prefix,uri)-> trie.add(uri, prefix)) ; Iterator<Triple> iter = graph.find(null, null, null) ; Set<String> inUse = new HashSet<>() ; Consumer<Node> process = (node)->{ if ( ! node.isURI() ) return ; String uri = node.getURI() ; List<String> hits = trie.partialSearch(uri) ; if ( hits.isEmpty() ) return ; inUse.addAll(hits) ; } ; while(iter.hasNext()) { Triple triple = iter.next() ; process.accept(triple.getSubject()) ; process.accept(triple.getPredicate()) ; process.accept(triple.getObject()) ; if ( pmap.size() == inUse.size() ) break ; } if ( pmap.size() == inUse.size() ) return prefixMapping ; PrefixMapping pmap2 = new PrefixMappingImpl() ; inUse.forEach((prefix)-> pmap2.setNsPrefix(prefix, prefixMapping.getNsPrefixURI(prefix)) ) ; return pmap2 ; }