auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void updateSslVerifyUser(boolean value) { StoredConfig userConfig = GlobalConfigCache.getInstance() .getUserConfig(); try { START userConfig.load(); END updateSslVerify(userConfig, value); } catch (IOException | ConfigInvalidException e) { // Log it, but otherwise ignore here. LOG.error(MessageFormat.format(JGitText.get().userConfigFileInvalid, userConfig, e)); } } If I understand this change correctly, this shouldn't be needed anymore?

Target:
private void updateSslVerifyUser(boolean value) { StoredConfig userConfig = null; try { userConfig = GlobalConfigCache.getInstance().getUserConfig(); updateSslVerify(userConfig, value); } catch (IOException | ConfigInvalidException e) { // Log it, but otherwise ignore here. LOG.error(MessageFormat.format(JGitText.get().userConfigFileInvalid, userConfig, e)); } }
Source:
START private boolean isUserBrickAdapter(BaseAdapter baseAdapter) { END return baseAdapter instanceof UserBrickAdapter; } this method could be static i guess? more relevant: is this method necessary? i only see one usage

Target:
private static boolean isUserBrickAdapter(BaseAdapter baseAdapter) { return baseAdapter instanceof UserBrickAdapter; }
Source:
private FormulaEditorFragment addResourceToActiveFormulaInFormulaEditor(CategoryListItem categoryListItem) { FormulaEditorFragment formulaEditorFragment = ((FormulaEditorFragment) getFragmentManager() .findFragmentByTag(FormulaEditorFragment.FORMULA_EDITOR_FRAGMENT_TAG)); START formulaEditorFragment.addResourceToActiveFormula(categoryListItem.nameResId); END return formulaEditorFragment; } Please check if the fragment exists. It could lead to a null-pointer exception.

Target:
private FormulaEditorFragment addResourceToActiveFormulaInFormulaEditor(CategoryListItem categoryListItem) { FormulaEditorFragment formulaEditorFragment = null; if (getFragmentManager() != null) { formulaEditorFragment = ((FormulaEditorFragment) getFragmentManager() .findFragmentByTag(FormulaEditorFragment.FORMULA_EDITOR_FRAGMENT_TAG)); if (formulaEditorFragment != null) { formulaEditorFragment.addResourceToActiveFormula(categoryListItem.nameResId); } } return formulaEditorFragment; }
Source:
public final ReviewCategoryStrategy reviewCategoryStrategy() { String s = reviewCategeoryStrategyRaw(); return s != null ? ReviewCategoryStrategy.valueOf(s) : START null; END } Shouldn't this return ReviewCategoryStrategy.NONE? Otherwise why do we have ReviewCategoryStrategy.NONE if null means NONE too?

Target:
public final ReviewCategoryStrategy reviewCategoryStrategy() { String s = reviewCategeoryStrategyRaw(); return s != null ? ReviewCategoryStrategy.valueOf(s) : ReviewCategoryStrategy.NONE; }
Source:
public Iterable<ConnectorFactory> getConnectorFactories() { START return ImmutableList.of(new HiveConnectorFactory(name, getClassLoader(), Optional.of(metastore))); END } `metastore` is nullable here

Target:
public Iterable<ConnectorFactory> getConnectorFactories() { return ImmutableList.of(new HiveConnectorFactory(name, getClassLoader(), metastore)); }
Source:
public void testDBConnectionTimeMetrics() { START metrics.setDBConnectionTime(14); END assertEquals(14, testUtil.getGaugeValue("dbConnectionTime")); } Did you apply saveaction?

Target:
public void testDBConnectionTimeMetrics() { this.metrics.setDBConnectionTime(14); assertEquals(14, this.testUtil.getGaugeValue("dbConnectionTime")); }
Source:
protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(getCacheMode(), true); START builder.clustering().stateTransfer().chunkSize(200).sync().replTimeout(45, TimeUnit.SECONDS); END createClusteredCaches(4, cacheName(), builder); } I think I like 20 better, to exercise the key migration code more.

Target:
protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(getCacheMode(), true); builder.clustering().stateTransfer().sync().replTimeout(45, TimeUnit.SECONDS); createClusteredCaches(4, cacheName(), builder); }
Source:
private String getByAccountName(CodeReviewCommit codeReviewCommit) { Account account = getAccount(codeReviewCommit); if (account != null && account.getFullName() != null) { return " by " + START account.getUserName(); END } return ""; } getFullName()

Target:
private String getByAccountName(CodeReviewCommit codeReviewCommit) { Account account = getAccount(codeReviewCommit); if (account != null && account.getFullName() != null) { return " by " + account.getFullName(); } return ""; }
Source:
public void findByUndefinedSchema() throws Exception { START context.turnOffAuthorisationSystem(); END getClient().perform(get("/api/core/metadatafields/search/bySchema") .param("schema", "undefined")) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$.page.size", is(20))) .andExpect(jsonPath("$.page.totalElements", is(0))); } I believe the Auth system should remain on in this method.

Target:
public void findByUndefinedSchema() throws Exception { getClient().perform(get("/api/core/metadatafields/search/bySchema") .param("schema", "undefined")) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$.page.size", is(20))) .andExpect(jsonPath("$.page.totalElements", is(0))); }
Source:
START private void addAll(QuantileDigest digest, long... values) END { requireNonNull(values, "values is null"); for (long value : values) { digest.add(value); } } private static

Target:
private static void addAll(QuantileDigest digest, long... values) { requireNonNull(values, "values is null"); for (long value : values) { digest.add(value); } }
Source:
protected Object encodeCommand(Command command) { initDevicePassword(command, LaipacProtocolDecoder.DEFAULT_DEVICE_PASSWORD); switch (command.getType()) { case Command.TYPE_CUSTOM: return formatCommand(command, "{%s}", Command.KEY_DATA); case Command.TYPE_POSITION_SINGLE: return formatCommand(command, "AVREQ,{%s},1", Command.KEY_DEVICE_PASSWORD); case Command.TYPE_REBOOT_DEVICE: return formatCommand(command, "AVRESET,{%s},{%s}", Command.KEY_UNIQUE_ID, Command.KEY_DEVICE_PASSWORD); default: break; } START return null; END } Move this to default.

Target:
protected Object encodeCommand(Command command) { initDevicePassword(command, LaipacProtocolDecoder.DEFAULT_DEVICE_PASSWORD); switch (command.getType()) { case Command.TYPE_CUSTOM: return formatCommand(command, "{%s}", Command.KEY_DATA); case Command.TYPE_POSITION_SINGLE: return formatCommand(command, "AVREQ,{%s},1", Command.KEY_DEVICE_PASSWORD); case Command.TYPE_REBOOT_DEVICE: return formatCommand(command, "AVRESET,{%s},{%s}", Command.KEY_UNIQUE_ID, Command.KEY_DEVICE_PASSWORD); default: return null; } }
Source:
public void close() throws IOException { START if (selectObjectContentResult != null) { END selectObjectContentResult.close(); selectObjectContentResult = null; selectObjectRequest = null; } } We shouldn't need to check or clear any fields here, as `SelectObjectContentResult` is a `Closeable` which guarantees that `close()` is idempotent: > If the stream is already closed then invoking this method has no effect.

Target:
public void close() throws IOException { selectObjectContentResult.close(); }
Source:
@Override public boolean isDisposed() { START return inner == null; END } `get()`. (Btw since `inner` is plain, this check may end up hoisted and you'd never see it turning null).

Target:
@Override public boolean isDisposed() { return get(); }
Source:
public void close() throws IOException { if (s3Object != null) { START s3Object.close(); END } } I think that we need `super.close()` here.

Target:
public void close() throws IOException { super.close(); if (s3Object != null) { s3Object.close(); } }
Source:
public void loadChunk(int x, int z) { START w.loadChunk(z, z); END } (z, z) certainly doesn't look right.

Target:
public void loadChunk(int x, int z) { w.loadChunk(x, z); }
Source:
START public GeneratorUtil(TypeOracle typeOracle, END Logger logger, GeneratorContext generatorContext) { this.typeOracle = typeOracle; this.logger = logger; this.generatorContext = generatorContext; } rm public

Target:
GeneratorUtil(TypeOracle typeOracle, Logger logger, GeneratorContext generatorContext) { this.typeOracle = typeOracle; this.logger = logger; this.generatorContext = generatorContext; }
Source:
protected boolean failPassthroughVnicHotPlug() { if START (VmInterfaceType.pciPassthrough.equals(VmInterfaceType.forValue(getParameters().getNic().getType()))) END { addCanDoActionMessage(EngineMessage.HOT_PLUG_UNPLUG_PASSTHROUGH_VNIC_NOT_SUPPORTED); return true; } return false; } replace equals with == for enums.

Target:
protected boolean failPassthroughVnicHotPlug() { if (VmInterfaceType.pciPassthrough == VmInterfaceType.forValue(getParameters().getNic().getType())) { addCanDoActionMessage(EngineMessage.HOT_PLUG_UNPLUG_PASSTHROUGH_VNIC_NOT_SUPPORTED); return true; } return false; }
Source:
START public List<Map> getStageReachedCounts(Context context) throws SQLException { END return workspaceItemDAO.getStageReachedCounts(context); } It would be great if this map could use generics so we know what it contains.

Target:
public List<Map.Entry<Integer, Long>> getStageReachedCounts(Context context) throws SQLException { return workspaceItemDAO.getStageReachedCounts(context); }
Source:
Evaluator( final ObjectMapper mapper, final AsyncTaskExecutor asyncTaskExecutor, START final long timeoutLength) { END this.mapper = mapper; this.asyncTaskExecutor = asyncTaskExecutor; this.timeoutLength = timeoutLength; } usually this `) {` is on the next line

Target:
protected Evaluator( final ObjectMapper mapper, final AsyncTaskExecutor asyncTaskExecutor, final long timeoutLength ) { this.mapper = mapper; this.asyncTaskExecutor = asyncTaskExecutor; this.timeoutLength = timeoutLength; }
Source:
public MetaMasterSync(Address masterAddress, MetaMasterMasterClient masterClient) START throws IOException { END // TODO(lu) should avoid throw exception in Java constructor to avoid half-baked class instances mMasterAddress = masterAddress; mMasterClient = masterClient; mHeartbeatTimeoutMs = (int) Configuration.getMs(PropertyKey.MASTER_HEARTBEAT_TIMEOUT_MS); mLastSuccessfulHeartbeatMs = System.currentTimeMillis() - mHeartbeatTimeoutMs; } do we still need to throw exception here? if not, you can remove the next TODO

Target:
public MetaMasterSync(Address masterAddress, MetaMasterMasterClient masterClient) { mMasterAddress = masterAddress; mMasterClient = masterClient; mHeartbeatTimeoutMs = (int) Configuration.getMs(PropertyKey.MASTER_HEARTBEAT_TIMEOUT_MS); mLastSuccessfulHeartbeatMs = System.currentTimeMillis() - mHeartbeatTimeoutMs; }
Source:
public void sendLayerDeleted(String layerName) { START listeners.stream().forEachOrdered(listener->{ END listener.layerDeleted(layerName); }); } Seems me a ```` listeners.forEach(listener -> layerDeleted(layerName)); ```` would have been at the same time more compact, readable, and faster (streams are very slow)

Target:
public void sendLayerDeleted(String layerName) { listeners.forEach(listener->{ listener.layerDeleted(layerName); }); }
Source:
public List<SqlIdentifier> getProjectionFields(MetadataType metadataLevel, OptionManager options) { START List<SqlIdentifier> columnList = new ArrayList<>(); END columnList.add(new SqlIdentifier(options.getString(ExecConstants.IMPLICIT_FQN_COLUMN_LABEL), SqlParserPos.ZERO)); columnList.add(new SqlIdentifier(options.getString(ExecConstants.IMPLICIT_LAST_MODIFIED_TIME_COLUMN_LABEL), SqlParserPos.ZERO)); return columnList; } Please immutable collection.

Target:
public List<SqlIdentifier> getProjectionFields(MetadataType metadataLevel, OptionManager options) { return Arrays.asList( new SqlIdentifier(options.getString(ExecConstants.IMPLICIT_FQN_COLUMN_LABEL), SqlParserPos.ZERO), new SqlIdentifier(options.getString(ExecConstants.IMPLICIT_LAST_MODIFIED_TIME_COLUMN_LABEL), SqlParserPos.ZERO)); }
Source:
protected TypedTransaction(Transaction tx, Encoder encoder, TypeLayer tl) { START super((Snapshot)tx, encoder, tl); END this.tx = tx; this.encoder = encoder; this.tl = tl; } can TypedSnapshotBase constructor take SnapshotBase instead of Snapshot?

Target:
protected TypedTransaction(Transaction tx, Encoder encoder, TypeLayer tl) { super(tx, encoder, tl); this.tx = tx; this.encoder = encoder; this.tl = tl; }
Source:
public int hashCode() { int result = name != null ? name.hashCode() : 0; START result = 31 * result + (permissions != null ? permissions.hashCode() : 0); END result = 31 * result + mask; return result; } `permissions` can't be `null`, otherwise the constructor would throw a NPE.

Target:
public int hashCode() { int result = name.hashCode(); result = 31 * result + permissions.hashCode(); result = 31 * result + mask; return result; }
Source:
public EEFTabbedPropertySheetPage(Object contributor, String contributorId) { if (contributor instanceof IEEFTabbedPropertySheetPageContributor) { this.contributor = (IEEFTabbedPropertySheetPageContributor) contributor; } else { this.contributor = new ContributorWrapper(contributor, contributorId); } this.registry = START EEFTabbedPropertyRegistry.getDefault(this.contributor.getContributorId()); END } this.contributor

Target:
public EEFTabbedPropertySheetPage(Object contributor, String contributorId) { if (contributor instanceof IEEFTabbedPropertySheetPageContributor) { this.contributor = (IEEFTabbedPropertySheetPageContributor) contributor; } else { this.contributor = new ContributorWrapper(contributor, contributorId); } this.registry = EEFTabbedPropertyRegistry.getDefault(this.contributor); }
Source:
public List<String> getSuggestions(String input) { START return WorldEdit.getInstance().getPlatformManager() END .queryCapability(Capability.GAME_HOOKS).getWorlds().stream() .map(World::getId) .filter(world -> world.startsWith(input)) .collect(Collectors.toList()); } You should probably extract the world-stream extraction to its own method.

Target:
public List<String> getSuggestions(String input) { return getWorlds() .map(World::getId) .filter(world -> world.startsWith(input)) .collect(Collectors.toList()); }
Source:
START protected void executeCommand() { END //disconnect the connection from vdsm boolean isStorageDisconnectSucceeded = disconnectStorage(); if(isStorageDisconnectSucceeded) { String connectionId = getConnection().getid(); if(StringUtils.isNotEmpty(connectionId)) { //remove the connection record from db getDbFacade().getStorageServerConnectionDao().remove(connectionId); setSucceeded(true); } } } I don't understand something - now we will perform the this command for one host and then the connection will be removed from db, how we will perform the disconnect for other hosts? the load of connection will return null..no? you should take care of that i guess.

Target:
protected void executeCommand() { //disconnect the connection from vdsm boolean isStorageDisconnectSucceeded = disconnectStorage(); if(isStorageDisconnectSucceeded) { String connectionId = getConnection().getid(); if(StringUtils.isNotEmpty(connectionId)) { //remove the connection record from db getDbFacade().getStorageServerConnectionDao().remove(connectionId); } setSucceeded(true); } }
Source:
public void testNotEliminateSorts() { @Language("SQL") String sql = "SELECT quantity, row_number() OVER (ORDER BY quantity) FROM lineitem ORDER BY tax"; PlanMatchPattern pattern = anyTree( sort( START window(windowMatcherBuilder -> windowMatcherBuilder END .specification(windowSpec) .addFunction(functionCall("row_number", Optional.empty(), ImmutableList.of())), anyTree(LINEITEM_TABLESCAN_Q)))); assertUnitPlan(sql, pattern); } curious: why remove `anyTree`?

Target:
public void testNotEliminateSorts() { @Language("SQL") String sql = "SELECT quantity, row_number() OVER (ORDER BY quantity) FROM lineitem ORDER BY tax"; PlanMatchPattern pattern = anyTree( sort( anyTree( window(windowMatcherBuilder -> windowMatcherBuilder .specification(windowSpec) .addFunction(functionCall("row_number", Optional.empty(), ImmutableList.of())), anyTree(LINEITEM_TABLESCAN_Q))))); assertUnitPlan(sql, pattern); }
Source:
public Program getAssociatedProgram(Artifact artifact) { String extension = getAssociatedExtension(artifact); Program program = START ProgramFinder.findProgram(extension.toLowerCase()); END if (program == null) { throw new OseeArgumentException("No program associated with the extension [%s] found on your local machine.", extension); } return program; } Perform this operation in the custom ProgramFinder.findProgram() method instead.

Target:
public Program getAssociatedProgram(Artifact artifact) { String extension = getAssociatedExtension(artifact); Program program = ProgramFinder.findProgram(extension); if (program == null) { throw new OseeArgumentException("No program associated with the extension [%s] found on your local machine.", extension); } return program; }
Source:
public final Iterable<N> toDepthFirstIterable() { START return () -> AbstractTree.this.depthFirstIterator(); END } Please replace all the occurrences of `AbstractTree.this`. Indeed, the code style we are using does not recommend to add `this` as a prefix of a function call when the function is in the current object.

Target:
public final Iterable<N> toDepthFirstIterable() { return () -> this.depthFirstIterator(); }
Source:
void put(final K key, final V value) { clusterRegistry.put(scope, key, value); START System.out.println("putting key "+key+" ffrom thread "+Thread.currentThread().getName()); END localCacheInsert(key, value); } This is definitely a leftover that must be removed.

Target:
void put(final K key, final V value) { clusterRegistry.put(scope, key, value); localCacheInsert(key, value); }
Source:
START public static String getWarningMessages(String filename){ END String warningMessage = ""; if (getErrorMessage(filename).length() == 0 && filename.length() > 0) { if (!filename.matches("[A-Za-z][A-Za-z0-9_]*")) { // check to make sure if filename has no spaces String errorMessage = MESSAGES.whitespaceProjectNameError(); filename = filename.replaceAll("( )+", " ").replace(" ","_"); warningMessage = errorMessage + ". \n '" + filename + "' will be used if continued."; } } return warningMessage; } Missed a space here between the `)` and `{`

Target:
public static String getWarningMessages(String filename) { String warningMessage = ""; if (getErrorMessage(filename).length() == 0 && filename.trim().length() > 0) { if (!filename.matches("[A-Za-z][A-Za-z0-9_]*")) { // check to make sure if filename has no spaces String errorMessage = MESSAGES.whitespaceProjectNameError(); filename = filename.trim().replaceAll("( )+", " ").replace(" ","_"); warningMessage = errorMessage + ". \n '" + filename + "' will be used if continued."; } } return warningMessage; }
Source:
public @NonNull TraceSessionComponent[] getSessions() { List<ITraceControlComponent> compenents = getChildren(TraceSessionGroup.class); if (compenents.size() > 0) { TraceSessionGroup group = (TraceSessionGroup)compenents.get(0); List<ITraceControlComponent> sessions = group.getChildren(TraceSessionComponent.class); return sessions.toArray(new @NonNull TraceSessionComponent[sessions.size()]); } return new START @NonNull TraceSessionComponent[0]; END } this doesn't seem to change anything for me?

Target:
public @NonNull TraceSessionComponent[] getSessions() { List<ITraceControlComponent> compenents = getChildren(TraceSessionGroup.class); if (compenents.size() > 0) { TraceSessionGroup group = (TraceSessionGroup)compenents.get(0); List<ITraceControlComponent> sessions = group.getChildren(TraceSessionComponent.class); return sessions.toArray(new @NonNull TraceSessionComponent[sessions.size()]); } return new TraceSessionComponent[0]; }
Source:
private static void cacheColors(Display display) { BG_COLOR_RGB= JFaceColors.getInformationViewerBackgroundColor(display).getRGB(); FG_COLOR_RGB= JFaceColors.getInformationViewerForegroundColor(display).getRGB(); Color hyperlinkText= JFaceColors.getHyperlinkText(display); START Color activeHyperlinkText= JFaceColors.getActiveHyperlinkText(display); END if (hyperlinkText != null) { LINK_COLOR_RGB= hyperlinkText.getRGB(); } if (activeHyperlinkText != null) { ACTIVE_LINK_COLOR_RGB= activeHyperlinkText.getRGB(); } } Minor: Move declaration before the if block where it is used?

Target:
private static void cacheColors(Display display) { BG_COLOR_RGB= JFaceColors.getInformationViewerBackgroundColor(display).getRGB(); FG_COLOR_RGB= JFaceColors.getInformationViewerForegroundColor(display).getRGB(); Color hyperlinkText= JFaceColors.getHyperlinkText(display); if (hyperlinkText != null) { LINK_COLOR_RGB= hyperlinkText.getRGB(); } Color activeHyperlinkText= JFaceColors.getActiveHyperlinkText(display); if (activeHyperlinkText != null) { ACTIVE_LINK_COLOR_RGB= activeHyperlinkText.getRGB(); } }
Source:
private IRadioButton<T> findFirstButtonInFieldTree(IFormField f) { if (f instanceof IRadioButton) { START return (IRadioButton<T>) f; //TODO: mnick END } else if (f instanceof ICompositeField) { for (IFormField sub : ((ICompositeField) f).getFields()) { IRadioButton<T> b = findFirstButtonInFieldTree(sub); if (b != null) { return b; } } } return null; } you can use TypeCastUtility.getGenericsParameterClass(getClass(), IHolder.class); to check the type parameter

Target:
private IRadioButton<T> findFirstButtonInFieldTree(IFormField f) { if (f instanceof IRadioButton) { return (IRadioButton) f; } else if (f instanceof ICompositeField) { for (IFormField sub : ((ICompositeField) f).getFields()) { IRadioButton<T> b = findFirstButtonInFieldTree(sub); if (b != null) { return b; } } } return null; }
Source:
public void testGenerateXpathSuppressionOptionEmptyConfig() throws Exception { final String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE suppressions PUBLIC\n" START + " \"-//Puppy Crawl//DTD Suppressions Xpath Experimental 1.2//EN\"\n" END + " \"http://checkstyle.sourceforge.net/dtds/" + "suppressions_1_2_xpath_experimental.dtd\">\n" + "<suppressions>\n" + "</suppressions>\n"; exit.checkAssertionAfterwards(() -> { assertEquals("Unexpected output log", expected, systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); Main.main("-c", getPath("InputMainConfig-empty.xml"), "--generate-xpath-suppression", getPath("InputMainComplexityOverflow.java")); } fix name

Target:
public void testGenerateXpathSuppressionOptionEmptyConfig() throws Exception { final String expected = ""; exit.checkAssertionAfterwards(() -> { assertEquals("Unexpected output log", expected, systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); Main.main("-c", getPath("InputMainConfig-empty.xml"), "--generate-xpath-suppression", getPath("InputMainComplexityOverflow.java")); }
Source:
public String getPackageName() { if (clazz.getPackage() != null) { return clazz.getPackage().getName(); } START return null; END } Can this method return null? Or should it return empty string?

Target:
public String getPackageName() { if (clazz.getPackage() != null) { return clazz.getPackage().getName(); } return ""; }
Source:
public void testIsStringLiteral() { Set<ASTLiteral> literals = getNodes(ASTLiteral.class, TEST1); ASTLiteral literal = literals.iterator().next(); assertTrue(literal.isStringLiteral()); START assertEquals("String", literal.getTypeImage()); END } This could also be `java.lang.String`.

Target:
public void testIsStringLiteral() { Set<ASTLiteral> literals = getNodes(ASTLiteral.class, TEST1); assertTrue((literals.iterator().next()).isStringLiteral()); }
Source:
public ImmutableMap<K, V> getAllPresent(final Iterable<K> keys) { ImmutableMap.Builder builder = ImmutableMap.builder(); for (K key : keys START ) { END V value = getIfPresent(key); if (value != null) { builder.put(key, value); } } return builder.build(); } formatting weird

Target:
public Map<K, V> getAllPresent(final Iterable<K> keys) { ImmutableMap.Builder builder = ImmutableMap.builder(); for (K key : keys ) { V value = getIfPresent(key); if (value != null) { builder.put(key, value); } } return builder.build(); }
Source:
START public void configure(ServerHttpSecurity http) { END ReactiveAuthenticationManager authenticationManager = getAuthenticationManager(); X509PrincipalExtractor principalExtractor = getPrincipalExtractor(); AuthenticationWebFilter filter = new AuthenticationWebFilter(authenticationManager); filter.setServerAuthenticationConverter(new ServerX509AuthenticationConverter(principalExtractor)); http.addFilterAt(filter, SecurityWebFiltersOrder.AUTHENTICATION); } Please make this protected to avoid exposing methods that consumers of the API do not care about.

Target:
protected void configure(ServerHttpSecurity http) { ReactiveAuthenticationManager authenticationManager = getAuthenticationManager(); X509PrincipalExtractor principalExtractor = getPrincipalExtractor(); AuthenticationWebFilter filter = new AuthenticationWebFilter(authenticationManager); filter.setServerAuthenticationConverter(new ServerX509AuthenticationConverter(principalExtractor)); http.addFilterAt(filter, SecurityWebFiltersOrder.AUTHENTICATION); }
Source:
public void action(AuthenticationFlowContext context) { if (DisplayUtils.isConsole(context)) { START ConsoleOTPFormAuthenticator.SINGLETON.action(context); END return; } validateOTP(context); } Would it not be better to obtain this from the session? With this approach it's not pluggable.

Target:
public void action(AuthenticationFlowContext context) { validateOTP(context); }
Source:
private void handleResourceChange(GitResourceVariantTreeSubscriber subscriber, Repository which, Collection<IFile> resources) { for (GitSynchronizeData gsd : gsds) { if (which.equals(gsd.getRepository())) { START if (!resources.isEmpty()) END refreshResources(subscriber, resources); else refreshRepository(subscriber); } } } A null check is needed also. An NPE will be thrown if reopening a very large project. java.lang.NullPointerException at org.eclipse.egit.core.synchronize.GitSubscriberMergeContext.handleResourceChange(GitSubscriberMergeContext.java:141) at org.eclipse.egit.core.synchronize.GitSubscriberMergeContext.access$1(GitSubscriberMergeContext.java:137) at org.eclipse.egit.core.synchronize.GitSubscriberMergeContext$2.indexDiffChanged(GitSubscriberMergeContext.java:69) at org.eclipse.egit.core.internal.indexdiff.IndexDiffCache.notifyListeners(IndexDiffCache.java:94) at org.eclipse.egit.core.internal.indexdiff.IndexDiffCache.access$0(IndexDiffCache.java:86) at org.eclipse.egit.core.internal.indexdiff.IndexDiffCache$1.indexDiffChanged(IndexDiffCache.java:81) at org.eclipse.egit.core.internal.indexdiff.IndexDiffCacheEntry.notifyListeners(IndexDiffCacheEntry.java:313) at org.eclipse.egit.core.internal.indexdiff.IndexDiffCacheEntry.access$6(IndexDiffCacheEntry.java:306) at org.eclipse.egit.core.internal.indexdiff.IndexDiffCacheEntry$3.run(IndexDiffCacheEntry.java:171) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)

Target:
private void handleResourceChange(GitResourceVariantTreeSubscriber subscriber, Repository which, Collection<IFile> resources) { for (GitSynchronizeData gsd : gsds) { if (which.equals(gsd.getRepository()) && resources != null && !resources.isEmpty()) refreshResources(subscriber, resources); } }
Source:
public static Set<Path> getIncludedFieldsOfRootEntityForSort(CompositeMetadata root, Sort rootSort) { START Set<Path> ret=new HashSet<Path>(); END if(rootSort!=null) { SortFieldInfo[] sfi=SortFieldInfo.buildSortFields(rootSort,root.getFieldTreeRoot()); for(SortFieldInfo fi:sfi) ret.add(fi.getName()); } return ret; } Don't necessarily need the type info in the right hand assignment anymore. Only mention it because you use both ways throughout.

Target:
public static Set<Path> getIncludedFieldsOfRootEntityForSort(CompositeMetadata root, Sort rootSort) { Set<Path> ret=new HashSet<>(); if(rootSort!=null) { SortFieldInfo[] sfi=SortFieldInfo.buildSortFields(rootSort,root.getFieldTreeRoot()); for(SortFieldInfo fi:sfi) ret.add(fi.getName()); } return ret; }
Source:
public LocalCluster(String jarFileName, int siteCount, int hostCount, int kfactor, int clusterId, BackendTarget target, FailureState failureState, boolean debug, boolean isRejoinTest, Map<String, String> env) { // NOTE: isRejoinTest is unused START this(null, null, jarFileName, siteCount, hostCount, kfactor, clusterId, target, failureState, debug, env); END } Why remove unused at only one level below if its not used at all remove all together.

Target:
public LocalCluster(String jarFileName, int siteCount, int hostCount, int kfactor, int clusterId, BackendTarget target, FailureState failureState, boolean debug, boolean isRejoinTest, Map<String, String> env) { this(null, null, jarFileName, siteCount, hostCount, kfactor, clusterId, target, failureState, debug, isRejoinTest, env); }
Source:
public void execute(String userName) { FollowModeManager currentFollowModeManager = followModeManager; User userToFollow = findUser(userName); if (currentFollowModeManager == null) { return; } START User currentlyFollowedUser = followModeManager.getFollowedUser(); END if ((currentlyFollowedUser != null && !currentlyFollowedUser.equals(userToFollow)) || (currentlyFollowedUser == null && userToFollow != null)) { currentFollowModeManager.follow(userToFollow); } actionPerformed(); } I would prefer to move this logic into the `FollowModeManager`

Target:
public void execute(String userName) { FollowModeManager currentFollowModeManager = followModeManager; User userToFollow = findUser(userName); if (currentFollowModeManager == null) { return; } currentFollowModeManager.follow(userToFollow); actionPerformed(); }
Source:
@Override public Appendable write(Appendable appendable, Context context) throws IOException { START String sep = ""; END for (TypeName className : typeNames) { appendable.append(sep); className.write(appendable, context); sep = " & "; } return appendable; } nit: `sep` –> `separator` ?

Target:
@Override public Appendable write(Appendable appendable, Context context) throws IOException { Iterator<TypeName> iterator = typeNames.iterator(); if (iterator.hasNext()) { iterator.next().write(appendable, context); while (iterator.hasNext()) { appendable.append(" & "); iterator.next().write(appendable, context); } } return appendable; }
Source:
public void flush() throws IOException { START entryLogManager.flushCurrentLogs(); END entryLogManager.flushRotatedLogs(); } for single-log manager, it is better to flush `rotated logs` before flushing `current logs`, because the way how it rotates files and do the checkpoint. I would prefer keeping existing logic unchanged to reduce the risks. besides that, why not provide `flush` method in EntryLogManager? so different entry log manager implementation can implement its own flushing logic rather than exposing this knowledge to EntryLogger. If you provide `flush` method, it is possible that you don't need to expose `flushCurrentLogs` and `flushRotatedLogs`.

Target:
public void flush() throws IOException { entryLogManager.flush(); }
Source:
public void disableWireframe() { boolean refreshTaskList = false; EnableFaceCulling faceCullingStateChange = new EnableFaceCulling(); START if (!getDesiredStateChanges().contains(faceCullingStateChange)) { END addDesiredStateChange(faceCullingStateChange); refreshTaskList = true; } if (getDesiredStateChanges().contains(wireframeStateChange)) { removeDesiredStateChange(wireframeStateChange); refreshTaskList = true; } if (refreshTaskList) { worldRenderer.requestTaskListRefresh(); } } Also notice OpaqueObjectsNode.java needs the same treatment.

Target:
public void disableWireframe() { if (getDesiredStateChanges().contains(wireframeStateChange)) { addDesiredStateChange(faceCullingStateChange); removeDesiredStateChange(wireframeStateChange); worldRenderer.requestTaskListRefresh(); } }
Source:
public boolean prepareConnectHostToStoragePoolServers(ConnectHostToStoragePoolServersParameters parameters, List<StorageServerConnections> connections) { List<StorageServerConnections> res = updateIfaces(connections, parameters.getVds().getId()); connections.clear(); connections.addAll(res); START return true; END } What's the point of this return value if it's always true?

Target:
public void prepareConnectHostToStoragePoolServers(ConnectHostToStoragePoolServersParameters parameters, List<StorageServerConnections> connections) { List<StorageServerConnections> res = updateIfaces(connections, parameters.getVds().getId()); connections.clear(); connections.addAll(res); }
Source:
public HibernateErrorReportingServiceDao() { START this.errorOccurrenceConverter = new ErrorOccurrenceConverter(); END } I am not sure that converter should be part of DAO. Given we still using save on single entity I would suggest i would move that code to Service layer.

Target:
public HibernateErrorReportingServiceDao() { }
Source:
public JettyConfig getJettyConfig() { START if(jettyConfig != null) END { return jettyConfig; } else { return new DefaultJettyConfig(); } } Would much rather use the ternary operator here. Or even Optional, since we're on Java8 now. ``` Optional.ofNullable(jettyConfig).orElse(() -> new DefaultJettyConfig()); ```

Target:
public JettyConfig getJettyConfig() { return jettyConfig != null ? jettyConfig : new DefaultJettyConfig(); }
Source:
public void setNumThreads(final Integer numThreads) { START m_threads = ConfigUtils.assertNotNull(numThreads, "threads"); END } Why do we not allow this field to be null?

Target:
public void setNumThreads(final Integer numThreads) { m_threads = numThreads; }
Source:
START public String getModeName() { END String header = getHeader(); return header.substring(0, header.indexOf('"') - 1); } change to private

Target:
private String getModeName() { String header = getHeader(); return header.substring(0, header.indexOf('"') - 1); }
Source:
private List<RequestInfo> pollForRequests() { // these are ids that were successfully put for an operation that eventually failed idsToDelete.clear(); START putManager.getIdsToDelete(idsToDelete); END // this is a best effort to delete ids for cleanup purposes (these may fail and we will // not do anything about it at this time). for (String blobId : idsToDelete) { // possibly add a batch api going forward. deleteManager .submitDeleteBlobOperation(operationIdGenerator.incrementAndGet(), blobId, new FutureResult<Void>(), null); } List<RequestInfo> requests = new ArrayList<RequestInfo>(); putManager.poll(requests); getManager.poll(requests); deleteManager.poll(requests); return requests; } If you make the getIdsToDelete() to return a list of blob Ids, we can avoid idsToDelete.clear(). We can just call idsToDelete = putManager.getIdsToDelete() everytime.

Target:
private List<RequestInfo> pollForRequests() { // these are ids that were successfully put for an operation that eventually failed idsToDelete.clear(); putManager.getIdsToDelete(idsToDelete); // this is a best effort to delete ids for cleanup purposes (these may fail and we will // not do anything about it at this time). for (String blobId : idsToDelete) { // possibly add a batch api going forward. deleteManager.submitDeleteBlobOperation(blobId, new FutureResult<Void>(), null); } List<RequestInfo> requests = new ArrayList<RequestInfo>(); putManager.poll(requests); getManager.poll(requests); deleteManager.poll(requests); return requests; }
Source:
public InternalAggregationFunction specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionManager functionManager) { Type type = boundVariables.getTypeVariable("E"); MethodHandle compareMethodHandle = functionManager.getScalarFunctionImplementation( START functionManager.resolveOperator(operatorType, TypeSignatureProvider.fromTypes(ImmutableList.of(type, type)))).getMethodHandle(); END return generateAggregation(type, compareMethodHandle); } Static import `fromTypes`.

Target:
public InternalAggregationFunction specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionManager functionManager) { Type type = boundVariables.getTypeVariable("E"); MethodHandle compareMethodHandle = functionManager.getScalarFunctionImplementation( functionManager.resolveOperator(operatorType, fromTypes(ImmutableList.of(type, type)))).getMethodHandle(); return generateAggregation(type, compareMethodHandle); }
Source:
public AccountInfo getAccountInfo() throws IOException { CoingiBalances coingiBalances; try { coingiBalances = getCoingiBalance(); } catch (CoingiException e) { throw CoingiErrorAdapter.adapt(e); } return CoingiAdapters.adaptAccountInfo( coingiBalances, exchange.getExchangeSpecification().getUserName()); START } END it would be easier to read if would surround the entire method with this type of try / catch like: ``` @Override public AccountInfo getAccountInfo() throws IOException { try { CoingiBalances coingiBalances = getCoingiBalance(); return CoingiAdapters.adaptAccountInfo( coingiBalances, exchange.getExchangeSpecification().getUserName()); } catch (CoingiException e) { throw CoingiErrorAdapter.adapt(e); } } ``` please apply this hint to all the methods that have this type of try catch

Target:
public AccountInfo getAccountInfo() throws IOException { try { CoingiBalances coingiBalances = getCoingiBalance(); return CoingiAdapters.adaptAccountInfo( coingiBalances, exchange.getExchangeSpecification().getUserName()); } catch (CoingiException e) { throw CoingiErrorAdapter.adapt(e); } }
Source:
public IdentityHashMap<TableScanNode, Void> visitPlan(PlanNode node, Void context) { START IdentityHashMap<TableScanNode, Void> ret = new IdentityHashMap<>(); END node.getSources().forEach(source -> ret.putAll(source.accept(this, context))); return ret; } `Map<TableScanNode, Void> result = new IdentityHashMap<>();`

Target:
public Map<TableScanNode, Void> visitPlan(PlanNode node, Void context) { Map<TableScanNode, Void> ret = new IdentityHashMap<>(); node.getSources().forEach(source -> ret.putAll(source.accept(this, context))); return ret; }
Source:
protected RevCommit findHead(Repository repo) { try (RevWalk walk = new RevWalk(repo)) { try { ObjectId head = repo.resolve(HEAD); return walk.parseCommit(head); START } catch (RevisionSyntaxException e) { END throw new RuntimeException(e); } catch (AmbiguousObjectException e) { throw new RuntimeException(e); } catch (IncorrectObjectTypeException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } } you handle all these exceptions in the same way so you can use multi-catch: } catch (RevisionSyntaxException | AmbiguousObjectException | IncorrectObjectTypeException | IOException e) {

Target:
protected RevCommit findHead(Repository repo) { try (RevWalk walk = new RevWalk(repo)) { try { ObjectId head = repo.resolve(HEAD); return walk.parseCommit(head); } catch (RevisionSyntaxException | IOException e) { throw new RuntimeException(e); } } }
Source:
public void process(EquivalentContentUpdatedMessage message) throws RecoverableException { Id contentId = message.getContentRef().getId(); START log.debug("Processing message on id {}, took PT{}S, message: {}", END contentId, getTimeToProcessInSeconds(message)); Timer.Context time = timer.time(); try { Content content = getContent(contentId); neo4JContentStore.writeContent(content); time.stop(); } catch (Exception e) { failureMeter.mark(); throw Throwables.propagate(e); } } You're not passing in the message even though you have a marker there. Think that might throw weird RTEs.

Target:
public void process(EquivalentContentUpdatedMessage message) throws RecoverableException { Id contentId = message.getContentRef().getId(); log.debug("Processing message on id {}, took PT{}S, message: {}", contentId, getTimeToProcessInSeconds(message), message); Timer.Context time = timer.time(); try { Content content = getContent(contentId); neo4JContentStore.writeContent(content); time.stop(); } catch (Exception e) { failureMeter.mark(); throw Throwables.propagate(e); } }
Source:
public String apply(String dimValue) { START if (dimValue == null) return null; END Matcher matcher = pattern.matcher(dimValue); return matcher.find() ? dimValue : null; } Internally Druid treats nulls and empty strings as similar values. So I think one workaround here is to do dimValue == null ? "" : dimValue Druid's handling of nulls and empty strings could definitely be better though.

Target:
public String apply(String dimValue) { dimValue = (dimValue == null) ? "" : dimValue; Matcher matcher = pattern.matcher(dimValue); return matcher.find() ? dimValue : null; }
Source:
private void writeSubscribeCommands( String repoName, List<SubscribeCommand> commands) throws IOException { write("repository " + repoName); for (SubscribeCommand cmd : commands) { switch (cmd.getCommand()) { case SUBSCRIBE: write("want " + cmd.getSpec()); break; case UNSUBSCRIBE: write("stop " + cmd.getSpec()); break; START } END } } default: throw new IllegalArgumentException...

Target:
private void writeSubscribeCommands( String repoName, List<SubscribeCommand> commands) throws IOException { write("repository " + repoName); for (SubscribeCommand cmd : commands) { switch (cmd.getCommand()) { case SUBSCRIBE: write("want " + cmd.getSpec()); break; case UNSUBSCRIBE: write("stop " + cmd.getSpec()); break; default: throw new IllegalArgumentException(); } } }
Source:
private Set<GlusterServerInfo> fetchServers(VDS upServer, List<VDS> existingServers) { Set<GlusterServerInfo> fetchedServers = null; START while (fetchedServers == null && existingServers.size() > 0) { END fetchedServers = fetchServers(upServer); if (fetchedServers == null) { logServerMessage(upServer, AuditLogType.GLUSTER_SERVERS_LIST_FAILED); // Couldn't fetch servers from the up server. Mark it as non-operational setNonOperational(upServer); existingServers.remove(upServer); upServer = getNewUpServer(existingServers, upServer); } } return fetchedServers; } consider !existingServes.isEmpty()

Target:
private Set<GlusterServerInfo> fetchServers(VDS upServer, List<VDS> existingServers) { Set<GlusterServerInfo> fetchedServers = null; while (fetchedServers == null && !existingServers.isEmpty()) { fetchedServers = fetchServers(upServer); if (fetchedServers == null) { logServerMessage(upServer, AuditLogType.GLUSTER_SERVERS_LIST_FAILED); // Couldn't fetch servers from the up server. Mark it as non-operational setNonOperational(upServer); existingServers.remove(upServer); upServer = getNewUpServer(existingServers, upServer); } } return fetchedServers; }
Source:
public static String sanitizeSecondCachedKey(final Contentlet vanityUrl) START throws DotDataException, DotRuntimeException, DotSecurityException { END Host host = hostAPI.find(vanityUrl.getStringProperty(VanityUrlContentType.SITE_FIELD_VAR), APILocator.systemUser(), false); return sanitizeSecondCacheKey(host.getIdentifier(), vanityUrl.getLanguageId()); } ![MINOR](https://sonarsource.github.io/sonar-github/severity-minor.png 'Severity: MINOR') Remove the redundant '!unknownSymbol!' thrown exception declaration(s). [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3ARedundantThrowsDeclarationCheck)

Target:
public static String sanitizeSecondCachedKey(final Contentlet vanityUrl) throws DotDataException, DotSecurityException { Host host = hostAPI.find(vanityUrl.getStringProperty(VanityUrlContentType.SITE_FIELD_VAR), APILocator.systemUser(), false); return sanitizeSecondCacheKey(host.getIdentifier(), vanityUrl.getLanguageId()); }
Source:
void remove(I key) { Integer prev = this.identityMap.remove(key); START if (prev != null) this.objectList.set(prev, null); END } please keep the body of an `if` on its own line

Target:
void remove(I key) { Integer prev = this.identityMap.remove(key); if (prev != null) { this.objectList.set(prev, null); } }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof TaskPropertyType)) { return false; } TaskPropertyType that = (TaskPropertyType) o; START if (!name.equals(that.name)) { END return false; } return true; } This is always FALSE. since name is `static final`

Target:
public boolean equals(Object o) { return this == o || o instanceof TaskPropertyType; }
Source:
START protected long obtainEntityId() { END return nextEntityId++; } This could be `private` right?

Target:
private long obtainEntityId() { return nextEntityId++; }
Source:
public void markInCatalog() { START exportLog.info("ExportDataSource for table " + m_tableName + " partition " + m_partitionId + " marked as in catalog."); END m_isInCatalog = true; } I'm not sure that this INFO message is helpful to users.

Target:
public void markInCatalog() { m_isInCatalog = true; }
Source:
private static boolean canConvert(ParameterDefinition def, ParameterValue v) { return def instanceof SimpleParameterDefinition && !(def instanceof StringParameterDefinition) && v instanceof StringParameterValue; START } END This results conversion will be applyed also to subclass of `StringParameterValue`. It would be better applied to exact `StringParameterValue`.

Target:
private static boolean canConvert(ParameterDefinition def, ParameterValue v) { return def instanceof SimpleParameterDefinition && !(def instanceof StringParameterDefinition) && v.getClass().equals(StringParameterValue.class); }
Source:
public void setUp() { START deviceHandler = new EventHandlerTest(); END passingHandler = new FilterHandler(); filtingHandler = new FilterHandler(); filtingHandler.setFilterInvalid(true); filtingHandler.setFilterZero(true); filtingHandler.setFilterDuplicate(true); filtingHandler.setFilterFuture(true); filtingHandler.setFilterApproximate(true); filtingHandler.setFilterStatic(true); filtingHandler.setFilterDistance(10); filtingHandler.setFilterLimit(10); } Why are you using `EventHandlerTest` here? It has nothing to do with filtering.

Target:
public void setUp() { passingHandler = new FilterHandler(); filtingHandler = new FilterHandler(); filtingHandler.setFilterInvalid(true); filtingHandler.setFilterZero(true); filtingHandler.setFilterDuplicate(true); filtingHandler.setFilterFuture(true); filtingHandler.setFilterApproximate(true); filtingHandler.setFilterStatic(true); filtingHandler.setFilterDistance(10); filtingHandler.setFilterLimit(10); }
Source:
public void download(String url, String downloadPath) { InputStream in = null; try { in = new URL(url).openStream(); FileUtils.writeByteArrayToFile(new File(downloadPath), IOUtils.toByteArray(in)); System.out.println(IOUtils.toString(in)); } catch (IOException e) { START log.error(e); END } finally { IOUtils.closeQuietly(in); } } The connector setup should fail when an exception occurs.

Target:
public boolean download(String url, String downloadPath) { InputStream in = null; try { in = new URL(url).openStream(); FileUtils.writeByteArrayToFile(new File(downloadPath), IOUtils.toByteArray(in)); return true; } catch (IOException e) { log.error(e); return false; } finally { IOUtils.closeQuietly(in); } }
Source:
private boolean getOldChildStale(IObservable child) { Boolean oldChildValue = staleMap.get(child); boolean oldChildStale = START oldChildValue == null ? false : oldChildValue .booleanValue(); END return oldChildStale; } Simpler: oldChildValue != && oldChildValue.booleanValue()

Target:
private boolean getOldChildStale(IObservable child) { Boolean oldChildValue = staleMap.get(child); boolean oldChildStale = oldChildValue != null && oldChildValue; return oldChildStale; }
Source:
public void invoke(@NotNull final Project project, final Editor editor, PsiFile file, DataContext dataContext) { if (!CommonRefactoringUtil.checkReadOnlyStatus(file)) return; if (editor.getSettings().isVariableInplaceRenameEnabled()) { final TemplateState templateState = TemplateManagerImpl.getTemplateState(editor); START if (templateState != null && !templateState.isFinished()) return; END } performAction(new GoIntroduceOperation(project, editor, file)); } Add tooltip

Target:
public void invoke(@NotNull final Project project, final Editor editor, PsiFile file, DataContext dataContext) { if (!CommonRefactoringUtil.checkReadOnlyStatus(file)) return; performAction(new GoIntroduceOperation(project, editor, file)); }