auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void extended_description_can_substitue_arguments() throws IOException { String description = "This references the second argument: $2" + " this the first one: $" + " and this the third named one: $third_arg"; Map<String, String> argumentMap = new LinkedHashMap<>(); argumentMap.put( "first_arg", "1" ); argumentMap.put( "second_arg", "2" ); argumentMap.put( "third_arg", "3" ); String expectedDescription = "This references the second argument: 2" + " this the first one: 1" + " and this the third named one: 3"; given().a_report_model() .and().step_$_of_scenario_$_has_extended_description_with_arguments( 1, 1, description, argumentMap ); jsonReports .and().the_report_exist_as_JSON_file(); whenReport.when().the_HTML_Report_Generator_is_executed(); when().the_page_of_scenario_$_is_opened( 1 ) <START> .and().show_angular_foundation_tooltip_with_$_ms_delay_for_element_$_with_attribute_$_and_value_$(251, "span", "class", "has-tip" ); <END> then().an_element_with_a_$_class_exists( "has-tip" ) .and().attribute_$_has_value_$( "tooltip-html-unsafe", expectedDescription ); }</code><technical_language>introduce another step hides internal details of implementation. perspective of a non-technical person, writing scenarios. For example: the_tooltip_of_extended_description_is_shown(). method call internal implementation</technical_language>

Target:
public void extended_description_can_substitue_arguments() throws IOException { String description = "This references the second argument: $2" + " this the first one: $" + " and this the third named one: $third_arg"; Map<String, String> argumentMap = new LinkedHashMap<>(); argumentMap.put( "first_arg", "1" ); argumentMap.put( "second_arg", "2" ); argumentMap.put( "third_arg", "3" ); String expectedDescription = "This references the second argument: 2" + " this the first one: 1" + " and this the third named one: 3"; given().a_report_model() .and().step_$_of_scenario_$_has_extended_description_with_arguments( 1, 1, description, argumentMap ); jsonReports .and().the_report_exist_as_JSON_file(); whenReport.when().the_HTML_Report_Generator_is_executed(); when().the_page_of_scenario_$_is_opened( 1 ) .and().show_tooltip_of_extended_description(); then().an_element_with_a_$_class_exists( "has-tip" ) .and().attribute_$_has_value_$( "tooltip-html-unsafe", expectedDescription ); }
Source:
<code>private static void awaitNextRetry( final Throwable e, @Nullable final String messageOnRetry, final int nTry, final int maxRetries, final boolean quiet ) throws InterruptedException { final long sleepMillis = nextRetrySleepMillis(nTry); <START> final String fullMessage = messageOnRetry == null ? <END> StringUtils.format("Retrying (%d of %d) in %,dms.", nTry, maxRetries, sleepMillis) : StringUtils.format( "%s, retrying (%d of %d) in %,dms.", messageOnRetry, nTry, maxRetries, sleepMillis ); if (quiet) { log.debug(e, fullMessage); } else { log.warn(e, fullMessage); } Thread.sleep(sleepMillis); }</code><technical_language>Please break if-else</technical_language>

Target:
public static void awaitNextRetry( final Throwable e, @Nullable final String messageOnRetry, final int nTry, final int maxRetries, final boolean quiet ) throws InterruptedException { final long sleepMillis = nextRetrySleepMillis(nTry); final String fullMessage; if (messageOnRetry == null) { fullMessage = StringUtils.format("Retrying (%d of %d) in %,dms.", nTry, maxRetries, sleepMillis); } else { fullMessage = StringUtils.format( "%s, retrying (%d of %d) in %,dms.", messageOnRetry, nTry, maxRetries, sleepMillis ); } if (quiet) { log.debug(e, fullMessage); } else { log.warn(e, fullMessage); } Thread.sleep(sleepMillis); }
Source:
<code>public String getLocationPrefix(Location location) { if (location != null) { <START> for (Object ob : location.getActiveAttributes().toArray()) { <END> LocationAttribute att = (LocationAttribute) ob; if (att.getAttributeType().getName().equalsIgnoreCase(getPrefixLocationAttributeType())) { String prefix = (String) att.getValue(); if (StringUtils.isNotBlank(prefix)) { return prefix; } } } } else { throw new APIException("No location prefix could be found up the location tree."); } return getLocationPrefix(location.getParentLocation()); }</code><technical_language>Is a reason say: for (LocationAttribute att : location.getActiveAttributes()) { ...</technical_language>

Target:
public String getLocationPrefix(Location location) { if (location != null) { for (Object ob : location.getActiveAttributes()) { LocationAttribute att = (LocationAttribute) ob; if (att.getAttributeType().getName().equalsIgnoreCase(getPrefixLocationAttributeType())) { String prefix = (String) att.getValue(); if (StringUtils.isNotBlank(prefix)) { return prefix; } } } } else { throw new APIException("No location prefix could be found up the location tree."); } return getLocationPrefix(location.getParentLocation()); }
Source:
<code>public Response createForm(String form) { Theme theme; try { theme = getTheme(); } catch (IOException e) { logger.error("Failed to create theme", e); return Response.serverError().build(); } Locale locale = session.getContext().resolveLocale(user); Properties messagesBundle = handleThemeResources(theme, locale); <START> if (authenticationSession != null && authenticationSession.getClientNote(Constants.KC_ACTION_EXECUTING) != null) { <END> attributes.put("isAppInitiatedAction", true); } handleMessages(locale, messagesBundle); UriBuilder uriBuilder = prepareBaseUriBuilder(false); createCommonAttributes(theme, locale, messagesBundle, uriBuilder, null); return processTemplate(theme, form, locale); }</code><technical_language>sense move this method "createCommonAttributes" remove block "createResponse" is code duplicated 2 places</technical_language>

Target:
public Response createForm(String form) { Theme theme; try { theme = getTheme(); } catch (IOException e) { logger.error("Failed to create theme", e); return Response.serverError().build(); } Locale locale = session.getContext().resolveLocale(user); Properties messagesBundle = handleThemeResources(theme, locale); handleMessages(locale, messagesBundle); UriBuilder uriBuilder = prepareBaseUriBuilder(false); createCommonAttributes(theme, locale, messagesBundle, uriBuilder, null); return processTemplate(theme, form, locale); }
Source:
<code>public boolean equals(final Object other) { <START> if(other instanceof EventQueryNode) { <END> final EventQueryNode otherNode = (EventQueryNode)other; return Objects.equals(subjectIsConstant, otherNode.subjectIsConstant) && Objects.equals(subjectVar, otherNode.subjectVar) && Objects.equals(geoFilters, otherNode.geoFilters) && Objects.equals(geoPattern, otherNode.geoPattern) && Objects.equals(temporalFilters, otherNode.temporalFilters) && Objects.equals(temporalPattern, otherNode.temporalPattern) && Objects.equals(bindingNames, otherNode.bindingNames) && Objects.equals(subjectConstant, otherNode.subjectConstant); } return false; }</code><technical_language>EqualsBuilder() in here</technical_language>

Target:
public boolean equals(final Object other) { if(other instanceof EventQueryNode) { final EventQueryNode otherNode = (EventQueryNode)other; return new EqualsBuilder() .append(subjectIsConstant, otherNode.subjectIsConstant) .append(subjectVar, otherNode.subjectVar) .append(geoFilters, otherNode.geoFilters) .append(geoPattern, otherNode.geoPattern) .append(temporalFilters, otherNode.temporalFilters) .append(temporalPattern, otherNode.temporalPattern) .append(bindingNames, otherNode.bindingNames) .append(subjectConstant, otherNode.subjectConstant) .isEquals(); } return false; }
Source:
<code>public boolean cancel(boolean mayInterruptIfRunning) { command.cancel(); <START> latch.countDown(); <END> return super.cancel(mayInterruptIfRunning); }</code><technical_language>latch released invoking cancellation avoid a state in latch is released Future is canceled yet. I wrapping cancel calls a try releasing latch in finally do job</technical_language>

Target:
public boolean cancel(boolean mayInterruptIfRunning) { try { command.cancel(); return super.cancel(mayInterruptIfRunning); } finally { latch.countDown(); } }
Source:
<code>public void unselect() { waitForEnabled(); setFocus(); asyncExec(new VoidResult() { public void run() { log.debug(MessageFormat.format("Unselecting all in {0}", widget)); TableItem[] items = widget.getSelection(); for (TableItem item : items) { <START> unselect(indexOf(item.getText())); <END> } } }); }</code><technical_language>guarantee multiple rows in table text. getSelectionIndices() instead</technical_language>

Target:
public void unselect() { waitForEnabled(); setFocus(); asyncExec(new VoidResult() { public void run() { log.debug(MessageFormat.format("Unselecting all in {0}", widget)); int[] selectedIndices = widget.getSelectionIndices(); for (int i = 0; i < selectedIndices.length; i++) { unselect(selectedIndices[i]); } } }); }
Source:
<code>public static JBossProduct getKnownProductByProductName(String productName) { for (JBossProduct product : KNOWN_PRODUCTS.values()) { if (product.PRODUCT_NAME.equals(productName)) { return product; } } <START> LOG.debug("No product type with product-name '" + productName + "' is known. returning UNKNOWN"); <END> return JBossProduct.unknown(); }</code><technical_language>debug logs string concats wrapped wih if LOG.isDebugEnabled</technical_language>

Target:
public static JBossProduct getKnownProductByProductName(String productName) { for (JBossProduct product : KNOWN_PRODUCTS.values()) { if (product.PRODUCT_NAME.equals(productName)) { return product; } } if (LOG.isDebugEnabled()) { LOG.debug("No product type with product-name '" + productName + "' is known. returning UNKNOWN"); } return JBossProduct.unknown(); }
Source:
<code>public void onEventMainThread(DiscussionCommentPostedEvent event) { if (discussionThread.containsComment(event.getComment())) { if (event.getParent() == null) { ((BaseFragmentActivity)getActivity()).showInfoMessage(getString(R.string.discussion_response_posted)); if (!responsesLoader.hasMorePages()) { courseDiscussionResponsesAdapter.addNewResponse(event.getComment()); discussionResponsesRecyclerView.smoothScrollToPosition( courseDiscussionResponsesAdapter.getItemCount() - 1); } } else { <START> ((BaseFragmentActivity)getActivity()).showInfoMessage(getString(R.string.discussion_comment_posted)); <END> courseDiscussionResponsesAdapter.addNewComment(event.getParent()); } } }</code><technical_language>In case I guess this behaviour is fine</technical_language>

Target:
public void onEventMainThread(DiscussionCommentPostedEvent event) { if (discussionThread.containsComment(event.getComment())) { if (event.getParent() == null) { ((BaseFragmentActivity)getActivity()).showInfoMessage(getString(R.string.discussion_response_posted)); if (!responsesLoader.hasMorePages()) { courseDiscussionResponsesAdapter.addNewResponse(event.getComment()); discussionResponsesRecyclerView.smoothScrollToPosition( courseDiscussionResponsesAdapter.getItemCount() - 1); } } else { if (event.getParent().getChildCount() == 0) { ((BaseFragmentActivity) getActivity()).showInfoMessage(getString(R.string.discussion_comment_posted)); } courseDiscussionResponsesAdapter.addNewComment(event.getParent()); } } }
Source:
<code>public void testCast() throws DatabaseEngineException { test5Columns(); engine.persist("TEST", entry().set("COL1", 1).set("COL5", "teste") .build()); engine.persist("TEST", entry().set("COL1", 2).set("COL5", "xpto") .build()); engine.persist("TEST", entry().set("COL1", 3).set("COL5", "xpto") .build()); engine.persist("TEST", entry().set("COL1", 4).set("COL5", "teste") .build()); final Query query = select(cast(k("22"), INT).alias("int"), cast(k(22), STRING).alias("string"), cast(k("true"), BOOLEAN).alias("bool"), cast(k("22"), DOUBLE).alias("double"), <START> cast(k(22), LONG).alias("long")); <END> final List<Map<String, ResultColumn>> result = engine.query(query); assertEquals("Result must be 22", new Integer(22), result.get(0).get("int").toInt()); assertEquals("Result must be '22'", "22", result.get(0).get("string").toString()); assertEquals("Result must be true", true, result.get(0).get("bool").toBoolean()); assertEquals("Result must be 22.0", new Double(22), result.get(0).get("double").toDouble()); assertEquals("Result must be 22", new Long(22), result.get(0).get("long").toLong()); }</code><technical_language>need test DbColumnTypes</technical_language>

Target:
public void testCast() throws DatabaseEngineException { final Query query = select(cast(k("22"), INT).alias("int"), cast(k(22), STRING).alias("string"), cast(k("1"), BOOLEAN).alias("bool"), cast(k("22"), DOUBLE).alias("double"), cast(k(22), LONG).alias("long")); if (config.engine.contains("MySqlEngine")) { exception.expect(OperationNotSupportedRuntimeException.class); } final List<Map<String, ResultColumn>> result = engine.query(query); assertEquals("Result must be 22", new Integer(22), result.get(0).get("int").toInt()); assertEquals("Result must be '22'", "22", result.get(0).get("string").toString()); assertEquals("Result must be true", true, result.get(0).get("bool").toBoolean()); assertEquals("Result must be 22.0", new Double(22), result.get(0).get("double").toDouble()); assertEquals("Result must be 22", new Long(22), result.get(0).get("long").toLong()); }
Source:
<code>private void initUI() { VBox milestoneDialogBox = createMilestoneDialogBox(); assignedMilestonePane = createAssignedMilestoneBox(); matchingMilestonesPane = createMatchingMilestonesBox(); inputField = createInputField(); milestoneDialogBox.getChildren().add(assignedMilestonePane); milestoneDialogBox.getChildren().add(inputField); <START> milestoneDialogBox.getChildren().add(matchingMilestonesPane); <END> getDialogPane().setContent(milestoneDialogBox); refreshUI(state); Platform.runLater(inputField::requestFocus); }</code><technical_language>getChildren().addAll()</technical_language>

Target:
private void initUI() { VBox milestoneDialogBox = createMilestoneDialogBox(); assignedMilestoneBox = createAssignedMilestoneBox(); matchingMilestonesBox = createMatchingMilestonesBox(); ScrollPane matchingMilestonesScrollPane = coverWithScrollPane(matchingMilestonesBox); inputField = createInputField(); milestoneDialogBox.getChildren().addAll(assignedMilestoneBox, inputField, matchingMilestonesScrollPane); getDialogPane().setContent(milestoneDialogBox); refreshUI(state); Platform.runLater(inputField::requestFocus); }
Source:
<code>void verifyCorrectOpCode( final int opCode, @AggregateWith(MethodAggregator.class) final Method method) { <START> final var remoteActionCode = method.getAnnotation(RemoteActionCode.class); <END> assertThat("No annotation present for " + method, remoteActionCode, is(notNullValue())); assertThat("Invalid value for " + method, remoteActionCode.value(), is(opCode)); }</code><technical_language>var is confusing here, offhand 100% return type is of getAnnotation. I is Class, fully evident. if variable name remoteActionCodeClass, clear benefit type information</technical_language>

Target:
void verifyCorrectOpCode( final int opCode, @AggregateWith(MethodAggregator.class) final Method method) { final RemoteActionCode remoteActionCode = method.getAnnotation(RemoteActionCode.class); assertThat( "Expected @RemoteActionCode annotation to be present for " + method, remoteActionCode, is(notNullValue())); assertThat("Invalid value for " + method, remoteActionCode.value(), is(opCode)); }
Source:
<code>public boolean poll(MessageHandler handler) throws MessageHandlingException { Message<?> message = this.source.receive(); AcknowledgmentCallback acknowledgmentCallback = StaticMessageHeaderAccessor.getAcknowledgmentCallback(message); <START> if (message != null) { <END> try { handler.handleMessage(message); if (acknowledgmentCallback != null && !acknowledgmentCallback.isAcknowledged()) { acknowledgmentCallback.acknowledge(Status.ACCEPT); } } catch (Exception e) { if (acknowledgmentCallback != null && !acknowledgmentCallback.isAcknowledged()) { acknowledgmentCallback.acknowledge(Status.REJECT); } throw new MessageHandlingException(message, e); } return true; } return false; }</code><technical_language>Need swap lines. perform getAcknowledgmentCallback null</technical_language>

Target:
public boolean poll(MessageHandler handler) { Assert.notNull(handler, "'handler' cannot be null"); Message<?> message = this.source.receive(); if (message != null) { AcknowledgmentCallback ackCallback = StaticMessageHeaderAccessor .getAcknowledgmentCallback(message); try { handler.handleMessage(message); AckUtils.autoAck(ackCallback); } catch (Exception e) { AckUtils.autoNack(ackCallback); throw new MessageHandlingException(message, e); } return true; } return false; }
Source:
<code>public Unit(Sector currentLocation, Faction faction, String shipname) { side = faction; unitName = shipname; this.currentLocation = currentLocation; <START> course = new ArrayDeque<Cood>(); <END> }</code><technical_language>class section titles I do in week of year. I mind if remove them, get rid of if do</technical_language>

Target:
public Unit(Sector currentLocation, Faction faction, String shipname) { side = faction; unitName = shipname; this.currentLocation = currentLocation; course = new ArrayDeque<Coordinates>(); }
Source:
<code>@Test public void testInjection() throws Exception { JavaFileObject source = JavaFileObjects.forSourceString("Test", Joiner.on('\n').join( "import com.contentful.vault.Asset;", "import com.contentful.vault.ContentType;", "import com.contentful.vault.Field;", "import com.contentful.vault.Resource;", "import com.contentful.vault.Space;", "import java.util.Map;", "class Test {", " @ContentType(\"cid\")", " static class Model extends Resource {", " @Field String fText;", " @Field Boolean fBoolean;", " @Field Integer fInteger;", " @Field Double fDouble;", " @Field Map fMap;", " @Field Model fLinkedModel;", " @Field Asset fLinkedAsset;", " }", "", " @Space(value = \"sid\", models = Model.class, locales = { \"foo\", \"bar\" })", " static class AwesomeSpace {", " }", "}")); JavaFileObject expectedSource = JavaFileObjects.forSourceString( "Test$AwesomeSpace$$SpaceHelper", readTestResource("SpaceInjection.java")); <START> assertAbout(javaSource()).that(source) <END> .processedWith(processors()) .compilesWithoutError() .and() .generatesSources(expectedSource); }</code><technical_language>this assert_().about rest or</technical_language>

Target:
@Test public void testInjection() throws Exception { JavaFileObject source = JavaFileObjects.forSourceString("Test", Joiner.on('\n').join( "import com.contentful.vault.Asset;", "import com.contentful.vault.ContentType;", "import com.contentful.vault.Field;", "import com.contentful.vault.Resource;", "import com.contentful.vault.Space;", "import java.util.Map;", "class Test {", " @ContentType(\"cid\")", " static class Model extends Resource {", " @Field String fText;", " @Field Boolean fBoolean;", " @Field Integer fInteger;", " @Field Double fDouble;", " @Field Map fMap;", " @Field Model fLinkedModel;", " @Field Asset fLinkedAsset;", " }", "", " @Space(value = \"sid\", models = Model.class, locales = { \"foo\", \"bar\" })", " static class AwesomeSpace {", " }", "}")); JavaFileObject expectedSource = JavaFileObjects.forSourceString( "Test$AwesomeSpace$$SpaceHelper", readTestResource("SpaceInjection.java")); assert_().about(javaSource()).that(source) .processedWith(processors()) .compilesWithoutError() .and() .generatesSources(expectedSource); }
Source:
<code>private InneractiveAdViewEventsListener createFyberAdViewListener(InneractiveAdSpot adSpot, final MediationBannerListener mediationBannerListener) { if (adSpot == null || !(adSpot.getSelectedUnitController() instanceof InneractiveAdViewUnitController)) { return null; } InneractiveAdViewUnitController controller = (InneractiveAdViewUnitController)mBannerSpot.getSelectedUnitController(); controller.bindView(mBannerWrapperView); InneractiveAdViewEventsListener adViewListener = new InneractiveAdViewEventsListenerAdapter() { @Override public void onAdImpression(InneractiveAdSpot adSpot) { <START> mediationBannerListener.onAdOpened(FyberMediationAdapter.this); <END> } @Override public void onAdClicked(InneractiveAdSpot adSpot) { mediationBannerListener.onAdClicked(FyberMediationAdapter.this); } @Override public void onAdWillCloseInternalBrowser(InneractiveAdSpot adSpot) { mediationBannerListener.onAdClosed(FyberMediationAdapter.this); } @Override public void onAdWillOpenExternalApp(InneractiveAdSpot adSpot) { mediationBannerListener.onAdLeftApplication(FyberMediationAdapter.this); } }; controller.setEventsListener(adViewListener); return adViewListener; }</code><technical_language>Move onAdClicked(). onAdOpened() implies ad clicked full-screen</technical_language>

Target:
private InneractiveAdViewEventsListener createFyberAdViewListener(InneractiveAdSpot adSpot, final MediationBannerListener mediationBannerListener) { if (adSpot == null || !(adSpot.getSelectedUnitController() instanceof InneractiveAdViewUnitController)) { return null; } InneractiveAdViewUnitController controller = (InneractiveAdViewUnitController)mBannerSpot.getSelectedUnitController(); controller.bindView(mBannerWrapperView); InneractiveAdViewEventsListener adViewListener = new InneractiveAdViewEventsListenerAdapter() { @Override public void onAdImpression(InneractiveAdSpot adSpot) { } @Override public void onAdClicked(InneractiveAdSpot adSpot) { mediationBannerListener.onAdClicked(FyberMediationAdapter.this); mediationBannerListener.onAdOpened(FyberMediationAdapter.this); } @Override public void onAdWillCloseInternalBrowser(InneractiveAdSpot adSpot) { mediationBannerListener.onAdClosed(FyberMediationAdapter.this); } @Override public void onAdWillOpenExternalApp(InneractiveAdSpot adSpot) { mediationBannerListener.onAdLeftApplication(FyberMediationAdapter.this); } }; controller.setEventsListener(adViewListener); return adViewListener; }
Source:
<code>private void addAttributes(Map<String, Object> parameters, Map<String, Object> parsedParameters, String paramPrefix) { <START> HashMap<String, String> nodes = (HashMap<String, String>) parameters.get(ATTRIBUTES); <END> for (String key : nodes.keySet()) { String attr = nodes.get(key); parsedParameters.put(paramPrefix + "/@" + key, attr); } }</code><technical_language>nodes declared Map, HashMap (the cast a Map)</technical_language>

Target:
private void addAttributes(Map<String, Object> parameters, Map<String, Object> parsedParameters, String paramPrefix) { Map<String, String> nodes = (Map<String, String>) parameters.get(ATTRIBUTES); for(Map.Entry<String, String> entry: nodes.entrySet()) { parsedParameters.put(paramPrefix + "/@" + entry.getKey(), entry.getValue()); } }
Source:
<code>public void createWithNegativeIterations() throws Exception { <START> class Callback implements RateController.Callback <END> { @Override public int onNext() { return 0; } } final List<RateControllerInterval> ivlsList = new ArrayList<RateControllerInterval>(); final RateControllerInterval ivl = new MessagesAtMessagesPerSecondInterval(1, 1); ivlsList.add(ivl); rc = new RateController(new Callback(), ivlsList, -1); }</code><technical_language>a lambda expression</technical_language>

Target:
public void createWithNegativeIterations() throws Exception { final List<RateControllerInterval> ivlsList = new ArrayList<RateControllerInterval>(); final RateControllerInterval ivl = new MessagesAtMessagesPerSecondInterval(1, 1); ivlsList.add(ivl); rc = new RateController(() -> { return 0; }, ivlsList, -1); }
Source:
<code>public ApiResponse handleApiAction(String name, JSONObject params) throws ApiException { switch (name) { case ACTION_IMPORT_FILE: { URI endpointUri = UriFromStr(params.getString(PARAM_ENDPOINT), PARAM_ENDPOINT); File file = new File(params.getString(PARAM_FILE)); <START> if (!file.exists() || !file.canRead()) { <END> throw new ApiException( ApiException.Type.DOES_NOT_EXIST, file.getAbsolutePath()); } if (!file.isFile()) { throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_FILE); } try { GraphQlParser.parse(FileUtils.readFileToString(file, "UTF-8"), endpointUri); } catch (IOException e) { throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_FILE); } break; } case ACTION_IMPORT_URL: { URI endpointUri = UriFromStr(params.getString(PARAM_ENDPOINT), PARAM_ENDPOINT); String schemaStr = params.optString(PARAM_URL, ""); if ("".equals(schemaStr)) { GraphQlParser.introspect(endpointUri); break; } URI schemaUri = UriFromStr(schemaStr, PARAM_URL); GraphQlParser.parse(schemaUri, endpointUri); break; } default: throw new ApiException(ApiException.Type.BAD_ACTION); } return ApiResponseElement.OK; }</code><technical_language>Move canRead if? "does exist" is misleading in case</technical_language>

Target:
public ApiResponse handleApiAction(String name, JSONObject params) throws ApiException { switch (name) { case ACTION_IMPORT_FILE: importFile(params); break; case ACTION_IMPORT_URL: importUrl(params); break; default: throw new ApiException(ApiException.Type.BAD_ACTION); } return ApiResponseElement.OK; }
Source:
<code>void insertBindings(List<Binding> bindings) { try (Connection conn = getConnection(); PreparedStatement preparedStatement = conn.prepareStatement(INSERT_BINDING)) { for (Binding binding : bindings) { preparedStatement.setString(1, binding.getMessageRouter()); preparedStatement.setString(2, binding.getQueueName()); preparedStatement.setString(3, binding.getBindingDetails()); preparedStatement.addBatch(); } preparedStatement.executeBatch(); } catch (SQLException e) { <START> logger.error("Error while inserting bindings", e); <END> } }</code><technical_language>log exception throwing. In updateBindings readBindings thrown exception. this intentional</technical_language>

Target:
void insertBindings(List<Binding> bindings) throws SQLException { try (Connection conn = getConnection(); PreparedStatement preparedStatement = conn.prepareStatement(INSERT_BINDING)) { for (Binding binding : bindings) { preparedStatement.setString(1, binding.getMessageRouter()); preparedStatement.setString(2, binding.getQueueName()); preparedStatement.setString(3, binding.getBindingDetails()); preparedStatement.addBatch(); } preparedStatement.executeBatch(); } }
Source:
<code>public void run() { ConnectorFacade facade = ConnectorFacadeFactory.INSTANCE.build(Configuration.instance().getProperty("cli.connector")); List<ReviewFile> reviewFiles = facade.listFiles(); <START> log.debug("Files to check: " + reviewFiles); <END> Review review = new Review(reviewFiles); List<ReviewProcessor> processors = createProcessors(); for (ReviewProcessor processor : processors) { review(review, processor); } facade.setReview(review.toReviewInput()); }</code><technical_language>logback's notation please</technical_language>

Target:
public void run() { ConnectorFacade facade = ConnectorFacadeFactory.INSTANCE.build(Configuration.instance().getProperty("cli.connector")); List<ReviewFile> reviewFiles = facade.listFiles(); log.debug("Files to check: {}", reviewFiles); Review review = new Review(reviewFiles); List<ReviewProcessor> processors = createProcessors(); for (ReviewProcessor processor : processors) { review(review, processor); } facade.setReview(review.toReviewInput()); }
Source:
<code>private void openBranch() throws MergeException { alreadyAccepted = new HashSet<RevCommit>(); try { branchUpdate = db.updateRef(destBranch.get()); if (branchUpdate.getOldObjectId() != null) { branchTip = (CodeReviewCommit) rw.parseCommit(branchUpdate.getOldObjectId()); alreadyAccepted.add(branchTip); } else { branchTip = null; } for (final Ref r : db.getAllRefs().values()) { <START> if ((r.getName().startsWith(Constants.R_HEADS) && r.getName().startsWith(destBranch.get())) <END> || r.getName().startsWith(Constants.R_TAGS)) { try { alreadyAccepted.add(rw.parseCommit(r.getObjectId())); } catch (IncorrectObjectTypeException iote) { } } } } catch (IOException e) { throw new MergeException("Cannot open branch", e); } }</code><technical_language>trolling branches this point, branch effectively mark other branches' commit history unacceptable dependancies contained missing. long assume dependancies in destination branch, reviewing a merge commit, Ok. Do allow reviewing a merge commit</technical_language>

Target:
private void openBranch() throws MergeException { try { branchUpdate = db.updateRef(destBranch.get()); if (branchUpdate.getOldObjectId() != null) { branchTip = (CodeReviewCommit) rw.parseCommit(branchUpdate.getOldObjectId()); } else { branchTip = null; } } catch (IOException e) { throw new MergeException("Cannot open branch", e); } }
Source:
<code>public List<IBaseResource> getResources(final int theFromIndex, final int theToIndex) { TransactionTemplate template = new TransactionTemplate(myTxManager); template.execute(new TransactionCallbackWithoutResult() { @Override <START> protected void doInTransactionWithoutResult(@NotNull TransactionStatus theStatus) { <END> boolean entityLoaded = ensureSearchEntityLoaded(); assert entityLoaded; } }); assert mySearchEntity != null; assert mySearchEntity.getSearchType() != null; switch (mySearchEntity.getSearchType()) { case HISTORY: return template.execute(theStatus -> doHistoryInTransaction(theFromIndex, theToIndex)); case SEARCH: case EVERYTHING: default: List<IBaseResource> retVal = doSearchOrEverything(theFromIndex, theToIndex); if (retVal.size() < theToIndex - theFromIndex) { mySearchEntity = null; } return retVal; } }</code><technical_language>lambda</technical_language>

Target:
public List<IBaseResource> getResources(final int theFromIndex, final int theToIndex) { TransactionTemplate template = new TransactionTemplate(myTxManager); template.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) { boolean entityLoaded = ensureSearchEntityLoaded(); assert entityLoaded; } }); assert mySearchEntity != null; assert mySearchEntity.getSearchType() != null; switch (mySearchEntity.getSearchType()) { case HISTORY: return template.execute(theStatus -> doHistoryInTransaction(theFromIndex, theToIndex)); case SEARCH: case EVERYTHING: default: List<IBaseResource> retVal = doSearchOrEverything(theFromIndex, theToIndex); if (retVal.size() < theToIndex - theFromIndex) { mySearchEntity = null; } return retVal; } }
Source:
<code>public void testFilteringStream() { final Stream<String> stream = Stream.of("1", "2", "3"); Expression expression = handler.getExpressionParser().parseExpression("filterObject ne '2'"); EvaluationContext context = handler.createEvaluationContext(authentication, methodInvocation); Object filtered = handler.filter(stream, expression, context); <START> Assert.assertTrue("response was wrong type", Stream.class.isAssignableFrom(filtered.getClass())); <END> List<String> list = ((Stream<String>) filtered).collect(Collectors.toList()); Assert.assertEquals(2, list.size()); Assert.assertFalse("contains filtered element", list.contains("2")); }</code><technical_language>nice if a static import for Assert</technical_language>

Target:
public void testFilteringStream() { final Stream<String> stream = Stream.of("1", "2", "3"); Expression expression = handler.getExpressionParser().parseExpression("filterObject ne '2'"); EvaluationContext context = handler.createEvaluationContext(authentication, methodInvocation); Object filtered = handler.filter(stream, expression, context); assertThat(filtered).isInstanceOf(Stream.class); List<String> list = ((Stream<String>) filtered).collect(Collectors.toList()); assertThat(list).containsExactly("1", "3"); }
Source:
<code>public Object resolve(Class type) { if (type == Configurator.class) { return configurator; } else if (type == ILogger.class) { return logger; } else if (type == ITimer.class) { return new TimerImpl(); } else if (type == ISpicePlugin.class) { return spicePluginProvider.get(); } else if (type == ISpiceNative.class) { <START> return attachRestApiSessionIdHandler(spiceNativeProvider.get()); <END> } else if (type == ISpiceHtml5.class) { return spiceHtml5Provider.get(); } else if (type == IRdpPlugin.class) { return rdpPluginProvider.get(); } else if (type == IRdpNative.class) { return rdpNativeProvider.get(); } else if (type == INoVnc.class) { return noVncProvider.get(); } else if (type == IVncNative.class) { return attachRestApiSessionIdHandler(vncNativeProvider.get()); } else if (type == ConsoleOptionsFrontendPersister.class) { return consoleOptionsFrontendPersister; } else if (type == ConsoleUtils.class) { return consoleUtils; } else if (type == ErrorPopupManager.class) { return errorPopupManager; } else if (type == CurrentUserRole.class) { return currentUserRole; } throw new RuntimeException("UiCommon Resolver cannot resolve type: " + type); }</code><technical_language>order of events is correct RestApiSessionAcquiredEvent fired specific impl get it. UiCommonDefaultTypeResolver listen event set impls</technical_language>

Target:
public Object resolve(Class type) { if (type == Configurator.class) { return configurator; } else if (type == ILogger.class) { return logger; } else if (type == ITimer.class) { return new TimerImpl(); } else if (type == ISpicePlugin.class) { return spicePluginProvider.get(); } else if (type == ISpiceNative.class) { return withSessionId(spiceNativeProvider.get()); } else if (type == ISpiceHtml5.class) { return spiceHtml5Provider.get(); } else if (type == IRdpPlugin.class) { return rdpPluginProvider.get(); } else if (type == IRdpNative.class) { return rdpNativeProvider.get(); } else if (type == INoVnc.class) { return noVncProvider.get(); } else if (type == IVncNative.class) { return withSessionId(vncNativeProvider.get()); } else if (type == ConsoleOptionsFrontendPersister.class) { return consoleOptionsFrontendPersister; } else if (type == ConsoleUtils.class) { return consoleUtils; } else if (type == ErrorPopupManager.class) { return errorPopupManager; } else if (type == CurrentUserRole.class) { return currentUserRole; } throw new RuntimeException("UiCommon Resolver cannot resolve type: " + type); }
Source:
<code>public void visitFunctionDef(FunctionDef functionDef) { FunctionSymbol functionSymbol = ((FunctionDefImpl) functionDef).functionSymbol(); ParameterList parameters = functionDef.parameters(); <START> if (functionSymbol != null && functionSymbol.is(Symbol.Kind.FUNCTION) && parameters != null) { <END> FunctionSymbolImpl functionSymbolImpl = (FunctionSymbolImpl) functionSymbol; functionSymbolImpl.setParametersWithType(parameters); } super.visitFunctionDef(functionDef); }</code><technical_language>I functionSymbol.is(Symbol.Kind.FUNCTION) necessary</technical_language>

Target:
public void visitFunctionDef(FunctionDef functionDef) { FunctionSymbol functionSymbol = ((FunctionDefImpl) functionDef).functionSymbol(); ParameterList parameters = functionDef.parameters(); if (functionSymbol != null && parameters != null) { FunctionSymbolImpl functionSymbolImpl = (FunctionSymbolImpl) functionSymbol; functionSymbolImpl.setParametersWithType(parameters); } super.visitFunctionDef(functionDef); }
Source:
<code>protected boolean validate() { boolean returnValue = super.validate() && checkStorageDomain() && (getStorageDomain().getStorageDomainSharedStatus() == StorageDomainSharedStatus.Unattached || checkStorageDomainStatusNotEqual(StorageDomainStatus.Active)); if (returnValue && getStorageDomain().getStorageDomainType() == StorageDomainType.Master && isAttachedStorageDomain()) { if <START> (!isLastStorageInPool() <END> && electNewMaster() == null) { returnValue = false; addValidationMessage(EngineMessage.ERROR_CANNOT_DESTROY_LAST_STORAGE_DOMAIN); } else if (!isLastStorageInPool() && !initializeVds()) { returnValue = false; addValidationMessage(EngineMessage.ERROR_CANNOT_DESTROY_LAST_STORAGE_DOMAIN_HOST_NOT_ACTIVE); } } if (returnValue && getStorageDomain().getStorageType() == StorageType.GLANCE) { addValidationMessage(EngineMessage.ERROR_CANNOT_MANAGE_STORAGE_DOMAIN); returnValue = false; } return returnValue; }</code><technical_language>please extract</technical_language>

Target:
protected boolean validate() { boolean returnValue = super.validate() && checkStorageDomain() && (getStorageDomain().getStorageDomainSharedStatus() == StorageDomainSharedStatus.Unattached || checkStorageDomainStatusNotEqual(StorageDomainStatus.Active)); if (returnValue && getStorageDomain().getStorageDomainType() == StorageDomainType.Master && isAttachedStorageDomain() && !isLastStorageInPool()) { if (electNewMaster() == null) { returnValue = false; addValidationMessage(EngineMessage.ERROR_CANNOT_DESTROY_LAST_STORAGE_DOMAIN); } else if (!initializeVds()) { returnValue = false; addValidationMessage(EngineMessage.ERROR_CANNOT_DESTROY_LAST_STORAGE_DOMAIN_HOST_NOT_ACTIVE); } } if (returnValue && getStorageDomain().getStorageType() == StorageType.GLANCE) { addValidationMessage(EngineMessage.ERROR_CANNOT_MANAGE_STORAGE_DOMAIN); returnValue = false; } return returnValue; }
Source:
<code><START> public void readInternal(long position, byte[] buffer, int bufferOffset, int bufferLength) <END> { try { long start = System.nanoTime(); inputStream.readFully(position, buffer, bufferOffset, bufferLength); stats.readDataBytesPerSecond(bufferLength, System.nanoTime() - start); } catch (PrestoException e) { throw e; } catch (Exception e) { throw new PrestoException(HIVE_FILESYSTEM_ERROR, format("Error reading from %s at position %s", getId(), position), e); } }</code><technical_language>public? visible for testing? protected</technical_language>

Target:
protected void readInternal(long position, byte[] buffer, int bufferOffset, int bufferLength) { try { long start = System.nanoTime(); inputStream.readFully(position, buffer, bufferOffset, bufferLength); stats.readDataBytesPerSecond(bufferLength, System.nanoTime() - start); } catch (PrestoException e) { throw e; } catch (Exception e) { throw new PrestoException(HIVE_FILESYSTEM_ERROR, format("Error reading from %s at position %s", getId(), position), e); } }
Source:
<code>public void testClientTagsBasedSelection() throws InterruptedException { assertResourceGroupWithClientTags(ImmutableSet.of("tag1"), new ResourceGroupId(ImmutableList.of("global", "bi-user"))); <START> assertResourceGroupWithClientTags(ImmutableSet.of("tag1", "tag2"), new ResourceGroupId(ImmutableList.of("global", "user-user", "adhoc-user"))); <END> }</code><technical_language>If tests this is common create a helper (minor suggestion)</technical_language>

Target:
public void testClientTagsBasedSelection() throws InterruptedException { assertResourceGroupWithClientTags(ImmutableSet.of("tag1"), createResourceGroupId("global", "bi-user")); assertResourceGroupWithClientTags(ImmutableSet.of("tag1", "tag2"), createResourceGroupId("global", "user-user", "adhoc-user")); }
Source:
<code>private TableResult buildDescribeResult(TableSchema schema) { Map<String, String> fieldToWatermark = schema.getWatermarkSpecs() .stream() .collect(Collectors.toMap(WatermarkSpec::getRowtimeAttribute, WatermarkSpec::getWatermarkExpr)); Map<String, String> fieldToPrimaryKey = new HashMap<>(); schema.getPrimaryKey().ifPresent((p) -> { List<String> columns = p.getColumns(); columns.forEach((c) -> fieldToPrimaryKey.put(c, String.format("PRI(%s)", String.join(",", columns)))); }); Object[][] rows = schema.getTableColumns() .stream() .map((c) -> { LogicalType logicalType = c.getType().getLogicalType(); return new Object[]{ c.getName(), StringUtils.removeEnd(logicalType.toString(), " NOT NULL"), logicalType.isNullable(), fieldToPrimaryKey.getOrDefault(c.getName(), null), c.getExpr().orElse(null), fieldToWatermark.getOrDefault(c.getName(), null)}; }).toArray(Object[][]::new); return buildResult( <START> new String[]{"name", "type", "null", "key", "compute column", "watermark"}, <END> new DataType[]{DataTypes.STRING(), DataTypes.STRING(), DataTypes.BOOLEAN(), DataTypes.STRING(), DataTypes.STRING(), DataTypes.STRING()}, rows); }</code><technical_language>computed column</technical_language>

Target:
private TableResult buildDescribeResult(TableSchema schema) { Map<String, String> fieldToWatermark = schema.getWatermarkSpecs() .stream() .collect(Collectors.toMap(WatermarkSpec::getRowtimeAttribute, WatermarkSpec::getWatermarkExpr)); Map<String, String> fieldToPrimaryKey = new HashMap<>(); schema.getPrimaryKey().ifPresent((p) -> { List<String> columns = p.getColumns(); columns.forEach((c) -> fieldToPrimaryKey.put(c, String.format("PRI(%s)", String.join(", ", columns)))); }); Object[][] rows = schema.getTableColumns() .stream() .map((c) -> { LogicalType logicalType = c.getType().getLogicalType(); return new Object[]{ c.getName(), StringUtils.removeEnd(logicalType.toString(), " NOT NULL"), logicalType.isNullable(), fieldToPrimaryKey.getOrDefault(c.getName(), null), c.getExpr().orElse(null), fieldToWatermark.getOrDefault(c.getName(), null)}; }).toArray(Object[][]::new); return buildResult( new String[]{"name", "type", "null", "key", "computed column", "watermark"}, new DataType[]{DataTypes.STRING(), DataTypes.STRING(), DataTypes.BOOLEAN(), DataTypes.STRING(), DataTypes.STRING(), DataTypes.STRING()}, rows); }
Source:
<code>public void testSkipAndEnable() throws Exception { Files.createDirectories(projectDir); addWorkflow(projectDir, "acceptance/schedule/daily10.dig", "daily10.dig"); addWorkflow(projectDir, "acceptance/schedule/hourly9.dig", "hourly9.dig"); Id projectId = pushProject(server.endpoint(), projectDir); RestSchedule daily = client.getSchedule(projectId, "daily10"); RestSchedule hourly = client.getSchedule(projectId, "hourly9"); Optional<String> skipToTime = Optional.of("2291-02-09T00:01:00Z"); { client.disableSchedule(daily.getId()); client.enableSchedule(daily.getId(), true, skipToTime); <START> RestSchedule enabled1 = client.getSchedule(daily.getId()); <END> assertThat(enabled1.getDisabledAt(), is(Optional.absent())); assertThat(enabled1.getNextRunTime(), is(Instant.parse("2291-02-09T10:00:00Z"))); assertThat(enabled1.getNextScheduleTime(), is(OffsetDateTime.parse("2291-02-09T00:00Z"))); } { client.disableSchedule(hourly.getId()); client.enableSchedule(hourly.getId(), true, skipToTime); RestSchedule enabled2 = client.getSchedule(hourly.getId()); assertThat(enabled2.getDisabledAt(), is(Optional.absent())); assertThat(enabled2.getNextRunTime(), is(Instant.parse("2291-02-09T00:09:00Z"))); assertThat(enabled2.getNextScheduleTime(), is(OffsetDateTime.parse("2291-02-09T00:00Z"))); } }</code><technical_language>do rename this? enabled isolated in this local scope conflict</technical_language>

Target:
public void testSkipAndEnable() throws Exception { Files.createDirectories(projectDir); addWorkflow(projectDir, "acceptance/schedule/daily10.dig", "daily10.dig"); addWorkflow(projectDir, "acceptance/schedule/hourly9.dig", "hourly9.dig"); Id projectId = pushProject(server.endpoint(), projectDir); RestSchedule daily = client.getSchedule(projectId, "daily10"); RestSchedule hourly = client.getSchedule(projectId, "hourly9"); Optional<String> skipToTime = Optional.of("2291-02-09T00:01:00Z"); { client.disableSchedule(daily.getId()); client.enableSchedule(daily.getId(), true, skipToTime); RestSchedule enabled = client.getSchedule(daily.getId()); assertThat(enabled.getDisabledAt(), is(Optional.absent())); assertThat(enabled.getNextRunTime(), is(Instant.parse("2291-02-09T10:00:00Z"))); assertThat(enabled.getNextScheduleTime(), is(OffsetDateTime.parse("2291-02-09T00:00Z"))); } { client.disableSchedule(hourly.getId()); client.enableSchedule(hourly.getId(), true, skipToTime); RestSchedule enabled = client.getSchedule(hourly.getId()); assertThat(enabled.getDisabledAt(), is(Optional.absent())); assertThat(enabled.getNextRunTime(), is(Instant.parse("2291-02-09T00:09:00Z"))); assertThat(enabled.getNextScheduleTime(), is(OffsetDateTime.parse("2291-02-09T00:00Z"))); } }
Source:
<code>protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { ByteBuf payloadAndCrc = (ByteBuf) super.decode(ctx, in); assert header != null; if (payloadAndCrc == null) { <START> return null; <END> } else { Segment segment = segmentCodec.decode(header, payloadAndCrc); header = null; return segment; } }</code><technical_language>suggestion header = null; return null; I need null out header in cases input buffer enough readable bytes decode full payload. is, next time super.decode is called hits assertion in getUnadjustedFrameLength</technical_language>

Target:
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { try { ByteBuf payloadAndCrc = (ByteBuf) super.decode(ctx, in); if (payloadAndCrc == null) { return null; } else { assert header != null; Segment segment = segmentCodec.decode(header, payloadAndCrc); header = null; return segment; } } catch (Exception e) { header = null; throw e; } }
Source:
<code>private int getDialogDisplayTime(PortletPreferences prefs, int timeout) { String dialogTimeStr = prefs.getValue("dialogDisplayTime", "60"); int time = DEFAULT_DIALOG_TIME; try { time = Integer.parseInt(dialogTimeStr); } catch (NumberFormatException e) { <START> logger.debug("Invalid dialogDisplayTime preference: {0}, using default of 60s", dialogTimeStr); <END> return DEFAULT_DIALOG_TIME; } if (time >= timeout) { logger.debug("Invalid dialogDisplayTime preference: {0}. Time can not exceed session timeout. Using default", dialogTimeStr); return DEFAULT_DIALOG_TIME; } return time; }</code><technical_language>I suggest warn level this error condition of administrator wish aware (an intended configuration is honored), more verbose diagnostics for understanding system is operating. message get default logs DEFAULT_DIALOG_TIME hard-coding 60s in message values diverge</technical_language>

Target:
private int getDialogDisplayTime(PortletPreferences prefs, int timeout) { String dialogTimeStr = prefs.getValue(PREF_DIALOG_DISPLAY_SECONDS, Integer.toString(DEFAULT_DIALOG_DISPLAY_SECONDS)); int time = DEFAULT_DIALOG_DISPLAY_SECONDS; try { time = Integer.parseInt(dialogTimeStr); } catch (NumberFormatException e) { logger.warn("Invalid dialogDisplayTime preference: {0}, using default of {1}s", dialogTimeStr, DEFAULT_DIALOG_DISPLAY_SECONDS); return DEFAULT_DIALOG_DISPLAY_SECONDS; } if (time >= timeout) { logger.warn("Invalid dialogDisplayTime preference: {0}. Time can not exceed session timeout. Using session timeout value", dialogTimeStr); return timeout; } return time; }