auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Set<SearchFilterItem> getActiveFilterItems(SearchFilter filter) { String filterMapKey = filter.getFilterTypeMapKey(); if (filterMapKey.equals(JournalFilterType.JOURNAL_FILTER_MAP_KEY)) { return filter.getActiveFilterItems(journalKeys); } else if (filterMapKey.equals(SingletonSearchFilterType.ARTICLE_TYPE.getFilterMapKey())) { return filter.getActiveFilterItems(articleTypes); } else if (filterMapKey.equals(SingletonSearchFilterType.SUBJECT_AREA.getFilterMapKey())) { return filter.getActiveFilterItems(subjectList); } else if (filterMapKey.equals(SingletonSearchFilterType.AUTHOR.getFilterMapKey())) { return filter.getActiveFilterItems(authors); } else if (filterMapKey.equals(SingletonSearchFilterType.SECTION.getFilterMapKey())) { <START> return filter.getActiveFilterItems(sections); <END> } else { throw new RuntimeException("Search Filter not configured with sane map key: " + filterMapKey); } }</code><technical_language>I idea for factor out else ifs. Want pair it</technical_language>

Target:
public Set<SearchFilterItem> getActiveFilterItems(SearchFilter filter) { String filterMapKey = filter.getFilterTypeMapKey(); Function<CommonParams, List<String>> getter = FILTER_KEYS_TO_FIELDS.get(filterMapKey); if (getter == null) { throw new RuntimeException("Search Filter not configured with sane map key: " + filterMapKey); } return filter.getActiveFilterItems(getter.apply(this)); }
Source:
<code>private Iterable<ImmutableBitmap> getBitmapIterable(final BitmapIndexSelector selector) { if (isSimpleEquals()) { return ImmutableList.of(selector.getBitmapIndex(dimension, likeMatcher.getPrefix())); } else if (isSimplePrefix()) { final BitmapIndex bitmapIndex = selector.getBitmapIndex(dimension); if (bitmapIndex == null) { return ImmutableList.of(likeMatcher.matches(null) ? Filters.allTrue(selector) : Filters.allFalse(selector)); } final Indexed<String> dimValues = selector.getDimensionValues(dimension); return Filters.bitmapsFromIndexes( getDimValueIndexIterableForPrefixMatch(bitmapIndex, dimValues), bitmapIndex ); } else { return ImmutableList.of( <START> Filters.matchPredicate( <END> dimension, selector, likeMatcher.predicateFactory(extractionFn).makeStringPredicate() ) ); } }</code><technical_language>getBitmapIterable() is called estimateSelectivity(), this fallback is nonsense, point of estimateSelectivity() is avoid materializing _this_ bitmap. fixed adding a method Iterable<ImmutableBitmap> Filters.predicateMatchingBitmaps()</technical_language>

Target:
private Iterable<ImmutableBitmap> getBitmapIterable(final BitmapIndexSelector selector) { if (isSimpleEquals()) { return ImmutableList.of(selector.getBitmapIndex(dimension, likeMatcher.getPrefix())); } else if (isSimplePrefix()) { final BitmapIndex bitmapIndex = selector.getBitmapIndex(dimension); if (bitmapIndex == null) { return ImmutableList.of(likeMatcher.matches(null) ? Filters.allTrue(selector) : Filters.allFalse(selector)); } final Indexed<String> dimValues = selector.getDimensionValues(dimension); return Filters.bitmapsFromIndexes( getDimValueIndexIterableForPrefixMatch(bitmapIndex, dimValues), bitmapIndex ); } else { return Filters.matchPredicateNoUnion( dimension, selector, likeMatcher.predicateFactory(extractionFn).makeStringPredicate() ); } }
Source:
<code><START> protected Child getNoLabelsChild() throws IllegalArgumentException { <END> if (noLabelsChild == null) { throw new IllegalArgumentException("For a labelled metric you must specify the labels"); } return noLabelsChild; }</code><technical_language>IllegalArgumentException is a runtime exception, need declare it</technical_language>

Target:
protected Child getNoLabelsChild() { if (noLabelsChild == null) { throw new IllegalArgumentException("For a labelled metric you must specify the labels"); } return noLabelsChild; }
Source:
<code>public boolean filter(CategoryDTO category) { boolean result = true; if (!containCommercialApplications.getValue()) { result &= category.getApplications().stream() .anyMatch(application -> application.getScripts().stream().anyMatch(script -> script.isFree())); } if (containRequiresPatchApplications.getValue()) { result &= category.getApplications().stream().anyMatch( application -> application.getScripts().stream().anyMatch(script -> !script.isRequiresPatch())); } if (!containTestingApplications.getValue()) { result &= category.getApplications().stream().anyMatch(application -> application.getScripts().stream() .anyMatch(script -> CollectionUtils.isEmpty(script.getTestingOperatingSystems()))); } if (!containAllOSCompatibleApplications.getValue()) { result &= category.getApplications().stream() .anyMatch(application -> application.getScripts().stream() .anyMatch(script -> script.getCompatibleOperatingSystems() <START> .contains(operatingSystemFetcher.fetchCurrentOperationSystem()))); <END> } return result && category.getApplications().stream() .anyMatch(application -> filterTextMatcher.test(filterText.getValue(), application)); }</code><technical_language>I guess this crash if getCompatibleOperatingSystems() returns null</technical_language>

Target:
public boolean filter(CategoryDTO category) { boolean result = true; if (!containCommercialApplications.getValue()) { result &= category.getApplications().stream() .anyMatch(application -> application.getScripts().stream().anyMatch(script -> script.isFree())); } if (containRequiresPatchApplications.getValue()) { result &= category.getApplications().stream().anyMatch( application -> application.getScripts().stream().anyMatch(script -> !script.isRequiresPatch())); } if (!containTestingApplications.getValue()) { result &= category.getApplications().stream().anyMatch(application -> application.getScripts().stream() .anyMatch(script -> CollectionUtils.isEmpty(script.getTestingOperatingSystems()))); } if (!containAllOSCompatibleApplications.getValue()) { result &= category.getApplications().stream() .anyMatch(application -> application.getScripts().stream() .filter(script -> !CollectionUtils.isEmpty(script.getCompatibleOperatingSystems())) .anyMatch(script -> script.getCompatibleOperatingSystems() .contains(operatingSystemFetcher.fetchCurrentOperationSystem()))); } return result && category.getApplications().stream() .anyMatch(application -> filterTextMatcher.test(filterText.getValue(), application)); }
Source:
<code>public ContainerLaunchContext preLaunch(ContainerLaunchContext context) { if (log.isDebugEnabled()) { log.debug("preLaunch: " + context); } AppmasterService service = getAppmasterService(); if (service != null) { int port = service.getPort(); String address = service.getHost(); Map<String, String> env = new HashMap<String, String>(context.getEnvironment()); env.put(YarnSystemConstants.AMSERVICE_PORT, Integer.toString(port)); env.put(YarnSystemConstants.AMSERVICE_HOST, address); <START> env.put(YarnSystemConstants.SYARN_CONTAINER_ID, ConverterUtils.toString(context.getContainerId())); <END> context.setEnvironment(env); return context; } else { return context; } }</code><technical_language>this converter does, is a plain toString in Shell. purpose</technical_language>

Target:
public ContainerLaunchContext preLaunch(ContainerLaunchContext context) { if (log.isDebugEnabled()) { log.debug("preLaunch: " + context); } AppmasterService service = getAppmasterService(); if (service != null) { int port = service.getPort(); String address = service.getHost(); Map<String, String> env = new HashMap<String, String>(context.getEnvironment()); env.put(YarnSystemConstants.AMSERVICE_PORT, Integer.toString(port)); env.put(YarnSystemConstants.AMSERVICE_HOST, address); env.put(YarnSystemConstants.SYARN_CONTAINER_ID, ConverterUtils.toString(context.getContainerId())); context.setEnvironment(env); } return context; }
Source:
<code>private void postIssueComment(PullRequestRef pr, PostJobIssue issue, Map<String, StashCommentReport> commentsByFile, StashDiffReport diffReport, StashClient stashClient, Optional<Severity> taskSeverityThreshold ) throws StashClientException, StashConfigurationException { String issueKey = issue.key(); String path = getIssuePath(issue); StashCommentReport comments = commentsByFile.get(path); String commentContent = getMarkdownPrinter().printIssueMarkdown(issue); Integer issueLine = issue.line(); if (issueLine == null) { issueLine = 0; } if (comments != null && comments.contains(commentContent, path, issueLine)) { LOGGER.debug("Comment \"{}\" already pushed on file ({})", issueKey, path, issueLine); return; } IssueType type = diffReport.getType(path, issueLine, config.issueVicinityRange()); if (type == null) { <START> LOGGER.debug( <END> "Comment \"{}\" cannot be pushed to Stash like it does not belong to diff view - (line: {})", issueKey, path, issueLine); return; } long line = diffReport.getLine(path, issueLine); StashComment comment = stashClient .postCommentLineOnPullRequest(pr, commentContent, path, line, type); LOGGER .info("Comment \"{}\" has been created ({}) on file ({})", issueKey, type, path, line); if ( taskSeverityThreshold.isPresent() && issue.severity().compareTo(taskSeverityThreshold.get()) >= 0 ) { stashClient.postTaskOnComment(issue.message(), comment.getId()); if (LOGGER.isInfoEnabled()) { LOGGER.info("Comment \"{}\" has been linked to a Stash task", comment.getId()); } } }</code><technical_language>Sorry. yes. This happen commonly. common case is in case of misconfigurations. clear level choose</technical_language>

Target:
private void postIssueComment(PullRequestRef pr, PostJobIssue issue, Map<String, StashCommentReport> commentsByFile, StashDiffReport diffReport, StashClient stashClient, Optional<Severity> taskSeverityThreshold ) throws StashClientException, StashConfigurationException { String issueKey = issue.key(); String path = getIssuePath(issue); StashCommentReport comments = commentsByFile.get(path); String commentContent = getMarkdownPrinter().printIssueMarkdown(issue); Integer issueLine = issue.line(); if (issueLine == null) { issueLine = 0; } if (comments != null && comments.contains(commentContent, path, issueLine)) { LOGGER.debug("Comment \"{}\" already pushed on file ({})", issueKey, path, issueLine); return; } IssueType type = diffReport.getType(path, issueLine, config.issueVicinityRange()); if (type == null) { LOGGER.info( "Comment \"{}\" cannot be pushed to Stash like it does not belong to diff view - (line: {})", issueKey, path, issueLine); return; } long line = diffReport.getLine(path, issueLine); StashComment comment = stashClient .postCommentLineOnPullRequest(pr, commentContent, path, line, type); LOGGER .info("Comment \"{}\" has been created ({}) on file ({})", issueKey, type, path, line); if ( taskSeverityThreshold.isPresent() && issue.severity().compareTo(taskSeverityThreshold.get()) >= 0 ) { stashClient.postTaskOnComment(issue.message(), comment.getId()); if (LOGGER.isInfoEnabled()) { LOGGER.info("Comment \"{}\" has been linked to a Stash task", comment.getId()); } } }
Source:
<code>public void getProjectById() throws Exception { final Project project = gd.getProjectService().getProjectById(this.project.getId()); <START> assertThat(project, project(this.project)); <END> }</code><technical_language>This is naturally readable. rename project() method hasSameIdAs(). naming problem is in other matchers</technical_language>

Target:
public void getProjectById() throws Exception { final Project project = gd.getProjectService().getProjectById(this.project.getId()); assertThat(project, hasSameIdAs(this.project)); }
Source:
<code><START> public void close() { <END> input.close(); }</code><technical_language>Build failed: Need throw IOException catch public void close(){ try { if (input != null) input.close() } catch (IOException e) { // } }</technical_language>

Target:
public void close() { try { if (input != null) input.close(); } catch (IOException e) { } }
Source:
<code>public void test() throws Exception { DesktopAgent desktop = connect(); desktop.query("button").click(); Assert.assertEquals("4", desktop.query("#result").as(Label.class).getValue()); desktop.query("button").click(); Assert.assertEquals("4", desktop.query("#result").as(Label.class).getValue()); desktop.query("button").click(); Assert.assertEquals("4", desktop.query("#result").as(Label.class).getValue()); <START> } <END></code><technical_language>add detach innerVM</technical_language>

Target:
public void test() throws Exception { DesktopAgent desktop = connect(); ComponentAgent saveBtn = desktop.query("#save"); saveBtn.click(); Assert.assertEquals("4", desktop.query("#result").as(Label.class).getValue()); saveBtn.click(); Assert.assertEquals("4", desktop.query("#result").as(Label.class).getValue()); saveBtn.click(); Assert.assertEquals("4", desktop.query("#result").as(Label.class).getValue()); desktop.query("#detach").click(); saveBtn.click(); Assert.assertEquals("1", desktop.query("#result").as(Label.class).getValue()); }
Source:
<code>public void testOperationExtractAlltext() throws Exception { <START> OperationChain chain = new OperationChain("testChain"); ctx.setInput(testDoc); chain.add(PDFExtractTextOperation.ID) .set("save", false) .set("targetxpath", "dc:description"); DocumentModel documentModified = (DocumentModel) automationService.run(ctx, chain); String text = (String) documentModified.getPropertyValue("dc:description"); assertNotNull(text); assertEquals(19045, text.length()); assertFalse(text.contains("Something that is not in the file")); assertTrue(text.contains("13.1")); chain = new OperationChain("testChain"); ctx.setInput(testDoc); chain.add(PDFExtractTextOperation.ID) .set("save", false) .set("targetxpath", "dc:description") .set("patterntofind", ""); documentModified = (DocumentModel) automationService.run(ctx, chain); text = (String) documentModified.getPropertyValue("dc:description"); assertNotNull(text); assertEquals(19045, text.length()); assertFalse(text.contains("Something that is not in the file")); assertTrue(text.contains("13.1")); <END> }</code><technical_language>factorize 2 cases difference is setting patterntofind not</technical_language>

Target:
public void testOperationExtractAlltext() throws Exception { doTestExtractAllText(false); doTestExtractAllText(true); }
Source:
<code><START> public FindEventsRequestBuilder withDefaults() { <END> this.eventLogCategory = DEFAULT_EVENT_LOG_CATEGORY; this.from = DateConverter.createXMLGregorianCalendar(DEFAULT_FROM.toDate()); this.until = DateConverter.createXMLGregorianCalendar(DEFAULT_UNTIL.toDate()); return this; }</code><technical_language>This implementation is good enough, I if replacing a call return fromParameterMap(Collections.emptyMap()) communicate parts defaults, if some parameters (next a bit shorter)</technical_language>

Target:
public FindEventsRequestBuilder withDefaults() { return this.fromParameterMap(Collections.emptyMap()); }
Source:
<code>private Timer getLoadTimer(final DSFSessionState sessionState, final int timeout) { <START> final VisualizerModel model = fDataModel; <END> Timer t = new Timer(timeout) { @Override public void run() { if (sessionState != null) { DsfSession session = DsfSession.getSession(sessionState.getSessionID()); if (session != null) { DsfExecutor executor = session.getExecutor(); if (executor != null) { executor.execute(new Runnable() { @Override public void run() { updateLoads(model); } }); } } } } }; return t; }</code><technical_language>I move this executor below. First, deal concurrency. Second, more important, allow fetch latest model time expires, instead of stuck a potentially model timer expires, model creation of timer, run of it. Note code "re-fetch" model updateLoads(), time called</technical_language>

Target:
private Timer getLoadTimer(final DSFSessionState sessionState, final int timeout) { Timer t = new Timer(timeout) { @Override public void run() { if (sessionState != null) { DsfSession session = DsfSession.getSession(sessionState.getSessionID()); if (session != null) { DsfExecutor executor = session.getExecutor(); if (executor != null) { executor.execute(new Runnable() { @Override public void run() { final VisualizerModel model = fDataModel; updateLoads(model); } }); } } } } }; return t; }
Source:
<code>public int complete(String buffer, int cursor, List<CharSequence> candidates) { int completionIndex = super.complete(buffer, cursor, candidates); int spaceIndex = buffer.indexOf(' '); String commandName = ((spaceIndex != -1) ? buffer.substring(0, spaceIndex) : ""); <START> if (commandName != null && !commandName.isEmpty()) { <END> for (Command command : this.commands) { if (command.getName().equals(commandName)) { if (cursor == buffer.length() && buffer.endsWith(" ")) { printUsage(command); break; } Completer completer = this.commandCompleters.get(command.getName()); if (completer != null) { completionIndex = completer.complete(buffer, cursor, candidates); break; } } } } return completionIndex; }</code><technical_language>commandName is trimmed change assert thing. StringUtils.hasText() here</technical_language>

Target:
public int complete(String buffer, int cursor, List<CharSequence> candidates) { int completionIndex = super.complete(buffer, cursor, candidates); int spaceIndex = buffer.indexOf(' '); String commandName = ((spaceIndex != -1) ? buffer.substring(0, spaceIndex) : ""); if (StringUtils.hasText(commandName)) { for (Command command : this.commands) { if (command.getName().equals(commandName)) { if (cursor == buffer.length() && buffer.endsWith(" ")) { printUsage(command); break; } Completer completer = this.commandCompleters.get(command.getName()); if (completer != null) { completionIndex = completer.complete(buffer, cursor, candidates); break; } } } } return completionIndex; }
Source:
<code>public Traverser traverse( final Iterable<Node> startNodes, final Iterable<Node> endNodes ) { return new DefaultTraverser( () -> { Resource resource = statementFactory.get(); try { return new BidirectionalTraverserIterator( resource, start, end, sideSelector, collisionPolicy, collisionEvaluator, maxDepth, startNodes, endNodes ); } <START> catch ( Exception e ) <END> { resource.close(); throw e; } } ); }</code><technical_language>I prefer success finally approach catch ( Exception e ) covering</technical_language>

Target:
public Traverser traverse( final Iterable<Node> startNodes, final Iterable<Node> endNodes ) { return new DefaultTraverser( () -> { Resource resource = statementFactory.get(); boolean success = false; try { BidirectionalTraverserIterator iterator = new BidirectionalTraverserIterator( resource, start, end, sideSelector, collisionPolicy, collisionEvaluator, maxDepth, startNodes, endNodes ); success = true; return iterator; } finally { if ( !success ) { resource.close(); } } } ); }
Source:
<code>private OnHeapValueHolder<V> internalGet(final K key, final boolean updateAccess) throws CacheAccessException { getObserver.begin(); final StoreEventSink<K, V> eventSink = storeEventDispatcher.eventSink(); try { OnHeapValueHolder<V> mapping = map.get(key); if (mapping == null) { getObserver.end(StoreOperationOutcomes.GetOutcome.MISS); storeEventDispatcher.releaseEventSink(eventSink); return null; } if (mapping.isExpired(timeSource.getTimeMillis(), TimeUnit.MILLISECONDS)) { expireMapping(key, mapping); getObserver.end(StoreOperationOutcomes.GetOutcome.MISS); storeEventDispatcher.releaseEventSink(eventSink); return null; } if (updateAccess) { <START> mapping = setAccessTimeAndExpiryThenReturnMapping(key, mapping, timeSource.getTimeMillis(), eventSink); <END> } if (mapping != null) { getObserver.end(StoreOperationOutcomes.GetOutcome.HIT); } storeEventDispatcher.releaseEventSink(eventSink); return mapping; } catch (RuntimeException re) { storeEventDispatcher.releaseEventSinkAfterFailure(eventSink, re); handleRuntimeException(re); return null; } }</code><technical_language>This is place need event sink, means created released this call</technical_language>

Target:
private OnHeapValueHolder<V> internalGet(final K key, final boolean updateAccess) throws CacheAccessException { getObserver.begin(); StoreEventSink<K, V> eventSink = null; try { OnHeapValueHolder<V> mapping = map.get(key); if (mapping == null) { getObserver.end(StoreOperationOutcomes.GetOutcome.MISS); return null; } if (mapping.isExpired(timeSource.getTimeMillis(), TimeUnit.MILLISECONDS)) { expireMapping(key, mapping); getObserver.end(StoreOperationOutcomes.GetOutcome.MISS); return null; } if (updateAccess) { eventSink = storeEventDispatcher.eventSink(); mapping = setAccessTimeAndExpiryThenReturnMapping(key, mapping, timeSource.getTimeMillis(), eventSink); storeEventDispatcher.releaseEventSink(eventSink); } if (mapping != null) { getObserver.end(StoreOperationOutcomes.GetOutcome.HIT); } else { getObserver.end(StoreOperationOutcomes.GetOutcome.MISS); } return mapping; } catch (RuntimeException re) { if (eventSink != null) { storeEventDispatcher.releaseEventSinkAfterFailure(eventSink, re); } handleRuntimeException(re); return null; } }
Source:
<code>private void registerGlobalActions() { IActionBars actionBars = getViewSite().getActionBars(); <START> actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(), copyAction); <END> }</code><technical_language>do setActionDefinitionId(ActionFactory.COPY.getCommandId()) --> displays keybinding</technical_language>

Target:
private void registerGlobalActions() { IActionBars actionBars = getViewSite().getActionBars(); actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(), fCopyAction); }
Source:
<code>private void putBlob(MessageInfo messageInfo, ByteBuffer messageBuf, long size) throws CloudStorageException, IOException, GeneralSecurityException { if (shouldUpload(messageInfo)) { BlobId blobId = (BlobId) messageInfo.getStoreKey(); boolean isRouterEncrypted = isRouterEncrypted(blobId); String kmsContext = null; EncryptionOrigin encryptionOrigin = isRouterEncrypted ? EncryptionOrigin.ROUTER : EncryptionOrigin.NONE; if (cloudConfig.vcrRequireEncryption) { if (isRouterEncrypted) { } else { if (cryptoAgent != null) { Timer.Context encryptionTimer = vcrMetrics.blobEncryptionTime.time(); messageBuf = cryptoAgent.encrypt(messageBuf); encryptionTimer.stop(); vcrMetrics.blobEncryptionCount.inc(); encryptionOrigin = EncryptionOrigin.VCR; kmsContext = cryptoAgent.getEncryptionContext(); } else { vcrMetrics.skipUnencryptedBlobsCount.inc(); return; } } } else { } CloudBlobMetadata blobMetadata = new CloudBlobMetadata(blobId, messageInfo.getOperationTimeMs(), messageInfo.getExpirationTimeInMs(), <START> messageInfo.getSize(), encryptionOrigin, kmsContext); <END> cloudDestination.uploadBlob(blobId, size, blobMetadata, new ByteBufferInputStream(messageBuf)); } }</code><technical_language>Is a reason add encryption algorithm cryptoAgent? If required change encryption algorithm, a blobs uploaded algorithm. I encryption algorithm cryptoAgent added metadata for compatibility. stored in payload DB. I prefer store agentFactory in payload, a blob is get, CloudBlobStore create deCryptoAgent while parsing payload</technical_language>

Target:
private void putBlob(MessageInfo messageInfo, ByteBuffer messageBuf, long size) throws CloudStorageException, IOException, GeneralSecurityException { if (shouldUpload(messageInfo)) { BlobId blobId = (BlobId) messageInfo.getStoreKey(); boolean isRouterEncrypted = isRouterEncrypted(blobId); String kmsContext = null; String cryptoAgentFactoryClass = null; EncryptionOrigin encryptionOrigin = isRouterEncrypted ? EncryptionOrigin.ROUTER : EncryptionOrigin.NONE; if (requireEncryption) { if (isRouterEncrypted) { } else { Timer.Context encryptionTimer = vcrMetrics.blobEncryptionTime.time(); messageBuf = cryptoAgent.encrypt(messageBuf); encryptionTimer.stop(); vcrMetrics.blobEncryptionCount.inc(); encryptionOrigin = EncryptionOrigin.VCR; kmsContext = cryptoAgent.getEncryptionContext(); cryptoAgentFactoryClass = this.cryptoAgentFactory.getClass().getName(); } } else { } CloudBlobMetadata blobMetadata = new CloudBlobMetadata(blobId, messageInfo.getOperationTimeMs(), messageInfo.getExpirationTimeInMs(), messageInfo.getSize(), encryptionOrigin, kmsContext, cryptoAgentFactoryClass); cloudDestination.uploadBlob(blobId, size, blobMetadata, new ByteBufferInputStream(messageBuf)); } }
Source:
<code>public void init(List<TransformFunction> arguments, Map<String, DataSource> dataSourceMap) { if (arguments.size() != 2) { throw new IllegalArgumentException("Exact 2 arguments are required for greater transform function"); <START> } <END> _leftTransformFunction = arguments.get(0); _rightTransformFunction = arguments.get(1); }</code><technical_language>also, check return types comparable, for e.g. if returns string other is int, throw exception</technical_language>

Target:
public void init(List<TransformFunction> arguments, Map<String, DataSource> dataSourceMap) { Preconditions .checkArgument(arguments.size() == 2, "Exact 2 arguments are required for binary operator transform function"); _leftTransformFunction = arguments.get(0); _rightTransformFunction = arguments.get(1); _leftDataType = _leftTransformFunction.getResultMetadata().getDataType(); _rightDataType = _rightTransformFunction.getResultMetadata().getDataType(); if (_leftDataType == FieldSpec.DataType.BYTES || _rightDataType == FieldSpec.DataType.BYTES) { Preconditions.checkState(_leftDataType == FieldSpec.DataType.BYTES && _rightDataType == FieldSpec.DataType.BYTES, String.format( "Unsupported data type for comparison: [Left Transform Function [%s] result type is [%s], Right Transform Function [%s] result type is [%s]]", _leftTransformFunction.getName(), _leftDataType, _rightTransformFunction.getName(), _rightDataType)); } }
Source:
<code><START> protected URI rewriteURI(HttpServletRequest request, String host) <END> { final StringBuilder uri = new StringBuilder("http://"); uri.append(host); uri.append(request.getRequestURI()); final String queryString = request.getQueryString(); if (queryString != null) { uri.append("?").append(queryString); } return URI.create(uri.toString()); }</code><technical_language>feel making this actual URI builder instead of a string builder</technical_language>

Target:
protected URI rewriteURI(HttpServletRequest request, String host) { return makeURI(host, request.getRequestURI(), request.getQueryString()); }
Source:
<code><START> public CleanupServer(final DimensionDataCloudControlApi api, final Timeouts timeouts) { <END> this.api = api; this.timeouts = timeouts; }</code><technical_language>Remove public modifier</technical_language>

Target:
CleanupServer(final DimensionDataCloudControlApi api, final Timeouts timeouts) { this.api = api; this.timeouts = timeouts; }
Source:
<code>private void checkFacadeJmxNotifications(List<Pair<String, String>> configurationStateTransitions, List<Pair<String, String>> runningStateTransitions) throws IOException, InterruptedException { final long end = System.currentTimeMillis() + TimeoutUtil.adjust(20000); while (true) { try { readAndCheckFile(JMX_FACADE_RUNTIME, list -> { <START> Assert.assertEquals(Arrays.toString(list.toArray(new String[list.size()])), <END> configurationStateTransitions.size(), list.size()); for (int i = 0; i < configurationStateTransitions.size(); i++) { Pair<String, String> transition = configurationStateTransitions.get(i); errorCollector.checkThat("Line " + list.get(i), list.get(i), containsString( "jboss.root:type=state The attribute 'RuntimeConfigurationState' has changed from '" + transition.getLeft() + "' to '" + transition.getRight() + "'")); } }); readAndCheckFile(JMX_FACADE_RUNNING, list -> { Assert.assertEquals(Arrays.toString(list.toArray(new String[list.size()])), runningStateTransitions.size(), list.size()); for (int i = 0; i < runningStateTransitions.size(); i++) { Pair<String, String> transition = runningStateTransitions.get(i); errorCollector.checkThat("Line " + list.get(i), list.get(i), containsString( "jboss.root:type=state The attribute 'RunningState' has changed from '" + transition.getLeft() + "' to '" + transition.getRight() + "'")); } }); break; } catch (AssertionError e) { if (System.currentTimeMillis() > end) { throw e; } Thread.sleep(1000); } } }</code><technical_language>(String.join(", ", list)</technical_language>

Target:
private void checkFacadeJmxNotifications(List<Pair<String, String>> configurationStateTransitions, List<Pair<String, String>> runningStateTransitions) throws IOException, InterruptedException { final long end = System.currentTimeMillis() + TimeoutUtil.adjust(20000); while (true) { try { readAndCheckFile(JMX_FACADE_RUNTIME, list -> { Assert.assertEquals(String.join(", ", list), configurationStateTransitions.size(), list.size()); for (int i = 0; i < configurationStateTransitions.size(); i++) { Pair<String, String> transition = configurationStateTransitions.get(i); errorCollector.checkThat("Transition " + i + ": " + list.get(i), list.get(i), containsString( "jboss.root:type=state The attribute 'RuntimeConfigurationState' has changed from '" + transition.getLeft() + "' to '" + transition.getRight() + "'")); } }); readAndCheckFile(JMX_FACADE_RUNNING, list -> { Assert.assertEquals(String.join(", ", list), runningStateTransitions.size(), list.size()); for (int i = 0; i < runningStateTransitions.size(); i++) { Pair<String, String> transition = runningStateTransitions.get(i); errorCollector.checkThat("Transition " + i + ": " + list.get(i), list.get(i), containsString( "jboss.root:type=state The attribute 'RunningState' has changed from '" + transition.getLeft() + "' to '" + transition.getRight() + "'")); } }); break; } catch (AssertionError e) { if (System.currentTimeMillis() > end) { throw e; } Thread.sleep(1000); } } }
Source:
<code><START> public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { <END> HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; if (FiltersHelper.isAuthenticated(req) && FiltersHelper.isSessionValid((HttpServletRequest) request, (HttpServletResponse) response)) { chain.doFilter(request, response); } else { try { req.setAttribute(FiltersHelper.Constants.REQUEST_SCHEMES_KEY, schemes); HttpSession session = req.getSession(false); Deque<AuthenticationProfile> stack = null; if (session != null) { stack = (Deque<AuthenticationProfile>) session.getAttribute(STACK_ATTR); } if (stack == null) { stack = new ArrayDeque<>(); stack.addAll(profiles); } String username = doAuth(req, resp, stack); if (!stack.isEmpty()) { req.getSession(true).setAttribute(STACK_ATTR, stack); } else { if (session != null) { session.removeAttribute(STACK_ATTR); } if (StringUtils.isNotEmpty(username)) { Map<String, Object> jsonResponse = SSOOAuthServiceUtils.loginOnBehalf(resp, username, scope); FiltersHelper.isStatusOk(jsonResponse); SSOUtils.createUserSession(req, FiltersHelper.getPayloadForToken(resp, (String) jsonResponse.get("access_token")), false); } chain.doFilter(req, resp); } } catch (Exception e) { log.error("Cannot authenticate using External Authentication: {}", e.getMessage()); log.debug("Cannot authenticate using External Authentication", e); } } }</code><technical_language>good! I understand works :)</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; if (FiltersHelper.isAuthenticated(req) && FiltersHelper.isSessionValid((HttpServletRequest) request, (HttpServletResponse) response)) { chain.doFilter(request, response); } else { try { req.setAttribute(FiltersHelper.Constants.REQUEST_SCHEMES_KEY, schemes); HttpSession session = req.getSession(false); Deque<AuthenticationProfile> stack = null; if (session != null) { stack = (Deque<AuthenticationProfile>) session.getAttribute(STACK_ATTR); } if (stack == null) { stack = new ArrayDeque<>(); stack.addAll(profiles); } String username = doAuth(req, resp, stack); if (!stack.isEmpty()) { req.getSession(true).setAttribute(STACK_ATTR, stack); } else { if (session != null) { session.removeAttribute(STACK_ATTR); } if (username != null) { Map<String, Object> jsonResponse = SSOOAuthServiceUtils.loginOnBehalf(resp, username, scope); FiltersHelper.isStatusOk(jsonResponse); SSOUtils.createUserSession(req, FiltersHelper.getPayloadForToken(resp, (String) jsonResponse.get("access_token")), false); } chain.doFilter(req, resp); } } catch (Exception e) { log.error("Cannot authenticate using External Authentication: {}", e.getMessage()); log.debug("Cannot authenticate using External Authentication", e); } } }
Source:
<code>public void actionPerformed(ActionEvent actionEvent) { <START> int result = chooser.showOpenDialog(FittingMainView.this); <END> if (result == JFileChooser.APPROVE_OPTION) { try { controller.saveJson(new FileOutputStream(chooser.getSelectedFile())); } catch(IOException ex) { NarrowOptionPane.showMessageDialog(FittingMainView.this, ex.getMessage(), "Error", NarrowOptionPane.ERROR_MESSAGE); } } }</code><technical_language>chooser.showSaveDialog() instead</technical_language>

Target:
public void actionPerformed(ActionEvent actionEvent) { int result = chooser.showSaveDialog(FittingMainView.this); if (result == JFileChooser.APPROVE_OPTION) { try { controller.saveJson(new FileOutputStream(chooser.getSelectedFile())); } catch(IOException ex) { NarrowOptionPane.showMessageDialog(FittingMainView.this, ex.getMessage(), "Error", NarrowOptionPane.ERROR_MESSAGE); } } }
Source:
<code>public void readFully(long position, byte[] buffer, int offset, int length) throws IOException { FileCacheKey key = new FileCacheKey(path, position, length); if (!cacheManager.get(key, buffer, offset)) { inputStream.readFully(position, buffer, offset, length); cacheManager.put(key, wrappedBuffer(buffer, offset, length)); } if (cacheValidationEnabled) { <START> byte[] validationBuffer = new byte[length]; <END> inputStream.readFully(position, validationBuffer, 0, length); for (int i = 0; i < length; i++) { verify(buffer[offset + i] == validationBuffer[i], "corrupted buffer at position " + i); } } }</code><technical_language>validate if is a cache hit</technical_language>

Target:
public void readFully(long position, byte[] buffer, int offset, int length) throws IOException { FileReadRequest key = new FileReadRequest(path, position, length); if (!cacheManager.get(key, buffer, offset)) { inputStream.readFully(position, buffer, offset, length); cacheManager.put(key, wrappedBuffer(buffer, offset, length)); return; } if (cacheValidationEnabled) { byte[] validationBuffer = new byte[length]; inputStream.readFully(position, validationBuffer, 0, length); for (int i = 0; i < length; i++) { verify(buffer[offset + i] == validationBuffer[i], "corrupted buffer at position " + i); } } }
Source:
<code>protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) { return ImmutableList.<String>builder() .addAll(cgoCommandPrefix) .add("-importpath", context.getBuildCellRootPath().toString()) .add("-srcdir", context.getBuildCellRootPath().toString()) .add("-objdir", outputDir.toString()) .add("--") .add("-I" + getBuildTarget().get().getBasePath().toString()) <START> .addAll(cgoCompilerFlags) <END> .addAll(srcs.stream().map(Object::toString).iterator()) .build(); }</code><technical_language>I this "--" cgoCompilerFlags passed gcc</technical_language>

Target:
protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) { return ImmutableList.<String>builder() .addAll(cgoCommandPrefix) .add("-importpath", context.getBuildCellRootPath().toString()) .add("-srcdir", context.getBuildCellRootPath().toString()) .add("-objdir", outputDir.toString()) .addAll(cgoCompilerFlags) .add("--") .add("-I" + getBuildTarget().get().getBasePath().toString()) .addAll(srcs.stream().map(Object::toString).iterator()) .build(); }
Source:
<code>private boolean ensureValidKeyAvailable() { boolean keyAvailableLocally = true; if (this.key == null) { try { <START> this.key = getKey().block().getKey(); <END> keyAvailableLocally = this.key.isValid(); initializeCryptoClients(); } catch (HttpResponseException | NullPointerException e) { logger.info("Failed to retrieve key from key vault"); keyAvailableLocally = false; } } return keyAvailableLocally; }</code><technical_language>getKey().block().getKey()</technical_language>

Target:
private boolean ensureValidKeyAvailable() { boolean keyAvailableLocally = true; if (this.key == null) { try { KeyVaultKey keyVaultKey = getKey().block(); this.key = keyVaultKey.getKey(); keyAvailableLocally = this.key.isValid(); initializeCryptoClients(); } catch (HttpResponseException | NullPointerException e) { logger.warning("Failed to retrieve key from key vault"); logger.logExceptionAsWarning(e); keyAvailableLocally = false; } } return keyAvailableLocally; }
Source:
<code>public AbsolutePositionProgressMonitorPart(Composite parent) { super(parent, null); setLayout(null); <START> this.setData(CSS_ID_KEY, SPLASH_PROGRESS_PART_ID); <END> fProgressIndicator.setData(CSS_ID_KEY, SPLASH_PROGRESS_INDICATOR_ID); fLabel.setData(CSS_ID_KEY, SPLASH_PROGRESS_TEXT_ID); }</code><technical_language>CSSSWTConstants.CSS_ID_KEY</technical_language>

Target:
public AbsolutePositionProgressMonitorPart(Composite parent) { super(parent, null); setLayout(null); setCSSData(); }
Source:
<code>public static ModelNode validateOperation(ModelNode operation) { ModelNode responseNode = new ModelNode(); StringBuilder errors = new StringBuilder(); if (!operation.hasDefined(OP) || operation.get(OP).asString() == null || operation.get(OP).asString().isEmpty()) { errors.append(ControllerLogger.ROOT_LOGGER.noOperationDefined(operation)); } if (operation.hasDefined(OP_ADDR)) { try { operation.get(OP_ADDR).asList(); } catch (IllegalArgumentException ex) { try { <START> ModelNode address = parseAddress(operation.get(OP_ADDR).asString()); <END> operation.get(OP_ADDR).set(address); } catch (IllegalArgumentException iaex) { if (errors.length() > 0) { errors.append(System.lineSeparator()); } errors.append(ControllerLogger.ROOT_LOGGER.attributeIsWrongType(OP_ADDR, ModelType.LIST, operation.get(OP_ADDR).getType()).getMessage()); } } } if (errors.length() > 0) { responseNode.get(OUTCOME).set(FAILED); responseNode.get(FAILURE_DESCRIPTION).set(errors.toString()); } return responseNode; }</code><technical_language>this mighty odd. check type of OP_ADDR attribute? if (operation.get(OP_ADDR).getType() == ModelType.STRING if is string try parse such, this try |catch is wrong</technical_language>

Target:
public static ModelNode validateOperation(ModelNode operation) { ModelNode responseNode = new ModelNode(); StringBuilder errors = new StringBuilder(); if (!operation.hasDefined(OP) || operation.get(OP).asString() == null || operation.get(OP).asString().isEmpty()) { errors.append(ControllerLogger.ROOT_LOGGER.noOperationDefined(operation)); } if (operation.hasDefined(OP_ADDR)) { try { if(operation.get(OP_ADDR).getType() == ModelType.STRING) { ModelNode address = PathAddress.parseCLIStyleAddress(operation.get(OP_ADDR).asString()).toModelNode(); operation.get(OP_ADDR).set(address); } else { operation.get(OP_ADDR).asList(); } } catch (IllegalArgumentException ex) { if (errors.length() > 0) { errors.append(System.lineSeparator()); } if(ex.getMessage() != null) { errors.append(ex.getMessage()); } else { errors.append(ControllerLogger.ROOT_LOGGER.attributeIsWrongType(OP_ADDR, ModelType.LIST, operation.get(OP_ADDR).getType()).getMessage()); } } } if (errors.length() > 0) { responseNode.get(OUTCOME).set(FAILED); responseNode.get(FAILURE_DESCRIPTION).set(errors.toString()); } return responseNode; }
Source:
<code>private void deleteButtons() { <START> if (this.getButton(BUTTON_REPLY_ID) != null) { <END> Button button = (this.getButton(BUTTON_REPLY_ID)); button.dispose(); } if (this.getButton(BUTTON_REPLY_DONE_ID) != null) { Button button = (this.getButton(BUTTON_REPLY_DONE_ID)); button.dispose(); } if (this.getButton(BUTTON_DISCARD_ID) != null) { Button button = (this.getButton(BUTTON_DISCARD_ID)); button.dispose(); } if (this.getButton(BUTTON_EDIT_ID) != null) { Button button = (this.getButton(BUTTON_EDIT_ID)); button.dispose(); } if (this.getButton(BUTTON_SAVE_ID) != null) { Button button = (this.getButton(BUTTON_SAVE_ID)); button.dispose(); } fCommentInputTextField.setEnabled(false); }</code><technical_language>for (int buttonId : new int[] {BUTTON_REPLY_ID, BUTTON_REPLY_DONE_ID, ...}) { Button button = getButton(buttonId); if (button!=null) button.dispose(); }</technical_language>

Target:
private void deleteButtons() { for (int buttonId : new int[] { BUTTON_REPLY_ID, BUTTON_REPLY_DONE_ID, BUTTON_DISCARD_ID, BUTTON_EDIT_ID, BUTTON_SAVE_ID }) { Button button = getButton(buttonId); if (button != null) { button.dispose(); } } fCommentInputTextField.setEnabled(false); }
Source:
<code><START> public WagedRebalancer(AssignmentMetadataStore assignmentMetadataStore, <END> RebalanceAlgorithm algorithm, MetricCollector metricCollector) throws JMException { this(assignmentMetadataStore, algorithm, new DelayedAutoRebalancer(), metricCollector); }</code><technical_language>move tests package this method protected</technical_language>

Target:
protected WagedRebalancer(AssignmentMetadataStore assignmentMetadataStore, RebalanceAlgorithm algorithm, MetricCollector metricCollector) { this(assignmentMetadataStore, algorithm, new DelayedAutoRebalancer(), null, metricCollector); }
Source:
<code>public void accumulateSerializedRowSizes(int[] serializedRowSizes) { for (int i = 0; i < positionCount; i++) { serializedRowSizes[i] += POSITION_SIZE; } <START> offsetsCopy = ensureCapacityWithAllocator(offsetsCopy, positionCount + 1, SMALL, NONE, allocator); <END> System.arraycopy(offsets, 0, offsetsCopy, 0, positionCount + 1); ((AbstractBlockEncodingBuffer) valuesBuffers).accumulateSerializedRowSizes(offsetsCopy, positionCount, serializedRowSizes); allocator.returnArray(offsetsCopy); offsetsCopy = null; }</code><technical_language>offsetsCopy a local variable: int[] offsetsCopy = ensureCapacityWithAllocator(null, positionCount + 1, SMALL, NONE, allocator); try { System.arraycopy(offsets, 0, offsetsCopy, 0, positionCount + 1); ((AbstractBlockEncodingBuffer) valuesBuffers).accumulateSerializedRowSizes(offsetsCopy, positionCount, serializedRowSizes); } finally { allocator.returnArray(offsetsCopy); }</technical_language>

Target:
public void accumulateSerializedRowSizes(int[] serializedRowSizes) { for (int i = 0; i < positionCount; i++) { serializedRowSizes[i] += POSITION_SIZE; } int[] offsetsCopy = ensureCapacity(null, positionCount + 1, SMALL, NONE, bufferAllocator); try { System.arraycopy(offsets, 0, offsetsCopy, 0, positionCount + 1); ((AbstractBlockEncodingBuffer) valuesBuffers).accumulateSerializedRowSizes(offsetsCopy, positionCount, serializedRowSizes); } finally { bufferAllocator.returnArray(offsetsCopy); } }
Source:
<code>private int smcReadKey(String key, SMCVal val, int retries) { SMCKeyData inputStructure = new SMCKeyData(); SMCKeyData outputStructure = new SMCKeyData(); inputStructure.key = strtoul16(key, 4); int result; do { <START> Util.sleep(8); <END> result = smcGetKeyInfo(inputStructure, outputStructure); if (result != 0) { continue; } val.dataSize = outputStructure.keyInfo.dataSize; val.dataType = new byte[5]; for (int i = 3; i >= 0; i--) { val.dataType[i] = (byte) (outputStructure.keyInfo.dataType >> (8 * (3 - i))); } inputStructure.keyInfo.dataSize = val.dataSize; inputStructure.data8 = IOKit.SMC_CMD_READ_BYTES; result = smcCall(IOKit.KERNEL_INDEX_SMC, inputStructure, outputStructure); if (result != 0) { continue; } } while (retries-- > 0); if (result != 0) { return result; } System.arraycopy(outputStructure.bytes, 0, val.bytes, 0, val.bytes.length); return 0; }</code><technical_language>This right :) I do in a loop succeeds if is more reliable</technical_language>

Target:
private int smcReadKey(String key, SMCVal val, int retries) { SMCKeyData inputStructure = new SMCKeyData(); SMCKeyData outputStructure = new SMCKeyData(); inputStructure.key = strtoul16(key, 4); int result; do { result = smcGetKeyInfo(inputStructure, outputStructure); if (result != 0) { continue; } val.dataSize = outputStructure.keyInfo.dataSize; val.dataType = new byte[5]; for (int i = 3; i >= 0; i--) { val.dataType[i] = (byte) (outputStructure.keyInfo.dataType >> (8 * (3 - i))); } inputStructure.keyInfo.dataSize = val.dataSize; inputStructure.data8 = IOKit.SMC_CMD_READ_BYTES; Util.sleep(4); result = smcCall(IOKit.KERNEL_INDEX_SMC, inputStructure, outputStructure); if (result != 0) { continue; } break; } while (--retries > 0); if (result != 0) { return result; } System.arraycopy(outputStructure.bytes, 0, val.bytes, 0, val.bytes.length); return 0; }
Source:
<code>public void run() { while (true) { updateTraceEntry(fTimeAnalysisEntry, Long.MAX_VALUE, fRange.getStartTime().toNanos(), fRange.getEndTime().toNanos()); synchronized (fProcessTraceThreads) { if (fRestart) { fRestart = false; } else { fProcessTraceThreads.remove(fTimeAnalysisEntry.getTrace()); <START> break; <END> } } } }</code><technical_language>this return</technical_language>

Target:
public void run() { while (true) { updateTraceEntry(fTimeAnalysisEntry, Long.MAX_VALUE, fRange.getStartTime().toNanos(), fRange.getEndTime().toNanos()); synchronized (fProcessTraceThreads) { if (fRestart) { fRestart = false; } else { fProcessTraceThreads.remove(fTimeAnalysisEntry.getTrace()); return; } } } }
Source:
<code><START> public Response getFieldTypes(@Context final HttpServletRequest req) throws DotDataException, DotSecurityException { <END> final InitDataObject initData = this.webResource.init(null, true, req, true, null); User user = initData.getUser(); return Response.ok( new ResponseEntityView( fieldTypeFactory.getFieldTypes(user) ) ).build(); }</code><technical_language>![MINOR](<LINK_2> 'Severity: MINOR') Remove redundant '!unknownSymbol!' thrown exception declaration(s). [![rule](<LINK_1>](<LINK_0></technical_language>

Target:
public Response getFieldTypes(@Context final HttpServletRequest req) { final InitDataObject initData = this.webResource.init(null, true, req, true, null); User user = initData.getUser(); return Response.ok( new ResponseEntityView( fieldTypeAPI.getFieldTypes(user) ) ).build(); }
Source:
<code>protected void updateBricksWithTaskID(GlusterAsyncTask asyncTask) { for (GlusterBrickEntity brickEntity : getParameters().getBricks()) { <START> getGlusterBrickDao().updateBrickTask(brickEntity.getId(), asyncTask.getTaskId()); <END> } getGlusterVolumeDao().updateVolumeTask(getGlusterVolumeId(), asyncTask.getTaskId()); }</code><technical_language>Spring jdbc batch here</technical_language>

Target:
protected void updateBricksWithTaskID(GlusterAsyncTask asyncTask) { for (GlusterBrickEntity brickEntity : getParameters().getBricks()) { brickEntity.getAsyncTask().setTaskId(asyncTask.getTaskId()); } getGlusterBrickDao().updateBrickTasksInBatch(getParameters().getBricks()); getGlusterVolumeDao().updateVolumeTask(getGlusterVolumeId(), asyncTask.getTaskId()); }