auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void writeResponse() { String result = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/html\r\n" + "Content-Length: " + 0 + "\r\n" + "Connection: close\r\n\r\n"; try { os.write(result.getBytes()); os.flush(); } catch (IOException e) { START e.printStackTrace(); END } } Please use logger instead of e.printStackTrace()

Target:
private void writeResponse() { String result = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/html\r\n" + "Content-Length: " + 0 + "\r\n" + "Connection: close\r\n\r\n"; try { os.write(result.getBytes()); os.flush(); } catch (IOException e) { logger.error(e.getMessage()); } }
Source:
private void writeResponse() { String result = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/html\r\n" + "Content-Length: " + 0 + "\r\n" + "Connection: close\r\n\r\n"; try { os.write(result.getBytes()); os.flush(); } catch (IOException e) { START logger.debug("ERROR: " + e.getMessage()); END } } Use parameterized logging instead of string concatenation.

Target:
private void writeResponse() { String result = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/html\r\n" + "Content-Length: " + 0 + "\r\n" + "Connection: close\r\n\r\n"; try { os.write(result.getBytes()); os.flush(); } catch (IOException e) { logger.error(e.getMessage()); } }
Source:
public boolean sizeIsZero() { START return somestring.length == 0; END } @amihaiemil should be `length()`

Target:
public boolean sizeIsZero() { return somestring.length() == 0; }
Source:
private static boolean isJavadocLineEmpty(final String line) { START return null != line && "*".equals(line.trim()); END } @dskalenko when line can be null?

Target:
private static boolean isJavadocLineEmpty(final String line) { return "*".equals(line.trim()); }
Source:
private static int getLineNoOfPreviousNode(final DetailAST node) { int start = 0; final DetailAST previous = node.getPreviousSibling(); START if (null != previous) { END start = previous.getLineNo(); } return start; } @dskalenko move `null` to right hand side

Target:
private static int getLineNoOfPreviousNode(final DetailAST node) { int start = 0; final DetailAST previous = node.getPreviousSibling(); if (previous != null) { start = previous.getLineNo(); } return start; }
Source:
public LineRanges within(final LineRanges ranges) { final LineRanges result = new LineRanges(); final Iterator<LineRange> iterator = ranges.iterate(); START while (iterator.hasNext()) { END final LineRange next = iterator.next(); for (final LineRange line : this.lines.collection()) { if (next.within(line)) { result.add(line); } } } return result; } @JimDeanSpivey can we go with a foreach? `for (final LineRange range : ranges)`?

Target:
public LineRanges within(final LineRanges ranges) { final LineRanges result = new LineRanges(); final Iterator<LineRange> iterator = ranges.iterator(); while (iterator.hasNext()) { final LineRange next = iterator.next(); for (final LineRange line : this.lines.collection()) { if (next.within(line)) { result.add(line); } } } return result; }
Source:
public void forbidsNonPublicCloneMethod() throws Exception { START final String file = "CloneMethodMustBePublic.java"; END new PMDAssert( file, Matchers.is(false), Matchers.containsString( String.format( PMDValidatorTest.BRACKETS, "CloneMethodMustBePublic" ) ) ).validate(); } @Happy-Neko we can inline this variable

Target:
public void forbidsNonPublicCloneMethod() throws Exception { new PMDAssert( "CloneMethodMustBePublic.java", Matchers.is(false), Matchers.containsString( String.format( PMDValidatorTest.BRACKETS, "CloneMethodMustBePublic" ) ) ).validate(); }
Source:
public void failValidationWithoutSchema() throws Exception { final Environment env = new Environment.Mock() .withFile( "src/main/resources/noschema.xml", // @checkstyle LineLength (1 line) "<Configuration><Appenders><Console name=\"CONSOLE\" target=\"SYSTEM_OUT\"><PatternLayout pattern=\"[%p] %t %c: %m%n\"/></Console></Appenders></Configuration>" ); final Validator validator = new XmlValidator(true); START validator.validate(env); END } @Happy-Neko how about ``` java new XmlValidator(true).validate( new Environment.Mock().withFile( ... ) ); ```

Target:
public void failValidationWithoutSchema() throws Exception { new XmlValidator(true).validate(new Environment.Mock() .withFile( "src/main/resources/noschema.xml", // @checkstyle LineLength (1 line) "<Configuration><Appenders><Console name=\"CONSOLE\" target=\"SYSTEM_OUT\"><PatternLayout pattern=\"[%p] %t %c: %m%n\"/></Console></Appenders></Configuration>" ) ); }
Source:
private static String toLegacyPathString(String moduleName) { final ModuleIdentifier moduleIdentifier = ModuleIdentifier.fromString(moduleName); START return moduleIdentifier.getName().replace('.', '/') + '/' + moduleIdentifier.getSlot() + '/'; END } Same problem with ending slash here.

Target:
private static String toLegacyPathString(String moduleName) { final ModuleIdentifier moduleIdentifier = ModuleIdentifier.fromString(moduleName); return moduleIdentifier.getName().replace('.', '/') + '/' + moduleIdentifier.getSlot(); }
Source:
public MulticurveProviderDiscount getMulticurveProvider() { START IssuerProviderInterface issuerProvider = getIssuerProvider(); END if (issuerProvider instanceof IssuerProviderDiscount) { return ((IssuerProviderDiscount) issuerProvider).getMulticurveProvider(); } else if (issuerProvider instanceof IssuerProviderIssuerDecoratedSpreadPeriodic) { return (MulticurveProviderDiscount) ((IssuerProviderIssuerDecoratedSpreadPeriodic) issuerProvider) .getMulticurveProvider(); } throw new IllegalArgumentException("unsupported type of issuer provider"); } Why this "if"? The original code does not work anymore? I should be a direct pass-through of the underlying curves.

Target:
public MulticurveProviderDiscount getMulticurveProvider() { return getIssuerProvider().getMulticurveProvider(); }
Source:
public void penaltyMatrixDiffOrderTooHighTest() { @SuppressWarnings("unused") START DoubleMatrix2D p = getPenaltyMatrix(6, 10); END } As above, no need to assign.

Target:
public void penaltyMatrixDiffOrderTooHighTest() { getPenaltyMatrix(6, 10); }
Source:
List<String> headers() { if (node.hasProperty(HEADERS) && !DYNAMIC_HEADERS.matcher(node.getPropertyValue(HEADERS)).find()) { START return Arrays.asList(node.getPropertyValue(HEADERS).split("\\s+")).stream().filter(header -> !header.isEmpty()).collect(Collectors.toList()); END } else { return Collections.emptyList(); } } You can use `Arrays.stream` instead

Target:
List<String> headers() { if (node.hasProperty(HEADERS) && !DYNAMIC_HEADERS.matcher(node.getPropertyValue(HEADERS)).find()) { return Arrays.stream(node.getPropertyValue(HEADERS).split("\\s+")).filter(header -> !header.isEmpty()).collect(Collectors.toList()); } else { return Collections.emptyList(); } }
Source:
private static boolean hasHeader(TagNode node) { if (node.getChildren().stream().anyMatch(TableWithoutHeaderCheck::isTableHeader)) { return true; } else { return node.getChildren().stream().filter(child -> !isTable(child)).anyMatch(TableWithoutHeaderCheck::hasHeader); START } END } You could use shortcircuit evaluation to avoid `if-else` block here: ``` return node.getChildren().stream().anyMatch(TableWithoutHeaderCheck::isTableHeader) || node.getChildren().stream().filter(child -> !isTable(child)).anyMatch(TableWithoutHeaderCheck::hasHeader); ```

Target:
private static boolean hasHeader(TagNode node) { return node.getChildren().stream().anyMatch(TableWithoutHeaderCheck::isTableHeader) || node.getChildren().stream().filter(child -> !isTable(child)).anyMatch(TableWithoutHeaderCheck::hasHeader); }
Source:
private static boolean isLayout(TagNode node) { String role = node.getAttribute("ROLE"); START return role != null && ("PRESENTATION".equalsIgnoreCase(role) || "NONE".equalsIgnoreCase(role)); END } null check seems unnecessary, given the yoda condition

Target:
private static boolean isLayout(TagNode node) { String role = node.getAttribute("ROLE"); return "PRESENTATION".equalsIgnoreCase(role) || "NONE".equalsIgnoreCase(role); }
Source:
private static boolean isHidden(TagNode node) { String ariaHidden = node.getAttribute("ARIA-HIDDEN"); START return ariaHidden != null && "TRUE".equalsIgnoreCase(ariaHidden); END } unneeded null check

Target:
private static boolean isHidden(TagNode node) { return "TRUE".equalsIgnoreCase(node.getAttribute("ARIA-HIDDEN")); }
Source:
private static boolean hasCaption(TagNode node) { if (node.getChildren().stream().anyMatch(TableWithoutCaptionCheck::isCaption)) { return true; } else { START return node.getChildren().stream().filter(child -> !isTable(child)).anyMatch(TableWithoutCaptionCheck::hasCaption); END } } per [html spec](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption) caption can only be first child of `<table>` element. We don't need to recurse through all children. (you can also update RSPEC of the rule with this)

Target:
private static boolean hasCaption(TagNode node) { return !node.getChildren().isEmpty() && isCaption(node.getChildren().get(0)); }
Source:
private static boolean hasFigCaption(TagNode node) { if (node.getChildren().stream().anyMatch(TableWithoutCaptionCheck::isFigCaption)) { return true; } else { START return node.getChildren().stream().filter(child -> !isTable(child)).anyMatch(TableWithoutCaptionCheck::hasFigCaption); END } } similar as above, `figcaption` is only allowed as first or last child. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figcaption

Target:
private static boolean hasFigCaption(TagNode node) { // node has one child at least return isFigCaption(node.getChildren().get(0)) || isFigCaption(node.getChildren().get(node.getChildren().size() - 1)); }
Source:
public JobInfo(String jobName_, String groupName_, Class job_, String shouldRecover) { this(jobName_, groupName_, job_); if(shouldRecover == null) { this.shouldRecover= true; } else { START this.shouldRecover = Boolean.getBoolean(shouldRecover); END } } you should use Boolean.valueOf instead of Boolean.getBoolean.

Target:
public JobInfo(String jobName_, String groupName_, Class job_, String shouldRecover) { this(jobName_, groupName_, job_); if(shouldRecover == null) { this.shouldRecover= true; } else { this.shouldRecover = Boolean.valueOf(shouldRecover); } }
Source:
public boolean apply(Game game, Ability source) { Player targetPlayer = game.getPlayer(targetPointer.getFirst(game, source)); if (targetPlayer == null) { return true; } int count = targetPlayer.discard(targetPlayer.getHand(), source, game).size(); targetPlayer.drawCards(count, source.getSourceId(), game); START return false; END } Must return `true`. Also must return `false` on code above (`targetPlayer == null`).

Target:
public boolean apply(Game game, Ability source) { Player targetPlayer = game.getPlayer(targetPointer.getFirst(game, source)); if (targetPlayer == null) { return false; } int count = targetPlayer.discard(targetPlayer.getHand(), source, game).size(); targetPlayer.drawCards(count, source.getSourceId(), game); return true; }
Source:
public boolean apply(Game game, Ability source) { Player player = game.getPlayer(source.getFirstTarget()); if (player != null) { START player.discard(player.getHand(), source, game); END } return false; } Missing return true

Target:
public boolean apply(Game game, Ability source) { Player player = game.getPlayer(source.getFirstTarget()); if (player == null) { return false; } player.discard(player.getHand(), source, game); return true; }
Source:
public FilterInstantSpell(String name) { super(name); START this.add(Predicates.or(CardType.INSTANT.getPredicate())); END } You don't need `Predicates.or` here

Target:
public FilterInstantSpell(String name) { super(name); this.add(CardType.INSTANT.getPredicate()); }
Source:
public FirecannonBlast(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{1}{R}{R}"); // Firecannon Blast deals 3 damage to target creature. // Raid - Firecannon Blast deals 6 damage to that creature instead if you attacked with a creature this turn. this.getSpellAbility().addEffect(new ConditionalOneShotEffect( new DamageTargetEffect(6), new DamageTargetEffect(3), START new InvertCondition(RaidCondition.instance), END "{this} deals 3 damage to target creature.<br><i>Raid</i> &mdash; {this} deals 6 damage instead if you attacked with a creature this turn")); this.getSpellAbility().addTarget(new TargetCreaturePermanent()); this.getSpellAbility().addWatcher(new PlayerAttackedWatcher()); } ```suggestion RaidCondition.instance, ```

Target:
public FirecannonBlast(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{1}{R}{R}"); // Firecannon Blast deals 3 damage to target creature. // Raid - Firecannon Blast deals 6 damage to that creature instead if you attacked with a creature this turn. this.getSpellAbility().addEffect(new ConditionalOneShotEffect( new DamageTargetEffect(6), new DamageTargetEffect(3), RaidCondition.instance, "{this} deals 3 damage to target creature.<br><i>Raid</i> &mdash; {this} deals 6 damage instead if you attacked with a creature this turn")); this.getSpellAbility().addTarget(new TargetCreaturePermanent()); this.getSpellAbility().addWatcher(new PlayerAttackedWatcher()); }
Source:
public FilterMana getPhyrexianColors() { START return this.phyrexianColors.copy(); END } Why it's makes copies in every getter call instead simple ref? Normal code: return ref objects and create copy on Copy/Create method (but you are using ref in copy -- see above/below).

Target:
public FilterMana getPhyrexianColors() { return this.phyrexianColors; }
Source:
public boolean checkTrigger(GameEvent event, Game game) { Spell spell = game.getStack().getSpell(event.getTargetId()); if (spell != null) { for (Ability ability : spell.getAbilities()) { START if (ability instanceof KickerAbility && ((KickerAbility) ability).getKickedCounter(game, spell.getSpellAbility()) > 0) { END return true; } } } return false; } This will only trigger once for a multikicked spell, it needs to trigger separately for each kick.

Target:
public boolean checkTrigger(GameEvent event, Game game) { return true; }
Source:
public TreacherousUrge(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{4}{B}"); START this.subtype.add(SubType.ARCANE); END // Target opponent reveals his or her hand. You may put a creature card from it onto the battlefield under your control. That creature gains haste. Sacrifice it at the beginning of the next end step. this.getSpellAbility().addEffect(new TreacherousUrgeEffect()); this.getSpellAbility().addTarget(new TargetOpponent()); } This needs to be removed

Target:
public TreacherousUrge(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{4}{B}"); // Target opponent reveals his or her hand. You may put a creature card from it onto the battlefield under your control. That creature gains haste. Sacrifice it at the beginning of the next end step. this.getSpellAbility().addEffect(new TreacherousUrgeEffect()); this.getSpellAbility().addTarget(new TargetOpponent()); }
Source:
public DeeprootWaters(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{2}{U}"); // Whenever you cast a Merfolk spell, create a 1/1 blue Merfolk creature token with hexproof. START this.addAbility(new SpellCastControllerTriggeredAbility(new CreateTokenEffect(new MerfolkHexproofToken(), 1, true, false), filter, false)); END } You can use the constructor for CreateTokenEffect that just takes the token as its only argument. The one you're using has tapped set to true.

Target:
public DeeprootWaters(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{2}{U}"); // Whenever you cast a Merfolk spell, create a 1/1 blue Merfolk creature token with hexproof. this.addAbility(new SpellCastControllerTriggeredAbility(new CreateTokenEffect(new MerfolkHexproofToken()), filter, false)); }
Source:
public void watch(GameEvent event, Game game) { if (event.getType() == GameEvent.EventType.DREW_CARD) { amountOfCardsDrawnThisTurn.putIfAbsent(event.getPlayerId(), 0); START amountOfCardsDrawnThisTurn.compute(event.getPlayerId(), (k, amount) -> amount += 1); END } } `amount + 1` is enough. You don't need to mutate `amount`.

Target:
public void watch(GameEvent event, Game game) { if (event.getType() == GameEvent.EventType.DREW_CARD) { amountOfCardsDrawnThisTurn.putIfAbsent(event.getPlayerId(), 0); amountOfCardsDrawnThisTurn.compute(event.getPlayerId(), (k, amount) -> amount + 1); } }
Source:
public boolean isEnchantedCreature(MageObject input, Game game) { START if (!input.getCardType().contains(CardType.CREATURE)) { END return false; } for (UUID attachmentId : ((Permanent)input).getAttachments()) { Permanent attachment = game.getPermanent(attachmentId); if (attachment != null && attachment.getCardType().contains(CardType.ENCHANTMENT)) { return true; } } return false; } check input to be != null

Target:
public boolean isEnchantedCreature(MageObject input, Game game) { if (input != null && !input.getCardType().contains(CardType.CREATURE)) { return false; } for (UUID attachmentId : ((Permanent)input).getAttachments()) { Permanent attachment = game.getPermanent(attachmentId); if (attachment != null && attachment.getCardType().contains(CardType.ENCHANTMENT)) { return true; } } return false; }
Source:
public boolean apply(Game game, Ability source) { Player activePlayer = game.getPlayer(game.getActivePlayerId()); START return activePlayer != null && game.getPlayer(game.getActivePlayerId()).hasOpponent(source.getControllerId(), game) && game.getPhase().getStep().getType().getIndex() < 5; END } Use the activePlayer object instead of retrieving it again

Target:
public boolean apply(Game game, Ability source) { Player activePlayer = game.getPlayer(game.getActivePlayerId()); return activePlayer != null && activePlayer.hasOpponent(source.getControllerId(), game) && game.getPhase().getStep().getType().getIndex() < 5; }
Source:
public boolean configure( StaplerRequest req, JSONObject formData) throws FormException { START this.stashRootUrl = null; END this.ignoreUnverifiedSsl = false; this.includeBuildNumberInKey = false; this.credentialsId = null; this.projectKey = null; this.prependParentProjectKey = false; this.disableInprogressNotification = false; this.considerUnstableAsSuccess = false; req.bindJSON(this, formData); save(); return true; } I suggest to keep the order consistent for easier reading/comparison: * field declarations in `StashNotifier` (maybe) * setters/getters in `StashNotifier` (maybe) * default values (lines 751-758) in `StashNotifier::configure` * assertThat calls (lines 27-33) in `ConfigAsCodeTest::should_support_jcasc_from_yaml` * setter calls (lines 40-47) in `ConfigAsCodeTest::should_support_jcasc_to_yaml`

Target:
public boolean configure( StaplerRequest req, JSONObject formData) throws FormException { this.considerUnstableAsSuccess = false; this.credentialsId = null; this.disableInprogressNotification = false; this.ignoreUnverifiedSsl = false; this.includeBuildNumberInKey = false; this.prependParentProjectKey = false; this.projectKey = null; this.stashRootUrl = null; req.bindJSON(this, formData); save(); return true; }
Source:
START public String getStashRootUrl() { END if ((stashRootUrl == null) || (stashRootUrl.trim().isEmpty())) { return null; } else { return stashRootUrl; } } Now that `trimToNull()` is used in `setStashRootUrl()` this can simply return the `stashRootUrl` value (like all other getters).

Target:
public String getStashRootUrl() { return stashRootUrl; }
Source:
public StashNotifier( String stashServerBaseUrl, String stashUserName, String stashUserPassword, boolean ignoreUnverifiedSSLPeer) { this.stashServerBaseUrl = stashServerBaseUrl; this.stashUserName = stashUserName; this.stashUserPassword = stashUserPassword; this.ignoreUnverifiedSSLPeer = ignoreUnverifiedSSLPeer; START jenkins = Jenkins.getInstance(); END httpClientfactory = new ConcreteHttpClientFactory(); notifierService = new ConfigurableStashNotifierService( stashServerBaseUrl, new JsonBuildEntityFactory(), new BasicStashRequestConfigurator(stashUserName, stashUserPassword)); } stashnotifier fails with a `NullPointerException` when trying to access `jenkins` in line `134`. The only explanation I can come up with is that `Jenkins.getInstance()` returns `null` when it is called during construction time of this plugin. I have no idea why that should be the case, though. Here's the exception I see in the Jenkins console output ``` ERROR: Publisher org.jenkinsci.plugins.stashNotifier.StashNotifier aborted due to exception java.lang.NullPointerException at org.jenkinsci.plugins.stashNotifier.StashNotifier.perform(StashNotifier.java:134) at hudson.tasks.BuildStepMonitor$3.perform(BuildStepMonitor.java:36) at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:810) at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:785) at hudson.maven.MavenModuleSetBuild$MavenModuleSetBuildExecution.post2(MavenModuleSetBuild.java:946) at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:732) at hudson.model.Run.execute(Run.java:1582) at hudson.maven.MavenModuleSetBuild.run(MavenModuleSetBuild.java:477) at hudson.model.ResourceController.execute(ResourceController.java:88) at hudson.model.Executor.run(Executor.java:236) Finished: FAILURE ```

Target:
public StashNotifier( String stashServerBaseUrl, String stashUserName, String stashUserPassword, boolean ignoreUnverifiedSSLPeer) { this.stashServerBaseUrl = stashServerBaseUrl; this.stashUserName = stashUserName; this.stashUserPassword = stashUserPassword; this.ignoreUnverifiedSSLPeer = ignoreUnverifiedSSLPeer; httpClientfactory = new ConcreteHttpClientFactory(); notifierService = new ConfigurableStashNotifierService( stashServerBaseUrl, new JsonBuildEntityFactory(), new BasicStashRequestConfigurator(stashUserName, stashUserPassword)); }
Source:
public void onNewSourceColumn() { if (!userPrefs_.allowSourceColumns().getValue()) pGlobalDisplay_.get().showMessage(GlobalDisplay.MSG_INFO, "Cannot Add Column", "Allow Source Columns preference is disabled."); START else if (additionalSourceCount_ == MAX_COLUMN_COUNT) END pGlobalDisplay_.get().showMessage(GlobalDisplay.MSG_INFO, "Cannot Add Column", "You can't add more than " + MAX_COLUMN_COUNT + " columns."); else createSourceColumn(); } Nit: although it's a constant now, if we ever make max column count configurable then maybe want this to be a `>=` comparison just to be safe in case where max changes to be smaller than current number of columns?

Target:
public void onNewSourceColumn() { if (!userPrefs_.allowSourceColumns().getValue()) pGlobalDisplay_.get().showMessage(GlobalDisplay.MSG_INFO, "Cannot Add Column", "Allow Source Columns preference is disabled."); else if (additionalSourceCount_ >= MAX_COLUMN_COUNT) pGlobalDisplay_.get().showMessage(GlobalDisplay.MSG_INFO, "Cannot Add Column", "You can't add more than " + MAX_COLUMN_COUNT + " columns."); else createSourceColumn(); }
Source:
public boolean equals(LogicalWindow window) { START if(normal_.equals(window.normal_)) END return true; return false; } Maybe simplify to `return normal_.equals(window.normal_)`?

Target:
public boolean equals(LogicalWindow window) { return normal_.equals(window.normal_); }
Source:
private void installConnectionsToolbar() { toolbar_.removeAllWidgets(); START newConnectionButton_ = END toolbar_.addLeftWidget(commands_.newConnection().createToolbarButton()); toolbar_.addLeftSeparator(); toolbar_.addRightWidget(searchWidget_); setSecondaryToolbarVisible(false); } Addition of this member variable looks unnecessary, and can be un-done I think?

Target:
private void installConnectionsToolbar() { toolbar_.removeAllWidgets(); toolbar_.addLeftWidget(commands_.newConnection().createToolbarButton()); toolbar_.addLeftSeparator(); toolbar_.addRightWidget(searchWidget_); setSecondaryToolbarVisible(false); }
Source:
protected Toolbar createMainToolbar() { toolbar_ = new Toolbar("Tutorial Tab"); // TODO: managing history within an iframe is surprisingly challenging, // so we just leave these buttons unavailable for now and just allow // navigation to home // toolbar_.addLeftWidget(commands_.tutorialBack().createToolbarButton()); // toolbar_.addLeftWidget(commands_.tutorialForward().createToolbarButton()); START toolbar_.addLeftWidget(homeButton_ = END commands_.tutorialHome().createToolbarButton()); toolbar_.addLeftWidget(commands_.tutorialPopout().createToolbarButton()); toolbar_.addLeftWidget(commands_.tutorialStop().createToolbarButton()); toolbar_.addRightWidget(commands_.tutorialRefresh().createToolbarButton()); return toolbar_; } Don't need the added `homeButton_` member variable.

Target:
protected Toolbar createMainToolbar() { toolbar_ = new Toolbar("Tutorial Tab"); // TODO: managing history within an iframe is surprisingly challenging, // so we just leave these buttons unavailable for now and just allow // navigation to home // toolbar_.addLeftWidget(commands_.tutorialBack().createToolbarButton()); // toolbar_.addLeftWidget(commands_.tutorialForward().createToolbarButton()); toolbar_.addLeftWidget(commands_.tutorialHome().createToolbarButton()); toolbar_.addLeftWidget(commands_.tutorialPopout().createToolbarButton()); toolbar_.addLeftWidget(commands_.tutorialStop().createToolbarButton()); toolbar_.addRightWidget(commands_.tutorialRefresh().createToolbarButton()); return toolbar_; }
Source:
public SourceAppCommand getSourceCommand(AppCommand command, SourceColumn column) { // check if we've already create a SourceAppCommand for this command for (SourceAppCommand cmd : sourceAppCommands_) { START if (cmd.getCommand() == command && END cmd.getColumn() == column.getName()) return cmd; } // if not found, create it SourceAppCommand sourceCommand = new SourceAppCommand(command, column.getName(), this); sourceAppCommands_.add(sourceCommand); return sourceCommand; } Testing JavaScript objects for equality has a bunch of weird edge cases so I'd recommend avoiding it. For example the object could be cloned and the clone won't match, but they'll look like the same object in the debugger so it won't be obvious WHY they don't match! How about storing `sourceAppCommands_` as a `HashMap`, using the command ID (from `command.getId()`) plus the column name as a key? Then lookups will be faster, plus identity will be more reliable as you'll just need to check for existence in the map.

Target:
public SourceAppCommand getSourceCommand(AppCommand command, SourceColumn column) { // check if we've already create a SourceAppCommand for this command String key = command.getId() + column.getName(); if (sourceAppCommands_.get(key) != null) return sourceAppCommands_.get(key); // if not found, create it SourceAppCommand sourceCommand = new SourceAppCommand(command, column.getName(), this); sourceAppCommands_.put(key, sourceCommand); return sourceCommand; }
Source:
public void setActive(String name) { if (StringUtil.isNullOrEmpty(name)) { START Debug.logWarning("Active column should be set to the main source window instead of null."); END if (activeColumn_ != null) { activeColumn_.setActiveEditor(""); activeColumn_ = null; } return; } // If we can't find the column, use the main column. This may happen on start up. SourceColumn column = getByName(name); if (column == null) column = getByName(MAIN_SOURCE_NAME); setActive(column); } Did you want to leave this in?

Target:
public void setActive(String name) { if (StringUtil.isNullOrEmpty(name)) { if (activeColumn_ != null) { activeColumn_.setActiveEditor(""); activeColumn_ = null; } return; } // If we can't find the column, use the main column. This may happen on start up. SourceColumn column = getByName(name); if (column == null) column = getByName(MAIN_SOURCE_NAME); setActive(column); }
Source:
void onDevtoolsLoadAll() { START source_.withSaveFilesBeforeCommand(new Command() { END @Override public void execute() { withDevtoolsLoadAllPath(new CommandWithArg<String>() { @Override public void execute(String loadAllPath) { sendLoadCommandToConsole( "devtools::load_all(\"" + loadAllPath + "\")"); } }); } }, new Command() { public void execute() { } }, "Build"); } While you're touching this... could be lambda-fied. Braces and newlines as you see fit: ``` source_.withSaveFilesBeforeCommand(() -> { withDevtoolsLoadAllPath(loadAllPath -> { sendLoadCommandToConsole("devtools::load_all(\"" + loadAllPath + "\")"); }); }, () -> {}, "Build"); ```

Target:
void onDevtoolsLoadAll() { source_.withSaveFilesBeforeCommand(() -> { withDevtoolsLoadAllPath(loadAllPath -> { sendLoadCommandToConsole("devtools::load_all(\"" + loadAllPath + "\")"); }); }, () -> {}, "Build"); }
Source:
public Command revertUnsavedChangesBeforeExitCommand( final Command onCompleted) { return new Command() { @Override public void execute() { handleUnsavedChangesBeforeExit( new ArrayList<UnsavedChangesTarget>(), onCompleted); } }; START } END Reduce this whole method to: ``` public Command revertUnsavedChangesBeforeExitCommand(final Command onCompleted) { return () -> handleUnsavedChangesBeforeExit(new ArrayList<>(), onCompleted); } ```

Target:
public Command revertUnsavedChangesBeforeExitCommand( final Command onCompleted) { return () -> handleUnsavedChangesBeforeExit(new ArrayList<UnsavedChangesTarget>(), onCompleted); }
Source:
private void runShinyApp() { source_.withSaveFilesBeforeCommand(() -> { events_.fireEvent(new LaunchShinyApplicationEvent(getPath(), prefs_.shinyBackgroundJobs().getValue() ? ShinyApplication.BACKGROUND_APP : ShinyApplication.FOREGROUND_APP, getExtendedFileType())); }, new Command() { public void execute() { START } END }, "Run Shiny Application"); } labmda: `() -> {}`

Target:
private void runShinyApp() { source_.withSaveFilesBeforeCommand(() -> { events_.fireEvent(new LaunchShinyApplicationEvent(getPath(), prefs_.shinyBackgroundJobs().getValue() ? ShinyApplication.BACKGROUND_APP : ShinyApplication.FOREGROUND_APP, getExtendedFileType())); }, () -> {}, "Run Shiny Application"); }
Source:
private void runPlumberAPI() { source_.withSaveFilesBeforeCommand(new Command() { @Override public void execute() { events_.fireEvent(new LaunchPlumberAPIEvent(getPath())); } }, new Command() { public void execute() { START } END }, "Run Plumber API"); } lambda: `() -> {}`

Target:
private void runPlumberAPI() { source_.withSaveFilesBeforeCommand(new Command() { @Override public void execute() { events_.fireEvent(new LaunchPlumberAPIEvent(getPath())); } }, () -> {}, "Run Plumber API"); }
Source:
public void executeCallback() { // This method must be called by a single HighlightPair, but because there can be multiple // pairs per query, we need to check if the callback has already executed before proceeding. if(!highlighter_.getCallbackProcessed(index_)) { highlighter_.setCallbackProcessed(index_, true); highlighter_.getServer().executeRCode(callback_, new ServerRequestCallback<String>(){ @Override public void onResponseReceived(String results) { // Remove listener from this element and all other elements with the same query highlighter_.clearEvents(); } @Override public void onError(ServerError error) { START Debug.logError(error); END } }); } } Should we clear highlight on error as well?

Target:
public void executeCallback() { // This method must be called by a single HighlightPair, but because there can be multiple // pairs per query, we need to check if the callback has already executed before proceeding. if(!highlighter_.getCallbackProcessed(index_)) { highlighter_.setCallbackProcessed(index_, true); highlighter_.getServer().executeRCode(callback_, new ServerRequestCallback<String>(){ @Override public void onResponseReceived(String results) { // Remove listener from this element and all other elements with the same query highlighter_.clearEvents(); } @Override public void onError(ServerError error) { // Remove listener from this element and all other elements with the same query highlighter_.clearEvents(); Debug.logError(error); } }); } }
Source:
public void ensureInputVisible() { // NOTE: we don't scroll immediately as this is normally called // in response to mutations of the console input buffer, and so // we need to wait until Ace has finished rendering in response // to that change. scrollIntoViewPending_ = true; // In case there wasn't an Ace render in-flight, force a check // for pending scroll (which will then force the cursor into view) START Scheduler.get().scheduleDeferred(() -> checkForPendingScroll()); END } Should we skip doing this if `scrollIntoViewPending_` is already true so there's no way for requests to stack up?

Target:
public void ensureInputVisible() { // NOTE: we don't scroll immediately as this is normally called // in response to mutations of the console input buffer, and so // we need to wait until Ace has finished rendering in response // to that change. // // In case there wasn't an Ace render in-flight, we also force a check // for pending scroll (which will then force the cursor into view) if (!scrollIntoViewPending_) { scrollIntoViewPending_ = true; Scheduler.get().scheduleDeferred(() -> checkForPendingScroll()); } }
Source:
public boolean visible() { switch (state_) { case HIDE: START return false; END case MINIMIZE: return false; default: return true; } } nit: don't need this `return false;` line

Target:
public boolean visible() { switch (state_) { case HIDE: case MINIMIZE: return false; default: return true; } }
Source:
public boolean presentationVisible() { START CheckBox lastCheckBox = checkBoxes_.get(checkBoxes_.size() - 1); END return StringUtil.equals(lastCheckBox.getText(), "Presentation") && lastCheckBox.isVisible(); } Is there any risk of this being called where checkBoxes_ is empty, so checkBoxes_.size() - 1 would be negative and (I think) end up throwing an exception? Might be worth a check for this if any chance of it happening.

Target:
public boolean presentationVisible() { if (checkBoxes_.size() <= 0) return false; CheckBox lastCheckBox = checkBoxes_.get(checkBoxes_.size() - 1); return StringUtil.equals(lastCheckBox.getText(), "Presentation") && lastCheckBox.isVisible(); }
Source:
public void focus() { widgets_.forEach(widget -> { if (widget.isVisible()) { START widget.focus(); END } }); } Should this exit after finding the first visible widget that can be focused?

Target:
public void focus() { widgets_.forEach(widget -> { if (widget.isVisible()) { widget.focus(); return; } }); }
Source:
public TerminalPopupMenu(TerminalList terminals) { START super(); END RStudioGinjector.INSTANCE.injectMembers(this); terminals_ = terminals; } A Java constructor automatically does a call to no-argument `super()` so this isn't needed.

Target:
public TerminalPopupMenu(TerminalList terminals) { RStudioGinjector.INSTANCE.injectMembers(this); terminals_ = terminals; }
Source:
private void nudgeAutosave() { // Cancel any existing autosave timer if (autoSaveTimer_.isRunning()) START autoSaveTimer_.cancel(); END // Start new timer if enabled if (prefs_.autoSaveOnIdle().getValue() == UserPrefs.AUTO_SAVE_ON_IDLE_COMMIT) autoSaveTimer_.schedule(prefs_.autoSaveMs()); } FWIW you can call `cancel()` directly (it will be a no-op if the timer is not running)

Target:
private void nudgeAutosave() { // Cancel any existing autosave timer autoSaveTimer_.cancel(); // Start new timer if enabled if (prefs_.autoSaveOnIdle().getValue() == UserPrefs.AUTO_SAVE_ON_IDLE_COMMIT) autoSaveTimer_.schedule(prefs_.autoSaveMs()); }
Source:
START public boolean contains(@Nonnull User user) { END return user.getProperty(GithubAccessTokenProperty.class) != null; } This class has no fields so its methods should be `static`.

Target:
public static boolean contains(@Nonnull User user) { return user.getProperty(GithubAccessTokenProperty.class) != null; }
Source:
public DelegatingResourceDescription getCreatableProperties() { DelegatingResourceDescription description = super.getCreatableProperties(); START description.addProperty("deathdateEstimated"); END description.addProperty("birthtime"); return description; } I think that `deathdateEstimated` was only added in 1.11.x, it should not be known in the context of 1.10.x compatibility.

Target:
public DelegatingResourceDescription getCreatableProperties() { DelegatingResourceDescription description = super.getCreatableProperties(); description.addProperty("birthtime"); return description; }
Source:
public String getUuidProperty() { START return RestTestConstants2_2.ORDER_UUID; END } This should be the resource uuid and not that of the parent, in this case the FulfillerDetails has no uuid property so this should possibly return null

Target:
public String getUuidProperty() { return null; }
Source:
public long getAllCount() { START return 1; END } I believe this should be zero

Target:
public long getAllCount() { return 0; }
Source:
public FulfillerDetails save(FulfillerDetails delegate) { Context.getOrderService().updateOrderFulfillerStatus(delegate.getOrder(), delegate.getFulfillerStatus(), delegate.getFulfillerComment()); START return delegate; END } I'm thinking this should return null, you don't need to send back any data to the client given the nature of the resource, the framework sends back an http OK status to the user in case of a success or 500 in case of an exception and that should be sufficient.

Target:
public FulfillerDetails save(FulfillerDetails delegate) { Context.getOrderService().updateOrderFulfillerStatus(delegate.getOrder(), delegate.getFulfillerStatus(), delegate.getFulfillerComment()); return null; }
Source:
public String getDisplayString(Diagnosis diagnosis) { if (diagnosis.getDiagnosis() == null) { return ""; } else { START if (diagnosis.getDiagnosis().getCoded() != null) END return diagnosis.getDiagnosis().getCoded().getName().getName(); return diagnosis.getDiagnosis().getNonCoded(); } } Can you use curly braces? https://wiki.openmrs.org/display/docs/Java+Conventions#JavaConventions-CodeStyle

Target:
public String getDisplayString(Diagnosis diagnosis) { if (diagnosis.getDiagnosis() == null) { return ""; } else { if (diagnosis.getDiagnosis().getCoded() != null) { return diagnosis.getDiagnosis().getCoded().getName().getName(); } return diagnosis.getDiagnosis().getNonCoded(); } }
Source:
public DelegatingResourceDescription getCreatableProperties() throws ResourceDoesNotSupportOperationException { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addRequiredProperty("diagnosis"); description.addRequiredProperty("encounter"); description.addRequiredProperty("uuid"); description.addRequiredProperty("condition"); description.addRequiredProperty("certainty"); description.addRequiredProperty("patient"); description.addRequiredProperty("rank"); START description.addRequiredProperty("voided"); END return description; } Remove voided from the creatable.

Target:
public DelegatingResourceDescription getCreatableProperties() throws ResourceDoesNotSupportOperationException { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addRequiredProperty("diagnosis"); description.addRequiredProperty("encounter"); description.addRequiredProperty("condition"); description.addRequiredProperty("certainty"); description.addRequiredProperty("patient"); description.addRequiredProperty("rank"); return description; }
Source:
public DelegatingResourceDescription getCreatableProperties() throws ResourceDoesNotSupportOperationException { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addRequiredProperty("diagnosis"); description.addRequiredProperty("encounter"); START description.addRequiredProperty("uuid"); END description.addRequiredProperty("condition"); description.addRequiredProperty("certainty"); description.addRequiredProperty("patient"); description.addRequiredProperty("rank"); return description; } uuid is not creatable

Target:
public DelegatingResourceDescription getCreatableProperties() throws ResourceDoesNotSupportOperationException { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addRequiredProperty("diagnosis"); description.addRequiredProperty("encounter"); description.addRequiredProperty("condition"); description.addRequiredProperty("certainty"); description.addRequiredProperty("patient"); description.addRequiredProperty("rank"); return description; }
Source:
public void started() { log.info("Started the REST Web Service module"); // Cache Swagger Spec START new SwaggerSpecificationCreator("host/openmrs/ws/rest").BuildJSON(); END } Since this is running from the server itself, can't you just use localhost?

Target:
public void started() { log.info("Started the REST Web Service module"); }
Source:
public void shutDownTask(TaskDefinition task) throws SchedulerException { if (Context.getSchedulerService().getTaskByName(task.getName()).getStarted()) { START Context.getSchedulerService().shutdownTask(task); END } } Same here as above. So let us get rid of this whole class. Because it is not adding value. And where it does, that is the business of the service layer API.

Target:
public void shutDownTask(TaskDefinition task) throws SchedulerException { Context.getSchedulerService().shutdownTask(task); }
Source:
public void shutDownTask(TaskDefinition task) throws SchedulerException { for (String taskDef : scheduledTasks) { START if (taskDef.equals(task.getName())) { END scheduledTasks.remove(taskDef); break; } } } Shouldn't this also just call Context.getSchedulerService(). shutDownTask(task) Same for the others.

Target:
public void shutDownTask(TaskDefinition task) throws SchedulerException { if (scheduledTasks.contains(task)) { scheduledTasks.remove(task); } }
Source:
public TaskDefinition save(TaskDefinition taskDefinition) { taskServiceWrapper.saveTaskDefinition(taskDefinition); START return Context.getSchedulerService().getTaskByName(taskDefinition.getName()); END } Why do you fetch the task again?

Target:
public TaskDefinition save(TaskDefinition taskDefinition) { taskServiceWrapper.saveTaskDefinition(taskDefinition); return taskDefinition; }
Source:
public void deleteTask(TaskDefinition task) throws SchedulerException { START if (Context.getSchedulerService().getTaskByName(task.getName()).getStarted()) { END Context.getSchedulerService().shutdownTask(task); } Context.getSchedulerService().deleteTask(task.getId()); } What is the use of this logic? Isn't it taken care of by the service layer? Why don't you just Context.getSchedulerService().deleteTask?

Target:
public void deleteTask(TaskDefinition task) throws SchedulerException { Context.getSchedulerService().deleteTask(task.getId()); }
Source:
public void shouldShutdownTask() throws Exception { mockTaskServiceWrapper.scheduledTasks.add(testTask); deserialize(handle(newPostRequest(getURI(), "{\"action\": \"shutdowntask\", \"tasks\":[\"" + getTestTaskName() + "\"]}"))); assertThat(mockTaskServiceWrapper.scheduledTasks, not(hasItem(testTask))); START } END How how are you that the task wasn't already shutdown even before the shutdown command?

Target:
public void shouldShutdownTask() throws Exception { mockTaskServiceWrapper.scheduledTasks.add(testTask); assertThat(mockTaskServiceWrapper.scheduledTasks, hasItem(testTask)); deserialize(handle(newPostRequest(getURI(), "{\"action\": \"shutdowntask\", \"tasks\":[\"" + getTestTaskName() + "\"]}"))); assertThat(mockTaskServiceWrapper.scheduledTasks, not(hasItem(testTask))); }
Source:
public boolean equals(Object o) { if (this == o) return true; START if (o == null || getClass() != o.getClass()) END return false; SearchParameter that = (SearchParameter) o; if (!name.equals(that.name)) return false; return value != null ? value.equals(that.value) : that.value == null; } What if you use SubresourceParameter? You should use instanceof here.

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof SearchParameter)) return false; SearchParameter that = (SearchParameter) o; if (!name.equals(that.name)) return false; return value != null ? value.equals(that.value) : that.value == null; }
Source:
private boolean operationHasRepresentationParam(Operation o) { boolean ret = false; for (Parameter p : o.getParameters()) { if (p.getName().equals("v")) { START ret = true; END } } return ret; } Shouldn't we return immediately to save some unnecessary cycles? Or at least break out of the for loop.

Target:
private boolean operationHasRepresentationParam(Operation o) { boolean ret = false; for (Parameter p : o.getParameters()) { if (p.getName().equals("v")) { ret = !ret; } } return ret; }
Source:
public Allergy newObject() { START Allergy allergy = Context.getPatientService().getAllergyByUuid(RestTestConstants2_0.ALLERGY_UUID); END return allergy; } Isn't this supposed to create and return a new (not yet in the database) allergy?

Target:
public Allergy newObject() { return Context.getPatientService().getAllergyByUuid(RestTestConstants2_0.ALLERGY_UUID); }
Source:
START public SimpleObject getValue(PersonAttribute pa) { END if (pa.getHydratedObject() == null) return null; SimpleObject simpleObject = new SimpleObject(); simpleObject.put("value", ConversionUtil.convertToRepresentation(pa.getHydratedObject(),Representation.REF)); return simpleObject; } Could you please try returning plain Object returned from pa.getHudratedObject() without converting to SimpleObject?

Target:
public Object getValue(PersonAttribute pa) { if (pa.getHydratedObject() == null) return null; SimpleObject simpleObject = new SimpleObject(); simpleObject.put("value", ConversionUtil.convertToRepresentation(pa.getHydratedObject(),Representation.REF)); return simpleObject; }
Source:
private List<String> getIgnorePatterns() { START int index = arguments.indexOf(toArg(IOptionKeys.IGNORE_PATTERN)); END return this.getValues(index); } if the argument expected doesnt exist the code will take another argument as the value for the Input argument. Should we check and complain or default ?

Target:
private List<String> getIgnorePatterns() { int index = arguments.indexOf(toArg(IOptionKeys.IGNORE_PATTERN)) + 1; return this.getValues(index); }
Source:
public LabelMetadataBuilder(String ID, String description) { START super(ID); this.description = description; this.priority = Integer.MAX_VALUE; END } we could replace this with `this(ID, description, Integer.MAX_VALUE);`

Target:
public LabelMetadataBuilder(String ID, String description) { this(ID, description, Integer.MAX_VALUE); }
Source:
public Object getDefaultValue() { START if (Boolean.class.isAssignableFrom(this.getType())) END { return false; } else return null; } You probably also want to support "boolean.class"

Target:
public Object getDefaultValue() { if (Boolean.class.isAssignableFrom(this.getType()) || boolean.class.isAssignableFrom(this.getType()) ) { return false; } else return null; }
Source:
public static XSLTTransformation using(String location) { // classLoader instance needed to see the file passed in the location START contextClassLoader = Thread.currentThread().getContextClassLoader(); END XSLTTransformation tansformation = new XSLTTransformation(); tansformation.location = location; return tansformation; } Good!

Target:
public static XSLTTransformation using(String location) { XSLTTransformation tansformation = new XSLTTransformation(); // classLoader instance needed to see the file passed in the location tansformation.contextClassLoader = Thread.currentThread().getContextClassLoader(); tansformation.location = location; return tansformation; }
Source:
public void perform(GraphRewrite event, EvaluationContext context) { checkVariableName(event, context); WindupVertexFrame payload = resolveVariable(event, getVariableName()); if (payload instanceof FileReferenceModel) { perform(event, context, ((FileReferenceModel) payload).getFile()); } else { START perform(event, context); END } } this is self-reference that I accidentally did. This would cause OutOfMemory when the classification is created for example on the variable that is FileModel (right now there is any such case). Could you please fix that in your PR to be `super.perform(event,context)` ?

Target:
public void perform(GraphRewrite event, EvaluationContext context) { checkVariableName(event, context); WindupVertexFrame payload = resolveVariable(event, getVariableName()); if (payload instanceof FileReferenceModel) { perform(event, context, ((FileReferenceModel) payload).getFile()); } else { super.perform(event, context); } }
Source:
START public GraphService(Class<T> type) END { this.type = type; } Should this constructor be protected?

Target:
protected GraphService(Class<T> type) { this.type = type; }