auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ElasticsearchQueryBuilder(List<ElasticsearchColumnHandle> columnHandles, ElasticsearchConnectorConfig config, ElasticsearchSplit split) { ElasticsearchTableDescription table = split.getTable(); tupleDomain = split.getTupleDomain(); index = table.getIndex(); type = table.getType(); shard = split.getShard(); try { Settings settings = Settings.builder().put("cluster.name", table.getClusterName()).build(); client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(split.getSearchNode()), table.getPort())); } catch (IOException e) { <START> throw new PrestoException(ELASTIC_SEARCH_CLIENT_ERROR, e); <END> } columns = columnHandles; scrollTime = config.getScrollTime(); scrollSize = config.getScrollSize(); }</code><technical_language>add a message this exception</technical_language>

Target:
public ElasticsearchQueryBuilder(List<ElasticsearchColumnHandle> columnHandles, ElasticsearchConnectorConfig config, ElasticsearchSplit split) { columns = requireNonNull(columnHandles, "columnHandles is null"); requireNonNull(config, "config is null"); requireNonNull(split, "split is null"); ElasticsearchTableDescription table = split.getTable(); tupleDomain = split.getTupleDomain(); index = split.getIndex(); type = table.getType(); shard = split.getShard(); try { Settings settings = Settings.builder().put("client.transport.ignore_cluster_name", true).build(); client = new PreBuiltTransportClient(settings).addTransportAddress(new TransportAddress(InetAddress.getByName(split.getSearchNode()), split.getPort())); } catch (IOException e) { throw new PrestoException(ELASTIC_SEARCH_CONNECTION_ERROR, "Error connecting to Elasticsearch SearchNode: " + split.getSearchNode() + " with port: " + split.getPort(), e); } scrollTimeout = config.getScrollTimeout(); scrollSize = config.getScrollSize(); }
Source:
<code>public void onActivityResult(int requestCode, int resultCode, final Intent data) { if (settingsActivityRequested(requestCode)) { handleSettingsActivityResult(resultCode); } else if (newArticleLanguageSelected(requestCode, resultCode) || galleryPageSelected(requestCode, resultCode)) { handleLangLinkOrPageResult(data); } else if (requestCode == Constants.ACTIVITY_REQUEST_BROWSE_TABS) { if (app.getTabCount() == 0 && resultCode != TabActivity.RESULT_NEW_TAB) { finish(); return; } if (resultCode == TabActivity.RESULT_NEW_TAB) { loadMainPage(TabPosition.NEW_TAB_FOREGROUND); animateTabsButton(); } else if (resultCode == TabActivity.RESULT_LOAD_FROM_BACKSTACK) { pageFragment.reloadFromBackstack(); } } else if (requestCode == Constants.ACTIVITY_REQUEST_IMAGE_CAPTION_EDIT && resultCode == RESULT_OK) { pageFragment.refreshPage(); FeedbackUtil.makeSnackbar(this, TextUtils.isEmpty(pageFragment.getLeadImageEditLang()) ? getString(R.string.description_edit_success_saved_image_caption_snackbar) <START> : getString(R.string.description_edit_success_saved_image_caption_in_lang_snackbar, app.language().getAppLanguageLocalizedName(StringUtils.defaultString(pageFragment.getLeadImageEditLang(), app.language().getAppLanguageCodes().get(0)))), FeedbackUtil.LENGTH_DEFAULT) <END> .setAction(R.string.suggested_edits_article_cta_snackbar_action, v -> pageFragment.showLeadImageInGallery()).show(); } else { super.onActivityResult(requestCode, resultCode, data); } }</code><technical_language>Is app.language().getAppLanguageCode() instead of app.language().getAppLanguageCodes().get(0)</technical_language>

Target:
public void onActivityResult(int requestCode, int resultCode, final Intent data) { if (settingsActivityRequested(requestCode)) { handleSettingsActivityResult(resultCode); } else if (newArticleLanguageSelected(requestCode, resultCode) || galleryPageSelected(requestCode, resultCode)) { handleLangLinkOrPageResult(data); } else if (requestCode == Constants.ACTIVITY_REQUEST_BROWSE_TABS) { if (app.getTabCount() == 0 && resultCode != TabActivity.RESULT_NEW_TAB) { finish(); return; } if (resultCode == TabActivity.RESULT_NEW_TAB) { loadMainPage(TabPosition.NEW_TAB_FOREGROUND); animateTabsButton(); } else if (resultCode == TabActivity.RESULT_LOAD_FROM_BACKSTACK) { pageFragment.reloadFromBackstack(); } } else if (requestCode == Constants.ACTIVITY_REQUEST_IMAGE_CAPTION_EDIT && resultCode == RESULT_OK) { pageFragment.refreshPage(); FeedbackUtil.makeSnackbar(this, TextUtils.isEmpty(pageFragment.getLeadImageEditLang()) ? getString(R.string.description_edit_success_saved_image_caption_snackbar) : getString(R.string.description_edit_success_saved_image_caption_in_lang_snackbar, app.language().getAppLanguageLocalizedName(StringUtils.defaultString(pageFragment.getLeadImageEditLang(), app.language().getAppLanguageCode()))), FeedbackUtil.LENGTH_DEFAULT) .setAction(R.string.suggested_edits_article_cta_snackbar_action, v -> pageFragment.openImageInGallery()).show(); } else { super.onActivityResult(requestCode, resultCode, data); } }
Source:
<code>public void afterCommit(final Transaction tx) { for (MessageReference ref : refsToAck) { queue.postAcknowledge(ref); } if (pagedMessagesToPostACK != null) { for (MessageReference refmsg : pagedMessagesToPostACK) { if (((PagedReference) refmsg).isLargeMessage()) { <START> decrementRefCount(refmsg); <END> } } } }</code><technical_language>I agree right of for large messages. if this out I a concerned introducing a future bug if other message types end relying this in future</technical_language>

Target:
public void afterCommit(final Transaction tx) { for (MessageReference ref : refsToAck) { synchronized (ref.getQueue()) { queue.postAcknowledge(ref); } } if (pagedMessagesToPostACK != null) { for (MessageReference refmsg : pagedMessagesToPostACK) { if (((PagedReference) refmsg).isLargeMessage()) { decrementRefCount(refmsg); } } } }
Source:
<code>@Override public CodeBlock render(int sdk) { <START> if (tintAttributeId.value != -1) { <END> return CodeBlock.of("target.$L = $T.getTintedDrawable(context, $L, $L)", name, UTILS, id.code, tintAttributeId.code); } if (sdk >= 21) { return CodeBlock.of("target.$L = context.getDrawable($L)", name, id.code); } return CodeBlock.of("target.$L = $T.getDrawable(context, $L)", name, CONTEXT_COMPAT, id.code); }</code><technical_language>this -1 is kind of a magic number. clear this class -1. a NO_ID constant in BindDrawable</technical_language>

Target:
@Override public CodeBlock render(int sdk) { if (tintAttributeId.value != NO_RES_ID) { return CodeBlock.of("target.$L = $T.getTintedDrawable(context, $L, $L)", name, UTILS, id.code, tintAttributeId.code); } if (sdk >= 21) { return CodeBlock.of("target.$L = context.getDrawable($L)", name, id.code); } return CodeBlock.of("target.$L = $T.getDrawable(context, $L)", name, CONTEXT_COMPAT, id.code); }
Source:
<code>public MedicationRequest updateFHIRMedicationRequest(MedicationRequest medicationRequest, String uuid) { List<String> errors = new ArrayList<String>(); DrugOrder requestDrugOrder = FHIRMedicationRequestUtil.generateDrugOrder(medicationRequest, errors); DrugOrder generatedDrugOrder = (DrugOrder) Context.getOrderService().getOrderByUuid(uuid); FHIRMedicationRequestUtil.copyObsAttributes(requestDrugOrder, generatedDrugOrder, errors); if (generatedDrugOrder != null) { if (!errors.isEmpty()) { StringBuilder errorMessage = new StringBuilder("The request cannot be processed due to the following issues \n"); for (int i = 0; i < errors.size(); i++) { errorMessage.append((i + 1) + " : " + errors.get(i) + "\n"); } throw new UnprocessableEntityException(errorMessage.toString()); } requestDrugOrder = (DrugOrder) Context.getOrderService().saveOrder(generatedDrugOrder, null); return FHIRMedicationRequestUtil.generateMedicationRequest(requestDrugOrder); } else { <START> if (medicationRequest.getId() == null) { END> IdType id = new IdType(); id.setValue(uuid); medicationRequest.setId(uuid); } return createFHIRMedicationRequest(medicationRequest); } }</code><technical_language>correct commnet</technical_language>

Target:
public MedicationRequest updateFHIRMedicationRequest(MedicationRequest medicationRequest, String uuid) { List<String> errors = new ArrayList<String>(); DrugOrder incomingDrugOrder = FHIRMedicationRequestUtil.generateDrugOrder(medicationRequest, errors); DrugOrder generatedDrugOrder = (DrugOrder) Context.getOrderService().getOrderByUuid(uuid); FHIRMedicationRequestUtil.copyObsAttributes(incomingDrugOrder, generatedDrugOrder, errors); if (generatedDrugOrder != null) { if (!errors.isEmpty()) { StringBuilder errorMessage = new StringBuilder("The request cannot be processed due to the " + "following issues \n"); for (int i = 0; i < errors.size(); i++) { errorMessage.append((i + 1) + " : " + errors.get(i) + "\n"); } throw new UnprocessableEntityException(errorMessage.toString()); } incomingDrugOrder = (DrugOrder) Context.getOrderService().saveOrder(generatedDrugOrder, null); return FHIRMedicationRequestUtil.generateMedicationRequest(incomingDrugOrder); } else { if (medicationRequest.getId() == null) { IdType id = new IdType(); id.setValue(uuid); medicationRequest.setId(uuid); } return createFHIRMedicationRequest(medicationRequest); } }
Source:
<code>public void participantJoined(String identifier) { if (this.participants.containsKey(identifier)) { Participant participant = participants.get(identifier); participant.joined(); TranscriptEvent event = transcript.notifyJoined(participant); if (event != null) { fireTranscribeEvent(event); } if (logger.isDebugEnabled()) logger.debug( <START> "Removed participant with identifier " + identifier); <END> return; } logger.warn("Participant with identifier " + identifier + " joined while it did not exist"); }</code><technical_language>removed</technical_language>

Target:
public void participantJoined(String identifier) { Participant participant = getParticipant(identifier); if (participant != null) { participant.joined(); TranscriptEvent event = transcript.notifyJoined(participant); if (event != null) { fireTranscribeEvent(event); } if (logger.isDebugEnabled()) logger.debug( "Added participant with identifier " + identifier); return; } logger.warn("Participant with identifier " + identifier + " joined while it did not exist"); }
Source:
<code>public FixedPollingStrategy(long interval, TimeUnit units, boolean syncInit) { <START> this.executor = Executors.newSingleThreadScheduledExecutor(ThreadFactories.newNamedDaemonThreadFactory("poller-%d")); <END> this.interval = interval; this.units = units; this.syncInit = syncInit; }</code><technical_language>handy archaius in thread name is easier spot a glance realize is archaius poller a poller for else</technical_language>

Target:
public FixedPollingStrategy(long interval, TimeUnit units, boolean syncInit) { this.executor = Executors.newSingleThreadScheduledExecutor(ThreadFactories.newNamedDaemonThreadFactory("Archaius-Poller-%d")); this.interval = interval; this.units = units; this.syncInit = syncInit; }
Source:
<code>public CoreMessage putByteProperty(final String key, final byte value) { messageChanged(); <START> getOrCreateProperties().putByteProperty(key(key), value); <END> return this; }</code><technical_language>delegated as: putByteProperty(key(key), value)</technical_language>

Target:
public CoreMessage putByteProperty(final String key, final byte value) { return putByteProperty(key(key), value); }
Source:
<code>private String toSnakeAndLowerCase(String attrName) { if (attrName == null || attrName.isEmpty()) { return attrName; } char firstChar = attrName.subSequence(0, 1).charAt(0); boolean prevCharIsUpperCaseOrUnderscore = Character.isUpperCase(firstChar) || firstChar == '_'; StringBuilder resultBuilder = new StringBuilder(attrName.length()).append(Character.toLowerCase(firstChar)); for (char attrChar : attrName.substring(1).toCharArray()) { boolean charIsUpperCase = Character.isUpperCase(attrChar); <START> if (attrChar == '.') { <END> resultBuilder.append("_"); } else if (attrChar == '-') { resultBuilder.append("_"); } else { if (!prevCharIsUpperCaseOrUnderscore && charIsUpperCase) { resultBuilder.append("_"); } resultBuilder.append(Character.toLowerCase(attrChar)); } prevCharIsUpperCaseOrUnderscore = charIsUpperCase || attrChar == '_'; } return resultBuilder.toString(); }</code><technical_language>merge 2 conditions operation is in cases ( resultBuilder.append("_"); )</technical_language>

Target:
private String toSnakeAndLowerCase(String attrName) { if (attrName == null || attrName.isEmpty()) { return attrName; } char firstChar = attrName.subSequence(0, 1).charAt(0); boolean prevCharIsUpperCaseOrUnderscore = Character.isUpperCase(firstChar) || firstChar == '_'; StringBuilder resultBuilder = new StringBuilder(attrName.length()).append(Character.toLowerCase(firstChar)); for (char attrChar : attrName.substring(1).toCharArray()) { boolean charIsUpperCase = Character.isUpperCase(attrChar); if (attrChar == '.' || attrChar == '-') { resultBuilder.append("_"); } else { if (!prevCharIsUpperCaseOrUnderscore && charIsUpperCase) { resultBuilder.append("_"); } resultBuilder.append(Character.toLowerCase(attrChar)); } prevCharIsUpperCaseOrUnderscore = charIsUpperCase || attrChar == '_'; } return resultBuilder.toString(); }
Source:
<code>public MemorySubjectData(PermissionService service) { <START> this.service = service; <END> }</code><technical_language>a null check if accept null values</technical_language>

Target:
public MemorySubjectData(PermissionService service) { checkNotNull(service); this.service = service; }
Source:
<code>public Iterable<? extends NodeMetadata> listNodesByIds(Iterable<String> ids) { <START> return FluentIterable.from(listDetailsOnNodesMatching(all())).filter(withIds(Iterables.toArray(ids, String.class))).toSet(); <END> }</code><technical_language>Another static import</technical_language>

Target:
public Iterable<? extends NodeMetadata> listNodesByIds(Iterable<String> ids) { return FluentIterable.from(listDetailsOnNodesMatching(all())).filter(withIds(toArray(ids, String.class))).toSet(); }
Source:
<code>static String getFqTypeName(Class clazz) { <START> return String.format("%s.%s", PACKAGE_NAME, clazz.getSimpleName()); <END> }</code><technical_language>String concatenation (due performance difference I rarely format)</technical_language>

Target:
static String getFqTypeName(Class clazz) { return PACKAGE_NAME + "." + clazz.getSimpleName(); }
Source:
<code>public List<BundleInfo> getBundles() { List<BundleInfo> res = new ArrayList<>(bundles.values()); <START> Collections.sort(res, Comparator.comparing(BundleInfo::getId)); <END> return res; }</code><technical_language>List#sort usage</technical_language>

Target:
public List<BundleInfo> getBundles() { List<BundleInfo> res = new ArrayList<>(bundles.values()); res.sort(Comparator.comparing(BundleInfo::getId)); return res; }
Source:
<code><START> public byte[] toPubsubData() { <END> return gson.toJson(this).getBytes(); }</code><technical_language>reason com.google.pubsub.v1.PubsubMessage byte? a weird place split helper functions</technical_language>

Target:
public byte[] toPubsubData() { return gson.toJson(this).getBytes(StandardCharsets.UTF_8); }
Source:
<code>protected void autoDeployResources(ProcessEngine processEngine) { if (deploymentResources != null && deploymentResources.length > 0) { final DefaultAutoDeploymentStrategy strategy = getAutoDeploymentStrategy(deploymentMode); <START> strategy.setProcessDefinitionResources(deploymentResources); <END> strategy.setProcessExtensionResources(processExtensionResources); strategy.deployResources(deploymentName, processEngine.getRepositoryService()); } }</code><technical_language>I need change this class</technical_language>

Target:
protected void autoDeployResources(ProcessEngine processEngine) { if (deploymentResources != null && deploymentResources.length > 0) { final AutoDeploymentStrategy strategy = getAutoDeploymentStrategy(deploymentMode); strategy.deployResources(deploymentName, deploymentResources, processEngine.getRepositoryService()); } }
Source:
<code>public void finalize() { try { if (!m_memoryDeque.isEmpty()) { m_memoryDeque.stream().filter((block) -> (!block.isPersisted())).forEachOrdered((_item) -> { <START> exportLog.error("Finalized StreamBlockQueue with items in the memory deque that are not persisted."); <END> }); } } finally { try { super.finalize(); } catch (Throwable ex) { ; } } }</code><technical_language>logging count instead of message for item sufficient</technical_language>

Target:
public void finalize() { try { int nonEmptyCnt = 0; nonEmptyCnt = m_memoryDeque.stream().filter((block) -> (!block.isPersisted())).map((_item) -> 1).reduce(nonEmptyCnt, Integer::sum); if (nonEmptyCnt > 0) { exportLog.error("Finalized StreamBlockQueue with " + nonEmptyCnt + " items in the memory deque that are not persisted."); } } finally { try { super.finalize(); } catch (Throwable ex) { ; } } }
Source:
<code>public void testAbuseFilterTriggerStopOnArbitraryErrorCode() { PageTitle title = new PageTitle(null, ABUSE_FILTER_ERROR_PAGE_TITLE, TEST_WIKI_SITE); String wikitext = "== Section 2 ==\n\nTriggering AbuseFilter number 152 by saying" + "appcrashtest many times at " + System.currentTimeMillis(); service.edit(TEST_WIKI_SITE, title, DEFAULT_SECTION_ID, wikitext, ANONYMOUS_TOKEN, DEFAULT_SUMMARY, false, null, null, new Edit.Callback() { @Override public void success(@NonNull EditingResult result) { assertThat(result, instanceOf(AbuseFilterEditResult.class)); assertThat(((AbuseFilterEditResult) result).getType(), <START> is(AbuseFilterEditResult.TYPE_WARNING)); <END> } @Override public void failure(@NonNull Throwable caught) { throw new RuntimeException(caught); } }); }</code><technical_language>latch</technical_language>

Target:
public void testAbuseFilterTriggerStopOnArbitraryErrorCode() { PageTitle title = new PageTitle(null, ABUSE_FILTER_ERROR_PAGE_TITLE, TEST_WIKI_SITE); String wikitext = "== Section 2 ==\n\nTriggering AbuseFilter number 152 by saying" + "appcrashtest many times at " + System.currentTimeMillis(); final TestLatch latch = new TestLatch(); client.request(TEST_WIKI_SITE, title, DEFAULT_SECTION_ID, wikitext, ANONYMOUS_TOKEN, DEFAULT_SUMMARY, false, null, null, new EditClient.Callback() { @Override public void success(@NonNull Call<Edit> call, @NonNull EditingResult result) { assertThat(result, instanceOf(AbuseFilterEditResult.class)); assertThat(((AbuseFilterEditResult) result).getType(), is(AbuseFilterEditResult.TYPE_ERROR)); latch.countDown(); } @Override public void failure(@NonNull Call<Edit> call, @NonNull Throwable caught) { throw new RuntimeException(caught); } }); latch.await(); }
Source:
<code>void addReplicasToPartition(AmbryPartition partition, List<AmbryReplica> replicas) { AmbryPartition currentPartition = addPartitionIfAbsent(partition, replicas.get(0).getCapacityInBytes()); ambryPartitionToAmbryReplicas.compute(currentPartition, (k, v) -> { v.addAll(replicas); return v; }); clusterWideAllocatedRawCapacityBytes.getAndAdd(replicas.get(0).getCapacityInBytes() * replicas.size()); for (ClusterMapChangeListener listener : clusterMapChangeListeners) { <START> listener.onReplicaAddedOrRemoved(replicas, Collections.emptyList()); <END> } }</code><technical_language>rebasing master branch, able remove this. In #1405, clustermap change listeners called DynamicClusterChangeHandler. If additional concern, talk offline</technical_language>

Target:
void addReplicasToPartition(AmbryPartition partition, List<AmbryReplica> replicas) { AmbryPartition currentPartition = addPartitionIfAbsent(partition, replicas.get(0).getCapacityInBytes()); ambryPartitionToAmbryReplicas.compute(currentPartition, (k, v) -> { v.addAll(replicas); return v; }); clusterWideAllocatedRawCapacityBytes.getAndAdd(replicas.get(0).getCapacityInBytes() * replicas.size()); }
Source:
<code>private boolean verifyEntityTypes(Item itemToProcess, EntityType entityTypeToProcess) { <START> List<MetadataValue> list = itemService.getMetadata(itemToProcess, "relationship", "type", null, Item.ANY); <END> if (list.isEmpty()) { return false; } String leftEntityType = list.get(0).getValue(); if (!StringUtils.equals(leftEntityType, entityTypeToProcess.getLabel())) { return false; } return true; }</code><technical_language>Please MetadataSchemaEnum created in above</technical_language>

Target:
private boolean verifyEntityTypes(Item itemToProcess, EntityType entityTypeToProcess) { List<MetadataValue> list = itemService.getMetadata(itemToProcess, "relationship", "type", null, Item.ANY); if (list.isEmpty()) { return false; } String leftEntityType = list.get(0).getValue(); return StringUtils.equals(leftEntityType, entityTypeToProcess.getLabel()); }
Source:
<code>private Adapter buildAdapter(org.opennms.netmgt.telemetry.config.model.Adapter adapterDef) throws Exception { <START> final Class<?> clazz = Class.forName(adapterDef.getClassName()); <END> final Constructor<?> ctor = clazz.getConstructor(); final Object adapterInstance = ctor.newInstance(); if (!(adapterInstance instanceof Adapter)) { throw new IllegalArgumentException(String.format("%s must implement %s", adapterDef.getClassName(), Adapter.class.getCanonicalName())); } final Adapter adapter = (Adapter)adapterInstance; final BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(adapter); wrapper.setPropertyValues(adapterDef.getParameterMap()); final AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory(); beanFactory.autowireBean(adapter); beanFactory.initializeBean(adapter, "adapter"); adapter.setProtocol(protocolDef); return adapter; }</code><technical_language>above. want throw a more meaningful exception a generic "ClassNotFound"-Exception in case adapter contains a non-existing class</technical_language>

Target:
private Adapter buildAdapter(org.opennms.netmgt.telemetry.config.model.Adapter adapterDef) throws Exception { final Object adapterInstance; try { final Class<?> clazz = Class.forName(adapterDef.getClassName()); final Constructor<?> ctor = clazz.getConstructor(); adapterInstance = ctor.newInstance(); } catch (Exception e) { throw new RuntimeException(String.format("Failed to instantiate adapter with class name '%s'.", adapterDef.getClassName(), e)); } if (!(adapterInstance instanceof Adapter)) { throw new IllegalArgumentException(String.format("%s must implement %s", adapterDef.getClassName(), Adapter.class.getCanonicalName())); } final Adapter adapter = (Adapter)adapterInstance; final BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(adapter); wrapper.setPropertyValues(adapterDef.getParameterMap()); final AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory(); beanFactory.autowireBean(adapter); beanFactory.initializeBean(adapter, "adapter"); adapter.setProtocol(protocolDef); return adapter; }
Source:
<code>public void testEmptyPartitionException() { InternalAggregationFunction function = getFunction(); int partitionCount = 10; List<OGCGeometry> geometries = ImmutableList.of(); Block geometryBlock = makeGeometryBlock(geometries); <START> Block partitionCountBlock = BlockAssertions.createRLEBlock(partitionCount, geometries.size()); <END> Page page = new Page(geometryBlock, partitionCountBlock); AccumulatorFactory accumulatorFactory = function.bind(Ints.asList(0, 1, 2), Optional.empty()); Accumulator accumulator = accumulatorFactory.createAccumulator(); accumulator.addInput(page); assertThrows(PrestoException.class, () -> getFinalBlock(accumulator)); }</code><technical_language>partitionCount geometries variables needed - need makeGeometryBlock method Block geometryBlock = GEOMETRY.createBlockBuilder(null, 0).build(); Block partitionCountBlock = BlockAssertions.createRLEBlock(10, 0);</technical_language>

Target:
public void testEmptyPartitionException() { InternalAggregationFunction function = getFunction(); Block geometryBlock = GEOMETRY.createBlockBuilder(null, 0).build(); Block partitionCountBlock = BlockAssertions.createRLEBlock(10, 0); Page page = new Page(geometryBlock, partitionCountBlock); AccumulatorFactory accumulatorFactory = function.bind(Ints.asList(0, 1, 2), Optional.empty()); Accumulator accumulator = accumulatorFactory.createAccumulator(); accumulator.addInput(page); try { getFinalBlock(accumulator); fail("Should fail creating spatial partition with no rows."); } catch (PrestoException e) { assertEquals(e.getErrorCode(), INVALID_FUNCTION_ARGUMENT.toErrorCode()); assertEquals(e.getMessage(), "No rows supplied to spatial partition."); } }
Source:
<code>public ITestAzureBlobFileSystemCheckAccess() throws Exception { <START> super(); <END> super.setup(); this.superUserFs = getFileSystem(); testUserGuid = getConfiguration() .get(FS_AZURE_BLOB_FS_CHECKACCESS_TEST_USER_GUID); this.testUserFs = getTestUserFs(); isCheckAccessEnabled = getConfiguration().isCheckAccessEnabled(); }</code><technical_language>cut</technical_language>

Target:
public ITestAzureBlobFileSystemCheckAccess() throws Exception { super.setup(); this.superUserFs = getFileSystem(); testUserGuid = getConfiguration() .get(FS_AZURE_BLOB_FS_CHECKACCESS_TEST_USER_GUID); this.testUserFs = getTestUserFs(); this.isCheckAccessEnabled = getConfiguration().isCheckAccessEnabled(); this.isHNSEnabled = getConfiguration() .getBoolean(FS_AZURE_TEST_NAMESPACE_ENABLED_ACCOUNT, false); }
Source:
<code>public <T> void execute( final Callback<T> callback ) { getSession().getCanvasValidationControl().validate( new CanvasValidatorCallback() { @Override public void onSuccess() { <START> if ( null != callback ) { <END> callback.onSuccess( null ); } } @Override public void onFail( final Iterable<CanvasValidationViolation> violations ) { if ( null != callback ) { callback.onSuccess( ( T ) violations ); } } } ); }</code><technical_language>check/assert callback is null in execute instead of sweeping problem rug simply do nothing</technical_language>

Target:
public <T> void execute( final Callback<T> callback ) { checkNotNull( "callback", callback ); getSession().getCanvasValidationControl().validate( new CanvasValidatorCallback() { @Override public void onSuccess() { callback.onSuccess( null ); } @Override public void onFail( final Iterable<CanvasValidationViolation> violations ) { callback.onSuccess( ( T ) violations ); } } ); }
Source:
<code>private void addChangelogsToRestoreConsumer(final Set<TopicPartition> partitions) { final Set<TopicPartition> assignment = new HashSet<>(restoreConsumer.assignment()); if (assignment.removeAll(partitions)) { throw new IllegalStateException("The current assignment " + restoreConsumer.assignment() + " " + "already contains some of the new partitions " + partitions); } assignment.addAll(partitions); restoreConsumer.assign(assignment); <START> log.debug("Added partitions to the restore consumer, current assignment is {}", partitions, assignment); <END> }</code><technical_language>consumer log this assign(...)</technical_language>

Target:
private void addChangelogsToRestoreConsumer(final Set<TopicPartition> partitions) { final Set<TopicPartition> assignment = new HashSet<>(restoreConsumer.assignment()); if (assignment.removeAll(partitions)) { throw new IllegalStateException("The current assignment " + restoreConsumer.assignment() + " " + "already contains some of the new partitions " + partitions); } assignment.addAll(partitions); restoreConsumer.assign(assignment); }
Source:
<code>public String describeTask(String container, String taskName) throws IOException { List<Map<String, Object>> list = parseBody(fetch(() -> client.tasks().list()), List.class); Optional<Map<String, Object>> task = list.stream().filter(i -> taskName.equals(i.get("name"))).findFirst(); <START> return task.get().toString(); <END> }</code><technical_language>task.get() throw a NoSuchElementException if task exist. is want? return empty string</technical_language>

Target:
public String describeTask(String container, String taskName) throws IOException { List<Map<String, Object>> list = parseBody(fetch(() -> client.tasks().list()), List.class); Optional<Map<String, Object>> task = list.stream().filter(i -> taskName.equals(i.get("name"))).findFirst(); return task.map(Object::toString).orElseThrow(() -> MSG.noSuchResource(taskName)); }
Source:
<code>public CompletableFuture<T> get(DataFetchingEnvironment environment) { return CompletableFuture.supplyAsync(() -> { try { return wrappedDataFetcher.get(environment); } catch (Exception e) { <START> throw new RuntimeException(e); <END> } }, executor); }</code><technical_language>Do a detection. if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new RuntimeException(e) }</technical_language>

Target:
public CompletableFuture<T> get(DataFetchingEnvironment environment) { return CompletableFuture.supplyAsync(() -> { try { return wrappedDataFetcher.get(environment); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new RuntimeException(e); } } }, executor); }
Source:
<code>public int compareTo(Object obj) { if (this == obj) { return 0; } if (obj == null) { return 1; } if (getClass() != obj.getClass()) { return 1; } RepositoryVersion other = (RepositoryVersion) obj; if (this.getMajor() == null || other.getMajor() == null) { return this.toString().compareTo(other.toString()); } int erg = this.getMajor() - other.getMajor(); if (erg != 0) { return erg; } if (this.getMinor() != null && other.getMinor() == null) { return 1; } else if (this.getMinor() == null && other.getMinor() != null) { return -1; } else if (this.getMinor() != null && other.getMinor() != null) { erg = this.getMinor() - other.getMinor(); if (erg != 0) { return erg; } } if (this.getMicro() != null && other.getMicro() == null) { return 1; } else if (this.getMicro() == null && other.getMicro() != null) { return -1; } else if (this.getMicro() != null && other.getMicro() != null) { erg = this.getMicro() - other.getMicro(); if (erg != 0) { return erg; } } if (this.getQualifier() != null && other.getQualifier() == null) { if (this.getQualifier().equals("+")) { return 1; } else { return -1; } } <START> if (this.getQualifier() == null && other.getQualifier() != null) { <END> if (other.getQualifier().equals("+")) { return -1; } else { return 1; } } if (this.getQualifier() != null && other.getQualifier() != null) { erg = this.getQualifier().compareTo(other.getQualifier()); if (this.getQualifier().equals("+") || other.getQualifier().equals("+")) { return erg * -1; } if (erg != 0) { return erg; } } return 0; }</code><technical_language>avoid code duplication super if methods compareMajor, compareMinor, etc. override here</technical_language>

Target:
public int compareTo(Object obj) { if (this == obj) { return 0; } if (obj == null) { return 1; } if (getClass() != obj.getClass()) { return 1; } RepositoryVersion other = (RepositoryVersion) obj; int erg = compareMajor(other); if (erg != 0) { return erg; } erg = compareMinor(other); if (erg != 0) { return erg; } erg = compareMicro(other); if (erg != 0) { return erg; } if (this.getQualifier() != null && other.getQualifier() == null) { if (this.getQualifier().equals("+")) { return 1; } else { return -1; } } if (this.getQualifier() == null && other.getQualifier() != null) { if (other.getQualifier().equals("+")) { return -1; } else { return 1; } } erg = compareQualifier(other); if (this.getQualifier().equals("+") || other.getQualifier().equals("+")) { return erg * -1; } return erg; }
Source:
<code>public ActionResult execute() { CourseUpdateRequest courseUpdateRequest = getAndValidateRequestBody(CourseUpdateRequest.class); String courseTimeZone = courseUpdateRequest.getTimeZone(); FieldValidator validator = new FieldValidator(); String timeZoneErrorMessage = validator.getInvalidityInfoForTimeZone(courseTimeZone); if (!timeZoneErrorMessage.isEmpty()) { return new JsonResult(timeZoneErrorMessage, HttpStatus.SC_BAD_REQUEST); } String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String courseName = courseUpdateRequest.getCourseName(); try { logic.updateCourseCascade( CourseAttributes.updateOptionsBuilder(courseId) .withName(courseName) .withTimezone(ZoneId.of(courseTimeZone)) .build()); } catch (InvalidParametersException ipe) { return new JsonResult(ipe.getMessage(), HttpStatus.SC_BAD_REQUEST); } catch (EntityDoesNotExistException edee) { return new JsonResult(edee.getMessage(), HttpStatus.SC_NOT_FOUND); } <START> return new JsonResult(new CourseData(logic.getCourse(courseId))); <END> }</code><technical_language>updateCourseCascade method return updated entity. is need query here</technical_language>

Target:
public ActionResult execute() { CourseUpdateRequest courseUpdateRequest = getAndValidateRequestBody(CourseUpdateRequest.class); String courseTimeZone = courseUpdateRequest.getTimeZone(); String timeZoneErrorMessage = FieldValidator.getInvalidityInfoForTimeZone(courseTimeZone); if (!timeZoneErrorMessage.isEmpty()) { return new JsonResult(timeZoneErrorMessage, HttpStatus.SC_BAD_REQUEST); } String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String courseName = courseUpdateRequest.getCourseName(); CourseAttributes updatedCourse; try { updatedCourse = logic.updateCourseCascade( CourseAttributes.updateOptionsBuilder(courseId) .withName(courseName) .withTimezone(ZoneId.of(courseTimeZone)) .build()); } catch (InvalidParametersException ipe) { return new JsonResult(ipe.getMessage(), HttpStatus.SC_BAD_REQUEST); } catch (EntityDoesNotExistException edee) { throw new EntityNotFoundException(edee); } return new JsonResult(new CourseData(updatedCourse)); }
Source:
<code>public static TaskTimer getTimer(IConfiguration config) throws Exception{ CronTimer cronTimer = null; switch (config.getBackupSchedulerType()) { case TIME: int hour = config.getBackupHour(); if (hour >= 0) { cronTimer = new CronTimer(JOBNAME, hour, 1, 0); logger.info("Starting snapshot backup with backup hour: " + hour); }else logger.info("Skipping snapshot backup as backup hour is less than 0: " + hour); break; case CRON: String cronExpression = config.getBackupCronExpression(); <START> if(!StringUtils.isEmpty(cronExpression) && cronExpression.equalsIgnoreCase("-1")){ <END> logger.info("Skipping snapshot backup as backup cron is set to NA"); }else { if(StringUtils.isEmpty(cronExpression) || !CronExpression.isValidExpression(cronExpression)) throw new Exception("Invalid CRON expression: " + cronExpression + ". Please use NA if you wish to disable backup else fix the CRON expression and try again!"); cronTimer = new CronTimer(JOBNAME, config.getBackupCronExpression()); logger.info(String.format("Starting snapshot backup with CRON expression %s", cronTimer.getCronExpression())); } break; } return cronTimer; }</code><technical_language>in this stage if cronExpression is set -1</technical_language>

Target:
public static TaskTimer getTimer(IConfiguration config) throws Exception{ CronTimer cronTimer = null; switch (config.getBackupSchedulerType()) { case HOUR: int hour = config.getBackupHour(); if (hour >= 0) { cronTimer = new CronTimer(JOBNAME, hour, 1, 0); logger.info("Starting snapshot backup with backup hour: " + hour); }else logger.info("Skipping snapshot backup as backup hour is less than 0: " + hour); break; case CRON: String cronExpression = config.getBackupCronExpression(); if(!StringUtils.isEmpty(cronExpression) && cronExpression.equalsIgnoreCase("-1")){ logger.info("Skipping snapshot backup as backup cron is set to NA"); }else { if(StringUtils.isEmpty(cronExpression) || !CronExpression.isValidExpression(cronExpression)) throw new Exception("Invalid CRON expression: " + cronExpression + ". Please use -1 if you wish to disable backup else fix the CRON expression and try again!"); cronTimer = new CronTimer(JOBNAME, config.getBackupCronExpression()); logger.info(String.format("Starting snapshot backup with CRON expression %s", cronTimer.getCronExpression())); } break; } return cronTimer; }
Source:
<code>public AbstractSegmentStoreAnalysisRequest(ISegmentStore<ISegment> segmentStore) { super(ITmfEvent.class, 0, ITmfEventRequest.ALL_DATA, ExecutionType.BACKGROUND); <START> fSegmentStore = segmentStore; <END> }</code><technical_language>call this() dependency level of 0</technical_language>

Target:
public AbstractSegmentStoreAnalysisRequest(ISegmentStore<ISegment> segmentStore) { this(segmentStore, 0); }
Source:
<code>private void handleRadioButtonClick(ClickEvent event) { getDetailModel().setViewFilterType((viewRadioGroup.getSelectedValue())); boolean attached = viewRadioGroup.getSelectedValue() == NetworkHostFilter.attached; getTable().ensureColumnPresent(hostStatus, constants.empty(), true, "30px"); getTable().ensureColumnPresent(nameColumn, constants.nameHost(), true, "200px"); getTable().ensureColumnPresent(clusterColumn, constants.clusterHost(), true, "200px"); getTable().ensureColumnPresent(dcColumn, constants.dcHost(), true, "200px"); getTable().ensureColumnPresent(nicStatusColumn, constants.statusNetworkHost(), attached, "140px"); <START> getTable().ensureColumnPresent(hostOutOfSync, constants.hostOutOfSync(), true, "100px"); END> getTable().ensureColumnPresent(nicColumn, constants.nicNetworkHost(), attached, "100px"); getTable().ensureColumnPresent(speedColumn, templates.sub(constants.speedNetworkHost(), constants.mbps()).asString(), attached, "100px"); getTable().ensureColumnPresent(nicRxColumn, templates.sub(constants.rxNetworkHost(), constants.mbps()).asString(), attached, "100px"); getTable().ensureColumnPresent(nicTxColumn, templates.sub(constants.txNetworkHost(), constants.mbps()).asString(), attached, "100px"); }</code><technical_language>true? This is meaningless for a host network attached</technical_language>

Target:
private void handleRadioButtonClick(ClickEvent event) { getDetailModel().setViewFilterType((viewRadioGroup.getSelectedValue())); boolean attached = viewRadioGroup.getSelectedValue() == NetworkHostFilter.attached; getTable().ensureColumnPresent(hostStatus, constants.empty(), true, "30px"); getTable().ensureColumnPresent(nameColumn, constants.nameHost(), true, "200px"); getTable().ensureColumnPresent(clusterColumn, constants.clusterHost(), true, "200px"); getTable().ensureColumnPresent(dcColumn, constants.dcHost(), true, "200px"); getTable().ensureColumnPresent(nicStatusColumn, constants.statusNetworkHost(), attached, "140px"); getTable().ensureColumnPresent(hostOutOfSync, constants.hostOutOfSync(), attached, "75px"); getTable().ensureColumnPresent(nicColumn, constants.nicNetworkHost(), attached, "100px"); getTable().ensureColumnPresent(speedColumn, templates.sub(constants.speedNetworkHost(), constants.mbps()).asString(), attached, "100px"); getTable().ensureColumnPresent(nicRxColumn, templates.sub(constants.rxNetworkHost(), constants.mbps()).asString(), attached, "100px"); getTable().ensureColumnPresent(nicTxColumn, templates.sub(constants.txNetworkHost(), constants.mbps()).asString(), attached, "100px"); }
Source:
<code>public void testGenerics16() throws Exception { ICompilationUnit cuIGeneric= createCUfromTestFile(getPackageP(), "IGeneric"); ICompilationUnit cuMainImpl= createCUfromTestFile(getPackageP(), "MainImpl"); ICompilationUnit cuOtherImpl= createCUfromTestFile(getPackageP(), "OtherImpl"); String[] methodNames= { "genericMethod" }; String[][] signatures= { { "QString;" } }; IType typeIGeneric= getType(cuIGeneric, "IGeneric"); IType typeMainImpl= getType(cuMainImpl, "MainImpl"); IMethod[] methods= getMethods(typeMainImpl, methodNames, signatures); PullUpRefactoringProcessor processor= createRefactoringProcessor(methods); Refactoring ref= processor.getRefactoring(); assertTrue("activation", ref.checkInitialConditions(new NullProgressMonitor()).isOK()); processor.setDestinationType(typeIGeneric); processor.setDeletedMethods(getMethods(processor.getMatchingElements(new NullProgressMonitor(), false))); RefactoringStatus result= performRefactoring(ref); <START> assertFalse("No errors should occur: " + result.getMessageMatchingSeverity(RefactoringStatus.ERROR), result != null && result.hasError()); <END> assertEqualLines("IGeneric", getFileContents(getOutputTestFileName("IGeneric")), cuIGeneric.getSource()); assertEqualLines("MainImpl", getFileContents(getOutputTestFileName("MainImpl")), cuMainImpl.getSource()); assertEqualLines("OtherImpl", getFileContents(getOutputTestFileName("OtherImpl")), cuOtherImpl.getSource()); }</code><technical_language>Yes, right. fixed in AutoRefactor</technical_language>

Target:
public void testGenerics16() throws Exception { ICompilationUnit cuIGeneric= createCUfromTestFile(getPackageP(), "IGeneric"); ICompilationUnit cuMainImpl= createCUfromTestFile(getPackageP(), "MainImpl"); ICompilationUnit cuOtherImpl= createCUfromTestFile(getPackageP(), "OtherImpl"); String[] methodNames= { "genericMethod" }; String[][] signatures= { { "QString;" } }; IType typeIGeneric= getType(cuIGeneric, "IGeneric"); IType typeMainImpl= getType(cuMainImpl, "MainImpl"); IMethod[] methods= getMethods(typeMainImpl, methodNames, signatures); PullUpRefactoringProcessor processor= createRefactoringProcessor(methods); Refactoring ref= processor.getRefactoring(); assertTrue("activation", ref.checkInitialConditions(new NullProgressMonitor()).isOK()); processor.setDestinationType(typeIGeneric); processor.setDeletedMethods(getMethods(processor.getMatchingElements(new NullProgressMonitor(), false))); RefactoringStatus result= performRefactoring(ref); if (result != null && result.hasError()) { fail("No errors should occur: " + result.getMessageMatchingSeverity(RefactoringStatus.ERROR)); } assertEqualLines("IGeneric", getFileContents(getOutputTestFileName("IGeneric")), cuIGeneric.getSource()); assertEqualLines("MainImpl", getFileContents(getOutputTestFileName("MainImpl")), cuMainImpl.getSource()); assertEqualLines("OtherImpl", getFileContents(getOutputTestFileName("OtherImpl")), cuOtherImpl.getSource()); }
Source:
<code>public Set<Entry<K, V>> entrySet() { <START> return commonCache.entrySet(); <END> }</code><technical_language>code protected doWithReadLock, do for isEmpty containsValue, etc</technical_language>

Target:
public Set<Entry<K, V>> entrySet() { return doWithReadLock(c -> c.entrySet()); }
Source:
<code>public static PartitionIterator read(SinglePartitionReadCommand.Group group, ConsistencyLevel consistencyLevel, ClientState state, long queryStartNanoTime) throws UnavailableException, IsBootstrappingException, ReadFailureException, ReadTimeoutException, InvalidRequestException { if (StorageService.instance.isBootstrapMode() && !systemKeyspaceQuery(group.queries)) { readMetrics.unavailables.mark(); readMetricsMap.get(consistencyLevel).unavailables.mark(); throw new IsBootstrappingException(); } if (BlacklistedPartitionCache.instance.size() > 0) { for (SinglePartitionReadQuery query : group.queries) { if (BlacklistedPartitionCache.instance.contains(query.metadata().id, query.partitionKey())) { <START> throw new InvalidRequestException("Cannot perform READ on a blacklisted partition"); <END> } } } return consistencyLevel.isSerialConsistency() ? readWithPaxos(group, consistencyLevel, state, queryStartNanoTime) : readRegular(group, consistencyLevel, queryStartNanoTime); }</code><technical_language>Do want expose parition key in exception message</technical_language>

Target:
public static PartitionIterator read(SinglePartitionReadCommand.Group group, ConsistencyLevel consistencyLevel, ClientState state, long queryStartNanoTime) throws UnavailableException, IsBootstrappingException, ReadFailureException, ReadTimeoutException, InvalidRequestException { if (StorageService.instance.isBootstrapMode() && !systemKeyspaceQuery(group.queries)) { readMetrics.unavailables.mark(); readMetricsMap.get(consistencyLevel).unavailables.mark(); throw new IsBootstrappingException(); } if (BlacklistedPartitionCache.instance.size() > 0) { for (SinglePartitionReadQuery query : group.queries) { if (BlacklistedPartitionCache.instance.contains(query.metadata().id, query.partitionKey())) { throw new InvalidRequestException(String.format("Cannot perform READ on a blacklisted partition: %s", query.partitionKey().toString())); } } } return consistencyLevel.isSerialConsistency() ? readWithPaxos(group, consistencyLevel, state, queryStartNanoTime) : readRegular(group, consistencyLevel, queryStartNanoTime); }
Source:
<code>public void required_spec309_requestNegativeNumberMustSignalIllegalArgumentException() throws Throwable { activePublisherTest(10, false, new PublisherTestRun<T>() { @Override public void run(Publisher<T> pub) throws Throwable { final ManualSubscriber<T> sub = env.newManualSubscriber(pub); <START> sub.request(-1); <END> sub.expectErrorWithMessage(IllegalArgumentException.class, "3.9"); } }); }</code><technical_language>Why</technical_language>

Target:
public void required_spec309_requestNegativeNumberMustSignalIllegalArgumentException() throws Throwable { activePublisherTest(10, false, new PublisherTestRun<T>() { @Override public void run(Publisher<T> pub) throws Throwable { final ManualSubscriber<T> sub = env.newManualSubscriber(pub); final Random r = new Random(); sub.request(-r.nextInt(Integer.MAX_VALUE) - 1); sub.expectErrorWithMessage(IllegalArgumentException.class, "3.9"); } }); }
Source:
<code>public void testMergeDataAfterAcceptingDeletion() { Assert.assertNotNull(subDiff); Assert.assertNotNull(deletionDiff); Assert.assertNotNull(oppositeDiff); ArrayList<Diff> uiDiff = Lists.newArrayList(deletionDiff, subDiff); MergeRunnableImpl mergeRunnable = new MergeRunnableImpl(true, false, MergeMode.ACCEPT); mergeRunnable.merge(uiDiff, false, mergerRegistry); <START> Assert.assertEquals(getMergeData(deletionDiff).getMergeMode(), MergeMode.ACCEPT); <END> Assert.assertEquals(getMergeData(subDiff).getMergeMode(), MergeMode.REJECT); Assert.assertEquals(getMergeData(oppositeDiff).getMergeMode(), MergeMode.REJECT); }</code><technical_language>write assertion resulting left model? is related bug bug understand purpose of this test</technical_language>

Target:
public void testMergeDataAfterAcceptingDeletion() { Assert.assertNotNull(subDiff); Assert.assertNotNull(deletionDiff); Assert.assertNotNull(oppositeDiff); ArrayList<Diff> uiDiff = Lists.newArrayList(deletionDiff, subDiff); MergeRunnableImpl mergeRunnable = new MergeRunnableImpl(true, false, MergeMode.ACCEPT); mergeRunnable.merge(uiDiff, false, mergerRegistry); Node rootNode = (Node)left.getContents().get(0); Assert.assertEquals(0, rootNode.getContainmentRef1().get(0).getContainmentRef1().size()); Assert.assertEquals(MergeMode.ACCEPT, getMergeData(deletionDiff).getMergeMode()); Assert.assertEquals(MergeMode.REJECT, getMergeData(subDiff).getMergeMode()); Assert.assertEquals(MergeMode.REJECT, getMergeData(oppositeDiff).getMergeMode()); }