auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testNoTransactionCommit() { TransactionManager transactionManager = createTestTransactionManager(); AccessControl accessControl = new AccessControlManager(transactionManager); Session session = sessionBuilder() .build(); QueryStateMachine stateMachine = QueryStateMachine.begin(new QueryId("query"), "COMMIT", session, URI.create("fake://uri"), true, transactionManager, accessControl, executor, metadata); try { try { getFutureValue(new CommitTask().execute(new Commit(), transactionManager, metadata, new AllowAllAccessControl(), stateMachine, emptyList())); fail(); } catch (CompletionException e) { <START> throwIfUnchecked(e.getCause()); <END> throw e; } } catch (PrestoException e) { assertEquals(e.getErrorCode(), NOT_IN_TRANSACTION.toErrorCode()); } assertFalse(stateMachine.getQueryInfoWithoutDetails().isClearTransactionId()); assertFalse(stateMachine.getQueryInfoWithoutDetails().getStartedTransactionId().isPresent()); assertTrue(transactionManager.getAllTransactionInfos().isEmpty()); }</code><technical_language>Ok, in a test. Nevermind than</technical_language>

Target:
public void testNoTransactionCommit() { TransactionManager transactionManager = createTestTransactionManager(); AccessControl accessControl = new AccessControlManager(transactionManager); Session session = sessionBuilder() .build(); QueryStateMachine stateMachine = QueryStateMachine.begin(new QueryId("query"), "COMMIT", session, URI.create("fake://uri"), true, transactionManager, accessControl, executor, metadata); try { getFutureValue(new CommitTask().execute(new Commit(), transactionManager, metadata, new AllowAllAccessControl(), stateMachine, emptyList())); fail(); } catch (PrestoException e) { assertEquals(e.getErrorCode(), NOT_IN_TRANSACTION.toErrorCode()); } assertFalse(stateMachine.getQueryInfoWithoutDetails().isClearTransactionId()); assertFalse(stateMachine.getQueryInfoWithoutDetails().getStartedTransactionId().isPresent()); assertTrue(transactionManager.getAllTransactionInfos().isEmpty()); }
Source:
<code>public List<CellWithTimestamp> getTimestamps( TableReference tableRef, byte[] startRowInclusive, int limit) { <START> String selQuery = "SELECT key, column1, column2 FROM %s WHERE token(key) >= token(%s) LIMIT %s;"; <END> CqlQuery query = new CqlQuery( selQuery, quotedTableName(tableRef), key(startRowInclusive), limit(limit)); try (CloseableTrace trace = startLocalTrace("cqlExecutor.getTimestamps(query {}, tableRef {}, limit {})", selQuery, LoggingArgs.safeTableOrPlaceholder(tableRef), limit)) { return query.executeAndGetCells(startRowInclusive, this::getCellFromRow); } }</code><technical_language>pass CqlQuery object thrift client trace there? currently splitting tracing classes</technical_language>

Target:
public List<CellWithTimestamp> getTimestamps( TableReference tableRef, byte[] startRowInclusive, int limit) { String selQuery = "SELECT key, column1, column2 FROM %s WHERE token(key) >= token(%s) LIMIT %s;"; CqlQuery query = new CqlQuery( selQuery, CqlQueryUtils.quotedTableName(tableRef), CqlQueryUtils.key(startRowInclusive), CqlQueryUtils.limit(limit)); return executeAndGetCells(query, startRowInclusive, CqlQueryUtils::getCellFromRow); }
Source:
<code>public Result<BpmnEdge> convertEdge(BaseElement baseElement, Map<String, BpmnNode> nodes) { return Match.of(BaseElement.class, Result.class) .when(SequenceFlow.class, e -> sequenceFlowConverter.convertEdge(e, nodes)) .when(BoundaryEvent.class, e -> boundaryEventConverter.convertEdge(e, nodes)) .when(Association.class, e -> associationConverter.convertEdge(e, nodes)) <START> .defaultValue(Result.ignored("Not an Edge element")) <END> .apply(baseElement) .value() .get(); }</code><technical_language>messageKey nice here, passing baseElement UUID facilitate node search in case bpmn2 inspected</technical_language>

Target:
public Result<BpmnEdge> convertEdge(BaseElement baseElement, Map<String, BpmnNode> nodes) { return Match.of(BaseElement.class, Result.class) .when(SequenceFlow.class, e -> sequenceFlowConverter.convertEdge(e, nodes)) .when(BoundaryEvent.class, e -> boundaryEventConverter.convertEdge(e, nodes)) .when(Association.class, e -> associationConverter.convertEdge(e, nodes)) .defaultValue(Result.ignored("Not an Edge element", getNotFoundMessage(baseElement))) .apply(baseElement) .value(); }
Source:
<code><START> public long getChildId(int groupPosition, int childPosition) { return childPosition; } <END></code><technical_language>multiple groups</technical_language>

Target:
public long getChildId(int groupPosition, int childPosition) { return getChild(groupPosition, childPosition).getId(); }
Source:
<code>public AwsListener getOrCreateListener(int port) { Optional<AwsListener> listenerOptional = listeners.stream() .filter(l -> l.getPort() == port) .findFirst(); <START> if (listenerOptional.isPresent()) { return listenerOptional.get(); } else { AwsListener listener = new AwsListener(scheme, port); listeners.add(listener); return listener; } <END> }</code><technical_language>I prefer utilizing power of Optional: public AwsListener getOrCreateListener(int port) { return listeners.stream() .filter(l -> l.getPort() == port) .findFirst().orElseGet(() -> createListener(port)); } private AwsListener createListener(int port) { AwsListener listener = new AwsListener(scheme, port); listeners.add(listener); return listener; }</technical_language>

Target:
public AwsListener getOrCreateListener(int port) { return listeners.stream() .filter(l -> l.getPort() == port) .findFirst().orElseGet(() -> createListener(port)); }
Source:
<code>public JPanel createPropertiesPanel() { jmsPropertiesTable = new JTable(tableModel); JMeterUtils.applyHiDPI(jmsPropertiesTable); jmsPropertiesTable.getTableHeader().setDefaultRenderer(new HeaderAsPropertyRenderer()); jmsPropertiesTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); jmsPropertiesTable.setPreferredScrollableViewportSize(new Dimension(100, 70)); TableColumn mechanismColumn = jmsPropertiesTable.getColumnModel().getColumn(COL_TYPE); mechanismColumn.setCellEditor(new TypeCellEditor()); JPanel panel = new JPanel(new BorderLayout(0, 5)); panel.setBorder(BorderFactory.createTitledBorder( JMeterUtils.getResString("jms_props"))); <START> panel.add(new JScrollPane(jmsPropertiesTable)); <END> panel.add(createButtonPanel(), BorderLayout.SOUTH); return panel; }</code><technical_language>I this aligned somehow. is true Darklaf's titledBorder render left-right-bottom borders, tables panel titled border border. However, other lafs produce borders (one for titled, another for scrollpane border) :-/</technical_language>

Target:
public JPanel createPropertiesPanel() { jmsPropertiesTable = new JTable(tableModel); JMeterUtils.applyHiDPI(jmsPropertiesTable); jmsPropertiesTable.getTableHeader().setDefaultRenderer(new HeaderAsPropertyRenderer()); jmsPropertiesTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); jmsPropertiesTable.setPreferredScrollableViewportSize(new Dimension(100, 70)); TableColumn mechanismColumn = jmsPropertiesTable.getColumnModel().getColumn(COL_TYPE); mechanismColumn.setCellEditor(new TypeCellEditor()); JPanel panel = new JPanel(new BorderLayout(0, 5)); panel.setBorder(BorderFactory.createTitledBorder( JMeterUtils.getResString("jms_props"))); panel.add(GuiUtils.emptyBorder(new JScrollPane(jmsPropertiesTable))); panel.add(createButtonPanel(), BorderLayout.SOUTH); return panel; }
Source:
<code>public long getFileSize(){ <START> if (length.length() == 0) { <END> return 0; } return Long.decode(length); }</code><technical_language>StringUtils.isBlank() ? is edge case, existing logic is specific passed this field (null, bogus blank strings, etc.). more protective hurt</technical_language>

Target:
public long getFileSize(){ try { return Long.decode(length); } catch (NumberFormatException e) { LOGGER.log(FINE, "Cannot determine file size of the artifact {0}. The length {1} is not a valid long value", new Object[] {this, length}); return 0; } }
Source:
<code>public void goOnline() { getMetadataStore().setOfflineState(false); List<StorageEngine<ByteArray, byte[], byte[]>> storageEngines = storageService.getStoreRepository().getStorageEnginesByClass(ReadOnlyStorageEngine.class); <START> if (storageEngines.size() > 0) { <END> logger.info("Will attempt to removeRemoteObsoleteState() for " + storageEngines.size() + " Read-Only stores."); for (StorageEngine storageEngine: storageEngines) { StoreVersionManager storeVersionManager = (StoreVersionManager) storageEngine.getCapability(StoreCapabilityType.DISABLE_STORE_VERSION); try { storeVersionManager.removeRemoteObsoleteState(); } catch (Exception e) { logger.error("Failed to removeRemoteObsoleteState() for store: " + storageEngine.getName(), e); } } } createOnlineServices(); startOnlineServices(); }</code><technical_language>this done based voldemortConfig clean state</technical_language>

Target:
public void goOnline() { ReadOnlyStoreStatusValidation validation = validateReadOnlyStoreStatusBeforeGoingOnline(); if (validation.readyToGoOnline) { getMetadataStore().setOfflineState(false); createOnlineServices(); startOnlineServices(); } if (validation.e != null) { throw new VoldemortException("Problem while going online!", validation.e); } }
Source:
<code>private <T extends Dao> T getDao(Class<T> daoType) { T dao = <START> CDI.current().select(daoType).get(); <END> if (dao == null) { throw new IllegalArgumentException("There is no Dao registered for dao type " + daoType.getName()); } return dao; }</code><technical_language>a provider of dao, it! daos.select(daoType).get()</technical_language>

Target:
private <T extends Dao> T getDao(Class<T> daoType) { T dao = daos.select(daoType).get(); if (dao == null) { throw new IllegalArgumentException("There is no Dao registered for dao type " + daoType.getName()); } return dao; }
Source:
<code>private void persistDiffPreferences() { AccountDiffPreference diffPref = new AccountDiffPreference(Gerrit.getUserAccount().getId()); diffPref.setIgnoreWhitespace(getIgnoreWhitespace()); diffPref.setTabSize(tabWidth.getIntValue()); diffPref.setLineLength(colWidth.getIntValue()); diffPref.setSyntaxHighlighting(syntaxHighlighting.getValue()); diffPref.setShowWhitespaceErrors(whitespaceErrors.getValue()); diffPref.setIntralineDifference(intralineDifference.getValue()); diffPref.setShowTabs(showTabs.getValue()); <START> Util.ACCOUNT_SVC.changeDiffPreferences(diffPref, new GerritCallback<VoidResult>() { <END> @Override public void onSuccess(VoidResult result) { } }); Gerrit.setAccountDiffPreference(diffPref); }</code><technical_language>setEnabled(false) first, run RPC, setEnabled(true) in onSuccess method. Update button re-enable updated view saved user's preferences. RPCs run in parallel, save faster, work do</technical_language>

Target:
private void persistDiffPreferences() { setEnabled(false); final AccountDiffPreference diffPref = new AccountDiffPreference(Gerrit.getUserAccount().getId()); diffPref.setIgnoreWhitespace(getIgnoreWhitespace()); diffPref.setTabSize(tabWidth.getIntValue()); diffPref.setLineLength(colWidth.getIntValue()); diffPref.setSyntaxHighlighting(syntaxHighlighting.getValue()); diffPref.setShowWhitespaceErrors(whitespaceErrors.getValue()); diffPref.setIntralineDifference(intralineDifference.getValue()); diffPref.setShowTabs(showTabs.getValue()); diffPref.setContext(getContext()); Util.ACCOUNT_SVC.changeDiffPreferences(diffPref, new GerritCallback<VoidResult>() { @Override public void onSuccess(VoidResult result) { Gerrit.setAccountDiffPreference(diffPref); setEnabled(true); } @Override public void onFailure(Throwable caught) { setEnabled(true); } }); }
Source:
<code>public EventDefinitionCrf findByStudyEventDefinitionIdAndCRFIdAndStudyId(Integer studyEventDefinitionId, Integer crfId, Integer studyId) { <START> String query = "select do from " + getDomainClassName() + " do,Study s where do.studyEventDefinition.studyEventDefinitionId = :studyeventdefid " <END> + " and (do.study.studyId = :studyid or (s.studyId = :studyid and s.study.studyId=do.study.studyId)) and do.crf.crfId = :crfid"; Query q = getCurrentSession().createQuery(query); q.setInteger("studyeventdefid", studyEventDefinitionId); q.setInteger("studyid", studyId); q.setInteger("crfid", crfId); return (EventDefinitionCrf) q.uniqueResult(); }</code><technical_language>try "findAllByDefinition" in EventDefinitionCRFDAO instead of changing this query break existing methods</technical_language>

Target:
public EventDefinitionCrf findByStudyEventDefinitionIdAndCRFIdAndStudyId(Integer studyEventDefinitionId, Integer crfId, Integer studyId) { String query = "from " + getDomainClassName() + " do where do.studyEventDefinition.studyEventDefinitionId = :studyeventdefid " + " and do.study.studyId = :studyid and do.crf.crfId = :crfid"; Query q = getCurrentSession().createQuery(query); q.setInteger("studyeventdefid", studyEventDefinitionId); q.setInteger("studyid", studyId); q.setInteger("crfid", crfId); return (EventDefinitionCrf) q.uniqueResult(); }
Source:
<code>public static BooleanExpression asBoolean(boolean value) { <START> return asBoolean(Expressions.constant(value)); <END> }</code><technical_language>this is Expressions, asBoolean(constant(value)), others</technical_language>

Target:
public static BooleanExpression asBoolean(boolean value) { return asBoolean(constant(value)); }
Source:
<code>public void handleCollision(GameObject other) { if (other instanceof Floor) { float MAX_DIFF_LANDING = 10f; if (getTop() < Gdx.graphics.getHeight() && between(overlapBottom(other), 0, MAX_DIFF_LANDING) && speedY < 0) { <START> setBottom(other.getTop()); <END> speedY = 0; timeSinceLastFloorContact = 0; canJump = true; } } }</code><technical_language>watch out for long lines, is set 120, put statement a new line <layout></technical_language>

Target:
public void handleCollision(GameObject other) { if (other instanceof Floor) { if (getTop() < Gdx.graphics.getHeight() && between(overlapBottom(other), 0, MAX_DIFF_LANDING) && speedY < 0) { setBottom(other.getTop()); speedY = 0; timeSinceLastFloorContact = 0; canJump = true; } } }
Source:
<code>private void applyPaymentToMemberAccounts(PaymentData paymentData, BigDecimal installmentsPaid) throws AccountException { for (LoanBO memberAccount : getMemberAccounts()) { BigDecimal memberPaid = memberAccount.findNumberOfPaidInstallments(); List<LoanScheduleEntity> memberInstallments = memberAccount.getLoanInstallments(); Money memberPaymentAmount = new Money(getCurrency()); int currentPayment; for(currentPayment = memberPaid.intValue(); currentPayment < installmentsPaid.intValue() ; currentPayment++) { memberPaymentAmount = memberPaymentAmount.add(memberInstallments.get(currentPayment).getAmountToBePaidToGetExpectedProportion(BigDecimal.ONE)); } BigDecimal afterComa = installmentsPaid.subtract(new BigDecimal(installmentsPaid.intValue())); if(afterComa.compareTo(BigDecimal.ZERO)==1) { memberPaymentAmount = memberPaymentAmount.add(memberInstallments.get(currentPayment).getAmountToBePaidToGetExpectedProportion(afterComa)); } <START> if(getState().getValue()!=(short)6 && memberPaymentAmount.subtract((memberAccount.getTotalRepayableAmount())).isTinyAmount()) { <END> memberPaymentAmount = memberPaymentAmount.subtract(new Money(getCurrency(), 0.1)); } PaymentData memberPayment = new PaymentData(memberPaymentAmount, paymentData.getPersonnel(), paymentData.getPaymentTypeId(), paymentData.getTransactionDate()); if(!memberPaymentAmount.isTinyAmount() && !memberPaymentAmount.isLessThanZero()) { memberAccount.applyPayment(memberPayment); } } }</code><technical_language>good AccountState short value</technical_language>

Target:
private void applyPaymentToMemberAccounts(PaymentData paymentData, BigDecimal installmentsPaid) throws AccountException { for (LoanBO memberAccount : getMemberAccounts()) { BigDecimal memberPaid = memberAccount.findNumberOfPaidInstallments(); List<LoanScheduleEntity> memberInstallments = memberAccount.getLoanInstallments(); Money memberPaymentAmount = new Money(getCurrency()); int currentPayment; for(currentPayment = memberPaid.intValue(); currentPayment < installmentsPaid.intValue() ; currentPayment++) { memberPaymentAmount = memberPaymentAmount.add(memberInstallments.get(currentPayment).getAmountToBePaidToGetExpectedProportion(BigDecimal.ONE)); } BigDecimal afterComa = installmentsPaid.subtract(new BigDecimal(installmentsPaid.intValue())); if(afterComa.compareTo(BigDecimal.ZERO)==1) { memberPaymentAmount = memberPaymentAmount.add(memberInstallments.get(currentPayment).getAmountToBePaidToGetExpectedProportion(afterComa)); } if(getState().compareTo(AccountState.LOAN_CLOSED_OBLIGATIONS_MET)!=0 && memberPaymentAmount.subtract((memberAccount.getTotalRepayableAmount())).isTinyAmount()) { memberPaymentAmount = memberPaymentAmount.subtract(new Money(getCurrency(), 0.1)); } PaymentData memberPayment = new PaymentData(memberPaymentAmount, paymentData.getPersonnel(), paymentData.getPaymentTypeId(), paymentData.getTransactionDate()); if(!memberPaymentAmount.isTinyAmount() && !memberPaymentAmount.isLessThanZero()) { memberAccount.applyPayment(memberPayment); } } }
Source:
<code>public static void main(String[] args) { Config config = new Config(); final SerializerConfig personProtoSerializerConfig = new SerializerConfig(); personProtoSerializerConfig.setTypeClass(Person.class); personProtoSerializerConfig.setImplementation(new PersonProtoSerializer()); config.getSerializationConfig().addSerializerConfig(personProtoSerializerConfig); final HazelcastInstance hazelcastInstance = newHazelcastInstance(config); final IMap<Integer, Person> personsMap = hazelcastInstance.getMap("person"); <START> populatePerson(personsMap); <END> System.out.println("---- where email is support@hazelcast.com"); System.out.println(personsMap.values(equal("email", "support@hazelcast.com"))); System.out.println("---- where email is not support@hazelcast.com"); System.out.println(personsMap.values(new SqlPredicate("email != support@hazelcast.com"))); }</code><technical_language>I call this 'populate'. Persons is implied map name populatePerson sounds a single person added</technical_language>

Target:
public static void main(String[] args) { Config config = new Config(); final SerializerConfig personProtoSerializerConfig = new SerializerConfig(); personProtoSerializerConfig.setTypeClass(Person.class); personProtoSerializerConfig.setImplementation(new PersonProtoSerializer()); config.getSerializationConfig().addSerializerConfig(personProtoSerializerConfig); final HazelcastInstance hazelcastInstance = newHazelcastInstance(config); final IMap<Integer, Person> personsMap = hazelcastInstance.getMap("person"); populate(personsMap); System.out.println("---- where email is support@hazelcast.com"); System.out.println(personsMap.values(equal("email", "support@hazelcast.com"))); System.out.println("---- where email is not support@hazelcast.com"); System.out.println(personsMap.values(new SqlPredicate("email != support@hazelcast.com"))); }
Source:
<code><START> private List<Tag> searchTagsInternal(final String tagName, final String siteOrFolderId, <END> final User user) { List<Tag> tags; try { Host host = APILocator.getHostAPI().find(siteOrFolderId, user, false); String internalSiteOrFolderId = siteOrFolderId; if ((!UtilMethods.isSet(host) || !UtilMethods.isSet(host.getInode())) && UtilMethods.isSet(siteOrFolderId)) { internalSiteOrFolderId = APILocator.getFolderAPI() .find(siteOrFolderId, user, false).getHostId(); } tags = APILocator.getTagAPI().getSuggestedTag(tagName, internalSiteOrFolderId); } catch (DotDataException | DotSecurityException e) { throw new BadRequestException(e, e.getMessage()); } return tags; }</code><technical_language>create TagHelper put this</technical_language>

Target:
private List<Tag> searchTagsInternal(final String tagName, final String siteOrFolderId, final User user) { List<Tag> tags; try { final Host host = APILocator.getHostAPI().find(siteOrFolderId, user, false); String internalSiteOrFolderId = siteOrFolderId; if ((!UtilMethods.isSet(host) || !UtilMethods.isSet(host.getInode())) && UtilMethods.isSet(siteOrFolderId)) { internalSiteOrFolderId = APILocator.getFolderAPI() .find(siteOrFolderId, user, false).getHostId(); } tags = APILocator.getTagAPI().getSuggestedTag(tagName, internalSiteOrFolderId); } catch (DotDataException | DotSecurityException e) { throw new BadRequestException(e, e.getMessage()); } return tags; }
Source:
<code>public static AbstractTaskEditorExtension getTaskEditorExtension(TaskRepository taskRepository, TaskAttribute taskAttribute) { init(); <START> String media = taskAttribute.getMetaData().getValue(TaskAttribute.META_ATTRIBUTE_MEDIA_TYPE); <END> if (media != null && media.contains(MARKUP_KEY)) { String markup = media.substring(media.indexOf(MARKUP_KEY) + MARKUP_KEY.length()); if (markup.contains(";")) { markup = markup.substring(0, markup.indexOf(";")); } SortedSet<RegisteredTaskEditorExtension> extensions = getTaskEditorExtensions(); for (RegisteredTaskEditorExtension extension : extensions) { if (markup.equals(extension.getName())) { return extension.getExtension(); } } } return getTaskEditorExtension(taskRepository); }</code><technical_language>markup language task attribute split a separate method</technical_language>

Target:
public static AbstractTaskEditorExtension getTaskEditorExtension(TaskRepository taskRepository, TaskAttribute taskAttribute) { init(); String input = taskAttribute.getMetaData().getMediaType(); if (input != null) { try { MediaType media = MediaType.parse(input); Multimap<String, String> parameters = media.parameters(); if (parameters.containsKey(MARKUP_KEY)) { Iterator<String> iter = parameters.get(MARKUP_KEY).iterator(); String markup = iter.next(); SortedSet<RegisteredTaskEditorExtension> extensions = getTaskEditorExtensions(); for (RegisteredTaskEditorExtension extension : extensions) { if (markup.equals(extension.getName())) { return extension.getExtension(); } } } } catch (IllegalArgumentException e) { StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, String.format( "Unable to parse markup type for attribute %s", taskAttribute.toString()), e)); } } return getTaskEditorExtension(taskRepository); }
Source:
<code>public void stopStreamProcessor(SamzaResource resource) { synchronized (lock) { Container container = allocatedResources.get(resource); if (container != null) { log.info("Stopping Container ID: on host: {}", resource.getContainerId(), resource.getHost()); this.nmClientAsync.stopContainerAsync(container.getId(), container.getNodeId()); <START> } else { <END> YarnContainer yarnContainer = state.runningProcessors.get(resource.getContainerId()); if (yarnContainer != null) { log.info("Stopping container from previous attempt with Container ID: on host: {}", resource.getContainerId(), resource.getHost()); amClient.releaseAssignedContainer(yarnContainer.id()); } else { log.info("No container with Container ID: exists. Ignoring the stop request", resource.getContainerId()); } } } }</code><technical_language>put this block AM-HA config</technical_language>

Target:
public void stopStreamProcessor(SamzaResource resource) { synchronized (lock) { Container container = allocatedResources.get(resource); String containerId = resource.getContainerId(); String containerHost = resource.getHost(); if (container != null) { log.info("Stopping Container ID: on host: {}", containerId, containerHost); this.nmClientAsync.stopContainerAsync(container.getId(), container.getNodeId()); } else { YarnContainer yarnContainer = state.runningProcessors.get(getRunningProcessorId(containerId)); if (yarnContainer != null) { log.info("Stopping container from previous attempt with Container ID: on host: {}", containerId, containerHost); amClient.releaseAssignedContainer(yarnContainer.id()); } else { log.info("No container with Container ID: exists. Ignoring the stop request", containerId); } } } }
Source:
<code><START> @Test public void parsesBooleanAttributes() { <END> String html = "<a normal=\"123\" boolean empty=\"\"></a>"; Element el = Jsoup.parse(html).select("a").first(); assertEquals("123", el.attr("normal")); assertEquals("", el.attr("boolean")); assertEquals("", el.attr("empty")); assertEquals(html, el.outerHtml()); }</code><technical_language>Assert type</technical_language>

Target:
@Test public void parsesBooleanAttributes() { String html = "<a normal=\"123\" boolean empty=\"\"></a>"; Element el = Jsoup.parse(html).select("a").first(); assertEquals("123", el.attr("normal")); assertEquals("", el.attr("boolean")); assertEquals("", el.attr("empty")); List<Attribute> attributes = el.attributes().asList(); assertEquals("There should be 3 attribute present", 3, attributes.size()); assertFalse("'normal' attribute should not be boolean", attributes.get(0) instanceof BooleanAttribute); assertTrue("'boolean' attribute should be boolean", attributes.get(1) instanceof BooleanAttribute); assertFalse("'empty' attribute should not be boolean", attributes.get(2) instanceof BooleanAttribute); assertEquals(html, el.outerHtml()); }
Source:
<code>public String eventsURI(Account account, Optional<ZonedDateTime> toDate, Optional<ZonedDateTime> fromDate, Integer page, Integer displaySize, String agreementId, String paymentId) { Map<String, String> params = new LinkedHashMap<>(); <START> toDate.ifPresent(zonedDateTime -> params.put("to_date", DateTimeUtils.toUTCDateString(zonedDateTime))); <END> fromDate.ifPresent(zonedDateTime -> params.put("from_date", DateTimeUtils.toUTCDateString(zonedDateTime))); if (agreementId != null) params.put("mandate_external_id", agreementId); if (paymentId != null) params.put("transaction_external_id", paymentId); params.put("page", Optional.ofNullable(page).orElse(1).toString()); params.put("display_size", Optional.ofNullable(displaySize).orElse(500).toString()); return buildConnectorUri(account, "/v1/events", params); }</code><technical_language>I formatter here: java toDate.ifPresent(zonedDateTime -> params.put(ISO_INSTANT_MILLISECOND_PRECISION.format(zonedDateTime));</technical_language>

Target:
public String eventsURI(Account account, Optional<ZonedDateTime> toDate, Optional<ZonedDateTime> fromDate, Integer page, Integer displaySize, String agreementId, String paymentId) { Map<String, String> params = new LinkedHashMap<>(); toDate.map(ISO_INSTANT_MILLISECOND_PRECISION::format).ifPresent(formattedDate -> params.put("to_date", formattedDate)); fromDate.map(ISO_INSTANT_MILLISECOND_PRECISION::format).ifPresent(formattedDate -> params.put("from_date", formattedDate)); if (agreementId != null) params.put("mandate_external_id", agreementId); if (paymentId != null) params.put("transaction_external_id", paymentId); params.put("page", Optional.ofNullable(page).orElse(1).toString()); params.put("display_size", Optional.ofNullable(displaySize).orElse(500).toString()); return buildConnectorUri(account, "/v1/events", params); }
Source:
<code>@Test public void getWithoutUrlThrows() { class Example { @GET Call<Object> method() { return null; } } try { <START> buildRequest(Example.class); <END> } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Missing either @GET URL or @Url parameter.\n" + " for method Example.method"); } }</code><technical_language>fail</technical_language>

Target:
@Test public void getWithoutUrlThrows() { class Example { @GET Call<Object> method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Missing either @GET URL or @Url parameter.\n" + " for method Example.method"); } }
Source:
<code>private static RuntimeException createAtlasDbDependencyException(Throwable ex) { <START> if (ex instanceof InterruptedException || ex instanceof InterruptedIOException) { <END> Thread.currentThread().interrupt(); } throwIfInstance(ex, AtlasDbDependencyException.class); return new AtlasDbDependencyException("The KVS or Timelock threw an exception.", ex); }</code><technical_language>nit: a bit funky static instanceof isInstance in unwrapAndThrow... - methods do need for throwIfInstance. standardise other, prefer instanceof createPalantirRuntimeException that</technical_language>

Target:
private static RuntimeException createAtlasDbDependencyException(Throwable ex) { if (ex instanceof InterruptedException || ex instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } throwIfInstance(ex, AtlasDbDependencyException.class); return new AtlasDbDependencyException("AtlasDB dependency threw an exception.", ex); }
Source:
<code>public void <START> setHashtags(HashtagsInput <END> input) throws RestApiException { try { postHashtags.get().apply(change, input); } catch (IOException | OrmException e) { throw new RestApiException("Cannot post hashtags", e); } }</code><technical_language>fine then</technical_language>

Target:
public void setHashtags(HashtagsInput input) throws RestApiException { try { postHashtags.apply(change, input); } catch (IOException | OrmException e) { throw new RestApiException("Cannot post hashtags", e); } }
Source:
<code>protected void setCellValue(Cell cell, Object value) { if (value instanceof Boolean) { cell.setCellValue(toBoolean(value)); } else if (value instanceof LocalDate) { <START> Instant instant = toLocalDate(value).atStartOfDay(timeZone.toZoneId()).toInstant(); <END> SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd"); simpleDateFormat.setTimeZone(timeZone); cell.setCellValue(simpleDateFormat.format(Date.from(instant))); } else if (value instanceof Instant) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd'T'hh:mm:ssZ"); simpleDateFormat.setTimeZone(timeZone); cell.setCellValue(simpleDateFormat.format(Date.from((Instant) value))); } else if (value instanceof Double) { cell.setCellValue(toDouble(value)); } else if (value instanceof Integer) { cell.setCellValue(toInt(value)); } else if (value instanceof Long) { cell.setCellValue(toLong(value)); } else if (value instanceof String) { cell.setCellValue(value.toString()); } else { throw new UnsupportedValueException(value); } }</code><technical_language>Potential performance bottleneck create a SimpleDateFormat for cell. setting a field a default format in constructor add setters user select a format (e.g. timezone)</technical_language>

Target:
void setCellValue(Cell cell, Object value) { if (value instanceof Boolean) { cell.setCellValue(toBoolean(value)); } else if (value instanceof LocalDate) { Instant instant = toLocalDate(value).atStartOfDay(timeZone.toZoneId()).toInstant(); cell.setCellValue(simpleDateFormat.format(Date.from(instant))); } else if (value instanceof Instant) { cell.setCellValue(simpleDateTimeFormat.format(Date.from((Instant) value))); } else if (value instanceof Double) { cell.setCellValue(toDouble(value)); } else if (value instanceof Integer) { cell.setCellValue(toInt(value)); } else if (value instanceof Long) { cell.setCellValue(toLong(value)); } else if (value instanceof String) { cell.setCellValue(value.toString()); } else { throw new UnsupportedValueException(value); } }
Source:
<code>static <T> List<T> without(List<T> list, Collection<Integer> indexes) { Set<Integer> indexesSet = ImmutableSet.copyOf(indexes); return IntStream.range(0, list.size()) .filter(index -> !indexesSet.contains(index)) <START> .mapToObj(ImmutableList.copyOf(list)::get) <END> .collect(toImmutableList()); }</code><technical_language>Drop this ImmutableList.copyOf wrapper. reduces clarity do expect random-access lists anyway</technical_language>

Target:
static <T> List<T> without(List<T> list, Collection<Integer> indexes) { Set<Integer> indexesSet = ImmutableSet.copyOf(indexes); return IntStream.range(0, list.size()) .filter(index -> !indexesSet.contains(index)) .mapToObj(list::get) .collect(toImmutableList()); }
Source:
<code>private Scope( Optional<Scope> parent, boolean queryBoundary, RelationId relationId, RelationType relation, Map<String, WithQuery> namedQueries, Map<Identifier, WindowSpecification> windowSpecifications) { this.parent = requireNonNull(parent, "parent is null"); this.relationId = requireNonNull(relationId, "relationId is null"); this.queryBoundary = queryBoundary; this.relation = requireNonNull(relation, "relation is null"); this.namedQueries = ImmutableMap.copyOf(requireNonNull(namedQueries, "namedQueries is null")); <START> this.windowSpecifications = ImmutableMap.copyOf(requireNonNull(windowSpecifications, "windowSpecifications is null")); <END> }</code><technical_language>requireNonNull is necessary here. ImmutableMap.copyOf() checks for nullness</technical_language>

Target:
private Scope( Optional<Scope> parent, boolean queryBoundary, RelationId relationId, RelationType relation, Map<String, WithQuery> namedQueries, Map<Identifier, WindowSpecification> windowSpecifications) { this.parent = requireNonNull(parent, "parent is null"); this.relationId = requireNonNull(relationId, "relationId is null"); this.queryBoundary = queryBoundary; this.relation = requireNonNull(relation, "relation is null"); this.namedQueries = ImmutableMap.copyOf(requireNonNull(namedQueries, "namedQueries is null")); this.windowSpecifications = ImmutableMap.copyOf(windowSpecifications); }
Source:
<code>private void handleReject(SQLException e) { IndexedRecord reject = new GenericData.Record(schemaReject); for (Schema.Field outField : schemaReject.getFields()) { Object outValue = null; if ("errorCode".equals(outField.name())) { outValue = e.getSQLState(); } else if ("errorMessage".equals(outField.name())) { outValue = e.getMessage(); <START> } <END> reject.put(outField.pos(), outValue); } rejectMessage = new HashMap<String, Object>(); rejectMessage.put("error", e.getMessage()); rejectMessage.put("errorCode", e.getSQLState()); rejectMessage.put("errorMessage", e.getMessage()); rejectMessage.put("exception", e.toString()); rejectMessage.put("talend_record", reject); isRejectError = true; }</code><technical_language>schemaReject.getField("fieldName") instead of loop</technical_language>

Target:
private void handleReject(SQLException e) { IndexedRecord reject = new GenericData.Record(schemaReject); reject.put(schemaReject.getField("errorCode").pos(), e.getSQLState()); reject.put(schemaReject.getField("errorMessage").pos(), e.getMessage()); rejectInfo = new HashMap<String, Object>(); rejectInfo.put("error", e.getMessage()); rejectInfo.put("errorCode", e.getSQLState()); rejectInfo.put("errorMessage", e.getMessage()); rejectInfo.put("exception", e.toString()); rejectInfo.put("talend_record", reject); isRejectError = true; }
Source:
<code>public void serialize(XMLExtendedStreamWriter writer, JdbcMixedStoreConfiguration configuration) throws XMLStreamException { writer.writeStartElement(Element.MIXED_KEYED_JDBC_STORE); writeJdbcStoreAttributes(writer, configuration); <START> writeJDBCStoreTable(writer, Element.STRING_KEYED_TABLE, configuration.stringTable()); <END> writeJDBCStoreTable(writer, Element.BINARY_KEYED_TABLE, configuration.binaryTable()); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); }</code><technical_language>missing KEY2STRING_MAPPER attribute</technical_language>

Target:
public void serialize(XMLExtendedStreamWriter writer, JdbcMixedStoreConfiguration configuration) throws XMLStreamException { writer.writeStartElement(Element.MIXED_KEYED_JDBC_STORE); writeJdbcStoreAttributes(writer, configuration); writeCommonStoreSubAttributes(writer, configuration); writeJDBCStoreTable(writer, Element.STRING_KEYED_TABLE, configuration.stringTable()); writeJDBCStoreTable(writer, Element.BINARY_KEYED_TABLE, configuration.binaryTable()); writeJDBCStoreConnection(writer, configuration); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); }
Source:
<code>private void intiChangeListener() { final EditText email = (EditText) findViewById(R.id.email); findViewById(R.id.confirm).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { User user = new User(); user.email = email.getText().toString(); <START> TaskQueue.loadQueueDefault(v.getContext()).execute(new UpdateUserTask(user)); <END> Toast.makeText(v.getContext(), "TODO", Toast.LENGTH_SHORT).show(); } }); }</code><technical_language>FIXME: user email changed successfully</technical_language>

Target:
private void intiChangeListener() { final EditText email = (EditText) findViewById(R.id.email); findViewById(R.id.confirm).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { User user = new User(); user.id = AppPrefs.getInstance(v.getContext()).getCurrentUserId(); user.email = email.getText().toString(); TaskQueue.loadQueueDefault(v.getContext()).execute(new UpdateUserTask(user)); } }); }
Source:
<code>public boolean checkValue(Collection<String> errorMessages) { if (!valueRequired) return true; <START> if ((value == null) || (value.isEmpty())) { END> errorMessages.add(name + " is not set properly"); return false; } return true; }</code><technical_language>true pw white space, a password consists of whitespace considered invalid? :)</technical_language>

Target:
public boolean checkValue(Collection<String> errorMessages) { if (!valueRequired) return true; if ((value == null) || (value.trim().isEmpty())) { errorMessages.add(name + " is not set properly"); return false; } return true; }
Source:
<code>public ZestExpressionURL deepCopy() { ZestExpressionURL copy = new ZestExpressionURL(); List<String> copyIncludeRegex = new ArrayList<>(includeRegexes); List<String> copyExcludeRegex = new ArrayList<>(excludeRegexes); List<Pattern> copyIncludePatterns = new ArrayList<>(includePatterns); <START> List<Pattern> copyExcludePatterns = new ArrayList<>(excludePatterns); <END> copy.excludePatterns = copyExcludePatterns; copy.includePatterns = copyIncludePatterns; copy.includeRegexes = copyIncludeRegex; copy.excludeRegexes = copyExcludeRegex; return copy; }</code><technical_language>Dont need deepCopy'ed</technical_language>

Target:
public ZestExpressionURL deepCopy() { ZestExpressionURL copy = new ZestExpressionURL(); List<String> copyIncludeRegex = new ArrayList<>(includeRegexes); List<String> copyExcludeRegex = new ArrayList<>(excludeRegexes); copy.includeRegexes = copyIncludeRegex; copy.excludeRegexes = copyExcludeRegex; return copy; }
Source:
<code>public Iterable<GroupInformationType> createGroupInformationElementsFor(Content content) { if (!permit.isPermitted(content)) { return ImmutableSet.of(); } if (content instanceof Film) { return ImmutableSet.of(groupInfoGenerator.generate((Film) content)); } if (content instanceof Brand) { return ImmutableSet.of(groupInfoGenerator.generate((Brand) content, hierarchy.lastItemFrom((Brand) content))); } <START> if (content instanceof Series) { <END> ImmutableSet.Builder<GroupInformationType> groupInfoElems = ImmutableSet.builder(); Series series = (Series) content; Optional<Brand> brand = hierarchy.brandFor(series); groupInfoElems.add(groupInfoGenerator.generate(series, brand, hierarchy.lastItemFrom(series))); if (brand.isPresent() && permit.isPermitted(brand.get())) { groupInfoElems.add(groupInfoGenerator.generate(brand.get(), hierarchy.lastItemFrom(brand.get()))); } return groupInfoElems.build(); } if (content instanceof Item) { ImmutableSet.Builder<GroupInformationType> groupInfoElems = ImmutableSet.builder(); Item item = (Item) content; Optional<Series> series = hierarchy.seriesFor(item); Optional<Brand> brand = hierarchy.brandFor(item); groupInfoElems.add(groupInfoGenerator.generate(item, series, brand)); if (series.isPresent() && permit.isPermitted(series.get())) { groupInfoElems.add(groupInfoGenerator.generate(series.get(), brand, hierarchy.lastItemFrom(series.get()))); } if (brand.isPresent() && permit.isPermitted(brand.get())) { groupInfoElems.add(groupInfoGenerator.generate(brand.get(), hierarchy.lastItemFrom(brand.get()))); } return groupInfoElems.build(); } throw new UnexpectedContentTypeException(content); }</code><technical_language>Split out separate methods</technical_language>

Target:
public Iterable<GroupInformationType> createGroupInformationElementsFor(Content content) { if (!permit.isPermitted(content)) { return ImmutableSet.of(); } if (content instanceof Film) { return groupInfoElemsForFilm(content); } if (content instanceof Brand) { return groupInfoElemsForBrand(content); } if (content instanceof Series) { return groupInfoElemsForSeries(content); } if (content instanceof Item) { return groupInfoElemsForItem(content); } throw new UnexpectedContentTypeException(content); }
Source:
<code>private static List<Path> findOpenOfficeDirectories(List<Path> programDirectories) { BiPredicate<Path, BasicFileAttributes> filePredicate = (path, attr) -> attr.isDirectory() && (path.toString().toLowerCase(Locale.ROOT).contains("openoffice") || path.toString().toLowerCase(Locale.ROOT).contains("libreoffice")); return programDirectories.stream().flatMap(dirs -> { try { return Files.find(dirs, 1, filePredicate); } catch (IOException e) { <START> return Stream.empty(); <END> } }).collect(Collectors.toList()); }</code><technical_language>Please add a Logger statement strange cases debugged</technical_language>

Target:
private static List<Path> findOpenOfficeDirectories(List<Path> programDirectories) { BiPredicate<Path, BasicFileAttributes> filePredicate = (path, attr) -> attr.isDirectory() && (path.toString().toLowerCase(Locale.ROOT).contains("openoffice") || path.toString().toLowerCase(Locale.ROOT).contains("libreoffice")); return programDirectories.stream().flatMap(dirs -> { try { return Files.find(dirs, 1, filePredicate); } catch (IOException e) { LOGGER.error("Problem searching for openoffice/libreoffice install directory", e); return Stream.empty(); } }).collect(Collectors.toList()); }
Source:
<code>public void setCurrentTabId(String category, String tabId, String... subTabIds) { if (category != null && category.equals(MAIN_TABS_CATEGORY) && tabId != null && currentTabActions.getCurrentTabIds() != null <START> && !currentTabActions.getCurrentTabIds().startsWith(category + ":" + tabId)) { <END> Events.instance().raiseEvent(EventNames.MAIN_TABS_CHANGED); } currentTabActions.setCurrentTabId(actionManager, createActionContext(), category, tabId, subTabIds); if (WebActions.DEFAULT_TABS_CATEGORY.equals(category)) { resetSubTabs(); } }</code><technical_language>!tabId.equals(getCurrentTabId(MAIN_TABS_CATEGORY))</technical_language>

Target:
public void setCurrentTabId(String category, String tabId, String... subTabIds) { if (category != null && category.equals(MAIN_TABS_CATEGORY) && tabId != null && currentTabActions.getCurrentTabIds() != null && !tabId.equals(getCurrentTabId(MAIN_TABS_CATEGORY))) { Events.instance().raiseEvent(EventNames.MAIN_TABS_CHANGED); } currentTabActions.setCurrentTabId(actionManager, createActionContext(), category, tabId, subTabIds); if (WebActions.DEFAULT_TABS_CATEGORY.equals(category)) { resetSubTabs(); } }
Source:
<code>public void onResume() { super.onResume(); boolean usersExist = true; UserAccount selectedAccount = null; final List<UserAccount> accounts = getAccounts(); if (accounts == null) { usersExist = false; } final String userHint = spConfig.getUserHint(); if (!TextUtils.isEmpty(userHint)) { final String[] userParts = userHint.split(COLON); if (userParts.length == 2) { final String orgId = userParts[0]; final String userId = userParts[1]; selectedAccount = SalesforceSDKManager.getInstance(). getUserAccountManager().getUserFromOrgAndUserId(orgId, userId); if (selectedAccount != null) { usersExist = true; } } } if (!usersExist) { accountSelected(null); } else { if (selectedAccount != null) { accountSelected(selectedAccount); <START> } <END> } }</code><technical_language>need usersExists flag. getUserFromOrgAndUserId handles accounts, simply do: java super.onresume(); UserAccount selectedAccount = null; final String userHint = spConfig.getUserHint(); if (!TextUtils.isEmpty(userHint)) { final String[] userParts = userHint.split(COLON); /* * for 'user_hint' of format 'orgId:userId' * 18-character versions of 'orgId' 'userId'. */ if (userParts.length == 2) { final String orgId = userParts[0]; final String userId = userParts[1]; selectedAccount = SalesforceSDKManager.getInstance(). getUserAccountManager().getUserFromOrgAndUserId(orgId, userId); } } /* * If build a user account 'user_hint' passed in, launches SP login flow for account. * Otherwise, launch new user login flow (because selectedAccount null). */ accountSelected(selectedAccount);</technical_language>

Target:
public void onResume() { super.onResume(); UserAccount selectedAccount = null; final String userHint = spConfig.getUserHint(); if (!TextUtils.isEmpty(userHint)) { final String[] userParts = userHint.split(COLON); if (userParts.length == 2) { final String orgId = userParts[0]; final String userId = userParts[1]; selectedAccount = SalesforceSDKManager.getInstance(). getUserAccountManager().getUserFromOrgAndUserId(orgId, userId); } } if (selectedAccount != null || getAccounts() == null) { accountSelected(selectedAccount); } }
Source:
<code>static URL getDockerImageUrl(String os, String version) throws MalformedURLException { if (parseVersion(version).isNewerThan(parseVersion("17.05.0-ce"))) return new URL("<LINK_0>" + os + "/docker-" + version); String osName=""; if (os.startsWith("linux")) osName = "Linux"; if (os.startsWith("win")) osName = "Windows"; <START> if (os.startsWith("mac")) osName = "Darwin"; <END> return new URL("<LINK_1>" + osName + os.substring(os.lastIndexOf("/")) + "/docker-" + version); }</code><technical_language>sense print warnings if is match? (e.g. new platform)</technical_language>

Target:
static URL getDockerImageUrl(String os, String version) throws MalformedURLException { final int i = os.indexOf("/"); if (parseVersion(version).isNewerThan(parseVersion("17.05.0-ce"))) { return new URL("<LINK_0>" + os.substring(0, i) + "/static/edge/"+ os.substring(i + 1) + "/docker-" + version); } return new URL("<LINK_1>" + FindArch.asGetDockerArchName(os) + os.substring(i +1) + "/docker-" + version); }