auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void partDeactivated(IWorkbenchPart part) { if ((part == AbstractTimeGraphView.this) && (fFindHandlerActivation != null)) { final Object service = PlatformUI.getWorkbench().getService(IHandlerService.class); ((IHandlerService) service).deactivateHandler(fFindHandlerActivation); } }

Target:
public void partDeactivated(IWorkbenchPart part) { if ((part == AbstractTimeGraphView.this) && (fFindHandlerActivation != null)) { final Object service = PlatformUI.getWorkbench().getService(IHandlerService.class); ((IHandlerService) service).deactivateHandler(fFindHandlerActivation); fFindHandlerActivation = null; } }
Source:
protected Object readArray(Object old, Schema expected, ResolvingDecoder in) throws IOException { Schema expectedType = expected.getElementType(); long l = in.readArrayStart(); if (l <= 0) { return newArray(old, 0, expected); } Object array = newArray(old, (int) l, expected); if (array instanceof Collection) { @SuppressWarnings("unchecked") Collection<Object> c = (Collection<Object>) array; return readCollection(c, expectedType, l, in); } else if (array instanceof Map && ReflectData.isMapWithNonStringKeysSchema(expected)) { Collection<Object> c = new ArrayList<Object> (); readCollection(c, expectedType, l, in); Map m = (Map)array; for (Object ele: c) { IndexedRecord rec = ((IndexedRecord)ele); Object key = rec.get(ReflectData.NS_MAP_KEY_INDEX); Object value = rec.get(ReflectData.NS_MAP_VALUE_INDEX); m.put (key, value); } return array; } else { return readJavaArray(array, expectedType, l, in); } }

Target:
protected Object readArray(Object old, Schema expected, ResolvingDecoder in) throws IOException { Schema expectedType = expected.getElementType(); long l = in.readArrayStart(); if (l <= 0) { return newArray(old, 0, expected); } Object array = newArray(old, (int) l, expected); if (array instanceof Collection) { @SuppressWarnings("unchecked") Collection<Object> c = (Collection<Object>) array; return readCollection(c, expectedType, l, in); } else if (array instanceof Map) { if (ReflectData.isNonStringMapSchema(expected)) { Collection<Object> c = new ArrayList<Object> (); readCollection(c, expectedType, l, in); Map m = (Map)array; for (Object ele: c) { IndexedRecord rec = ((IndexedRecord)ele); Object key = rec.get(ReflectData.NS_MAP_KEY_INDEX); Object value = rec.get(ReflectData.NS_MAP_VALUE_INDEX); m.put (key, value); } return array; } else { String msg = "Expected a schema of map with non-string keys but got " + expected; throw new AvroRuntimeException(msg); } } else { return readJavaArray(array, expectedType, l, in); } }
Source:
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_angular_foundation_tooltip_with_$_ms_delay_for_element_$_with_attribute_$_and_value_$(251, "span", "class", "has-tip" ); then().an_element_with_a_$_class_exists( "has-tip" ) .and().attribute_$_has_value_$( "tooltip-html-unsafe", expectedDescription ); }

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:
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); final String fullMessage = messageOnRetry == null ? 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); }

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:
public String getLocationPrefix(Location location) { if (location != null) { for (Object ob : location.getActiveAttributes().toArray()) { 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()); }

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:
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); if (authenticationSession != null && authenticationSession.getClientNote(Constants.KC_ACTION_EXECUTING) != null) { attributes.put("isAppInitiatedAction", true); } handleMessages(locale, messagesBundle); UriBuilder uriBuilder = prepareBaseUriBuilder(false); createCommonAttributes(theme, locale, messagesBundle, uriBuilder, null); return processTemplate(theme, form, locale); }

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:
public boolean equals(final Object other) { if(other instanceof EventQueryNode) { 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; }

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:
public boolean cancel(boolean mayInterruptIfRunning) { command.cancel(); latch.countDown(); return super.cancel(mayInterruptIfRunning); }

Target:
public boolean cancel(boolean mayInterruptIfRunning) { try { command.cancel(); return super.cancel(mayInterruptIfRunning); } finally { latch.countDown(); } }
Source:
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) { unselect(indexOf(item.getText())); } } }); }

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:
public static JBossProduct getKnownProductByProductName(String productName) { for (JBossProduct product : KNOWN_PRODUCTS.values()) { if (product.PRODUCT_NAME.equals(productName)) { return product; } } LOG.debug("No product type with product-name '" + productName + "' is known. returning UNKNOWN"); return JBossProduct.unknown(); }

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:
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 { ((BaseFragmentActivity)getActivity()).showInfoMessage(getString(R.string.discussion_comment_posted)); courseDiscussionResponsesAdapter.addNewComment(event.getParent()); } } }

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:
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"), cast(k(22), LONG).alias("long")); 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()); }

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:
private void initUI() { VBox milestoneDialogBox = createMilestoneDialogBox(); assignedMilestonePane = createAssignedMilestoneBox(); matchingMilestonesPane = createMatchingMilestonesBox(); inputField = createInputField(); milestoneDialogBox.getChildren().add(assignedMilestonePane); milestoneDialogBox.getChildren().add(inputField); milestoneDialogBox.getChildren().add(matchingMilestonesPane); getDialogPane().setContent(milestoneDialogBox); refreshUI(state); Platform.runLater(inputField::requestFocus); }

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:
void verifyCorrectOpCode( final int opCode, @AggregateWith(MethodAggregator.class) final Method method) { final var remoteActionCode = method.getAnnotation(RemoteActionCode.class); assertThat("No annotation present for " + method, remoteActionCode, is(notNullValue())); assertThat("Invalid value for " + method, remoteActionCode.value(), is(opCode)); }

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:
public boolean poll(MessageHandler handler) throws MessageHandlingException { Message<?> message = this.source.receive(); AcknowledgmentCallback acknowledgmentCallback = StaticMessageHeaderAccessor.getAcknowledgmentCallback(message); if (message != null) { 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; }

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:
public Unit(Sector currentLocation, Faction faction, String shipname) { side = faction; unitName = shipname; this.currentLocation = currentLocation; course = new ArrayDeque<Cood>(); }

Target:
public Unit(Sector currentLocation, Faction faction, String shipname) { side = faction; unitName = shipname; this.currentLocation = currentLocation; course = new ArrayDeque<Coordinates>(); }
Source:
@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")); assertAbout(javaSource()).that(source) .processedWith(processors()) .compilesWithoutError() .and() .generatesSources(expectedSource); }

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:
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) { mediationBannerListener.onAdOpened(FyberMediationAdapter.this); } @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; }

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:
private void addAttributes(Map<String, Object> parameters, Map<String, Object> parsedParameters, String paramPrefix) { HashMap<String, String> nodes = (HashMap<String, String>) parameters.get(ATTRIBUTES); for (String key : nodes.keySet()) { String attr = nodes.get(key); parsedParameters.put(paramPrefix + "/@" + key, attr); } }

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:
public void createWithNegativeIterations() throws Exception { class Callback implements RateController.Callback { @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); }

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:
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)); if (!file.exists() || !file.canRead()) { 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; }

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:
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) { logger.error("Error while inserting bindings", e); } }

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:
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()); }

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:
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()) { if ((r.getName().startsWith(Constants.R_HEADS) && r.getName().startsWith(destBranch.get())) || 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); } }

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:
public List<IBaseResource> getResources(final int theFromIndex, final int theToIndex) { TransactionTemplate template = new TransactionTemplate(myTxManager); template.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(@NotNull 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; } }

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:
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); Assert.assertTrue("response was wrong type", Stream.class.isAssignableFrom(filtered.getClass())); List<String> list = ((Stream<String>) filtered).collect(Collectors.toList()); Assert.assertEquals(2, list.size()); Assert.assertFalse("contains filtered element", list.contains("2")); }

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:
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 attachRestApiSessionIdHandler(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 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); }

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:
public void visitFunctionDef(FunctionDef functionDef) { FunctionSymbol functionSymbol = ((FunctionDefImpl) functionDef).functionSymbol(); ParameterList parameters = functionDef.parameters(); if (functionSymbol != null && functionSymbol.is(Symbol.Kind.FUNCTION) && parameters != null) { FunctionSymbolImpl functionSymbolImpl = (FunctionSymbolImpl) functionSymbol; functionSymbolImpl.setParametersWithType(parameters); } super.visitFunctionDef(functionDef); }

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:
protected boolean validate() { boolean returnValue = super.validate() && checkStorageDomain() && (getStorageDomain().getStorageDomainSharedStatus() == StorageDomainSharedStatus.Unattached || checkStorageDomainStatusNotEqual(StorageDomainStatus.Active)); if (returnValue && getStorageDomain().getStorageDomainType() == StorageDomainType.Master && isAttachedStorageDomain()) { if (!isLastStorageInPool() && 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; }

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:
public 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); } }

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:
public void testClientTagsBasedSelection() throws InterruptedException { assertResourceGroupWithClientTags(ImmutableSet.of("tag1"), new ResourceGroupId(ImmutableList.of("global", "bi-user"))); assertResourceGroupWithClientTags(ImmutableSet.of("tag1", "tag2"), new ResourceGroupId(ImmutableList.of("global", "user-user", "adhoc-user"))); }

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:
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", "compute column", "watermark"}, new DataType[]{DataTypes.STRING(), DataTypes.STRING(), DataTypes.BOOLEAN(), DataTypes.STRING(), DataTypes.STRING(), DataTypes.STRING()}, rows); }

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:
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 enabled1 = client.getSchedule(daily.getId()); 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"))); } }

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:
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { ByteBuf payloadAndCrc = (ByteBuf) super.decode(ctx, in); assert header != null; if (payloadAndCrc == null) { return null; } else { Segment segment = segmentCodec.decode(header, payloadAndCrc); header = null; return segment; } }

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:
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) { logger.debug("Invalid dialogDisplayTime preference: {0}, using default of 60s", dialogTimeStr); 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; }

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; }
Source:
public static boolean isValidInstance(Resource instanceResources, long minInstanceRam, Resource maxContainerResources, int paddingPercentage) { if (instanceResources.getRam() < minInstanceRam) { LOG.severe(String.format( "Instance requires %d MB ram which is less than the minimum %d MB ram per instance", instanceResources.getRam(), minInstanceRam / Constants.MB)); return false; } if (instanceResources.getRam() + (paddingPercentage * instanceResources.getRam()) / 100 > maxContainerResources.getRam()) { LOG.severe(String.format( "This instance requires containers of at least %d MB ram. The current max container" + "size is %d MB", instanceResources.getRam() + (paddingPercentage * instanceResources.getRam()) / 100, maxContainerResources.getRam())); return false; } if (Math.round(instanceResources.getCpu() + (paddingPercentage * instanceResources.getCpu()) / 100) > maxContainerResources.getCpu()) { LOG.severe(String.format( "This instance requires containers with at least %s cpu cores. The current max container" + "size is %s cores", Math.round(instanceResources.getCpu() + (paddingPercentage * instanceResources.getCpu()) / 100) > maxContainerResources.getCpu(), maxContainerResources.getCpu())); return false; } if (instanceResources.getDisk() + (paddingPercentage * instanceResources.getDisk()) / 100 > maxContainerResources.getDisk()) { LOG.severe(String.format( "This instance requires containers of at least %d MB disk. The current max container" + "size is %d MB", instanceResources.getDisk() + (paddingPercentage * instanceResources.getDisk() / 100), maxContainerResources.getDisk())); return false; } return true; }

Target:
public static boolean isValidInstance(Resource instanceResources, long minInstanceRam, Resource maxContainerResources, int paddingPercentage) { if (instanceResources.getRam() < minInstanceRam) { LOG.severe(String.format( "Instance requires %d MB ram which is less than the minimum %d MB ram per instance", instanceResources.getRam(), minInstanceRam / Constants.MB)); return false; } long instanceRam = PackingUtils.increaseBy(instanceResources.getRam(), paddingPercentage); if (instanceRam > maxContainerResources.getRam()) { LOG.severe(String.format( "This instance requires containers of at least %d MB ram. The current max container" + "size is %d MB", instanceRam, maxContainerResources.getRam())); return false; } double instanceCpu = Math.round(PackingUtils.increaseBy( instanceResources.getCpu(), paddingPercentage)); if (instanceCpu > maxContainerResources.getCpu()) { LOG.severe(String.format( "This instance requires containers with at least %s cpu cores. The current max container" + "size is %s cores", instanceCpu > maxContainerResources.getCpu(), maxContainerResources.getCpu())); return false; } long instanceDisk = PackingUtils.increaseBy(instanceResources.getDisk(), paddingPercentage); if (instanceDisk > maxContainerResources.getDisk()) { LOG.severe(String.format( "This instance requires containers of at least %d MB disk. The current max container" + "size is %d MB", instanceDisk, maxContainerResources.getDisk())); return false; } return true; }