auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public FunctionKindRowColumnHeaderMetaData(final Supplier<FunctionDefinition> functionSupplier, <END> final CellEditorControlsView.Presenter cellEditorControls, final KindPopoverView.Presenter editor, final Optional<String> editorTitle, final FunctionGrid gridWidget) { super(cellEditorControls, editor, editorTitle); this.functionSupplier = functionSupplier; this.gridWidget = gridWidget; }</code><technical_language>class _package_ protected access constructor _package_ protection too</technical_language>

Target:
FunctionKindRowColumnHeaderMetaData(final Supplier<FunctionDefinition> functionSupplier, final CellEditorControlsView.Presenter cellEditorControls, final KindPopoverView.Presenter editor, final Optional<String> editorTitle, final FunctionGrid gridWidget) { super(cellEditorControls, editor, editorTitle); this.functionSupplier = functionSupplier; this.gridWidget = gridWidget; }
Source:
<code>public <C> void addFilteredListener(Object listener, CacheEventFilter<? super K, ? super V> filter, CacheEventConverter<? super K, ? super V, C> converter, Set<Class<? extends Annotation>> filterAnnotations) { ListenerHolder listenerHolder = new ListenerHolder(listener, encoder, wrapper); Cache unwrapped = super.unwrapCache(this.cache); <START> if(unwrapped instanceof CacheImpl) { <END> ((CacheImpl)unwrapped).addFilteredListener(listenerHolder, filter, converter, filterAnnotations); } else { super.addFilteredListener(listener, filter, converter, filterAnnotations); } }</code><technical_language>Nitpick: space</technical_language>

Target:
public <C> void addFilteredListener(Object listener, CacheEventFilter<? super K, ? super V> filter, CacheEventConverter<? super K, ? super V, C> converter, Set<Class<? extends Annotation>> filterAnnotations) { ListenerHolder listenerHolder = new ListenerHolder(listener, keyEncoderClass, valueEncoderClass, keyWrapperClass, valueWrapperClass); Cache unwrapped = super.unwrapCache(this.cache); if (unwrapped instanceof CacheImpl) { ((CacheImpl) unwrapped).addFilteredListener(listenerHolder, filter, converter, filterAnnotations); } else { super.addFilteredListener(listener, filter, converter, filterAnnotations); } }
Source:
<code>public void clickOnFilterBoxTitle() { waitForElementVisibleByElement(mapFrame); scrollToElement(mapFrame); driver.switchTo().frame(mapFrame); waitForElementByElement(filterBoxTitle); Actions actions = new Actions(driver); actions.moveToElement(filterBoxTitle).click().perform(); <START> driver.switchTo().defaultContent(); <END> }</code><technical_language>Add Pagelogging</technical_language>

Target:
public void clickOnFilterBoxTitle() { waitForElementVisibleByElement(mapFrame); scrollToElement(mapFrame); driver.switchTo().frame(mapFrame); waitForElementByElement(filterBoxTitle); Actions actions = new Actions(driver); actions.moveToElement(filterBoxTitle).click().perform(); driver.switchTo().defaultContent(); PageObjectLogging.log("clickOnFilterBoxTitle", "Filter box title was clicked", true); }
Source:
<code>Mono<Response<DocumentResultCollection<RecognizeLinkedEntitiesResult>>> recognizeBatchLinkedEntitiesWithResponse( List<TextDocumentInput> textInputs, TextAnalyticsRequestOptions options, Context context) { final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() .setDocuments(convertToMultiLanguageInput(textInputs)); return service.entitiesLinkingWithRestResponseAsync( batchInput, options == null ? null : options.getModelVersion(), options == null ? null : options.showStatistics(), context) <START> .doOnSubscribe(ignoredValue -> logger.info("A batch of linked entities input - {}", ignoredValue)) <END> .doOnSuccess(response -> logger.info("A batch of linked entities output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to linked entities - {}", error)) .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); }</code><technical_language>This is log reactive stream Subscription</technical_language>

Target:
Mono<Response<DocumentResultCollection<RecognizeLinkedEntitiesResult>>> recognizeBatchLinkedEntitiesWithResponse( List<TextDocumentInput> textInputs, TextAnalyticsRequestOptions options, Context context) { Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() .setDocuments(convertToMultiLanguageInput(textInputs)); return service.entitiesLinkingWithRestResponseAsync( batchInput, options == null ? null : options.getModelVersion(), options == null ? null : options.showStatistics(), context) .doOnSubscribe(ignoredValue -> logger.info("A batch of linked entities input - {}", textInputs.toString())) .doOnSuccess(response -> logger.info("A batch of linked entities output - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to linked entities - {}", error)) .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); }
Source:
<code>private ModuleInfoWriter nameAccessAndVersion(Entry<String, Attrs> instruction, Parameters requireCapability, Analyzer analyzer) { Attrs attrs = instruction.getValue(); String name = instruction.getKey(); String access = attrs.computeIfAbsent("access", k -> String.valueOf(access(requireCapability))); String version = attrs.computeIfAbsent("version", k -> analyzer.getVersion()); return new ModuleInfoWriter(Clazz.JAVA.OpenJDK9.getMajor(), name, version, <START> Integer.valueOf(access) == ModuleAttribute.ACC_OPEN); <END> }</code><technical_language>Integer.parseInt(access) == ModuleAttribute.ACC_OPEN create Integer == int boxed Integer. Integers necessary</technical_language>

Target:
private ModuleInfoWriter nameAccessAndVersion(Entry<String, Attrs> instruction, Parameters requireCapability, Analyzer analyzer) { Attrs attrs = instruction.getValue(); String name = instruction.getKey(); String access = attrs.computeIfAbsent("access", k -> String.valueOf(access(requireCapability))); String version = attrs.computeIfAbsent("version", k -> analyzer.getVersion()); return new ModuleInfoWriter(Clazz.JAVA.OpenJDK9.getMajor(), name, version, Integer.parseInt(access) == ModuleAttribute.ACC_OPEN); }
Source:
<code>@Test public void testGeoServerEnvParametrization() throws Exception { GeoServerSecurityManager secMgr = getSecurityManager(); SecurityManagerConfig config = secMgr.loadSecurityConfig(); String oldRoleServiceName = config.getRoleServiceName(); try { if (GeoServerEnvironment.ALLOW_ENV_PARAMETRIZATION) { <START> System.setProperty("TEST_SYS_PROPERTY", oldRoleServiceName); <END> config.setRoleServiceName("${TEST_SYS_PROPERTY}"); secMgr.saveSecurityConfig(config); SecurityManagerConfig config1 = secMgr.loadSecurityConfig(); assertEquals(config1.getRoleServiceName(), oldRoleServiceName); } } finally { config.setRoleServiceName(oldRoleServiceName); secMgr.saveSecurityConfig(config); } }</code><technical_language>suggest clear property in finally, create accidental coupling other tests</technical_language>

Target:
@Test public void testGeoServerEnvParametrization() throws Exception { GeoServerSecurityManager secMgr = getSecurityManager(); SecurityManagerConfig config = secMgr.loadSecurityConfig(); String oldRoleServiceName = config.getRoleServiceName(); try { if (GeoServerEnvironment.ALLOW_ENV_PARAMETRIZATION) { System.setProperty("TEST_SYS_PROPERTY", oldRoleServiceName); config.setRoleServiceName("${TEST_SYS_PROPERTY}"); secMgr.saveSecurityConfig(config); SecurityManagerConfig config1 = secMgr.loadSecurityConfig(); assertEquals(config1.getRoleServiceName(), oldRoleServiceName); } } finally { config.setRoleServiceName(oldRoleServiceName); secMgr.saveSecurityConfig(config); System.setProperty("TEST_SYS_PROPERTY", ""); } }
Source:
<code>public CurrencyAmount presentValue( ResolvedCdsIndex cdsIndex, CreditRatesProvider ratesProvider, LocalDate referenceDate, PriceType priceType, ReferenceData refData) { if (isExpired(cdsIndex, ratesProvider)) { return CurrencyAmount.of(cdsIndex.getCurrency(), 0d); } ResolvedCds cds = cdsIndex.toSingleNameCds(); LocalDate stepinDate = cds.getStepinDateOffset().adjust(ratesProvider.getValuationDate(), refData); LocalDate effectiveStartDate = cds.calculateEffectiveStartDate(stepinDate); double recoveryRate = underlyingPricer.recoveryRate(cds, ratesProvider); Triple<CreditDiscountFactors, LegalEntitySurvivalProbabilities, Double> rates = reduceDiscountFactors(cds, ratesProvider); double protectionLeg = (1d - recoveryRate) * underlyingPricer.protectionFull(cds, rates.getFirst(), rates.getSecond(), referenceDate, effectiveStartDate); double rpv01 = underlyingPricer.riskyAnnuity( cds, rates.getFirst(), rates.getSecond(), referenceDate, stepinDate, effectiveStartDate, priceType); <START> return CurrencyAmount.of(cds.getCurrency(), <END> cds.getBuySell().normalize(cds.getNotional()) * rates.getThird() * (protectionLeg - rpv01 * cds.getFixedRate())); }</code><technical_language>This line do breaking a bit</technical_language>

Target:
public CurrencyAmount presentValue( ResolvedCdsIndex cdsIndex, CreditRatesProvider ratesProvider, LocalDate referenceDate, PriceType priceType, ReferenceData refData) { if (isExpired(cdsIndex, ratesProvider)) { return CurrencyAmount.of(cdsIndex.getCurrency(), 0d); } ResolvedCds cds = cdsIndex.toSingleNameCds(); LocalDate stepinDate = cds.getStepinDateOffset().adjust(ratesProvider.getValuationDate(), refData); LocalDate effectiveStartDate = cds.calculateEffectiveStartDate(stepinDate); double recoveryRate = underlyingPricer.recoveryRate(cds, ratesProvider); Triple<CreditDiscountFactors, LegalEntitySurvivalProbabilities, Double> rates = reduceDiscountFactors(cds, ratesProvider); double protectionLeg = (1d - recoveryRate) * underlyingPricer.protectionFull(cds, rates.getFirst(), rates.getSecond(), referenceDate, effectiveStartDate); double rpv01 = underlyingPricer.riskyAnnuity( cds, rates.getFirst(), rates.getSecond(), referenceDate, stepinDate, effectiveStartDate, priceType); double amount = cds.getBuySell().normalize(cds.getNotional()) * rates.getThird() * (protectionLeg - rpv01 * cds.getFixedRate()); return CurrencyAmount.of(cds.getCurrency(), amount); }
Source:
<code>public void activateHoverHelp(final Control control) { control.addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseHover(MouseEvent event) { if ((event.stateMask & SWT.BUTTON_MASK) != 0) { return; } Point pt = new Point(event.x, event.y); Control timeGraphControl = (Control) event.widget; Point ptInDisplay = control.toDisplay(event.x, event.y); fInitialDeadzone = new Rectangle(ptInDisplay.x - 5, ptInDisplay.y - 5, 10, 10); createTooltipShell(timeGraphControl.getShell()); for (Control child : fTipComposite.getChildren()) { child.dispose(); } fill(control, event, pt); if (fTipComposite.getChildren().length == 0) { return; } fTipShell.pack(); Point tipPosition = control.toDisplay(pt); setHoverLocation(fTipShell, tipPosition); fTipShell.setVisible(true); <START> Display.getDefault().addFilter(SWT.MouseExit, fListener); <END> } }); }</code><technical_language>dead zone is respected, dispose MouseMove event</technical_language>

Target:
public void activateHoverHelp(final Control control) { control.addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseHover(MouseEvent event) { if ((event.stateMask & SWT.BUTTON_MASK) != 0) { return; } Point pt = new Point(event.x, event.y); Control timeGraphControl = (Control) event.widget; Point ptInDisplay = control.toDisplay(event.x, event.y); fInitialDeadzone = new Rectangle(ptInDisplay.x - MOUSE_DEADZONE, ptInDisplay.y - MOUSE_DEADZONE, 2 * MOUSE_DEADZONE, 2 * MOUSE_DEADZONE); createTooltipShell(timeGraphControl.getShell()); for (Control child : fTipComposite.getChildren()) { child.dispose(); } fill(control, event, pt); if (fTipComposite.getChildren().length == 0) { return; } fTipShell.pack(); Point tipPosition = control.toDisplay(pt); setHoverLocation(fTipShell, tipPosition); fTipShell.setVisible(true); Display.getDefault().addFilter(SWT.MouseMove, fListener); } }); }
Source:
<code>synchronized void destroy() { <START> if (shutdownHook != null) { <END> Runtime.getRuntime().removeShutdownHook(shutdownHook); } if (workerMultiplexer.isAlive()) { workerMultiplexer.interrupt(); } workerMultiplexer.destroyMultiplexer(); }</code><technical_language>This false. smells fishy</technical_language>

Target:
synchronized void destroy() throws IOException { super.destroy(); try { WorkerMultiplexerManager.removeInstance(workerKey.hashCode()); } catch (InterruptedException e) { logger.warning("InterruptedException was caught while destroying multiplexer. " + "It could because the multiplexer was interrupted."); } catch (UserExecException e) { logger.warning(e.toString()); } }
Source:
<code><START> static boolean targetEqualsSource(Object target, Object srcObject) { <END> if (target == null) { return false; } if (target instanceof Iterable) { for (Object relatedObject : (Iterable<?>) target) { if (relatedObject.equals(srcObject)) { return true; } } } if (target.getClass().isArray()) { for (Object relatedObject : (Object[]) target) { if (relatedObject.equals(srcObject)) { return true; } } } return target.equals(srcObject); }</code><technical_language>this private extraction I do other change referring it</technical_language>

Target:
private static boolean targetEqualsSource(Object target, Object srcObject) { if (target == null) { return false; } if (target instanceof Iterable) { for (Object relatedObject : (Iterable<?>) target) { if (relatedObject.equals(srcObject)) { return true; } } } if (target.getClass().isArray()) { for (Object relatedObject : (Object[]) target) { if (relatedObject.equals(srcObject)) { return true; } } } return target.equals(srcObject); }
Source:
<code>public void beginTask(String name, int totalWork) { final long timestamp = System.currentTimeMillis(); fStartTime = timestamp; final boolean animated = (totalWork == UNKNOWN || totalWork == 0); Runnable timer = () -> StatusLine.this.startTask(timestamp, animated); <START> if (fProgressBar == null) { <END> return; } fProgressBar.getDisplay().timerExec(DELAY_PROGRESS, timer); inUIThread(() -> { if (!animated) { fProgressBar.beginTask(totalWork); } if (name == null) { fTaskName = Util.ZERO_LENGTH_STRING; } else { fTaskName = name; } setMessage(fTaskName); }); }</code><technical_language>code below, I this if moved of method, right fStartTime=timestamp</technical_language>

Target:
public void beginTask(String name, int totalWork) { final long timestamp = System.currentTimeMillis(); fStartTime = timestamp; if (fProgressBar == null) { return; } final boolean animated = (totalWork == UNKNOWN || totalWork == 0); Runnable timer = () -> StatusLine.this.startTask(timestamp, animated); inUIThread(() -> { fProgressBar.getDisplay().timerExec(DELAY_PROGRESS, timer); if (!animated) { fProgressBar.beginTask(totalWork); } if (name == null) { fTaskName = Util.ZERO_LENGTH_STRING; } else { fTaskName = name; } setMessage(fTaskName); }); }
Source:
<code>public void complete() { <START> cleanup(getId()); <END> finalizeStats(); setFinishTime(); eventHandler.handle(new SubQueryCompletedEvent(getId(), SubQueryState.SUCCEEDED)); }</code><technical_language>get block id calling block.getId(). So, cleanup() need execution block id</technical_language>

Target:
public void complete() { cleanup(); finalizeStats(); setFinishTime(); eventHandler.handle(new SubQueryCompletedEvent(getId(), SubQueryState.SUCCEEDED)); }
Source:
<code>public void testIndirectIAMAndNotificationOutcomeSuccess() throws Exception { service.setSuccess(true); sessionManager.initSessionFromCache(); sessionManager.onInAppMessageReceived(IAM_ID); sessionManager.onNotificationReceived(NOTIFICATION_ID); sessionManager.restartSessionIfNeeded(OneSignal.AppEntryAction.APP_OPEN); controller.sendOutcomeEvent(OUTCOME_NAME); threadAndTaskWait(); new Thread(new Runnable() { @Override public void run() { <START> handler.setOutcomes(repository.getSavedOutcomeEvents()); <END> } }, "OS_GET_SAVED_OUTCOMES_SUCCESS").start(); threadAndTaskWait(); assertEquals(0, outcomeEvents.size()); assertEquals("{\"id\":\"testing\",\"sources\":{\"indirect\":{\"notification_ids\":[\"notification_id\"],\"in_app_message_ids\":[\"iam_id\"]}},\"device_type\":1}", service.getLastJsonObjectSent()); }</code><technical_language>run this thread</technical_language>

Target:
public void testIndirectIAMAndNotificationOutcomeSuccess() throws Exception { service.setSuccess(true); sessionManager.initSessionFromCache(); sessionManager.onInAppMessageReceived(IAM_ID); sessionManager.onNotificationReceived(NOTIFICATION_ID); sessionManager.restartSessionIfNeeded(OneSignal.AppEntryAction.APP_OPEN); controller.sendOutcomeEvent(OUTCOME_NAME); threadAndTaskWait(); handler.setOutcomes(repository.getSavedOutcomeEvents()); threadAndTaskWait(); assertEquals(0, outcomeEvents.size()); assertEquals("{\"id\":\"testing\",\"sources\":{\"indirect\":{\"notification_ids\":[\"notification_id\"],\"in_app_message_ids\":[\"iam_id\"]}},\"device_type\":1}", service.getLastJsonObjectSent()); }
Source:
<code><START> public static <T extends IndexedRecord> T decodeAvroGenericRecord(Schema schema, byte[] bytes, T reuse) <END> throws IOException { BinaryDecoder binDecoder = DecoderFactory.defaultFactory().createBinaryDecoder(bytes, null); GenericDatumReader<T> reader = new GenericDatumReader<>(schema); return reader.read(reuse, binDecoder); }</code><technical_language>is this method used</technical_language>

Target:
public static <T> T decodeAvroGenericRecord(Schema schema, byte[] bytes, T reuse) throws IOException { BinaryDecoder binDecoder = DecoderFactory.defaultFactory().createBinaryDecoder(bytes, null); GenericDatumReader<T> reader = new GenericDatumReader<>(schema); return reader.read(reuse, binDecoder); }
Source:
<code>public static ClassFilter of(Predicate<String> namePredicate, Predicate<Class<?>> classPredicate) { Preconditions.notNull(namePredicate, "name predicate must not be null"); <START> Preconditions.notNull(classPredicate, "class predicate must not be null"); <END> return new ClassFilter(namePredicate, classPredicate); }</code><technical_language>I precondition checks moved constructor</technical_language>

Target:
public static ClassFilter of(Predicate<String> namePredicate, Predicate<Class<?>> classPredicate) { return new ClassFilter(namePredicate, classPredicate); }
Source:
<code>private void scheduleExplictLacFlush() { int explicitLacIntervalInSec = lh.bk.getExplicitLacInterval(); final SafeRunnable updateLacTask = new SafeRunnable() { @Override public void safeRun() { if (getExplicitLac() < getPiggyBackedLac()) { LOG.debug("ledgerid: {}", lh.getId()); LOG.debug("explicitLac:{} piggybackLac:{}", getExplicitLac(), getPiggyBackedLac()); setExplicitLac(getPiggyBackedLac()); return; } if (lh.getLastAddConfirmed() > getExplicitLac()) { LOG.debug("ledgerid: {}", lh.getId()); asyncExplicitLacFlush(lh.getLastAddConfirmed()); setExplicitLac(lh.getLastAddConfirmed()); LOG.debug("After sending explict LAC lac: explicitLac:{}", lh.getLastAddConfirmed(), getExplicitLac()); } } @Override public String toString() { return String.format("UpdateLacTask ledgerId - (%d)", lh.getId()); } }; try { scheduledFuture = lh.bk.mainWorkerPool.scheduleAtFixedRateOrdered(lh.getId(), updateLacTask, <START> explicitLacIntervalInSec, explicitLacIntervalInSec, TimeUnit.MILLISECONDS); <END> } catch (RejectedExecutionException re) { LOG.error("Scheduling of ExplictLastAddConfirmedFlush for ledger: has failed because of {}", lh.getId(), re); } }</code><technical_language>variable names in Seconds timeunit interpret milliseconds. Please rename variables</technical_language>

Target:
private void scheduleExplictLacFlush() { int explicitLacIntervalInMs = lh.bk.getExplicitLacInterval(); final SafeRunnable updateLacTask = new SafeRunnable() { @Override public void safeRun() { if (getExplicitLac() < getPiggyBackedLac()) { LOG.debug("ledgerid: {}", lh.getId()); LOG.debug("explicitLac:{} piggybackLac:{}", getExplicitLac(), getPiggyBackedLac()); setExplicitLac(getPiggyBackedLac()); return; } if (lh.getLastAddConfirmed() > getExplicitLac()) { LOG.debug("ledgerid: {}", lh.getId()); asyncExplicitLacFlush(lh.getLastAddConfirmed()); setExplicitLac(lh.getLastAddConfirmed()); LOG.debug("After sending explict LAC lac: explicitLac:{}", lh.getLastAddConfirmed(), getExplicitLac()); } } @Override public String toString() { return String.format("UpdateLacTask ledgerId - (%d)", lh.getId()); } }; try { scheduledFuture = lh.bk.mainWorkerPool.scheduleAtFixedRateOrdered(lh.getId(), updateLacTask, explicitLacIntervalInMs, explicitLacIntervalInMs, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException re) { LOG.error("Scheduling of ExplictLastAddConfirmedFlush for ledger: has failed because of {}", lh.getId(), re); } }
Source:
<code>public AboutInfo[] getFeatureInfos() { List infos = new ArrayList(); IBundleGroupProvider[] providers = Platform.getBundleGroupProviders(); if (providers != null) { for (IBundleGroupProvider provider : providers) { <START> IBundleGroup[] bundleGroups = provider.getBundleGroups(); <END> for (IBundleGroup bundleGroup : bundleGroups) { infos.add(new AboutInfo(bundleGroup)); } } } return (AboutInfo[]) infos.toArray(new AboutInfo[infos.size()]); }</code><technical_language>inline</technical_language>

Target:
public AboutInfo[] getFeatureInfos() { List infos = new ArrayList(); IBundleGroupProvider[] providers = Platform.getBundleGroupProviders(); if (providers != null) { for (IBundleGroupProvider provider : providers) { for (IBundleGroup bundleGroup : provider.getBundleGroups()) { infos.add(new AboutInfo(bundleGroup)); } } } return (AboutInfo[]) infos.toArray(new AboutInfo[infos.size()]); }
Source:
<code>public void add(Parse daughter, HeadRules rules) { if (daughter.prevPunctSet != null) { parts.addAll(daughter.prevPunctSet); } parts.add(daughter); this.span = new Span(span.getStart(),daughter.getSpan().getEnd()); this.head = rules.getHead(getChildren(),type); if (head == null) { System.err.println(parts); <START> throw new IllegalArgumentException("Rule returned null head!"); <END> } this.headIndex = head.headIndex; }</code><technical_language>This happen in cases, need understand impact</technical_language>

Target:
public void add(Parse daughter, HeadRules rules) { if (daughter.prevPunctSet != null) { parts.addAll(daughter.prevPunctSet); } parts.add(daughter); this.span = new Span(span.getStart(),daughter.getSpan().getEnd()); this.head = rules.getHead(getChildren(),type); this.headIndex = head.headIndex; }
Source:
<code>private static AECableType from( AECableVariant variant, AECableSize size ) { switch( variant ) { case GLASS: switch( size ) { case THIN: return GLASS; default: break; } break; <START> case COVERED: <END> switch( size ) { case NORMAL: return COVERED; case DENSE: return DENSE_COVERED; default: break; } break; case SMART: switch( size ) { case NORMAL: return SMART; case DENSE: return DENSE_SMART; default: break; } break; default: break; } return NONE; }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') Reduce this switch case number of lines 10 5, for example extracting code methods. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private static AECableType from( AECableVariant variant, AECableSize size ) { switch( variant ) { case GLASS: switch( size ) { case NORMAL: return GLASS; default: break; } break; case COVERED: switch( size ) { case NORMAL: return COVERED; case DENSE: return DENSE_COVERED; default: break; } break; case SMART: switch( size ) { case NORMAL: return SMART; case DENSE: return DENSE_SMART; default: break; } break; default: break; } return NONE; }
Source:
<code>public static float STATS_NULL_FRACTION(ColumnStatisticsImpl itemStatistics){ if(itemStatistics==null) return 0; if (itemStatistics.notNullCount() == 0) return 0; <START> return ((float) itemStatistics.nullCount()/ (float) itemStatistics.notNullCount()); <END> }</code><technical_language>nullCount / (nullCount + notNullCount) equivalent</technical_language>

Target:
public static float STATS_NULL_FRACTION(ColumnStatisticsImpl itemStatistics){ if(itemStatistics==null) return 0; if (itemStatistics.notNullCount() + itemStatistics.nullCount() == 0) return 0; return ((float) itemStatistics.nullCount()/ (float) (itemStatistics.notNullCount()+itemStatistics.nullCount())); }
Source:
<code>private synchronized void resetLogUnit(CorfuPayloadMsg<Long> msg, ChannelHandlerContext ctx, IServerRouter r) { if (msg.getPayload() <= serverContext.getLogUnitEpochWaterMark() || msg.getPayload() != serverContext.getServerEpoch()) { log.info("LogUnit Server Reset request received but reset already done."); r.sendResponse(ctx, msg, CorfuMsgType.ACK.msg()); return; } serverContext.setLogUnitEpochWaterMark(msg.getPayload()); <START> Lock lock = resetLock.writeLock(); lock.lock(); <END> try { CompletableFuture<Void> cf = batchWriter .addTask(RESET, msg) .thenRun(() -> { dataCache.invalidateAll(); log.info("LogUnit Server Reset."); r.sendResponse(ctx, msg, CorfuMsgType.ACK.msg()); }) .exceptionally(ex -> { handleException(ex, ctx, msg, r); return null; }); cf.join(); } finally { lock.unlock(); } }</code><technical_language>Locking is bad, reset op is added BatchProcessor, run previous write operations in queue finished, reads blocked. This is a performance issue. if put lock streamLogFiles need do cf.join() below</technical_language>

Target:
private synchronized void resetLogUnit(CorfuPayloadMsg<Long> msg, ChannelHandlerContext ctx, IServerRouter r) { if (msg.getPayload() <= serverContext.getLogUnitEpochWaterMark() || msg.getPayload() != serverContext.getServerEpoch()) { log.info("LogUnit Server Reset request received but reset already done."); r.sendResponse(ctx, msg, CorfuMsgType.ACK.msg()); return; } serverContext.setLogUnitEpochWaterMark(msg.getPayload()); CompletableFuture<Void> cf = batchWriter .addTask(RESET, msg) .thenRun(() -> { dataCache.invalidateAll(); log.info("LogUnit Server Reset."); r.sendResponse(ctx, msg, CorfuMsgType.ACK.msg()); }) .exceptionally(ex -> { handleException(ex, ctx, msg, r); return null; }); }
Source:
<code>public QuorumServer(long id, String hostname, Integer port, Integer electionPort, LearnerType type) { this.id = id; this.hostname=hostname; if (port!=null){ this.port=port; } if (electionPort!=null){ this.electionPort=electionPort; } if (type!=null){ this.type = type; } String checkIPReachableValue = System.getProperty("zookeeper.checkIPTimeout"); <START> if(checkIPReachableValue != null){ <END> this.checkIPReachableTO = Integer.parseInt(checkIPReachableValue); } this.recreateSocketAddresses(); }</code><technical_language>nit: space if (</technical_language>

Target:
public QuorumServer(long id, String hostname, Integer port, Integer electionPort, LearnerType type) { this.id = id; this.hostname=hostname; if (port!=null){ this.port=port; } if (electionPort!=null){ this.electionPort=electionPort; } if (type!=null){ this.type = type; } this.recreateSocketAddresses(); }
Source:
<code>public boolean explodeWithEvent() { if (power < 0.1f) { return true; } Set<BlockVector> droppedBlocks = calculateBlocks(); List<Block> blocks = toBlockList(droppedBlocks); if (source != null) { EntityExplodeEvent event = EventFactory.getInstance().callEvent( new EntityExplodeEvent(source, location, blocks, yield)); if (event.isCancelled()) { return false; } yield = event.getYield(); } else { BlockExplodeEvent event = EventFactory.getInstance().callEvent( new BlockExplodeEvent(location.getBlock(), blocks, yield)); if (event.isCancelled()) { return false; } yield = event.getYield(); } playOutSoundAndParticles(); for (Block block : blocks) { handleBlockExplosion((GlowBlock) block); } if (incendiary) { for (Block block : blocks) { setBlockOnFire((GlowBlock) block); } } damageEntities(); Collection<GlowPlayer> affectedPlayers = collectPlayersInRadius(EXPLOSION_VISIBILITY_RADIUS * (int)this.power); for (GlowPlayer player : affectedPlayers) { if (player.getGameMode() != GameMode.CREATIVE <START> & player.getGameMode() != GameMode.SPECTATOR) { <END> playOutExplosion(player, blocks); } } return true; }</code><technical_language>a switch statement here. If getGameMode() nontrivial, want call once, a switch is more elegant extracting a variable</technical_language>

Target:
public boolean explodeWithEvent() { if (power < 0.1f) { return true; } Set<BlockVector> droppedBlocks = calculateBlocks(); List<Block> blocks = toBlockList(droppedBlocks); if (source != null) { EntityExplodeEvent event = EventFactory.getInstance().callEvent( new EntityExplodeEvent(source, location, blocks, yield)); if (event.isCancelled()) { return false; } yield = event.getYield(); } else { BlockExplodeEvent event = EventFactory.getInstance().callEvent( new BlockExplodeEvent(location.getBlock(), blocks, yield)); if (event.isCancelled()) { return false; } yield = event.getYield(); } playOutSoundAndParticles(); for (Block block : blocks) { handleBlockExplosion((GlowBlock) block); } if (incendiary) { for (Block block : blocks) { setBlockOnFire((GlowBlock) block); } } damageEntities(); Collection<GlowPlayer> affectedPlayers = collectPlayersInRadius(EXPLOSION_VISIBILITY_RADIUS * (int)this.power); for (GlowPlayer player : affectedPlayers) { switch(player.getGameMode()){ case GameMode.CREATIVE: case GameMode.SPECTATOR: break; default: playOutExplosion(player, blocks); } } return true; }
Source:
<code>public void writeModelsToDisk(String dir, String modelName){ <START> chunker.write(dir + modelName + ".lc", dir + modelName + ".lex"); <END> System.out.println("Done training, models are in " + dir+modelName+".lc (.lex)"); }</code><technical_language>Minor: safe is [already a folder. ](<LINK_0></technical_language>

Target:
public void writeModelsToDisk(String dir, String modelName){ IOUtils.mkdir(dir); chunker.write(dir + File.separator + modelName + ".lc", dir + File.separator + modelName + ".lex"); System.out.println("Done training, models are in " + dir+File.separator+modelName+".lc (.lex)"); }
Source:
<code>public void start(final Environment env) throws IOException { try { parseCommandLine(); if (Strings.isNullOrEmpty(commandName)) { StringWriter msg = new StringWriter(); msg.write(usage()); throw new UnloggedFailure(1, msg.toString()); } final CommandProvider p = commands.get(commandName); if (p == null) { String msg = (getName().isEmpty() ? "Gerrit Code Review" : getName()) + ": " + commandName + ": not found"; throw new UnloggedFailure(1, msg); } final Command cmd = p.getProvider().get(); <START> checkRequiresCapability(getName(), cmd); <END> if (cmd instanceof BaseCommand) { final BaseCommand bc = (BaseCommand) cmd; if (getName().isEmpty()) bc.setName(commandName); else bc.setName(getName() + " " + commandName); bc.setArguments(args.toArray(new String[args.size()])); } else if (!args.isEmpty()) { throw new UnloggedFailure(1, commandName + " does not take arguments"); } provideStateTo(cmd); atomicCmd.set(cmd); cmd.start(env); } catch (UnloggedFailure e) { String msg = e.getMessage(); if (!msg.endsWith("\n")) { msg += "\n"; } err.write(msg.getBytes(ENC)); err.flush(); onExit(e.exitCode); } }</code><technical_language>I getName() in this context. command aliasing return getName alias plugin. capabilities check incorrectly</technical_language>

Target:
public void start(final Environment env) throws IOException { try { parseCommandLine(); if (Strings.isNullOrEmpty(commandName)) { StringWriter msg = new StringWriter(); msg.write(usage()); throw new UnloggedFailure(1, msg.toString()); } final CommandProvider p = commands.get(commandName); if (p == null) { String msg = (getName().isEmpty() ? "Gerrit Code Review" : getName()) + ": " + commandName + ": not found"; throw new UnloggedFailure(1, msg); } final Command cmd = p.getProvider().get(); checkRequiresCapability(cmd); if (cmd instanceof BaseCommand) { final BaseCommand bc = (BaseCommand) cmd; if (getName().isEmpty()) bc.setName(commandName); else bc.setName(getName() + " " + commandName); bc.setArguments(args.toArray(new String[args.size()])); } else if (!args.isEmpty()) { throw new UnloggedFailure(1, commandName + " does not take arguments"); } provideStateTo(cmd); atomicCmd.set(cmd); cmd.start(env); } catch (UnloggedFailure e) { String msg = e.getMessage(); if (!msg.endsWith("\n")) { msg += "\n"; } err.write(msg.getBytes(ENC)); err.flush(); onExit(e.exitCode); } }
Source:
<code>public void execute() { for (NetworkHealthBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { String hostname = provider.getHostname(itemName); int port = provider.getPort(itemName); if (provider.getTimeout(itemName) > 0) { timeout = provider.getTimeout(itemName); } boolean success = false; try { success = Ping.checkVitality(hostname, port, timeout); if(success) logger.debug("established connection [host '{}' port '{}' timeout '{}']", new Object[] { hostname, port, timeout }); else <START> logger.debug("couldn't established connection [host '{}' port '{}' timeout '{}']", <END> new Object[] { hostname, port, timeout }); } catch (SocketTimeoutException se) { logger.debug("timed out while connecting [host '{}' port '{}' timeout '{}']", new Object[] { hostname, port, timeout }); } catch (IOException ioe) { logger.debug("couldn't establish network connection [host '{}' port '{}' timeout '{}']", new Object[] { hostname, port, timeout }); } if (eventPublisher != null) { if (shouldPostUpdate(hostname, port, success)) { eventPublisher.postUpdate(itemName, success ? OnOffType.ON : OnOffType.OFF); } } } } }</code><technical_language>Small grammar fix here: "couldn't established" "couldn't establish"</technical_language>

Target:
public void execute() { for (NetworkHealthBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { String hostname = provider.getHostname(itemName); int port = provider.getPort(itemName); if (provider.getTimeout(itemName) > 0) { timeout = provider.getTimeout(itemName); } boolean success = false; try { success = Ping.checkVitality(hostname, port, timeout); if(success) { logger.debug("established connection [host '{}' port '{}' timeout '{}']", new Object[] { hostname, port, timeout }); } else { logger.debug("couldn't establish connection [host '{}' port '{}' timeout '{}']", new Object[] { hostname, port, timeout }); } } catch (SocketTimeoutException se) { logger.debug("timed out while connecting [host '{}' port '{}' timeout '{}']", new Object[] { hostname, port, timeout }); } catch (IOException ioe) { logger.debug("couldn't establish network connection [host '{}' port '{}' timeout '{}']", new Object[] { hostname, port, timeout }); } if (eventPublisher != null) { if (shouldPostUpdate(hostname, port, success)) { eventPublisher.postUpdate(itemName, success ? OnOffType.ON : OnOffType.OFF); } } } } }
Source:
<code>protected void putManagedState(Object tuple) { <START> ((ManagedTimeUnifiedStateImpl)managedState).put(getTime(tuple), getKey(tuple), new Slice(null)); <END> }</code><technical_language>required for upgrade. Please separate JIRA PR</technical_language>

Target:
protected void putManagedState(Object tuple) { ((ManagedTimeUnifiedStateImpl)managedState).put(getTime(tuple), getKey(tuple), new Slice(null, 0, 0)); }
Source:
<code>beginRecognizeReceipts(Flux<ByteBuffer> receipt, long length, RecognizeReceiptsOptions recognizeReceiptsOptions, Context context) { try { Objects.requireNonNull(receipt, "'receipt' is required and cannot be null."); recognizeReceiptsOptions = getRecognizeReceiptOptions(recognizeReceiptsOptions); final boolean isFieldElementsIncluded = recognizeReceiptsOptions.isFieldElementsIncluded(); final String localeInfo <START> = recognizeReceiptsOptions.getLocale() == null ? "" : recognizeReceiptsOptions.getLocale(); <END> return new PollerFlux<>( recognizeReceiptsOptions.getPollInterval(), streamActivationOperation( (contentType -> service.analyzeReceiptAsyncWithResponseAsync( contentType, receipt, length, isFieldElementsIncluded, localeInfo, context) .map(response -> new FormRecognizerOperationResult( parseModelId(response.getDeserializedHeaders().getOperationLocation())))), receipt, recognizeReceiptsOptions.getContentType()), pollingOperation(resultId -> service.getAnalyzeReceiptResultWithResponseAsync(resultId, context)), (activationResponse, pollingContext) -> monoError(logger, new RuntimeException("Cancellation is not supported")), fetchingOperation(resultId -> service.getAnalyzeReceiptResultWithResponseAsync(resultId, context)) .andThen(after -> after.map(modelSimpleResponse -> toRecognizedForm(modelSimpleResponse.getValue().getAnalyzeResult(), isFieldElementsIncluded)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExist))); } catch (RuntimeException ex) { return PollerFlux.error(ex); } }</code><technical_language>is normal for Java pass empty string instead of null request if user a param</technical_language>

Target:
beginRecognizeReceipts(Flux<ByteBuffer> receipt, long length, RecognizeReceiptsOptions recognizeReceiptsOptions, Context context) { try { Objects.requireNonNull(receipt, "'receipt' is required and cannot be null."); recognizeReceiptsOptions = getRecognizeReceiptOptions(recognizeReceiptsOptions); final boolean isFieldElementsIncluded = recognizeReceiptsOptions.isFieldElementsIncluded(); final String localeInfo = recognizeReceiptsOptions.getLocale(); return new PollerFlux<>( recognizeReceiptsOptions.getPollInterval(), streamActivationOperation( (contentType -> service.analyzeReceiptAsyncWithResponseAsync( contentType, receipt, length, isFieldElementsIncluded, localeInfo, context) .map(response -> new FormRecognizerOperationResult( parseModelId(response.getDeserializedHeaders().getOperationLocation())))), receipt, recognizeReceiptsOptions.getContentType()), pollingOperation(resultId -> service.getAnalyzeReceiptResultWithResponseAsync(resultId, context)), (activationResponse, pollingContext) -> monoError(logger, new RuntimeException("Cancellation is not supported")), fetchingOperation(resultId -> service.getAnalyzeReceiptResultWithResponseAsync(resultId, context)) .andThen(after -> after.map(modelSimpleResponse -> toRecognizedForm(modelSimpleResponse.getValue().getAnalyzeResult(), isFieldElementsIncluded, null)) .onErrorMap(Utility::mapToHttpResponseExceptionIfExist))); } catch (RuntimeException ex) { return PollerFlux.error(ex); } }
Source:
<code>public Iterable<Channel> allChannels(ChannelQuery query) { MongoQueryBuilder mongoQuery = new MongoQueryBuilder(); if (query.getBroadcaster().isPresent()) { mongoQuery.fieldEquals(ChannelTranslator.BROADCASTER, query.getBroadcaster().get().key()); } if (query.getMediaType().isPresent()) { mongoQuery.fieldEquals(ChannelTranslator.MEDIA_TYPE, query.getMediaType().get().name()); } if (query.getAvailableFrom().isPresent()) { mongoQuery.fieldEquals(ChannelTranslator.AVAILABLE_ON, query.getAvailableFrom().get().key()); } if (query.getChannelGroups().isPresent()) { <START> mongoQuery.longFieldIn(JOIN_ON_DOT.join(ChannelTranslator.NUMBERINGS, ChannelNumberingTranslator.CHANNEL_GROUP_KEY, MongoConstants.ID), query.getChannelGroups().get()); <END> } return Iterables.transform(collection.find(mongoQuery.build()), DB_TO_CHANNEL_TRANSLATOR); }</code><technical_language>key is a constant right</technical_language>

Target:
public Iterable<Channel> allChannels(ChannelQuery query) { MongoQueryBuilder mongoQuery = new MongoQueryBuilder(); if (query.getBroadcaster().isPresent()) { mongoQuery.fieldEquals(ChannelTranslator.BROADCASTER, query.getBroadcaster().get().key()); } if (query.getMediaType().isPresent()) { mongoQuery.fieldEquals(ChannelTranslator.MEDIA_TYPE, query.getMediaType().get().name()); } if (query.getAvailableFrom().isPresent()) { mongoQuery.fieldEquals(ChannelTranslator.AVAILABLE_ON, query.getAvailableFrom().get().key()); } if (query.getChannelGroups().isPresent()) { mongoQuery.longFieldIn(NUMBERING_CHANNEL_GROUP_ID, query.getChannelGroups().get()); } return Iterables.transform(getOrderedCursor(mongoQuery.build()), DB_TO_CHANNEL_TRANSLATOR); }
Source:
<code>private boolean CanFindVdsToRun(List<String> messages, boolean isMigrate, Iterable<VDS> vdss) { VdcBllMessages messageToReturn = VdcBllMessages.Unassigned; RpmVersion vdsVersion = null; <START> boolean noVDSs = true; <END> StringBuffer sb = new StringBuffer(); for (VDS curVds : vdss) { if (isMigrate && getVm().getrun_on_vds() != null && getVm().getrun_on_vds().equals(curVds.getId())) { continue; } noVDSs = false; ValidationResult result = validateHostIsReadyToRun(curVds, sb); if (result.isValid()) { return true; } else { if (messageToReturn.getValue() < result.getMessage().getValue()) { messageToReturn = result.getMessage(); vdsVersion = curVds.getVersion(); } } } if (noVDSs) { if (messages != null) { messageToReturn = VdcBllMessages.ACTION_TYPE_FAILED_NO_VDS_AVAILABLE_IN_CLUSTER; } } if (messages != null) { messages.add(messageToReturn.toString()); if (messageToReturn == VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_VERSION && vdsVersion != null) { VmHandler.UpdateVmGuestAgentVersion(getVm()); messages.add("$toolsVersion " + getVm().getPartialVersion()); messages.add("$serverVersion " + vdsVersion.getRpmName()); } } log.info(sb.toString()); return false; }</code><technical_language>StringBuilder</technical_language>

Target:
private boolean CanFindVdsToRun(List<String> messages, boolean isMigrate, Iterable<VDS> vdss) { VdcBllMessages messageToReturn = VdcBllMessages.Unassigned; RpmVersion vdsVersion = null; boolean noVDSs = true; StringBuilder sb = new StringBuilder(); for (VDS curVds : vdss) { if (isMigrate && getVm().getrun_on_vds() != null && getVm().getrun_on_vds().equals(curVds.getId())) { continue; } noVDSs = false; ValidationResult result = validateHostIsReadyToRun(curVds, sb); if (result.isValid()) { return true; } else { if (messageToReturn.getValue() < result.getMessage().getValue()) { messageToReturn = result.getMessage(); vdsVersion = curVds.getVersion(); } } } if (noVDSs) { if (messages != null) { messageToReturn = VdcBllMessages.ACTION_TYPE_FAILED_NO_VDS_AVAILABLE_IN_CLUSTER; } } if (messages != null) { messages.add(messageToReturn.toString()); if (messageToReturn == VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_VERSION && vdsVersion != null) { VmHandler.UpdateVmGuestAgentVersion(getVm()); messages.add("$toolsVersion " + getVm().getPartialVersion()); messages.add("$serverVersion " + vdsVersion.getRpmName()); } } log.info(sb.toString()); return false; }
Source:
<code>public static RelDataType getMaxPrecisionScaleDecimal(RelDataTypeFactory factory) { int maxPrecision = factory.getTypeSystem().getMaxNumericPrecision(); int maxScale = factory.getTypeSystem().getMaxNumericScale(); while (maxScale >= maxPrecision) { maxScale = maxScale / 2; <START> } <END> return factory.createSqlType(SqlTypeName.DECIMAL, maxPrecision, maxScale); }</code><technical_language>afraid sql engines rule maxScale = maxScale / 2, add a check for validity instead of modifying silently. inclined fix default max precision/scale for Calcite type system</technical_language>

Target:
public static RelDataType getMaxPrecisionScaleDecimal(RelDataTypeFactory factory) { int maxPrecision = factory.getTypeSystem().getMaxNumericPrecision(); int scale = maxPrecision / 2; return factory.createSqlType(SqlTypeName.DECIMAL, maxPrecision, scale); }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { boolean doFilter = false; try { HttpSession httpSession = ((HttpServletRequest) request).getSession(false); if (httpSession != null) { String engineSession = (String) httpSession.getAttribute(FiltersHelper.Constants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); InitialContext ctx = null; if (engineSession != null) { ctx = new InitialContext(); try { VdcQueryReturnValue returnValue = FiltersHelper.getBackend(ctx) .runPublicQuery(VdcQueryType.ValidateSession, new VdcQueryParametersBase(engineSession)); if (!returnValue.getSucceeded()) { httpSession.invalidate(); } } finally { ctx.close(); } } } doFilter = true; } catch (Exception ex) { <START> doFilter = false; <END> String msg = String.format("An error has occurred while session validation. Message is %1$s", ex.getMessage()); log.error(msg); if (log.isDebugEnabled()) { log.debug("", ex); } ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } if (doFilter) { chain.doFilter(request, response); } }</code><technical_language>need</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { boolean doFilter = false; try { HttpSession httpSession = ((HttpServletRequest) request).getSession(false); if (httpSession != null) { String engineSession = (String) httpSession.getAttribute(FiltersHelper.Constants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); InitialContext ctx = null; if (engineSession != null) { ctx = new InitialContext(); try { VdcQueryReturnValue returnValue = FiltersHelper.getBackend(ctx) .runPublicQuery(VdcQueryType.ValidateSession, new VdcQueryParametersBase(engineSession)); if (!returnValue.getSucceeded()) { httpSession.invalidate(); } } finally { ctx.close(); } } } doFilter = true; } catch (Exception ex) { log.error(String.format("An error has occurred while session validation. Message is %1$s", ex.getMessage())); if (log.isDebugEnabled()) { log.debug("", ex); } ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } if (doFilter) { chain.doFilter(request, response); } }
Source:
<code>public boolean releaseLease(String leaseId) { try { leaseBlob.releaseLease(AccessCondition.generateLeaseCondition(leaseId)); return true; } catch (StorageException e) { <START> LOG.error("Wasn't able to release lease.", new SamzaException(e)); <END> return false; } }</code><technical_language>above. wrap exception for logging</technical_language>

Target:
public boolean releaseLease(String leaseId) { try { leaseBlob.releaseLease(AccessCondition.generateLeaseCondition(leaseId)); return true; } catch (StorageException storageException) { LOG.error("Wasn't able to release lease with lease id: " + leaseId, storageException); return false; } }