auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void ensureConsoleAppenderIsDefined(Logger logger) { if (logger != null) { ConsoleAppender consoleAppender = null; for (Object appender : Collections.list(logger.getAllAppenders())) { if (appender instanceof ConsoleAppender) { consoleAppender = (ConsoleAppender) appender; <START> break; <END> } } if (consoleAppender == null) { consoleAppender = new ConsoleAppender(); consoleAppender.setWriter(new OutputStreamWriter(System.out)); consoleAppender.setLayout(new PatternLayout("%d{ABSOLUTE} %-5p [%c{1}] %m%n")); logger.addAppender(consoleAppender); } } }</code><technical_language>return here, it? need if statement line 99 define consoleAppender variable line initialize (currently line 100)</technical_language>

Target:
protected void ensureConsoleAppenderIsDefined(Logger logger) { if (logger != null) { for (Object appender : Collections.list(logger.getAllAppenders())) { if (appender instanceof ConsoleAppender) { return; } } ConsoleAppender consoleAppender = new ConsoleAppender(); consoleAppender.setWriter(new OutputStreamWriter(System.out)); consoleAppender.setLayout(new PatternLayout("%d{ABSOLUTE} %-5p [%c{1}] %m%n")); logger.addAppender(consoleAppender); } }
Source:
<code>public NamespaceListener(String token) { log.info("Creating NamespaceListener"); this.token = token; <START> namespaces = new HashMap<String, String>(); <END> log.info("Namespace listener starting"); new Thread(new Listener()).start(); }</code><technical_language><String, String> is redundant</technical_language>

Target:
public NamespaceListener(String token) { log.debug("Creating NamespaceListener"); this.token = token; namespaces = new HashMap<>(); log.debug("Namespace listener starting."); new Thread(new Listener()).start(); }
Source:
<code>public boolean isDTS() { <START> return getCodecA() != null && (getCodecA().startsWith("dts") || "dca".equals(getCodecA()) || "dca (dts)".equals(getCodecA())); <END> }</code><technical_language>return getCodecA() != null && ("dts".contains(getCodecA()) || "dca".contains(getCodecA()));</technical_language>

Target:
public boolean isDTS() { return getCodecA() != null && (getCodecA().contains("dts") || getCodecA().contains("dca")); }
Source:
<code>public void uploadWithResponse(InputStream data, long length, ParallelTransferOptions parallelTransferOptions, BlobHttpHeaders headers, Map<String, String> metadata, AccessTier tier, BlobRequestConditions requestConditions, Duration timeout, Context context) { BlockBlobClient blockBlobClient = this.getBlockBlobClient(); final ParallelTransferOptions validatedParallelTransferOptions = ModelHelper.populateAndApplyDefaults(parallelTransferOptions); if (length < validatedParallelTransferOptions.getMaxSingleUploadSize()) { blockBlobClient.uploadWithResponse(data, length, headers, metadata, tier, null, requestConditions, timeout, context); } else { BlobOutputStream blobOutputStream = BlobOutputStream.blockBlobOutputStream(client, validatedParallelTransferOptions, headers, metadata, tier, requestConditions); try { <START> data.transferTo(blobOutputStream); <END> blobOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }</code><technical_language>I thought this method java 9</technical_language>

Target:
public void uploadWithResponse(InputStream data, long length, ParallelTransferOptions parallelTransferOptions, BlobHttpHeaders headers, Map<String, String> metadata, AccessTier tier, BlobRequestConditions requestConditions, Duration timeout, Context context) { BlockBlobClient blockBlobClient = this.getBlockBlobClient(); final ParallelTransferOptions validatedParallelTransferOptions = ModelHelper.populateAndApplyDefaults(parallelTransferOptions); if (length < validatedParallelTransferOptions.getMaxSingleUploadSize()) { blockBlobClient.uploadWithResponse(data, length, headers, metadata, tier, null, requestConditions, timeout, context); } else { BlobOutputStream blobOutputStream = BlobOutputStream.blockBlobOutputStream(client, validatedParallelTransferOptions, headers, metadata, tier, requestConditions); try { StorageImplUtils.copyToOutputStream(data, length, blobOutputStream); blobOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
Source:
<code>public void should_canUserSeeProcessInstance_call_engine_api_false() throws Exception { <START> final boolean expected = false; <END> checkCanUserSeeProcessInstanceWhenApiReturn(expected); }</code><technical_language>inlined</technical_language>

Target:
public void should_canUserSeeProcessInstance_call_engine_api_false() throws Exception { checkCanUserSeeProcessInstanceWhenApiReturn(false); }
Source:
<code>public boolean isKnownFormat(CharSource charSource) { try (CsvIterator csv = CsvIterator.of(charSource, true)) { if (!csv.containsHeader(TENOR_HEADER) && !csv.containsHeader(DATE_HEADER)) { return false; } if (csv.containsHeader(REFERENCE_HEADER) || csv.containsHeader(TYPE_HEADER)) { return true; } else { <START> return csv.headers().stream() <END> .filter(header -> knownReference(header)) .findAny() .isPresent(); } } catch (RuntimeException ex) { return false; } }</code><technical_language>return csv.headers().stream().anyMatch(header -> knownReference(header));</technical_language>

Target:
public boolean isKnownFormat(CharSource charSource) { try (CsvIterator csv = CsvIterator.of(charSource, true)) { if (!csv.containsHeader(TENOR_HEADER) && !csv.containsHeader(DATE_HEADER)) { return false; } if (csv.containsHeader(REFERENCE_HEADER) || csv.containsHeader(TYPE_HEADER)) { return true; } else { return csv.headers().stream().anyMatch(SensitivityCsvLoader::knownReference); } } catch (RuntimeException ex) { return false; } }
Source:
<code>void addThreadMetrics(List<MetricFamilySamples> sampleFamilies) { sampleFamilies.add( new GaugeMetricFamily( "jvm_threads_current", "Current thread count of a JVM", threadBean.getThreadCount())); sampleFamilies.add( new GaugeMetricFamily( "jvm_threads_daemon", "Daemon thread count of a JVM", threadBean.getDaemonThreadCount())); sampleFamilies.add( new GaugeMetricFamily( "jvm_threads_peak", "Peak thread count of a JVM", threadBean.getPeakThreadCount())); sampleFamilies.add( new CounterMetricFamily( "jvm_threads_started_total", "Started thread count of a JVM", threadBean.getTotalStartedThreadCount())); sampleFamilies.add( new GaugeMetricFamily( "jvm_threads_deadlocked", "Cycles of JVM-threads that are in deadlock waiting to acquire object monitors or ownable synchronizers", nullSafeArrayLength(threadBean.findDeadlockedThreads()))); sampleFamilies.add( new GaugeMetricFamily( "jvm_threads_deadlocked_monitor", "Cycles of JVM-threads that are in deadlock waiting to acquire object monitors", nullSafeArrayLength(threadBean.findMonitorDeadlockedThreads()))); Map<Thread.State, Integer> threadStateCounts = getThreadStateCountMap(); for (Map.Entry<Thread.State, Integer> entry : threadStateCounts.entrySet()) { String stateName = entry.getKey().toString().toLowerCase(); sampleFamilies.add( new GaugeMetricFamily( <START> String.format("jvm_threads_%s", stateName), <END> String.format("Current count of threads in state '%s'", stateName), entry.getValue().doubleValue())); } }</code><technical_language>This a label, part of a metric name</technical_language>

Target:
void addThreadMetrics(List<MetricFamilySamples> sampleFamilies) { sampleFamilies.add( new GaugeMetricFamily( "jvm_threads_current", "Current thread count of a JVM", threadBean.getThreadCount())); sampleFamilies.add( new GaugeMetricFamily( "jvm_threads_daemon", "Daemon thread count of a JVM", threadBean.getDaemonThreadCount())); sampleFamilies.add( new GaugeMetricFamily( "jvm_threads_peak", "Peak thread count of a JVM", threadBean.getPeakThreadCount())); sampleFamilies.add( new CounterMetricFamily( "jvm_threads_started_total", "Started thread count of a JVM", threadBean.getTotalStartedThreadCount())); sampleFamilies.add( new GaugeMetricFamily( "jvm_threads_deadlocked", "Cycles of JVM-threads that are in deadlock waiting to acquire object monitors or ownable synchronizers", nullSafeArrayLength(threadBean.findDeadlockedThreads()))); sampleFamilies.add( new GaugeMetricFamily( "jvm_threads_deadlocked_monitor", "Cycles of JVM-threads that are in deadlock waiting to acquire object monitors", nullSafeArrayLength(threadBean.findMonitorDeadlockedThreads()))); GaugeMetricFamily threadStateFamily = new GaugeMetricFamily( "jvm_threads_state", "Current count of threads by state", Collections.singletonList("state")); Map<Thread.State, Integer> threadStateCounts = getThreadStateCountMap(); for (Map.Entry<Thread.State, Integer> entry : threadStateCounts.entrySet()) { threadStateFamily.addMetric( Collections.singletonList(entry.getKey().toString()), entry.getValue() ); } }
Source:
<code>private BlockRead getBlock(String _lookup, BlockCache cache, BlockLoader loader) throws IOException { BlockReader _currBlock; Lock loadLock = null; if (cache != null) { CacheEntry cb = null; cb = cache.getBlock(_lookup); if (cb != null) { return new CachedBlockRead(cb, cb.getBuffer()); } loadLock = cache.getLoadLock(_lookup); } try { if (loadLock != null) { loadLock.lock(); CacheEntry cb = null; <START> cb = cache.getBlockNoStats(_lookup); <END> if (cb != null) { return new CachedBlockRead(cb, cb.getBuffer()); } } _currBlock = loader.get(); return cacheBlock(_lookup, cache, _currBlock, loader.getInfo()); } finally { if (loadLock != null) loadLock.unlock(); } }</code><technical_language>Combine this variable declaration above. suggestion CacheEntry cb = cache.getBlockNoStats(_lookup);</technical_language>

Target:
private BlockRead getBlock(String _lookup, BlockCache cache, BlockLoader loader) throws IOException { BlockReader _currBlock; Lock loadLock = null; if (cache != null) { CacheEntry cb = null; cb = cache.getBlock(_lookup); if (cb != null) { return new CachedBlockRead(cb, cb.getBuffer()); } loadLock = cache.getLoadLock(_lookup); } try { if (loadLock != null) { loadLock.lock(); CacheEntry cb = cache.getBlockNoStats(_lookup); if (cb != null) { return new CachedBlockRead(cb, cb.getBuffer()); } } _currBlock = loader.get(); return cacheBlock(_lookup, cache, _currBlock, loader.getInfo()); } finally { if (loadLock != null) loadLock.unlock(); } }
Source:
<code>public SSLSession getSSLSession() { if (!hasSSLSupport()) { <START> throw new IllegalStateException("This websocket does use ws instead of wss. No SSLSession available."); <END> } return ((ISSLChannel) channel).getSSLEngine().getSession(); }</code><technical_language>Also, message intended "This websocket ws instead of wss. SSLSession available."</technical_language>

Target:
public SSLSession getSSLSession() { if (!hasSSLSupport()) { throw new IllegalArgumentException("This websocket uses ws instead of wss. No SSLSession available."); } return ((ISSLChannel) channel).getSSLEngine().getSession(); }
Source:
<code>public static CacheHeader readHeader(InputStream is, boolean includeResponseHeaders) throws IOException { CacheHeader entry = new CacheHeader(); int magic = readInt(is); if (magic != CACHE_MAGIC) { throw new IOException(); } entry.key = readString(is); entry.etag = readString(is); if (entry.etag.equals("")) { entry.etag = null; } entry.serverDate = readLong(is); entry.ttl = readLong(is); entry.softTtl = readLong(is); <START> Map<String, String> headers = readStringStringMap(is); <END> if (includeResponseHeaders) { entry.responseHeaders = headers; } else { entry.responseHeaders = new HashMap<>(); } return entry; }</code><technical_language>this moved if() clause for maximal memory savings</technical_language>

Target:
public static CacheHeader readHeader(InputStream is, boolean includeResponseHeaders) throws IOException { CacheHeader entry = new CacheHeader(); int magic = readInt(is); if (magic != CACHE_MAGIC) { throw new IOException(); } entry.key = readString(is); entry.etag = readString(is); if (entry.etag.equals("")) { entry.etag = null; } entry.serverDate = readLong(is); entry.ttl = readLong(is); entry.softTtl = readLong(is); if (includeResponseHeaders) { entry.responseHeaders = readStringStringMap(is); } else { entry.responseHeaders = new HashMap<>(); } return entry; }
Source:
<code>public Operation operationDispatched(Request request, Operation operation) { <START> if (!request.getHttpRequest().getServletPath().equals("/ogc") <END> && request.getOutputFormat().equals(JSONLDGetFeatureResponse.MIME)) { FeatureTypeInfo typeInfo = null; GetFeatureRequest getFeature = null; getFeature = GetFeatureRequest.adapt(operation.getParameters()[0]); List<Query> queries = getFeature.getQueries(); if (getFeature != null && queries != null && queries.size() > 0) { for (int i = 0; i < queries.size(); i++) { Query q = queries.get(i); QName type = q.getTypeNames().get(0); typeInfo = catalog.getFeatureTypeByName( new NameImpl(type.getPrefix(), type.getLocalPart())); if (typeInfo != null) { try { RootBuilder root = configuration.getTemplate(typeInfo); JsonLdPathVisitor visitor = new JsonLdPathVisitor(typeInfo.getFeatureType()); if (q.getFilter() != null) { Filter newFilter = (Filter) q.getFilter().accept(visitor, root); q.setFilter(newFilter); } } catch (Exception e) { throw new RuntimeException(e); } } } } } return super.operationDispatched(request, operation); }</code><technical_language>Servlet path tests fragile: - service a workspace specific one, 100% do wrappers, this point "workspace/ogc" servlet path - OGC services end moved another position upgrade (not sure) - Other plugins in future json-ld (e.g., dunno, GetFeatureInfo, a WPS process) based this plugin safer me, "WFS".equalsIgnoreCase(request.getService()) test for WFS, output format type</technical_language>

Target:
public Operation operationDispatched(Request request, Operation operation) { if ("WFS".equalsIgnoreCase(request.getService()) && request.getOutputFormat() != null && request.getOutputFormat().equals(JSONLDGetFeatureResponse.MIME)) { FeatureTypeInfo typeInfo = null; GetFeatureRequest getFeature = null; getFeature = GetFeatureRequest.adapt(operation.getParameters()[0]); List<Query> queries = getFeature.getQueries(); if (getFeature != null && queries != null && queries.size() > 0) { for (int i = 0; i < queries.size(); i++) { Query q = queries.get(i); QName type = q.getTypeNames().get(0); typeInfo = catalog.getFeatureTypeByName( new NameImpl(type.getPrefix(), type.getLocalPart())); if (typeInfo != null) { try { RootBuilder root = configuration.getTemplate(typeInfo); JsonLdPathVisitor visitor = new JsonLdPathVisitor(typeInfo.getFeatureType()); if (q.getFilter() != null) { Filter newFilter = (Filter) q.getFilter().accept(visitor, root); q.setFilter(newFilter); } } catch (Exception e) { throw new RuntimeException(e); } } } } } return super.operationDispatched(request, operation); }
Source:
<code>public List<Credential> fromRequest(final HttpServletRequest request, final MultiValueMap<String, String> requestBody) { if (requestBody == null || requestBody.isEmpty()) { <START> LOGGER.debug("Skipping because the requestBody is null or empty", this); <END> return new ArrayList<>(0); } final String cert = requestBody.getFirst(CERTIFICATE); LOGGER.debug("Certificate in the request body: [{}]", cert); if (StringUtils.isBlank(cert)) { return new ArrayList<>(0); } try (InputStream is = new ByteArrayInputStream(cert.getBytes(StandardCharsets.UTF_8))) { final InputStreamSource iso = new InputStreamResource(is); final X509Certificate certificate = CertUtils.readCertificate(iso); final X509CertificateCredential credential = new X509CertificateCredential(new X509Certificate[]{certificate}); credential.setCertificate(certificate); return CollectionUtils.wrap(credential); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return new ArrayList<>(0); }</code><technical_language>above; Consider getClass().getSimpleName() instead of this</technical_language>

Target:
public List<Credential> fromRequest(final HttpServletRequest request, final MultiValueMap<String, String> requestBody) { if (requestBody == null || requestBody.isEmpty()) { LOGGER.debug("Skipping because the requestBody is null or empty", getClass().getSimpleName()); return new ArrayList<>(0); } final String cert = requestBody.getFirst(CERTIFICATE); LOGGER.debug("Certificate in the request body: [{}]", cert); if (StringUtils.isBlank(cert)) { return new ArrayList<>(0); } try (InputStream is = new ByteArrayInputStream(cert.getBytes(StandardCharsets.UTF_8))) { final InputStreamSource iso = new InputStreamResource(is); final X509Certificate certificate = CertUtils.readCertificate(iso); final X509CertificateCredential credential = new X509CertificateCredential(new X509Certificate[]{certificate}); credential.setCertificate(certificate); return CollectionUtils.wrap(credential); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return new ArrayList<>(0); }
Source:
<code>public void store(Item item, String alias) { if (isAgentConnected()) { String hwid = SiteWhereConfigurationManager.getInstance() .getFieldMapper().getHardwareIdForItem(item.getName()); if (hwid == null) { LOGGER.warn("No mapping found for field: " + item.getName()); return; } try { State state = item.getState(); if (state instanceof PercentType) { addDeviceMeasurement(hwid, item, ((PercentType) state) .toBigDecimal().doubleValue()); } else if (state instanceof DecimalType) { addDeviceMeasurement(hwid, item, ((DecimalType) state) .toBigDecimal().doubleValue()); } else if (state instanceof DateTimeType) { addDeviceAlert(hwid, item, (DateTimeType) state); } else if (state instanceof OnOffType) { addDeviceAlert(hwid, item, (OnOffType) state); } else if (state instanceof OpenClosedType) { addDeviceAlert(hwid, item, (OpenClosedType) state); } else if (state instanceof StringType) { addDeviceAlert(hwid, item, (StringType) state); } else { LOGGER.warn("Unable to store item of type: " + item.getState().getClass().getSimpleName()); return; } } catch (SiteWhereAgentException e) { LOGGER.warn("Unable to store item: " + item.getName(), e); } <START> } <END> }</code><technical_language>add log statement else block DEBUG level</technical_language>

Target:
public void store(Item item, String alias) { if (isAgentConnected()) { String hwid = getConfiguration().getDefaultHardwareId(); try { State state = item.getState(); if (state instanceof PercentType) { addDeviceMeasurement(hwid, item, ((PercentType) state) .toBigDecimal().doubleValue()); } else if (state instanceof DecimalType) { addDeviceMeasurement(hwid, item, ((DecimalType) state) .toBigDecimal().doubleValue()); } else if (state instanceof DateTimeType) { addDeviceAlert(hwid, item, (DateTimeType) state); } else if (state instanceof OnOffType) { addDeviceAlert(hwid, item, (OnOffType) state); } else if (state instanceof OpenClosedType) { addDeviceAlert(hwid, item, (OpenClosedType) state); } else if (state instanceof StringType) { addDeviceAlert(hwid, item, (StringType) state); } else if (state instanceof PointType) { addDeviceLocation(hwid, item, (PointType) state); } else { LOGGER.debug("Unable to store item of type: " + item.getState().getClass().getSimpleName()); return; } } catch (SiteWhereAgentException e) { LOGGER.warn("Unable to store item: " + item.getName(), e); } } }
Source:
<code>@Override public boolean equals(Object obj) { return obj == this || obj instanceof MutableScan && rel.getTable().equals(((MutableScan) obj).rel.getTable()); <START> } <END></code><technical_language>MaterializedViewSubstitutionVisitor directly</technical_language>

Target:
@Override public boolean equals(Object obj) { return obj == this || obj instanceof MutableScan && rel.getTable().getQualifiedName().equals(((MutableScan) obj).rel .getTable().getQualifiedName()); }
Source:
<code>public void validate_shouldFailValidationIfDoseUnitsIsNullForDosingTypeSimple() throws Exception { DrugOrder order = new DrugOrder(); order.setDosingType(DrugOrder.DosingType.SIMPLE); order.setDoseUnits(null); Errors errors = new BindException(order, "order"); new DrugOrderValidator().validate(order, errors); <START> Assert.assertTrue(errors.hasFieldErrors("dose")); <END> }</code><technical_language>this doseUnits? :)</technical_language>

Target:
public void validate_shouldFailValidationIfDoseUnitsIsNullForDosingTypeSimple() throws Exception { DrugOrder order = new DrugOrder(); order.setDosingType(DrugOrder.DosingType.SIMPLE); order.setDoseUnits(null); Errors errors = new BindException(order, "order"); new DrugOrderValidator().validate(order, errors); Assert.assertTrue(errors.hasFieldErrors("doseUnits")); }
Source:
<code>public static Settings fromJson(JSONObject settingsObject) throws JSONException { Settings settings = new Settings(); settings.firstSurvey = settingsObject.optLong("first_survey"); settings.timeDelay = settingsObject.optInt("time_delay"); <START> settings.userID = settingsObject.optLong("user_id"); <END> if (settingsObject.has("account_id")) { settings.accountID = settingsObject.optLong("account_id"); } else { settings.accountID = (long) Constants.NOT_SET; } JSONObject localizedTextsJson = settingsObject.optJSONObject("localized_texts"); settings.localizedTexts = LocalizedTexts.fromJson(localizedTextsJson); JSONObject customMessagesJson = settingsObject.optJSONObject("messages"); settings.adminPanelCustomMessage = WootricCustomMessage.fromJson(customMessagesJson); return settings; }</code><technical_language>Do check for account_id user_id eventually phased out</technical_language>

Target:
public static Settings fromJson(JSONObject settingsObject) throws JSONException { Settings settings = new Settings(); settings.firstSurvey = settingsObject.optLong("first_survey"); settings.timeDelay = settingsObject.optInt("time_delay"); if (settingsObject.has("account_id")) { settings.accountID = settingsObject.optLong("account_id"); } else { settings.accountID = (long) Constants.NOT_SET; } if (settingsObject.has("user_id")) { settings.userID = settingsObject.optLong("user_id"); } else { settings.userID = (long) Constants.NOT_SET; } JSONObject localizedTextsJson = settingsObject.optJSONObject("localized_texts"); settings.localizedTexts = LocalizedTexts.fromJson(localizedTextsJson); JSONObject customMessagesJson = settingsObject.optJSONObject("messages"); settings.adminPanelCustomMessage = WootricCustomMessage.fromJson(customMessagesJson); return settings; }
Source:
<code>public boolean provides(IOperation operation) { boolean provide = false; String currentDiagramType; EObject referenceElement = ((IEditPartOperation) operation).getView().getElement(); if ((operation instanceof CreateGraphicEditPartOperation) && (referenceElement instanceof Classifier) && (CapsuleUtils.isCapsule((Classifier) referenceElement))) { currentDiagramType = ((IEditPartOperation) operation).getView().getDiagram().getType(); if ((diagramType == null) || (!diagramType.equals(currentDiagramType))) { provide = false; } else { provide = super.provides(operation); } } if ((operation instanceof CreateGraphicEditPartOperation) && (referenceElement instanceof Property) && (CapsulePartUtils.isCapsulePart((Property) referenceElement))) { currentDiagramType = ((IEditPartOperation) operation).getView().getDiagram().getType(); <START> if ((diagramType == null) || (!diagramType.equals(currentDiagramType))) { <END> provide = false; } else { provide = super.provides(operation); } } if ((operation instanceof CreateGraphicEditPartOperation) && (RTPortUtils.isRTPort(referenceElement))) { currentDiagramType = ((IEditPartOperation) operation).getView().getDiagram().getType(); if ((diagramType == null) || (!diagramType.equals(currentDiagramType))) { provide = false; } else { provide = super.provides(operation); } } return provide; }</code><technical_language>invert</technical_language>

Target:
public boolean provides(IOperation operation) { boolean provide = false; String currentDiagramType; EObject referenceElement = ((IEditPartOperation) operation).getView().getElement(); if ((operation instanceof CreateGraphicEditPartOperation) && (referenceElement instanceof Classifier) && (CapsuleUtils.isCapsule((Classifier) referenceElement))) { currentDiagramType = ((IEditPartOperation) operation).getView().getDiagram().getType(); if ((diagramType == null) || (!diagramType.equals(currentDiagramType))) { provide = false; } else { provide = super.provides(operation); } } if ((operation instanceof CreateGraphicEditPartOperation) && (referenceElement instanceof Property) && (CapsulePartUtils.isCapsulePart((Property) referenceElement))) { currentDiagramType = ((IEditPartOperation) operation).getView().getDiagram().getType(); if ((null == diagramType) || (!diagramType.equals(currentDiagramType))) { provide = false; } else { provide = super.provides(operation); } } if ((operation instanceof CreateGraphicEditPartOperation) && (RTPortUtils.isRTPort(referenceElement))) { currentDiagramType = ((IEditPartOperation) operation).getView().getDiagram().getType(); if ((null == diagramType) || (!diagramType.equals(currentDiagramType))) { provide = false; } else { provide = super.provides(operation); } } return provide; }
Source:
<code>SubscriberTask(@Nonnull StreamManager streamManager, @Nonnull StreamListener listener, @Nonnull String namespace, @Nonnull List<TableSchema<K, V, M>> tableSchemas, long startAddress) { this.streamManager = streamManager; this.listener = listener; this.namespace = namespace; this.tablesOfInterest = new HashMap<>(); this.shutdown = new AtomicBoolean(); tableSchemas.forEach(tableSchema -> tablesOfInterest.put( CorfuRuntime.getStreamID( TableRegistry.getFullyQualifiedTableName(namespace, tableSchema.getTableName()) ), tableSchema )); this.startAddress = startAddress; StreamOptions options = StreamOptions.builder() <START> .cacheEntries(!runtime.getParameters().isCacheDisabled()) <END> .build(); this.txnStream = runtime.getStreamsView() .get(ObjectsView.TRANSACTION_STREAM_ID, options); this.txnStream.seek(startAddress + 1); }</code><technical_language>I disable cache for poller. If privous corfustore stream DCN, disabled cache avoid polluting addressSpaceView cache, a lot of NoRollbackException</technical_language>

Target:
SubscriberTask(@Nonnull StreamManager streamManager, @Nonnull StreamListener listener, @Nonnull String namespace, @Nonnull List<TableSchema<K, V, M>> tableSchemas, long startAddress) { this.streamManager = streamManager; this.listener = listener; this.namespace = namespace; this.tablesOfInterest = new HashMap<>(); tableSchemas.forEach(tableSchema -> tablesOfInterest.put( CorfuRuntime.getStreamID( TableRegistry.getFullyQualifiedTableName(namespace, tableSchema.getTableName()) ), tableSchema )); StreamOptions options = StreamOptions.builder() .cacheEntries(false) .build(); this.txnStream = runtime.getStreamsView() .get(ObjectsView.TRANSACTION_STREAM_ID, options); this.txnStream.seek(startAddress + 1); }
Source:
<code><START> public ExtractUnallocAction(String title, Volume volume) throws NoCurrentCaseException { <END> super(title); isImage = false; OutputFileData outputFileData = new OutputFileData(volume); filesToExtract.add(outputFileData); }</code><technical_language>Thinking this some more, propagate NoCurrentCaseException constructors, lets catch log cal setEnabled(false) action grayed out, omitted node context menu</technical_language>

Target:
public ExtractUnallocAction(String title, Volume volume){ super(title); isImage = false; try { OutputFileData outputFileData = new OutputFileData(volume); filesToExtract.add(outputFileData); } catch (NoCurrentCaseException ex) { logger.log(Level.SEVERE, "Exception while getting open case.", ex); setEnabled(false); } }
Source:
<code>public boolean loadSegment(final DataSegment segment) throws SegmentLoadingException { final Segment adapter = getAdapter(segment); final DataSourceState computeResult = dataSources.compute( segment.getDataSource(), (k, v) -> { final DataSourceState dataSourceState = v == null ? new DataSourceState() : v; final VersionedIntervalTimeline<String, ReferenceCountingSegment> loadedIntervals = dataSourceState.getTimeline(); final PartitionHolder<ReferenceCountingSegment> entry = loadedIntervals.findEntry( segment.getInterval(), segment.getVersion() ); if ((entry != null) && (entry.getChunk(segment.getShardSpec().getPartitionNum()) != null)) { log.warn("Told to load a adapter for a segment[%s] that already exists", segment.getIdentifier()); <START> return null; <END> } else { loadedIntervals.add( segment.getInterval(), segment.getVersion(), segment.getShardSpec().createChunk(new ReferenceCountingSegment(adapter)) ); dataSourceState.addSegment(segment); return dataSourceState; } } ); return computeResult != null; }</code><technical_language>Returning null entry removal dataSources Map, happen</technical_language>

Target:
public boolean loadSegment(final DataSegment segment) throws SegmentLoadingException { final Segment adapter = getAdapter(segment); final SettableSupplier<Boolean> resultSupplier = new SettableSupplier<>(); dataSources.compute( segment.getDataSource(), (k, v) -> { final DataSourceState dataSourceState = v == null ? new DataSourceState() : v; final VersionedIntervalTimeline<String, ReferenceCountingSegment> loadedIntervals = dataSourceState.getTimeline(); final PartitionHolder<ReferenceCountingSegment> entry = loadedIntervals.findEntry( segment.getInterval(), segment.getVersion() ); if ((entry != null) && (entry.getChunk(segment.getShardSpec().getPartitionNum()) != null)) { log.warn("Told to load a adapter for a segment[%s] that already exists", segment.getIdentifier()); resultSupplier.set(false); } else { loadedIntervals.add( segment.getInterval(), segment.getVersion(), segment.getShardSpec().createChunk(new ReferenceCountingSegment(adapter)) ); dataSourceState.addSegment(segment); resultSupplier.set(true); } return dataSourceState; } ); return resultSupplier.get(); }
Source:
<code>public void <START> testUrlParsing() <END> { UrlParseRequest nullUrl = new UrlParseRequest(null); UrlParseRequest emptyUrl = new UrlParseRequest(""); UrlParseRequest noHost = new UrlParseRequest("http:/ UrlParseRequest badProtocol = new UrlParseRequest("bad:http://foo"); }</code><technical_language>Thank for considering tests. some asserts in them</technical_language>

Target:
public void testUrlParsing() { UrlParseRequest nullUrl = new UrlParseRequest(null); assertEquals(0, nullUrl.getTrafficStatsTag()); UrlParseRequest emptyUrl = new UrlParseRequest(""); assertEquals(0, emptyUrl.getTrafficStatsTag()); UrlParseRequest noHost = new UrlParseRequest("http:/ assertEquals(0, noHost.getTrafficStatsTag()); UrlParseRequest badProtocol = new UrlParseRequest("bad:http://foo"); assertEquals(0, badProtocol.getTrafficStatsTag()); UrlParseRequest goodProtocol = new UrlParseRequest("http://foo"); assertFalse(0 == goodProtocol.getTrafficStatsTag()); }
Source:
<code>public void handleError(HttpServletRequest request, HttpServletResponse response, HandlerContext context) { Object error = request.getAttribute(HandlerContext.ERROR_ATTRIBUTE); if (error instanceof AuthenticationException) { <START> response.setHeader("Location", loginUri); <END> try { PrintWriter writer = response.getWriter(); writer.println("<html><head>"); writer.println("<meta http-equiv=\"refresh\" content=\"0; url=" + loginUri + "\" />"); writer.println("</head><body>Redirecting to login page</body></html>"); writer.flush(); } catch (IOException e) { logger.warn("Couldn't generate or send client response", e); } } else { context.execute(request, response); } }</code><technical_language>pass called url a parameter, form redirect user authenticated successfully</technical_language>

Target:
public void handleError(HttpServletRequest request, HttpServletResponse response, HandlerContext context) { Object error = request.getAttribute(HandlerContext.ERROR_ATTRIBUTE); if (response.getStatus() == 403 || response.getStatus() == 401) { return; } if (error instanceof AuthenticationException) { String redirectUri = loginUri + "?" + REDIRECT_PARAM_NAME + "=" + request.getRequestURI(); response.setHeader("Location", redirectUri); try { PrintWriter writer = response.getWriter(); writer.println("<html><head>"); writer.println("<meta http-equiv=\"refresh\" content=\"0; url=" + redirectUri + "\" />"); writer.println("</head><body>Redirecting to login page</body></html>"); writer.flush(); } catch (IOException e) { logger.warn("Couldn't generate or send client response", e); } } else { context.execute(request, response); } }
Source:
<code>public void verticalTest() { Rectangle bounds = new Rectangle(0, 0, 1000, 1000); <START> bounds.x = 0; bounds.y = 0; bounds.height = 1000; bounds.width <END> = 1000; int x0 = 100; int y0 = -10000; int x1 = 100; int y1 = 10000; Rectangle rect = LineClipper.clip(bounds, x0, y0, x1, y1); assertEquals(new Rectangle(100, 0, 0, 1000), rect); }</code><technical_language>tritto</technical_language>

Target:
public void verticalTest() { Rectangle bounds = new Rectangle(0, 0, 1000, 1000); int x0 = 100; int y0 = -10000; int x1 = 100; int y1 = 10000; Rectangle rect = LineClipper.clip(bounds, x0, y0, x1, y1); assertEquals(new Rectangle(100, 0, 0, 1000), rect); }
Source:
<code>private void equalizeIrrelevantData(AccountAttributes expected, AccountAttributes actual) { expected.createdAt = actual.createdAt; if (actual.studentProfile == null) { expected.studentProfile = null; } else { if (expected.studentProfile == null) { expected.studentProfile = new StudentProfileAttributes(); expected.studentProfile.googleId = actual.googleId; } expected.studentProfile.modifiedDate = actual.studentProfile.modifiedDate; <START> expected.sanitizeForSaving(); <END> } }</code><technical_language>full control of expected data, right? self-sanitize (I if term exists?) data in expected</technical_language>

Target:
private void equalizeIrrelevantData(AccountAttributes expected, AccountAttributes actual) { expected.createdAt = actual.createdAt; if (actual.studentProfile == null) { expected.studentProfile = null; } else { if (expected.studentProfile == null) { expected.studentProfile = new StudentProfileAttributes(); expected.studentProfile.googleId = actual.googleId; } expected.studentProfile.modifiedDate = actual.studentProfile.modifiedDate; } }
Source:
<code>public void add(FeatureEntry entry, SimpleFeatureCollection collection) throws IOException { FeatureEntry e = new FeatureEntry(); e.init(entry); if (e.getBounds() == null) { e.setBounds(collection.getBounds()); } create(e, collection.getSchema()); Transaction tx = new DefaultTransaction(); try { SimpleFeatureWriter w = writer(e, true, null, tx); SimpleFeatureIterator it = collection.features(); try { while (it.hasNext()) { SimpleFeature f = it.next(); SimpleFeature g = w.next(); for (PropertyDescriptor pd : collection.getSchema().getDescriptors()) { String name = pd.getName().getLocalPart(); if (pd.getType().getBinding() == Boolean.class) { int bool = (Boolean)(f.getAttribute(name)) ? 1 : 0; g.setAttribute(name, bool); } else { g.setAttribute(name, f.getAttribute(name)); } } w.write(); } } finally { w.close(); it.close(); } tx.commit(); } catch (Exception ex) { tx.rollback(); throw new IOException(ex); } finally { <START> tx.close(); <END> } entry.init(e); }</code><technical_language>questions this change: 1. if is null? need a null check here. 2. if get a list of Features a GeoPackage store? converted Booleans? 3. Is for GeoPackage files written GeoTools this fix boolean values, GeoTools read correctly? 4. this affect GeoServer GeoPackage output format; this bug show there</technical_language>

Target:
public void add(FeatureEntry entry, SimpleFeatureCollection collection) throws IOException { FeatureEntry e = new FeatureEntry(); e.init(entry); if (e.getBounds() == null) { e.setBounds(collection.getBounds()); } create(e, collection.getSchema()); Transaction tx = new DefaultTransaction(); try { SimpleFeatureWriter w = writer(e, true, null, tx); SimpleFeatureIterator it = collection.features(); try { while (it.hasNext()) { SimpleFeature f = it.next(); SimpleFeature g = w.next(); for (PropertyDescriptor pd : collection.getSchema().getDescriptors()) { String name = pd.getName().getLocalPart(); if (pd.getType().getBinding() == Boolean.class) { int bool = 0; if (f.getAttribute(name) != null) { bool = (Boolean)(f.getAttribute(name)) ? 1 : 0; } g.setAttribute(name, bool); } else { g.setAttribute(name, f.getAttribute(name)); } } w.write(); } } finally { w.close(); it.close(); } tx.commit(); } catch (Exception ex) { tx.rollback(); throw new IOException(ex); } finally { tx.close(); } entry.init(e); }
Source:
<code>public static boolean isConstraintInPayload(final Map constraints, final Map payload) { for (Object key : constraints.keySet()) { if (!payload.containsKey(key) || payload.get(key) == null) { log.info("Webhook trigger ignored. Item " + key.toString() + " was not found in payload"); return false; } <START> if (!constraints.get(key).equals("") && (!constraints.get(key).equals(payload.get(key)))){ <END> log.info("Webhook trigger ignored. Value of item " + key.toString() + " in payload does not match constraint"); return false; } } return true; }</code><technical_language>Do want this equals match</technical_language>

Target:
public static boolean isConstraintInPayload(final Map constraints, final Map payload) { for (Object key : constraints.keySet()) { if (!payload.containsKey(key) || payload.get(key) == null) { log.info("Webhook trigger ignored. Item " + key.toString() + " was not found in payload"); return false; } if (constraints.get(key) != null && !matches(constraints.get(key).toString(), payload.get(key).toString()) ) { log.info("Webhook trigger ignored. Value of item " + key.toString() + " (" + payload.get(key) + ") in payload does not match constraint " + constraints.get(key)); return false; } } return true; }
Source:
<code><START> public static Snapshot map(org.ovirt.engine.core.common.businessentities.Snapshot entity, Snapshot template) { <END> Snapshot model = template != null ? template : new Snapshot(); model.setId(entity.getId().toString()); if (entity.getDescription() != null) { model.setDescription(entity.getDescription()); } return model; }</code><technical_language>is this used</technical_language>

Target:
public static Snapshot map(org.ovirt.engine.core.common.businessentities.Snapshot entity, Snapshot template) { Snapshot model = template != null ? template : new Snapshot(); model.setId(entity.getId().toString()); if (entity.getDescription() != null) { model.setDescription(entity.getDescription()); } if (entity.getCreationDate() != null) { model.setDate(DateMapper.map(entity.getCreationDate(), null)); } return model; }
Source:
<code>default boolean allowRetry(Throwable exception) { if ( exception instanceof KeeperException) { final int rc = ((KeeperException) exception).code().intValue(); return (rc == KeeperException.Code.CONNECTIONLOSS.intValue()) || (rc == KeeperException.Code.OPERATIONTIMEOUT.intValue()) || (rc == KeeperException.Code.SESSIONMOVED.intValue()) || (rc == KeeperException.Code.SESSIONEXPIRED.intValue()) || <START> (rc == -13); END> } return false; }</code><technical_language>@Randgalt move this a constant longer supporting 3.4</technical_language>

Target:
default boolean allowRetry(Throwable exception) { if ( exception instanceof KeeperException) { final int rc = ((KeeperException) exception).code().intValue(); return (rc == KeeperException.Code.CONNECTIONLOSS.intValue()) || (rc == KeeperException.Code.OPERATIONTIMEOUT.intValue()) || (rc == KeeperException.Code.SESSIONMOVED.intValue()) || (rc == KeeperException.Code.SESSIONEXPIRED.intValue()); } return false; }
Source:
<code>private URI determineApplicationModelURI(IApplicationContext appContext) { Optional<String> appModelPath = getArgValue(IWorkbench.XMI_URI_ARG, appContext, false); <START> String appModelPathValue = appModelPath.filter(path -> path.isEmpty()).orElseGet(() -> { <END> Bundle brandingBundle = appContext.getBrandingBundle(); if (brandingBundle != null) { return brandingBundle.getSymbolicName() + "/" + E4Application.APPLICATION_MODEL_PATH_DEFAULT; } else { Logger logger = new WorkbenchLogger(PLUGIN_ID); logger.error(new Exception(), "applicationXMI parameter not set and no branding plugin defined. "); } return null; }); URI applicationModelURI = null; if (URIHelper.isPlatformURI(appModelPathValue)) { applicationModelURI = URI.createURI(appModelPathValue, true); } else { applicationModelURI = URI.createPlatformPluginURI(appModelPathValue, true); } return applicationModelURI; }</code><technical_language>forgot a !. (path -> !path.isEmpty()</technical_language>

Target:
private URI determineApplicationModelURI(IApplicationContext appContext) { Optional<String> appModelPath = getArgValue(IWorkbench.XMI_URI_ARG, appContext, false); String appModelPathValue = appModelPath.filter(path -> !path.isEmpty()).orElseGet(() -> { Bundle brandingBundle = appContext.getBrandingBundle(); if (brandingBundle != null) { return brandingBundle.getSymbolicName() + "/" + E4Application.APPLICATION_MODEL_PATH_DEFAULT; } else { Logger logger = new WorkbenchLogger(PLUGIN_ID); logger.error(new Exception(), "applicationXMI parameter not set and no branding plugin defined. "); } return null; }); URI applicationModelURI = null; if (URIHelper.isPlatformURI(appModelPathValue)) { applicationModelURI = URI.createURI(appModelPathValue, true); } else { applicationModelURI = URI.createPlatformPluginURI(appModelPathValue, true); } return applicationModelURI; }
Source:
<code>public void register(ExtensionBuilder builder) { builder.observer(ConfigurationRegistrar.class); builder.service(ConfigurationPlaceholderResolver.class, ConfigurationSysPropResolver.class); <START> builder.service(ConfigurationPlaceholderResolver.class, ClasspathConfigurationPlaceholderResolver.class); <END> }</code><technical_language>Please, unify naming format of classes: ConfigurationSysPropResolver ClasspathConfigurationPlaceholderResolver</technical_language>

Target:
public void register(ExtensionBuilder builder) { builder.observer(ConfigurationRegistrar.class); builder.service(ConfigurationPlaceholderResolver.class, SystemPropertiesConfigurationPlaceholderResolver.class); builder.service(ConfigurationPlaceholderResolver.class, ClasspathConfigurationPlaceholderResolver.class); }
Source:
<code>public ColumnMatchResult validate(Column column, ChecksumResult controlResult, ChecksumResult testResult) { checkColumnType(column); <START> ImmutableList<String> aliases = ImmutableList.<String>builder() <END> .add(getChecksumAlias(column)) .addAll(getFields(column).stream() .map(field -> getChecksumAlias(column, field)) .collect(Collectors.toList())) .build(); return new ColumnMatchResult( aliases.stream().allMatch(alias -> Objects.equals(controlResult.getChecksum(alias), testResult.getChecksum(alias))), prepareMatchMessage(aliases, controlResult, testResult)); }</code><technical_language>ImmutableList -> List</technical_language>

Target:
public ColumnMatchResult validate(Column column, ChecksumResult controlResult, ChecksumResult testResult) { checkColumnType(column); List<Field> fields = getFields(column); List<String> aliases = ImmutableList.<String>builder() .add(getChecksumAlias(column)) .addAll(IntStream.range(0, fields.size()) .mapToObj(index -> getChecksumAlias(column, fields.get(index), index)) .collect(Collectors.toList())) .build(); return new ColumnMatchResult( aliases.stream().allMatch(alias -> Objects.equals(controlResult.getChecksum(alias), testResult.getChecksum(alias))), prepareMatchMessage(aliases, controlResult, testResult)); }
Source:
<code>public ViewerCell getNeighbor(int directionMask, boolean sameLevel) { ViewerRow row; if ((directionMask & ABOVE) == ABOVE) { row = this.row.getNeighbor(ViewerRow.ABOVE, sameLevel); } else if ((directionMask & BELOW) == BELOW) { row = this.row.getNeighbor(ViewerRow.BELOW, sameLevel); } else { row = this.row; } if (row != null) { int columnIndex; columnIndex = getVisualIndex(); int modifier = 0; if ((directionMask & LEFT) == LEFT) { modifier = -1; } else if ((directionMask & RIGHT) == RIGHT) { modifier = 1; } columnIndex += modifier; if (columnIndex >= 0 && columnIndex < row.getColumnCount()) { ViewerCell cell = row.getCellAtVisualIndex(columnIndex); if (cell != null) { <START> while (columnIndex < row.getColumnCount() - 1 <END> && columnIndex > 0) { if (cell.isVisible()) { break; } columnIndex += modifier; cell = row.getCellAtVisualIndex(columnIndex); if (cell == null) { break; } } } return cell; } } return null; }</code><technical_language>I find to: * check in while condition * Remove if * remove null check line 300 (which is covered condition in while, conditions break</technical_language>

Target:
public ViewerCell getNeighbor(int directionMask, boolean sameLevel) { ViewerRow row; if ((directionMask & ABOVE) == ABOVE) { row = this.row.getNeighbor(ViewerRow.ABOVE, sameLevel); } else if ((directionMask & BELOW) == BELOW) { row = this.row.getNeighbor(ViewerRow.BELOW, sameLevel); } else { row = this.row; } if (row != null) { int columnIndex; columnIndex = getVisualIndex(); int modifier = 0; if ((directionMask & LEFT) == LEFT) { modifier = -1; } else if ((directionMask & RIGHT) == RIGHT) { modifier = 1; } columnIndex += modifier; if (columnIndex >= 0 && columnIndex < row.getColumnCount()) { ViewerCell cell = row.getCellAtVisualIndex(columnIndex); while (cell != null && columnIndex < row.getColumnCount() - 1 && columnIndex > 0) { if (cell.isVisible()) { break; } columnIndex += modifier; cell = row.getCellAtVisualIndex(columnIndex); } return cell; } } return null; }
Source:
<code>protected void updateScores() { if (!StorageService.instance.isGossipActive()) return; <START> if (!registered) <END> { if (MessagingService.instance() != null) { MessagingService.instance().register(this); registered = true; } } this.scores = calculateScores(samples); }</code><technical_language>do register in updateScores? A bit weird no? MessagingService store a list of WeakReferences need unregister? unregister</technical_language>

Target:
protected void updateScores() { if (!StorageService.instance.isGossipActive() || !MessagingService.instance().isListening()) { return; } this.scores = calculateScores(samples); }
Source:
<code><START> default Set<EntityHit> getIntersectingEntities(Entity looker, double distance, Predicate<EntityHit> filter) { <END> final Vector3d rotation = looker.getRotation(); final Vector3d direction = Quaterniond.fromAxesAnglesDeg(rotation.getX(), -rotation.getY(), rotation.getZ()).getDirection(); final Optional<EyeLocationProperty> data = looker.getProperty(EyeLocationProperty.class); final Vector3d start = data.map(EyeLocationProperty::getValue).orElse(looker.getLocation().getPosition()); return getIntersectingEntities(start, direction, distance, filter); }</code><technical_language>checkNotNull</technical_language>

Target:
default Set<EntityHit> getIntersectingEntities(Entity looker, double distance, Predicate<EntityHit> filter) { checkNotNull(looker, "looker"); final Vector3d rotation = looker.getRotation(); final Vector3d direction = Quaterniond.fromAxesAnglesDeg(rotation.getX(), -rotation.getY(), rotation.getZ()).getDirection(); final Optional<EyeLocationProperty> data = looker.getProperty(EyeLocationProperty.class); final Vector3d start = data.map(EyeLocationProperty::getValue).orElse(looker.getLocation().getPosition()); return getIntersectingEntities(start, direction, distance, filter); }
Source:
<code>public void strSubstitutorTest() { Map<String, String> data = new HashMap<String, String>(6); data.put("value", "1234"); data.put("field_format", "String"); StrSubstitutor sub = new StrSubstitutor(data); String message = "The value ${value} in row ${row_number} and column ${column_number} is not type ${field_type} and format ${field_format}"; String result = sub.replace(message); <START> System.out.println("XXXXXXXX:" + result); <END> Assert.assertTrue(result.contains("1234")); }</code><technical_language>I print this in a unit test</technical_language>

Target:
public void strSubstitutorTest() { Map<String, String> data = new HashMap<String, String>(6); data.put("value", "1234"); data.put("field_format", "String"); StrSubstitutor sub = new StrSubstitutor(data); String message = "The value ${value} in row ${row_number} and column ${column_number} is not type ${field_type} and format ${field_format}"; String result = sub.replace(message); Assert.assertTrue(result.contains("1234")); }
Source:
<code>private static Optional<Path> sourcesJarPath(Project project) { <START> return PantsBspData.importsFor(project).stream().findFirst() <END> .map(path -> Paths.get(path.getBspPath().toString(), ".bloop", "sources-jar")); }</code><technical_language>a method return bloop directory this bloopJarsPath resolve single child. better, resolve bsp path, for librariesFile</technical_language>

Target:
private static Optional<Path> sourcesJarPath(Project project) { return bspDir(project).map(path -> Paths.get(path, ".bloop", "sources-jar")); }