auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ListenableFuture<SegmentsAndMetadata> publish( final TransactionalSegmentPublisher publisher, final Committer committer, final Collection<String> sequenceNames ) { final List<SegmentIdentifier> theSegments = getSegmentWithStates(sequenceNames) .map(SegmentWithState::getSegmentIdentifier) .collect(Collectors.toList()); final ListenableFuture<SegmentsAndMetadata> publishFuture = ListenableFutures.transformAsync( pushInBackground(wrapCommitter(committer), theSegments), sam -> publishInBackground( sam, publisher ) ); return ListenableFutures.transformAsync(publishFuture, sam -> { synchronized (segments) { sequenceNames.forEach(segments::remove); } <START> final SettableFuture<SegmentsAndMetadata> future = SettableFuture.create(); <END> future.set(sam); return future; }); }</code><technical_language>change this async transform generates a useless future, instead of keeping a normal transform</technical_language>

Target:
public ListenableFuture<SegmentsAndMetadata> publish( final TransactionalSegmentPublisher publisher, final Committer committer, final Collection<String> sequenceNames ) { final List<SegmentIdentifier> theSegments = getSegmentWithStates(sequenceNames) .map(SegmentWithState::getSegmentIdentifier) .collect(Collectors.toList()); final ListenableFuture<SegmentsAndMetadata> publishFuture = ListenableFutures.transformAsync( pushInBackground(wrapCommitter(committer), theSegments), sam -> publishInBackground( sam, publisher ) ); return Futures.transform( publishFuture, (Function<? super SegmentsAndMetadata, ? extends SegmentsAndMetadata>) sam -> { synchronized (segments) { sequenceNames.forEach(segments::remove); } return sam; } ); }
Source:
<code>private void watchLogsIfDebugEnabled(Map<String, String> startOptions, Pod pluginBrokerPod) throws InfrastructureException { if (startOptions == null) { LOG.debug( "'startOptions' is null so we won't watch the plugin broker pod logs for workspace '{}'", runtimeId.getWorkspaceId()); return; } boolean shouldWatchContainerStartupLogs = Boolean.parseBoolean( startOptions.getOrDefault(DEBUG_WORKSPACE_START, Boolean.FALSE.toString())); if (shouldWatchContainerStartupLogs) { namespace .deployments() .watchLogs( new PodLogHandlerToEventPublisher(runtimeEventsPublisher, runtimeId), <START> new LogWatchTimeouts(5_000, 100, 2_500), <END> ImmutableSet.of(pluginBrokerPod.getMetadata().getName())); } }</code><technical_language>extracted constants defaults somewhere</technical_language>

Target:
private void watchLogsIfDebugEnabled(Map<String, String> startOptions, Pod pluginBrokerPod) throws InfrastructureException { if (startOptions == null || startOptions.isEmpty()) { LOG.debug( "'startOptions' is null or empty so we won't watch the plugin broker pod logs for workspace '{}'", runtimeId.getWorkspaceId()); return; } boolean shouldWatchContainerStartupLogs = Boolean.parseBoolean( startOptions.getOrDefault(DEBUG_WORKSPACE_START, Boolean.FALSE.toString())); if (shouldWatchContainerStartupLogs) { namespace .deployments() .watchLogs( new PodLogToEventPublisher(runtimeEventsPublisher, runtimeId), LogWatchTimeouts.AGGRESSIVE, ImmutableSet.of(pluginBrokerPod.getMetadata().getName()), LogWatcher.getLogLimitBytes(startOptions)); } }
Source:
<code>public Diff getPrimeRefining() { Diff main = null; <START> if (primeRefining != null) { <END> main = primeRefining; } else { for (Diff refBy : this.getRefinedBy()) { if (refBy instanceof ReferenceChange) { ReferenceChange rc = (ReferenceChange)refBy; if (rc.getReference().isContainment() && (this.getDiscriminant() == rc.getValue())) { main = rc; break; } } } } return main; }</code><technical_language>replace test (primeRefining == null) execute statements else block. return primeRefining field "if", main local variable is useful</technical_language>

Target:
public Diff getPrimeRefining() { if (primeRefining == null) { for (Diff refBy : this.getRefinedBy()) { if (refBy instanceof ReferenceChange) { ReferenceChange rc = (ReferenceChange)refBy; if (rc.getReference().isContainment() && (this.getDiscriminant() == rc.getValue())) { primeRefining = rc; break; } } } } return primeRefining; }
Source:
<code>public void runWESCommand(String jsonString, File localPrimaryDescriptorFile, File zippedEntry) { String workflowURL = localPrimaryDescriptorFile.getName(); final File tempDir = Files.createTempDir(); List<File> workflowAttachment = new ArrayList<>(); workflowAttachment.add(localPrimaryDescriptorFile); addFilesToWorkflowAttachment(workflowAttachment, this.zippedEntry, tempDir); File jsonInputFile = new File(jsonString); workflowAttachment.add(jsonInputFile); String languageType = this.languageType.toString().toUpperCase(); String workflowTypeVersion = WORKFLOW_TYPE_VERSION; if ("CWL".equals(languageType.toUpperCase())) { workflowTypeVersion = "v" + WORKFLOW_TYPE_VERSION; <START> } else if ("WDL".equals(languageType.toUpperCase())) { <END> workflowTypeVersion = WDL_WORKFLOW_TYPE_VERSION; } try { RunId response = clientWorkflowExecutionServiceApi.runWorkflow(jsonInputFile, languageType, workflowTypeVersion, TAGS, "", workflowURL, workflowAttachment); System.out.println("Launched WES run with id: " + response.toString()); } catch (io.openapi.wes.client.ApiException e) { LOG.error("Error launching WES run", e); } finally { try { FileUtils.deleteDirectory(tempDir); } catch (IOException ioe) { LOG.error("Could not delete temporary directory" + tempDir + " for workflow attachment files", ioe); } } }</code><technical_language>check if enum for "WDL", possibly equalsignorecase</technical_language>

Target:
public void runWESCommand(String jsonString, File localPrimaryDescriptorFile, File zippedEntry) { String workflowURL = localPrimaryDescriptorFile.getName(); final File tempDir = Files.createTempDir(); List<File> workflowAttachment = new ArrayList<>(); workflowAttachment.add(localPrimaryDescriptorFile); addFilesToWorkflowAttachment(workflowAttachment, this.zippedEntry, tempDir); File jsonInputFile = new File(jsonString); workflowAttachment.add(jsonInputFile); String languageType = this.languageType.toString().toUpperCase(); String workflowTypeVersion = WORKFLOW_TYPE_VERSION; if ("CWL".equalsIgnoreCase(languageType)) { workflowTypeVersion = "v" + WORKFLOW_TYPE_VERSION; } else if ("WDL".equalsIgnoreCase(languageType)) { workflowTypeVersion = WDL_WORKFLOW_TYPE_VERSION; } try { RunId response = clientWorkflowExecutionServiceApi.runWorkflow(jsonInputFile, languageType, workflowTypeVersion, TAGS, "", workflowURL, workflowAttachment); System.out.println("Launched WES run with id: " + response.toString()); } catch (io.openapi.wes.client.ApiException e) { LOG.error("Error launching WES run", e); } finally { try { FileUtils.deleteDirectory(tempDir); } catch (IOException ioe) { LOG.error("Could not delete temporary directory" + tempDir + " for workflow attachment files", ioe); } } }
Source:
<code>public void set(double position) { if (isInverted) { <START> position = invertPosition(lastPosition); <END> } for (Servo servo : servos) { servo.set(position); } lastPosition = position; }</code><technical_language>position = invertPosition(**lastPosition**)? why? position=invertPosition(position)</technical_language>

Target:
public void set(double position) { if (isInverted) { position = ServoSubsystem.invertPosition(position); } for (Servo servo : servos) { servo.set(position); } lastPosition = position; }
Source:
<code>public Graph getGraph(Node gn) { Node key = ( gn != null ) ? gn : Quad.defaultGraphNodeGenerated; <START> return ngCache.getOrFill(gn, ()->GraphViewSwitchable.createNamedGraph(this, key)); <END> }</code><technical_language>gn reference this line changed key adding a potentially null key cache</technical_language>

Target:
public Graph getGraph(Node gn) { Node key = ( gn != null ) ? gn : Quad.defaultGraphNodeGenerated; return ngCache.getOrFill(key, ()->GraphViewSwitchable.createNamedGraph(this, key)); }
Source:
<code>private DirectoryUser findDirectoryUser(String directoryName, User user) { DirectoryUser result = null; if (user.isSetId()) { String userId = DirectoryEntryIdUtils.decode(user.getId()); result = getEntity( DirectoryUser.class, VdcQueryType.GetDirectoryUserById, new DirectoryIdQueryParameters(directoryName, user.getNamespace(), userId), userId, true); } else { if (user.isSetUserName()) { result = getEntity( DirectoryUser.class, SearchType.DirectoryUser, getDirectoryUserSearchPattern( <START> user.getUserName().contains("@") ? user.getUserName().substring(0, user.getUserName().indexOf("@")) : user.getUserName(), <END> user.getNamespace(), directoryName) ); } } return result; }</code><technical_language>index of please</technical_language>

Target:
private DirectoryUser findDirectoryUser(String directoryName, User user) { DirectoryUser result = null; String namespace = user.getNamespace(); if (user.isSetDomainEntryId()) { result = getUserById(directoryName, namespace, user.getDomainEntryId()); } else if (user.isSetId()) { result = getUserById(directoryName, namespace, user.getId()); } else { if (user.isSetUserName()) { result = getEntity( DirectoryUser.class, SearchType.DirectoryUser, getDirectoryUserSearchPattern( user.getUserName().contains("@") ? user.getUserName().substring(0, user.getUserName().indexOf("@")) : user.getUserName(), user.getNamespace(), directoryName) ); } } return result; }
Source:
<code>public void doRun(IProgressMonitor monitor, String projectID, String bsId) throws CoreException { if (bsId == null) { <START> SubMonitor submonitor = SubMonitor.convert(monitor, 1); <END> doRun(submonitor.split(1), projectID); } else { Object[] selection = getCheckedElements(); if (selection != null) { int totalSelected = selection.length; if (totalSelected > 0) { if (monitor == null) { monitor = new NullProgressMonitor(); } SubMonitor submonitor = SubMonitor.convert(monitor, 1); submonitor.subTask(CUIPlugin.getResourceString(KEY_TITLE)); convertProjects(selection, bsId, submonitor.split(1)); } } } }</code><technical_language>I suppose is wrong this, is need either, is there? (other cases of marked ditto3)</technical_language>

Target:
public void doRun(IProgressMonitor monitor, String projectID, String bsId) throws CoreException { if (bsId == null) { SubMonitor submonitor = SubMonitor.convert(monitor, 1); doRun(submonitor.split(1), projectID); } else { Object[] selection = getCheckedElements(); if (selection != null) { int totalSelected = selection.length; if (totalSelected > 0) { SubMonitor submonitor = SubMonitor.convert(monitor, CUIPlugin.getResourceString(KEY_TITLE), 1); convertProjects(selection, bsId, submonitor.split(1)); } } } }
Source:
<code>public void MethodReferenceUsingThis() throws Exception { Result result = Result.createFor("MethodReferencesThis"); JavaSymbol bar1 = result.symbol("bar1"); assertThat(bar1.usages()).hasSize(2); JavaSymbol bar = result.symbol("bar"); assertThat(bar.usages()).hasSize(1); MethodReferenceTree methodRef = (MethodReferenceTree) bar.usages().get(0).parent(); assertThat(methodRef.symbolType().is("java.util.function.Consumer")).isTrue(); MethodInvocationTree foreach = (MethodInvocationTree) methodRef.parent().parent(); <START> assertThat(foreach.symbol().isUnknown()).isFalse(); <END> assertThat(foreach.symbol().owner().type().is("java.lang.Iterable")).isTrue(); }</code><technical_language>required test</technical_language>

Target:
public void MethodReferenceUsingThis() throws Exception { Result result = Result.createFor("MethodReferencesThis"); JavaSymbol bar1 = result.symbol("bar1"); assertThat(bar1.usages()).hasSize(2); JavaSymbol bar = result.symbol("bar"); assertThat(bar.usages()).hasSize(1); MethodReferenceTree methodRef = (MethodReferenceTree) bar.usages().get(0).parent(); assertThat(methodRef.symbolType().is("java.util.function.Consumer")).isTrue(); MethodInvocationTree foreach = (MethodInvocationTree) methodRef.parent().parent(); assertThat(foreach.symbol().owner().type().is("java.lang.Iterable")).isTrue(); }
Source:
<code>public List<RelationshipMetadataValue> getRelationshipMetadata(Item item, boolean enableVirtualMetadata) { Context context = new Context(); List<RelationshipMetadataValue> fullMetadataValueList = new LinkedList<>(); try { List<MetadataValue> list = item.getMetadata(); String entityType = getEntityTypeStringFromMetadata(list); if (StringUtils.isNotBlank(entityType)) { List<Relationship> relationships = relationshipService.findByItem(context, item); for (Relationship relationship : relationships) { fullMetadataValueList .addAll(handleItemRelationship(context, item, entityType, relationship, enableVirtualMetadata)); } } } catch (SQLException e) { <START> log.error(e, e); <END> } return fullMetadataValueList; }</code><technical_language>Please add a more informative error message this log.error</technical_language>

Target:
public List<RelationshipMetadataValue> getRelationshipMetadata(Item item, boolean enableVirtualMetadata) { Context context = new Context(); List<RelationshipMetadataValue> fullMetadataValueList = new LinkedList<>(); try { List<MetadataValue> list = item.getMetadata(); String entityType = getEntityTypeStringFromMetadata(list); if (StringUtils.isNotBlank(entityType)) { List<Relationship> relationships = relationshipService.findByItem(context, item); for (Relationship relationship : relationships) { fullMetadataValueList .addAll(handleItemRelationship(context, item, entityType, relationship, enableVirtualMetadata)); } } } catch (SQLException e) { log.error("Lookup for Relationships for item with uuid: " + item.getID() + " caused DSpace to crash", e); } return fullMetadataValueList; }
Source:
<code>public NetMatcher(String commaSeparatedNets, DNSService dnsServer) { this.dnsServer = dnsServer; <START> List<String> nets = Arrays.asList(commaSeparatedNets.split(NETS_SEPARATOR_PATTERN)); <END> initInetNetworks(nets); }</code><technical_language>trim netwok string calling splitToList get result</technical_language>

Target:
public NetMatcher(String commaSeparatedNets, DNSService dnsServer) { this.dnsServer = dnsServer; List<String> nets = Splitter.on(NETS_SEPARATOR).trimResults().splitToList(commaSeparatedNets); initInetNetworks(nets); }
Source:
<code><START> public void getCashPointsByLocation_shouldReturnAnEmptyListIfTheLocationHasNoCashpoints() throws Exception { <END> Location location = Context.getLocationService().getLocation(1); List<CashPoint> results = service.getCashPointsByLocation(location,false); Assert.assertNotNull(results); Assert.assertEquals(1,results.size()); }</code><technical_language>This test is test. This test a location cash points returns a non-null list zero items</technical_language>

Target:
public void getCashPointsByLocation_shouldReturnAnEmptyListIfTheLocationHasNoCashpoints() throws Exception { Location location = Context.getLocationService().getLocation(4); List<CashPoint> results = service.getCashPointsByLocation(location,false); Assert.assertNotNull(results); Assert.assertEquals(0,results.size()); }
Source:
<code>public void testSearchResult() { final List<Long> ll = Collections.singletonList(Long.MAX_VALUE - 1); final SearchResult infos = new SearchResult(ll, 1L); final List<Long> result = infos.getMessageNumbers(); <START> final long modSeq = infos.getHighestModSeq(); <END> Assert.assertEquals(result.size(), 1, "Result mismatched."); Assert.assertEquals(result.get(0), Long.valueOf(Long.MAX_VALUE - 1), "Result mismatched."); Assert.assertEquals(modSeq, 1L, "Result mismatched."); }</code><technical_language>getHighestModSeq returns a Long object, nullable. get result in a Long check for null check for actual value</technical_language>

Target:
public void testSearchResult() { final List<Long> ll = Collections.singletonList(Long.MAX_VALUE - 1); final SearchResult sr = new SearchResult(ll, 1L); final List<Long> result = sr.getMessageNumbers(); final Long modSeq = sr.getHighestModSeq(); Assert.assertNotNull(result, "getMessageNumbers() should not return null."); Assert.assertEquals(result.size(), 1, "getMessageNumbers() size mismatched."); Assert.assertEquals(result.get(0), Long.valueOf(Long.MAX_VALUE - 1), "getMessageNumbers() mismatched."); Assert.assertNotNull(modSeq, "getHighestModSeq() should not return null"); Assert.assertEquals(modSeq, Long.valueOf(1), "getHighestModSeq() mismatched."); }
Source:
<code>public static void encodeDictionary(final BufferedWriter writer, Iterator<SAMSequenceRecord> samSequenceRecordIterator) { final SAMSequenceDictionaryCodec samDictCodec = new SAMSequenceDictionaryCodec(writer); samDictCodec.encodeHeaderLine(false); final SortingCollection<String> sequenceNames = makeSortingCollection(); while (samSequenceRecordIterator.hasNext()) { final SAMSequenceRecord samSequenceRecord = samSequenceRecordIterator.next(); samDictCodec.encodeSequenceRecord(samSequenceRecord); sequenceNames.add(samSequenceRecord.getSequenceName()); } final CloseableIterator<String> iterator = sequenceNames.iterator(); <START> if(!iterator.hasNext()) return; <END> String current = iterator.next(); while (iterator.hasNext()) { final String next = iterator.next(); if (current.equals(next)) { throw new PicardException("Sequence name " + current + " appears more than once in reference file"); } current = next; } }</code><technical_language>please format if lines, e.g. if (!iterator.hasNext()) { return; }</technical_language>

Target:
public static void encodeDictionary(final BufferedWriter writer, Iterator<SAMSequenceRecord> samSequenceRecordIterator) { final SAMSequenceDictionaryCodec samDictCodec = new SAMSequenceDictionaryCodec(writer); samDictCodec.encodeHeaderLine(false); final SortingCollection<String> sequenceNames = makeSortingCollection(); while (samSequenceRecordIterator.hasNext()) { final SAMSequenceRecord samSequenceRecord = samSequenceRecordIterator.next(); samDictCodec.encodeSequenceRecord(samSequenceRecord); sequenceNames.add(samSequenceRecord.getSequenceName()); } final CloseableIterator<String> iterator = sequenceNames.iterator(); if (!iterator.hasNext()) { return; } String current = iterator.next(); while (iterator.hasNext()) { final String next = iterator.next(); if (current.equals(next)) { throw new PicardException("Sequence name " + current + " appears more than once in reference file"); } current = next; } }
Source:
<code>public void aggregate(Object item) { if (item instanceof ObjectNode) { ObjectNode objectNode = (ObjectNode) item; <START> if (objectNode.hasNonNull("count")) { <END> long count = objectNode.get("count").asLong(); if (count == 0) { return; } if (objectNode.has("max")) { item = getValue(objectNode.get("max")); } else { item = Undefined.value(); } } } if (item == Undefined.value()) { return; } if (Undefined.value().equals(this.value)) { this.value = item; } else if (ItemComparator.getInstance().compare(item, this.value) > 0) { this.value = item; } }</code><technical_language>constant for of "count", "max" etc, other places</technical_language>

Target:
public void aggregate(Object item) { if (item instanceof ObjectNode) { ObjectNode objectNode = (ObjectNode) item; if (objectNode.hasNonNull(MinAggregator.COUNT_PROPERTY_NAME)) { long count = objectNode.get(MinAggregator.COUNT_PROPERTY_NAME).asLong(); if (count == 0) { return; } if (objectNode.has(MAX_PROPERTY_NAME)) { item = getValue(objectNode.get(MAX_PROPERTY_NAME)); } else { item = Undefined.value(); } } } if (item == Undefined.value()) { return; } if (Undefined.value().equals(this.value)) { this.value = item; } else if (ItemComparator.getInstance().compare(item, this.value) > 0) { this.value = item; } }
Source:
<code>public void setDiagramScaleLevel(Integer theDiagramScaleLevel) { <START> this.diagramScaleLevel = theDiagramScaleLevel; <END> }</code><technical_language>if (theDiagramScaleLevel < 0 && theDiagramScaleLevel > 100) { throw new IllegalArgumentException("The scale level a percente (between 0 100)."); } externalization of message</technical_language>

Target:
public void setDiagramScaleLevel(Integer theDiagramScaleLevel) { if (theDiagramScaleLevel < 0 && theDiagramScaleLevel > 100) { throw new IllegalArgumentException(Messages.ExportAction_invalidLevel); } else { this.diagramScaleLevel = theDiagramScaleLevel; } }
Source:
<code>public void postMessage(Direction direction, Tuple update) { Map<Tuple, Integer> activeQueue = getActiveQueue(); Integer count = activeQueue.get(update); if (count == null) { count = 0; } if (direction == Direction.REVOKE) { count--; } else { count++; } if (count == 0) { activeQueue.remove(update); } else { activeQueue.put(update, count); } if (container != null) { if (activeQueue.isEmpty()) { <START> container.getTracker().notifyLostAllMessages(this); <END> } else { container.getTracker().notifyHasMessage(this); } } }</code><technical_language>getTracker saved a field do fetch for tuple mailbox..</technical_language>

Target:
public void postMessage(Direction direction, Tuple update) { Map<Tuple, Integer> activeQueue = getActiveQueue(); Integer count = activeQueue.get(update); if (count == null) { count = 0; } if (direction == Direction.REVOKE) { count--; } else { count++; } if (count == 0) { activeQueue.remove(update); } else { activeQueue.put(update, count); } if (container != null) { if (activeQueue.isEmpty()) { tracker.notifyLostAllMessages(this); } else { tracker.notifyHasMessage(this); } } }
Source:
<code>public IntegerStateValue(int valueAsInt) { <START> this.value = new Integer(valueAsInt); <END> }</code><technical_language>I assume want re-box it? ;) (btw, I learned recently, in cases do Integer.valueOf(int) new Integer(int), valueOf cache often-used values, new Integer() create a new object time.)</technical_language>

Target:
public IntegerStateValue(int valueAsInt) { this.value = valueAsInt; }
Source:
<code>public void shutdown() { <START> logger.info("Terminating executor health checker."); <END> this.scheduler.shutdown(); try { if (!this.scheduler.awaitTermination(60, TimeUnit.SECONDS)) { this.scheduler.shutdownNow(); } } catch (final InterruptedException ex) { this.scheduler.shutdownNow(); Thread.currentThread().interrupt(); } }</code><technical_language>function name is 'shutdown' message 'Terminating'. Is choose of words consistent? "Shutdown" association a more orderly, proactive cleanup "terminating". This in making choice</technical_language>

Target:
public void shutdown() { logger.info("Shutting down executor health checker."); this.scheduler.shutdown(); try { if (!this.scheduler.awaitTermination(60, TimeUnit.SECONDS)) { this.scheduler.shutdownNow(); } } catch (final InterruptedException ex) { this.scheduler.shutdownNow(); Thread.currentThread().interrupt(); } }
Source:
<code><START> public void throttle() { <END> if (log.isDebugEnabled()) { log.debug("try to wait for te engine update the host memory and cpu stats"); } decreaseLock.lock(); try { decreased.await(Config.<Integer> GetValue(ConfigValues.VdsRefreshRate), TimeUnit.SECONDS); } catch (InterruptedException e) { } finally { decreaseLock.unlock(); } }</code><technical_language>again, throttle</technical_language>

Target:
public void throttle() { if (log.isDebugEnabled()) { log.debug("try to wait for te engine update the host memory and cpu stats"); } decreaseLock.lock(); try { long t = Math.max( ResourceManager.getInstance().GetVdsManager(getCurrentVdsId()).getLastUpdateElapsed(), TimeUnit.SECONDS.toMillis(Config.<Integer> GetValue(VdsRefreshRate))); t = Math.max(Config.<Integer> GetValue(ConfigValues.ThrottlerMaxWaitForVdsUpdateInMillis), t); decreased.await(t, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { } finally { decreaseLock.unlock(); } }
Source:
<code>public long getRawSize() throws IOException { <START> if (size() == Integer.MAX_VALUE) { <END> throw new IOException("Unknown block size of at least " + Integer.MAX_VALUE + " bytes."); } return size() & 0x00000000ffffffffL; }</code><technical_language>+1: a reasonable strategy here</technical_language>

Target:
public long getRawSize() throws IOException { return size() & 0x00000000ffffffffL; }
Source:
<code>public FilterResult isFiltered(StructuralNode node) { HistoryReference href = node.getHistoryReference(); <START> if (href != null) { <END> int statusCode = href.getStatusCode(); return this.isFiltered(statusCode, null); } else { return FilterResult.NOT_FILTERED; } }</code><technical_language>removed (same in other filters)</technical_language>

Target:
public FilterResult isFiltered(StructuralNode node) { HistoryReference href = node.getHistoryReference(); int statusCode = href.getStatusCode(); return this.isFiltered(statusCode); }
Source:
<code>public boolean isDisplay() { <START> if (displayNetwork == null) <END> return true; else return displayNetwork; }</code><technical_language>add curly braces coding conventions reduce a ternary</technical_language>

Target:
public boolean isDisplay() { if (displayNetwork == null) { return true; } else { return displayNetwork; } }
Source:
<code>public static <START> int compareAccessibility(int <END> a, int b) { a = getAccessibility(a); b = getAccessibility(b); if (a == b) { return 0; } switch (a) { case JModifier.PRIVATE: return -1; case JModifier.DEFAULT: return b == JModifier.PRIVATE ? 1 : -1; case JModifier.PROTECTED: return b == JModifier.PUBLIC ? -1 : 1; default: assert a == JModifier.PUBLIC; return 1; } }</code><technical_language>Personnaly I prefer enum result more understandable 0, 1 -1</technical_language>

Target:
static ComparisonResult compareAccessibility(int a, int b) { a = JModifier.getAccessibility(a); b = JModifier.getAccessibility(b); if (a == b) { return ComparisonResult.EQUAL; } switch (a) { case JModifier.PRIVATE: return ComparisonResult.SECOND_WIDER; case JModifier.DEFAULT: return b == JModifier.PRIVATE ? ComparisonResult.FIRST_WIDER : ComparisonResult.SECOND_WIDER; case JModifier.PROTECTED: return b == JModifier.PUBLIC ? ComparisonResult.SECOND_WIDER : ComparisonResult.FIRST_WIDER; default: assert a == JModifier.PUBLIC; return ComparisonResult.FIRST_WIDER; } }
Source:
<code>public void doPost(HttpServletRequest request,HttpServletResponse response){ M_log.debug("doPOST: Called"); try { if(request.getParameterMap().containsKey("oauth_consumer_key")){ for (Object e : request.getParameterMap().entrySet()) { Map.Entry<String, String[]> entry = (Map.Entry<String, String[]>) e; String name = entry.getKey(); for (String value : entry.getValue()) { <START> System.out.println(name + " = " + value); <END> } } Properties appExtSecureProperties = SectionUtilityToolFilter.appExtSecurePropertiesFile; if(appExtSecureProperties!=null) { ltiKey = appExtSecureProperties.getProperty(SectionUtilityToolFilter.PROPERTY_LTI_KEY); ltiSecret = appExtSecureProperties.getProperty(SectionUtilityToolFilter.PROPERTY_LTI_SECRET); ltiUrl = props.getString(SectionUtilityToolFilter.PROPERTY_LTI_URL); boolean myRequest = RequestSignatureUtils.verifySignature(request, ltiKey, ltiSecret, ltiUrl); M_log.info("MyRequest: " + myRequest); } else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); M_log.error("Failed to load system properties(sectionsToolProps.properties) for SectionsTool"); return; } doRequest(request, response); return; } canvasRestApiCall(request, response); }catch(Exception e) { M_log.error("POST request has some exceptions",e); } }</code><technical_language>out System.out do DEBUG instead if need</technical_language>

Target:
public void doPost(HttpServletRequest request,HttpServletResponse response){ M_log.debug("doPOST: Called"); try { if(request.getParameterMap().containsKey("oauth_consumer_key")){ processLti(request, response); return; } canvasRestApiCall(request, response); }catch(Exception e) { M_log.error("POST request has some exceptions",e); } }
Source:
<code>private SelectionListener onImportProject(ServerSettingsWizardPageModel model, final Shell shell) { return new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Map<com.openshift.restclient.model.IProject, Collection<IBuildConfig>> projectsAndBuildConfigs = new HashMap<>(); if (model.getResource() != null) { projectsAndBuildConfigs.put(model.getResource().getProject(), Collections.emptyList()); <START> } <END> ImportApplicationWizard wizard = new ImportApplicationWizard(projectsAndBuildConfigs); final boolean done = WizardUtils.openWizardDialog(wizard, shell); if (done) { model.setDeployProject(ResourcesPlugin.getWorkspace().getRoot().getProject(wizard.getModel().getRepoName())); } } }; }</code><technical_language>this if wont store build configs (if model holds a resource, store empt list of buildconfigs for project of resource). dont get build configs more. testing it, this doesnt correct. Is it</technical_language>

Target:
private SelectionListener onImportProject(ServerSettingsWizardPageModel model, final Shell shell) { return new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (model.getResource() == null) { MessageDialog.openWarning(shell, "No Build Configurations found", "A build config is used to import a project to Eclipse"); return; } Map<com.openshift.restclient.model.IProject, Collection<IBuildConfig>> projectsAndBuildConfigs = new HashMap<>(); projectsAndBuildConfigs.put(model.getResource().getProject(), Collections.emptyList()); ImportApplicationWizard wizard = new ImportApplicationWizard(projectsAndBuildConfigs); final boolean done = WizardUtils.openWizardDialog(wizard, shell); if (done) { model.setDeployProject(ResourcesPlugin.getWorkspace().getRoot().getProject(wizard.getModel().getRepoName())); } } }; }
Source:
<code>public CaffeineCache(long maxSize) { <START> final Caffeine<String, Entries> caffeine = Caffeine.newBuilder() <END> .expireAfter(new Expiry<String, Entries>() { @Override public long expireAfterCreate(String key, Entries value, long currentTime) { return TimeUnit.SECONDS.toNanos(value.ttl()); } @Override public long expireAfterUpdate(String key, Entries value, long currentTime, long currentDuration) { return currentDuration; } @Override public long expireAfterRead(String key, Entries value, long currentTime, long currentDuration) { return currentDuration; } }) .recordStats(); if (maxSize > 0) { caffeine.maximumSize(maxSize); } cache = caffeine.build(); }</code><technical_language>this Caffeine<String, Entries<E>></technical_language>

Target:
public CaffeineCache(long maxSize) { final Caffeine<String, Entries<E>> caffeine = Caffeine.newBuilder() .expireAfter(new Expiry<String, Entries<E>>() { @Override public long expireAfterCreate(String key, Entries<E> value, long currentTime) { return TimeUnit.SECONDS.toNanos(value.ttl()); } @Override public long expireAfterUpdate(String key, Entries<E> value, long currentTime, long currentDuration) { return Math.min(TimeUnit.SECONDS.toNanos(value.ttl()), currentDuration); } @Override public long expireAfterRead(String key, Entries<E> value, long currentTime, long currentDuration) { return currentDuration; } }) .recordStats(); if (maxSize > 0) { caffeine.maximumSize(maxSize); } cache = caffeine.build(); }
Source:
<code>private static void evaluateApplicationInitiatedActionTrigger(final KeycloakSession session, final RequiredActionProvider provider, final RequiredActionProviderModel model, final AuthenticationSessionModel authSession ) { if (provider.initiatedActionSupport() == InitiatedActionSupport.NOT_SUPPORTED) return; String aia = authSession.getClientNote(AIA_REQUEST); if (aia == null) return; if (!aia.equalsIgnoreCase(model.getProviderId())) return; <START> if (session.getContext().getClient().getRole(AccountRoles.INITIATE_ACTION) == null) { <END> logger.error("Client must have initiate-action role to perform application-initiated action."); return; } authSession.addRequiredAction(model.getProviderId()); authSession.removeClientNote(AIA_REQUEST); authSession.setClientNote(IS_AIA_REQUEST, "true"); }</code><technical_language>I remove AccountRoles.INITIATE_ACTION remove this check. this point authentication of client happened this is pretty meaningless a client_id a app (such Keycloak account console). Checking client permissions (manage_account a separate role) is needed for follow-up work a consent screen is required, bypassed clients is permitted do (and supply a valid id_token_hint "authenticate" itself)</technical_language>

Target:
private static void evaluateApplicationInitiatedActionTrigger(final KeycloakSession session, final RequiredActionProvider provider, final RequiredActionProviderModel model, final AuthenticationSessionModel authSession ) { if (provider.initiatedActionSupport() == InitiatedActionSupport.NOT_SUPPORTED) return; String aia = authSession.getClientNote(AIA_REQUEST); if (aia == null) return; if (!aia.equalsIgnoreCase(model.getProviderId())) return; if (session.getContext().getClient().getRole(AccountRoles.MANAGE_ACCOUNT) == null) { throw new ForbiddenException("Client must have manage-account role to perform application-initiated actions."); } authSession.addRequiredAction(model.getProviderId()); authSession.removeClientNote(AIA_REQUEST); authSession.setClientNote(IS_AIA_REQUEST, "true"); }
Source:
<code>static long calculateGrouping(long groupId, List<Integer> columns, List<List<Integer>> groupingSetDescriptors) { long grouping = (1L << columns.size()) - 1; <START> List<Integer> groupingSet = groupingSetDescriptors.get((int) groupId); <END> for (Integer groupingColumn : groupingSet) { int index = columns.indexOf(groupingColumn); if (index != -1) { grouping = grouping & ~(1L << (columns.size() - 1 - index)); } } return grouping; }</code><technical_language>int for groupId checked cast here</technical_language>

Target:
static long calculateGrouping(long groupId, List<Integer> columns, List<List<Integer>> groupingSetDescriptors) { long grouping = (1L << columns.size()) - 1; List<Integer> groupingSet = groupingSetDescriptors.get(toIntExact(groupId)); for (Integer groupingColumn : groupingSet) { int index = columns.indexOf(groupingColumn); if (index != -1) { grouping = grouping & ~(1L << (columns.size() - 1 - index)); } } return grouping; }
Source:
<code><START> public MaxHitRateTracker(int defaultTimeRangeInSeconds, int maxTimeRangeInSeconds) { <END> super(maxTimeRangeInSeconds, (int) (maxTimeRangeInSeconds * 1000L / ONE_SECOND_BUCKET_WIDTH_MS)); _defaultTimeRangeMs = defaultTimeRangeInSeconds * 1000L; _maxTimeRangeMs = maxTimeRangeInSeconds * 1000L; }</code><technical_language>do need this constructor</technical_language>

Target:
private MaxHitRateTracker(int defaultTimeRangeInSeconds, int maxTimeRangeInSeconds) { super(maxTimeRangeInSeconds, (int) (maxTimeRangeInSeconds * 1000L / ONE_SECOND_BUCKET_WIDTH_MS)); _defaultTimeRangeMs = defaultTimeRangeInSeconds * 1000L; _maxTimeRangeMs = maxTimeRangeInSeconds * 1000L; }
Source:
<code>public void initializeUI(UIBuilder builder) throws Exception { Project project = getSelectedProject(builder); if (project.hasFacet(StackFacet.class)) { StackFacet facet = project.getFacet(StackFacet.class); <START> Iterable valueChoices = jaxrsVersion.getValueChoices(); <END> Set newChoices = facet.getStack().filter(CDIFacet.class, valueChoices); jaxrsVersion.setValueChoices(newChoices); jaxrsVersion.setDefaultValue((RestFacet) null); } List<RestFacet> valueChoices = Lists.toList(jaxrsVersion.getValueChoices()); int size = valueChoices.size(); if (size == 1) { jaxrsVersion.setDefaultValue(valueChoices.get(0)); } else if (size > 1) { builder.add(jaxrsVersion); } configureActivationStrategy(builder.getUIContext(), project); builder.add(applicationPath).add(config).add(targetPackage).add(className); }</code><technical_language>Yeah, abstracted</technical_language>

Target:
public void initializeUI(UIBuilder builder) throws Exception { Project project = getSelectedProject(builder); if (filterValueChoicesFromStack(project, jaxrsVersion)) { builder.add(jaxrsVersion); } configureActivationStrategy(builder.getUIContext(), project); builder.add(applicationPath).add(config).add(targetPackage).add(className); }
Source:
<code>private String getDisplayPlaceValue() { if (diagramElement != null) { <START> return NotationUtils.getStringValue((View) diagramElement, StereotypeDisplayUtils.STEREOTYPE_PROPERTY_LOCATION, "Compartment"); <END> } else { return null; } }</code><technical_language>Create replace a constant</technical_language>

Target:
private String getDisplayPlaceValue() { if (diagramElement != null) { return NotationUtils.getStringValue((View) diagramElement, StereotypeDisplayUtils.STEREOTYPE_PROPERTY_LOCATION, DEFAULT_LOCATION); } else { return null; } }
Source:
<code>public static <T> T decode(DnsRecord record) { DnsRecordType type = record.type(); Function<DnsRecord, ?> decoder = decoders.get(type); if (decoder == null) { throw new IllegalStateException("Unsupported resource record type [id: " + type + "]."); } T result = null; try { result = (T) decoder.apply(record); } catch (Exception e) { <START> throw new IllegalStateException(e.getMessage(), e.getCause()); <END> } return result; }</code><technical_language>log throw ISE</technical_language>

Target:
public static <T> T decode(DnsRecord record) { DnsRecordType type = record.type(); Function<DnsRecord, ?> decoder = decoders.get(type); if (decoder == null) { throw new IllegalStateException("Unsupported resource record type [id: " + type + "]."); } T result = null; try { result = (T) decoder.apply(record); } catch (Exception e) { log.error(e.getMessage(), e.getCause()); } return result; }
Source:
<code>private void lockNotificationSequenceForUpdate() throws MetaException { if (sqlGenerator.getDbProduct() == DatabaseProduct.DERBY && directSql != null) { <START> directSql.lockDbTable("NOTIFICATION_SEQUENCE"); <END> } else { String selectQuery = "select \"NEXT_EVENT_ID\" from \"NOTIFICATION_SEQUENCE\""; String lockingQuery = sqlGenerator.addForUpdateClause(selectQuery); new RetryingExecutor(conf, () -> { prepareQuotes(); Query query = pm.newQuery("javax.jdo.query.SQL", lockingQuery); query.setUnique(true); query.execute(); query.closeAll(); }).run(); } }</code><technical_language>if records ..does select for update sense ? lock table for other kind of db</technical_language>

Target:
private void lockNotificationSequenceForUpdate() throws MetaException { if (sqlGenerator.getDbProduct() == DatabaseProduct.DERBY && directSql != null) { new RetryingExecutor(conf, () -> { directSql.lockDbTable("NOTIFICATION_SEQUENCE"); }).run(); } else { String selectQuery = "select \"NEXT_EVENT_ID\" from \"NOTIFICATION_SEQUENCE\""; String lockingQuery = sqlGenerator.addForUpdateClause(selectQuery); new RetryingExecutor(conf, () -> { prepareQuotes(); Query query = pm.newQuery("javax.jdo.query.SQL", lockingQuery); query.setUnique(true); query.execute(); query.closeAll(); }).run(); } }
Source:
<code>default void deleteToken(String processorName, int segment) throws UnableToClaimTokenException { <START> throw new UnsupportedOperationException(""); <END> }</code><technical_language>missing exception description again</technical_language>

Target:
default void deleteToken(String processorName, int segment) throws UnableToClaimTokenException { throw new UnsupportedOperationException("Explicit initialization (which is required to reliably delete tokens) is not supported by this TokenStore implementation"); }
Source:
<code>public WorkDefinitionMatch getWorkDefinitionMatch(String id) { <START> return WorkDefinitionFactory.get().getWorkDefinition(id); <END> }</code><technical_language>Code duplication issue - WorkDefinitionFactory.get() is repeated alot .. need a common private method wrapping this. This change this in future static singleton pattern</technical_language>

Target:
public WorkDefinitionMatch getWorkDefinitionMatch(String id) { return factory.getWorkDefinition(id); }
Source:
<code>public void testResourceBoundary() { String[] charBuffer = {"~", "!", "@", "#", "%", "^", "*", "+", "=", "{", "}", "|", "\\", "<", ">", "\"", "\'", ";"}; for (String aCharBuffer : charBuffer) { try { <START> System.out.println(aCharBuffer); <END> resourceAdminServiceClient.addTextResource(PARENT_PATH + "/" + WSO2_COLL, TEXT_FILE_NAME + aCharBuffer, "text/plain", "sample", "Hello world"); log.error("Invalid resource added with illigal character " + aCharBuffer); resourceAdminServiceClient.deleteResource("/TestAutomation"); fail("Invalid resource added with illigal character " + aCharBuffer); } catch (Exception e) { assertTrue(e.getMessage().contains( "contains one or more illegal characters (~!@#;%^*()+={}|\\<>\"',)" + "" + ""), "Invalid resource added with illigal character " + aCharBuffer); } } }</code><technical_language>is a system.out here</technical_language>

Target:
public void testResourceBoundary() { String[] charBuffer = {"~", "!", "@", "#", "%", "^", "*", "+", "=", "{", "}", "|", "\\", "<", ">", "\"", "\'", ";"}; for (String aCharBuffer : charBuffer) { try { resourceAdminServiceClient.addTextResource(PARENT_PATH + "/" + WSO2_COLL, TEXT_FILE_NAME + aCharBuffer, "text/plain", "sample", "Hello world"); log.error("Invalid resource added with illigal character " + aCharBuffer); resourceAdminServiceClient.deleteResource("/TestAutomation"); fail("Invalid resource added with illigal character " + aCharBuffer); } catch (Exception e) { assertTrue(e.getMessage().contains( "contains one or more illegal characters (~!@#;%^*()+={}|\\<>\"',)" + "" + ""), "Invalid resource added with illigal character " + aCharBuffer); } } }
Source:
<code>ValidClientsByTaskLoadQueue(final Map<UUID, ClientState> clientStates, final BiFunction<UUID, TaskId, Boolean> validClientCriteria) { clientsByTaskLoad = getClientPriorityQueueByTaskLoad(clientStates); <START> this.validClientCriteria = validClientCriteria; <END> }</code><technical_language>awesome tool for optimization this class is. Kudos @cadonna</technical_language>

Target:
ValidClientsByTaskLoadQueue(final Map<UUID, ClientState> clientStates, final BiFunction<UUID, TaskId, Boolean> validClientCriteria) { this.validClientCriteria = validClientCriteria; clientsByTaskLoad = new PriorityQueue<>( (client, other) -> { final double clientTaskLoad = clientStates.get(client).taskLoad(); final double otherTaskLoad = clientStates.get(other).taskLoad(); if (clientTaskLoad < otherTaskLoad) { return -1; } else if (clientTaskLoad > otherTaskLoad) { return 1; } else { return client.compareTo(other); } }); }
Source:
<code>public CachedRemoteStreamProvider(int size) { cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("preConfigured", CacheConfigurationBuilder.newCacheConfigurationBuilder(URL.class, AudioStreamCache.class, <START> ResourcePoolsBuilder.newResourcePoolsBuilder().heap(size, MemoryUnit.MB)) <END> .build()) .build(true); }</code><technical_language>nice option for disk caches. builder option <LINK_0> require a new flag coming form configuration</technical_language>

Target:
public CachedRemoteStreamProvider(int size) { log.info("Create AudioCache with size: " + size + "Mb"); cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("preConfigured", CacheConfigurationBuilder.newCacheConfigurationBuilder(URL.class, ByteStreamCache.class, ResourcePoolsBuilder.newResourcePoolsBuilder().heap(size, MemoryUnit.MB)) .build()) .build(true); sizeChangedListener = new ByteStreamCache.ISizeChangedListener() { @Override public void onSizeChanged(final URL uri, final ByteStreamCache self) { log.debug("onSizeChanged for " + uri); getCache().put(uri, self); } }; }
Source:
<code>public String toString() { return "Container{" + "id='" + id + '\'' + ", names=" + names + ", created='" + created + '\'' + ", path='" + path + '\'' + ", args=" + Arrays.toString(args) + ", config=" + config + ", state=" + state + ", image='" + image + '\'' + ", networkSettings=" + networkSettings + ", sysInitPath='" + sysInitPath + '\'' + ", resolvConfPath='" + resolvConfPath + '\'' + ", volumes=" + volumes + ", sizeRw=" + sizeRw + ", sizeRootFs=" + sizeRootFs + ", command='" + command + '\'' + ", status='" + status + '\'' + ", hostConfig=" + hostConfig + ", ports=" + ports + <START> '}'; <END> }</code><technical_language>Objects.toStringHelper in Config class</technical_language>

Target:
public String toString() { return Objects.toStringHelper(this) .add("id", id) .add("name", name) .add("created", created) .add("path", path) .add("args", args) .add("containerConfig", containerConfig) .add("state", state) .add("image", image) .add("networkSettings", networkSettings) .add("resolvConfPath", resolvConfPath) .add("driver", driver) .add("execDriver", execDriver) .add("volumes", volumes) .add("volumesRW", volumesRW) .add("command", command) .add("status", status) .add("hostConfig", hostConfig) .add("ports", ports) .add("hostnamePath", hostnamePath) .toString(); }
Source:
<code>public Integer getNumberOfFiles(URI directory) { int count = 0; if (directory.isAbsolute()) { if (isDirectory(directory)) { ArrayList<URI> children = getSubUris(directory); for (URI aChildren : children) { if (isDirectory(aChildren)) { count += getNumberOfFiles(aChildren); } else { count += 1; } } } } else { directory = getAbsoluteURI(directory, MappingType.DATA, null, null); ArrayList<URI> children = getSubUris(directory); if (isDirectory(directory)) { for (URI aChildren : children) { if (isDirectory(aChildren)) { count += getNumberOfFiles(aChildren); } else { count += 1; <START> } <END> } } } return count; }</code><technical_language>iterations list of URIs similar: move this counting method? This reduce level of nested if statements</technical_language>

Target:
public Integer getNumberOfFiles(URI directory) { int count = 0; if (directory.isAbsolute()) { count += iterateOverDirectories(directory); } else { directory = getAbsoluteURI(directory, MappingType.DATA, null, null); count += iterateOverDirectories(directory); } return count; }
Source:
<code>protected HdfsSinkConnectorConfig(ConfigDef configDef, Map<String, String> props) { super(configDef, props); ConfigDef storageCommonConfigDef = StorageCommonConfig.newConfigDef(STORAGE_CLASS_RECOMMENDER); commonConfig = new StorageCommonConfig(storageCommonConfigDef, originalsStrings()); hiveConfig = new HiveConfig(originalsStrings()); ConfigDef partitionerConfigDef = PartitionerConfig.newConfigDef(PARTITIONER_CLASS_RECOMMENDER); partitionerConfig = new PartitionerConfig(partitionerConfigDef, originalsStrings()); this.name = parseName(originalsStrings()); this.hadoopConfig = new Configuration(); <START> this.url = extractUrl(originalsStrings()); <END> addToGlobal(hiveConfig); addToGlobal(partitionerConfig); addToGlobal(commonConfig); addToGlobal(this); }</code><technical_language>do need a copy here? props directly</technical_language>

Target:
protected HdfsSinkConnectorConfig(ConfigDef configDef, Map<String, String> props) { super(configDef, props); ConfigDef storageCommonConfigDef = StorageCommonConfig.newConfigDef(STORAGE_CLASS_RECOMMENDER); commonConfig = new StorageCommonConfig(storageCommonConfigDef, originalsStrings()); hiveConfig = new HiveConfig(originalsStrings()); ConfigDef partitionerConfigDef = PartitionerConfig.newConfigDef(PARTITIONER_CLASS_RECOMMENDER); partitionerConfig = new PartitionerConfig(partitionerConfigDef, originalsStrings()); this.name = parseName(originalsStrings()); this.hadoopConfig = new Configuration(); addToGlobal(hiveConfig); addToGlobal(partitionerConfig); addToGlobal(commonConfig); addToGlobal(this); this.url = extractUrl(); }