auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public SnapshotReadMessage read() { if (currentStreamInfo == null || !currentStreamInfo.iterator.hasNext()) { <START> if (streamsToSent.isEmpty()) { <END> return new SnapshotReadMessage(null, true); } currentStreamInfo = new StreamInfo(streamsToSent.poll(), rt, globalSnapshot); } List msgs = new ArrayList<TxMessage>(); msgs.add(next(currentStreamInfo)); return new SnapshotReadMessage(msgs, streamsToSent.isEmpty()&&!currentStreamInfo.iterator.hasNext()); }</code><technical_language>change -> streamsToSend</technical_language>

Target:
public SnapshotReadMessage read() { if (currentStreamInfo == null || !currentStreamInfo.iterator.hasNext()) { while (!streamsToSend.isEmpty()) { currentStreamInfo = new OpaqueStreamIterator(streamsToSend.poll(), rt, globalSnapshot); if (currentStreamInfo.iterator.hasNext()) { break; } log.info("Snapshot reader will skip reading stream as there are no entries to send", currentStreamInfo.uuid); } if (streamsToSend.isEmpty() && !currentStreamInfo.iterator.hasNext()) { log.info(""); return new SnapshotReadMessage(null, true); } } List msgs = new ArrayList<TxMessage>(); msgs.add(read(currentStreamInfo)); if (!currentStreamInfo.iterator.hasNext()) { log.debug("Snapshot reader finish reading stream {}", currentStreamInfo.uuid); } if (streamsToSend.isEmpty()) { log.info("Snapshot reader finish reading all streams {}", streams); } return new SnapshotReadMessage(msgs, streamsToSend.isEmpty()&&!currentStreamInfo.iterator.hasNext()); }
Source:
<code>private void glusterHostAdd(Guid targetClusterId) { String hostName = (getVds().gethost_name().isEmpty()) ? getVds().getManagmentIp() <START> : getVds().gethost_name(); <END> VDSReturnValue returnValue = runVdsCommand( VDSCommandType.GlusterHostAdd, new GlusterHostAddVDSParameters(getClusterUtils().getUpServer(targetClusterId).getId(), hostName)); setSucceeded(returnValue.getSucceeded()); if (!getSucceeded()) { handleVdsError(returnValue); errorType = AuditLogType.GLUSTER_HOST_ADD_FAILED; return; } }</code><technical_language>logic is relevant in remove</technical_language>

Target:
private boolean glusterHostAdd(Guid targetClusterId) { String hostName = (getVds().gethost_name().isEmpty()) ? getVds().getManagmentIp() : getVds().gethost_name(); VDSReturnValue returnValue = runVdsCommand( VDSCommandType.GlusterHostAdd, new GlusterHostAddVDSParameters(getClusterUtils().getUpServer(targetClusterId).getId(), hostName)); if (getSucceeded()) { return true; } else { handleVdsError(returnValue); errorType = AuditLogType.GLUSTER_HOST_ADD_FAILED; return false; } }
Source:
<code>public void emitTuples() { if (currentWindowId <= windowDataManager.getLargestCompletedWindow()) { return; } if (inputStream == null) { try { if (currentFile != null && offset > 0) { int tmpOffset = offset; if (fs.exists(new Path(currentFile))) { this.inputStream = openFile(new Path(currentFile)); offset = tmpOffset; skipCount = tmpOffset; } else { currentFile = null; offset = 0; skipCount = 0; } } else if (!unfinishedFiles.isEmpty()) { retryFailedFile(unfinishedFiles.poll()); } else if (!pendingFiles.isEmpty()) { String newPathString = pendingFiles.iterator().next(); pendingFiles.remove(newPathString); if (fs.exists(new Path(newPathString))) { this.inputStream = openFile(new Path(newPathString)); } } else if (!failedFiles.isEmpty()) { retryFailedFile(failedFiles.poll()); } else { scanDirectory(); } } catch (IOException ex) { failureHandling(ex); } } if (inputStream != null) { int startOffset = offset; String file = currentFile; boolean fileClosed = false; try { int counterForTuple = 0; while (counterForTuple++ < emitBatchSize) { T line = readEntity(); if (line == null) { LOG.info("done reading file ({} entries).", offset); closeFile(inputStream); <START> fileClosed = true; <END> break; } if (skipCount == 0) { offset++; emit(line); } else { skipCount--; } } } catch (IOException e) { failureHandling(e); } if (offset > startOffset) { currentWindowRecoveryState.add(new RecoveryEntry(file, startOffset, offset, fileClosed)); } } }</code><technical_language>Check empty file: replay, openFile() closeFile() calls skipped recovery entries for file</technical_language>

Target:
public void emitTuples() { if (currentWindowId <= windowDataManager.getLargestCompletedWindow()) { return; } if (inputStream == null) { try { if (currentFile != null && offset > 0) { long tmpOffset = offset; if (fs.exists(new Path(currentFile))) { this.inputStream = openFile(new Path(currentFile)); offset = tmpOffset; skipCount = tmpOffset; } else { currentFile = null; offset = 0; skipCount = 0; } } else if (!unfinishedFiles.isEmpty()) { retryFailedFile(unfinishedFiles.poll()); } else if (!pendingFiles.isEmpty()) { String newPathString = pendingFiles.iterator().next(); pendingFiles.remove(newPathString); if (fs.exists(new Path(newPathString))) { this.inputStream = openFile(new Path(newPathString)); } } else if (!failedFiles.isEmpty()) { retryFailedFile(failedFiles.poll()); } else { scanDirectory(); } } catch (IOException ex) { failureHandling(ex); } } if (inputStream != null) { long startOffset = offset; String file = currentFile; boolean fileClosed = false; try { int counterForTuple = 0; while (counterForTuple++ < emitBatchSize) { T line = readEntity(); if (line == null) { LOG.info("done reading file ({} entries).", offset); closeFile(inputStream); fileClosed = true; break; } if (skipCount == 0) { offset++; emit(line); } else { skipCount--; } } } catch (IOException e) { failureHandling(e); } if (offset >= startOffset) { currentWindowRecoveryState.add(new RecoveryEntry(file, startOffset, offset, fileClosed)); } } }
Source:
<code><START> void postSpans(byte[] json) throws Exception { <END> HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); json = compressRequestIfApplicable(json); RequestEntity<byte[]> requestEntity = new RequestEntity<>(json, httpHeaders, HttpMethod.POST, URI.create(this.url)); this.restTemplate.exchange(requestEntity, String.class); }</code><technical_language>RestTemplate throws Exception (vs Runtime IOException)</technical_language>

Target:
void postSpans(byte[] json) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); RequestEntity<byte[]> requestEntity = new RequestEntity<>(json, httpHeaders, HttpMethod.POST, URI.create(this.url)); this.restTemplate.exchange(requestEntity, String.class); }
Source:
<code>private Set<String> convertToTagSet(Object tagObject) { if (tagObject instanceof String) { LOGGER.trace("Found single tag {}", tagObject); return Collections.singleton((String) tagObject); } if (tagObject instanceof Set) { LOGGER.trace("Found set of tags {}", tagObject); Set<?> tagSet = (Set) tagObject; if (tagSet.size() <START> != tagSet.stream().filter(String.class::isInstance).collect(Collectors.toSet()).size()) { <END> LOGGER.trace("At least one of the objects in the set is not a string"); return Collections.emptySet(); } return tagSet.stream().map(String.class::cast).collect(Collectors.toSet()); } LOGGER.trace("Unrecognized tag object {}", tagObject); return Collections.emptySet(); }</code><technical_language>replace .collect(Collectors.toSet()).size() .count()</technical_language>

Target:
private Set<String> convertToTagSet(Object tagObject) { if (tagObject instanceof String) { LOGGER.trace("Found single tag {}", tagObject); return Collections.singleton((String) tagObject); } if (tagObject instanceof Set) { LOGGER.trace("Found set of tags {}", tagObject); Set<?> tagSet = (Set) tagObject; if (tagSet.size() != tagSet.stream().filter(String.class::isInstance).count()) { LOGGER.trace("At least one of the objects in the set is not a string"); return Collections.emptySet(); } return tagSet.stream().map(String.class::cast).collect(Collectors.toSet()); } LOGGER.trace("Unrecognized tag object {}", tagObject); return Collections.emptySet(); }
Source:
<code>public <S extends Message, T extends Message> void dispatch(SinkModule<S, T> module, String topic, T message) { try (MDCCloseable mdc = Logging.withPrefixCloseable(MessageConsumerManager.LOG_PREFIX)) { LOG.trace("dispatch({}): sending message {}", topic, message); final String queueName = getModuleMetadata(module); final String queueUrl = getQueueUrl(queueName); if (queueUrl == null) { LOG.warn("Cannot obtain URL for queue {}. The message cannot be sent.", queueName); } else { <START> sqs.sendMessage(queueUrl, module.marshal((T)message)); <END> } } }</code><technical_language>this behave if SQS is reachable</technical_language>

Target:
public <S extends Message, T extends Message> void dispatch(SinkModule<S, T> module, String topic, T message) { try (MDCCloseable mdc = Logging.withPrefixCloseable(MessageConsumerManager.LOG_PREFIX)) { LOG.trace("dispatch({}): sending message {}", topic, message); final String queueName = awsSqsManager.getQueueName(awsConfig, module); final String queueUrl = getQueueUrl(queueName); if (queueUrl == null) { LOG.error("Cannot obtain URL for queue {}. The message cannot be sent.", queueName); } else { try { final String messageId = awsSqsManager.sendMessage(awsConfig, sqs, queueUrl, module.marshal((T)message)); LOG.debug("SQS Message with ID has been successfully sent to {}", messageId, queueUrl); } catch (RuntimeException ex) { LOG.error("Unexpected AWS SDK exception while sending a message", ex); } } } }
Source:
<code>private void onOpenCategory(String categoryId) { <START> categoryWidgets.entrySet().stream().filter(entry -> !entry.getKey().equals(categoryId)).forEach(entry -> entry.getValue().setVisible(false)); <END> DefinitionPaletteCategoryWidget widget = categoryWidgets.get(categoryId); widget.setVisible(true); }</code><technical_language>Streams in proper way, I propose slight improvement: java categoryWidgets.entrySet() .stream() .filter(entry -> !Objects.equals(entry.getKey(), categoryId)) .forEach(entry -> entry.getValue().setVisible(false)); I proposed formatting is more readable prevents NPE in filter part, WDYT</technical_language>

Target:
private void onOpenCategory(String categoryId) { categoryWidgets.entrySet() .stream() .filter(entry -> !Objects.equals(entry.getKey(), categoryId)) .forEach(entry -> entry.getValue().setVisible(false)); DefinitionPaletteCategoryWidget widget = categoryWidgets.get(categoryId); widget.setVisible(true); }
Source:
<code>private void waitUntilCheck(Predicate<JsonRpcClient> check, String formatBefore, String formatAfter) throws InterruptedException { String hostname = client.getHostname(); if (logger.isDebugEnabled()) { logger.debug(formatBefore, hostname); } int retries = 50; while (check.test(this.client)) { if (retries == 0) { throw new VDSNetworkException("Unable to reconnect to " + hostname + " after policy reset"); } retries--; <START> TimeUnit.MILLISECONDS.sleep(200); <END> } if (logger.isDebugEnabled()) { logger.debug(formatAfter, hostname); } }</code><technical_language>is? if this Thread.sleep? I there, calls Thread.sleep number of ms increased 1. solve issue talking about. I right</technical_language>

Target:
private void waitUntilCheck(Predicate<JsonRpcClient> check, String formatBefore, String formatAfter) throws InterruptedException { String hostname = client.getHostname(); logger.debug(formatBefore, hostname); int retries = 50; while (check.test(this.client)) { if (retries == 0) { throw new VDSNetworkException("Unable to reconnect to " + hostname + " after policy reset"); } retries--; TimeUnit.MILLISECONDS.sleep(200); } logger.debug(formatAfter, hostname); }
Source:
<code>public EntitlerJobConfig setConsumer(final Consumer consumer) { if (consumer == null) { throw new IllegalArgumentException("Consumer is null"); } final String uuid = consumer.getUuid(); this.addConstraint(new ThrottlingConstraint(this.throttle, new AggregateJobMatcher( new MatchByJobKey(JOB_KEY), <START> new MatchByArgument(CONSUMER_UUID_KEY, uuid) <END> ))) .setJobArgument(CONSUMER_UUID_KEY, uuid); return this; }</code><technical_language>complexity of constructing a Constraint object here, good utilize JobConstraints class in a similar uniqueByArgument class is constructed. a user of constraints API, I worry implementation details AggregateJobMatcher, MatchByJobKey MatchByJobKey, simply able do .addConstraint(JobConstraints.uniqueByArgumentAndThrottle( conf.getInt(ConfigProperties.ENTITLER_JOB_THROTTLE), CONSUMER_UUID_KEY) );</technical_language>

Target:
public EntitlerJobConfig setConsumer(final Consumer consumer) { if (consumer == null) { throw new IllegalArgumentException("Consumer is null"); } this.setJobArgument(CONSUMER_UUID_KEY, consumer.getUuid()); return this; }
Source:
<code>public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof HashMap) { <START> final Iterator<?> thisIt = this.iterator(); <END> final Iterator<?> thatIt = ((HashMap<?,?>) o).iterator(); while (thisIt.hasNext() && thatIt.hasNext()) { if (!Objects.equals(thisIt.next(), thatIt.next())) { return false; } } return thisIt.hasNext() == thatIt.hasNext(); } else { return false; } }</code><technical_language>change Iterator.equals(Iterator<? extends T> that) Iterator.equals(Iterator<?> that) final HashMap<?, ?> = (HashMap<?, ?>) o; return this.iterator().equals(that.iterator())? this reduces duplicate code in other collections</technical_language>

Target:
public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof HashMap) { final HashMap<?,?> that = (HashMap<?,?>) o; return this.iterator().equals(that.iterator()); } else { return false; } }
Source:
<code>public DaysOfMonthSelector() { initWidget(wrapperPanel); style = RESOURCES.daysOfMonthSelectorCSS(); style.ensureInjected(); daysOfMonth.setStyleName("daysOfMonthWidget"); showDaysOfMonth(); daysOfMonth.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { Cell cellClicked = daysOfMonth.getCellForEvent(event); int cellColumn = cellClicked.getCellIndex(); int cellRow = cellClicked.getRowIndex(); int actualCellIndex = cellRow * DAYS_IN_WEEK + cellColumn + 1; if (!clickedList.get(actualCellIndex)) { clickedList.set(actualCellIndex, true); <START> onSelectedItemsChange(actualCellIndex, true); <END> } else { clickedList.set(actualCellIndex, false); onSelectedItemsChange(actualCellIndex, false); } } }); }</code><technical_language>want add selectedFlexTableCell style here, clicked it</technical_language>

Target:
public DaysOfMonthSelector() { initWidget(wrapperPanel); style = RESOURCES.daysOfMonthSelectorCSS(); style.ensureInjected(); daysOfMonth.setStyleName(style.daysOfMonthWidget()); showDaysOfMonth(); daysOfMonth.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { Cell cellClicked = daysOfMonth.getCellForEvent(event); int cellColumn = cellClicked.getCellIndex(); int cellRow = cellClicked.getRowIndex(); int actualCellIndex = (cellRow - 1) * DAYS_IN_WEEK + cellColumn; if (!clickedList.get(actualCellIndex)) { ValueChangeEvent.fire(DaysOfMonthSelector.this, addSelectedDate(getValue(), getDateFromIndex(actualCellIndex))); } else { ValueChangeEvent.fire(DaysOfMonthSelector.this, removeSelectedDate(getValue(), getDateFromIndex(actualCellIndex))); } } }); }
Source:
<code>private void commitFile(TopicPartition topicPart) throws IOException, InterruptedException { long startOffset = offsets.get(topicPart) + 1; long endOffset = startOffset + recordCounters.get(topicPart) - 1; <START> offsets.put(topicPart, endOffset); <END> String tempFileName = tempFileNames.get(topicPart); String finalFileName = FileUtils.committedFileName(url, topicsDir, topicPart, startOffset, endOffset); WAL wal = wals.get(topicPart); wal.append(tempFileName, finalFileName); FileUtils.renameFile(fs, tempFileName, finalFileName); }</code><technical_language>update offsets map successfully committed</technical_language>

Target:
private void commitFile(TopicPartition topicPart) throws IOException { long startOffset = offsets.get(topicPart) + 1; long endOffset = startOffset + recordCounters.get(topicPart) - 1; String tempFileName = tempFileNames.get(topicPart); String finalFileName = FileUtils.committedFileName(url, topicsDir, topicPart, startOffset, endOffset); storage.commit(tempFileName, finalFileName); offsets.put(topicPart, endOffset); }
Source:
<code>public void deleteUpload(Contribution contribution) { compositeDisposable.add(repository.deleteContributionFromDB(contribution) <START> .observeOn(mainThreadScheduler) <END> .subscribeOn(ioThreadScheduler) .subscribe()); }</code><technical_language>I need observe thread</technical_language>

Target:
public void deleteUpload(Contribution contribution) { compositeDisposable.add(repository.deleteContributionFromDB(contribution) .subscribeOn(ioThreadScheduler) .subscribe()); }
Source:
<code>public UsersWorkspaceImpl(String id, String name, String owner, Map<String, String> attributes, List<? extends Command> commands, List<? extends ProjectConfig> projects, Map<String, ? extends Environment> environments, String defaultEnvironment, String description) { this.id = id; this.name = name; this.owner = owner; this.description = description; if (environments != null) { this.environments = environments.values() .stream() .collect(toMap(Environment::getName, EnvironmentImpl::new)); } if (commands != null) { this.commands = commands.stream() .map(CommandImpl::new) .collect(toList()); } if (projects != null) { this.projects = projects.stream() .map(ProjectConfigImpl::new) .collect(toList()); } if (attributes != null) { <START> this.attributes = new HashMap<>(attributes); <END> } setDefaultEnvName(defaultEnvironment); }</code><technical_language><LINK_0>,%20T)</technical_language>

Target:
public UsersWorkspaceImpl(String id, String name, String owner, Map<String, String> attributes, List<? extends Command> commands, List<? extends ProjectConfig> projects, Map<String, ? extends Environment> environments, String defaultEnvironment, String description) { this.id = id; this.name = name; this.owner = owner; this.description = description; if (environments != null) { this.environments = environments.values() .stream() .collect(toMap(Environment::getName, EnvironmentStateImpl::new)); } if (commands != null) { this.commands = commands.stream() .map(CommandImpl::new) .collect(toList()); } if (projects != null) { this.projects = projects.stream() .map(ProjectConfigImpl::new) .collect(toList()); } if (attributes != null) { this.attributes = new HashMap<>(attributes); } setDefaultEnvName(defaultEnvironment); }
Source:
<code>public void attemptAddBudget(){ boolean cancel = false; View focusView = null; mBudgetAmountView.setError(null); mBudgetNameView.setError(null); if (mBudgetAmountView.getText().toString().isEmpty()) { mBudgetAmountView.setError(getString(R.string.error_invalid_amount)); focusView = mBudgetAmountView; cancel = true; } <START> if (!cancel&& Double.parseDouble(mBudgetAmountView.getText().toString()) == 0.0) { <END> mBudgetAmountView.setError(getString(R.string.error_zero_amount)); mBudgetAmountView.requestFocus(); focusView = mBudgetAmountView; cancel = true; } if (mBudgetNameView.getText().toString().isEmpty()) { mBudgetNameView.setError(getString(R.string.error_invalid_budget_name)); focusView = mBudgetNameView; cancel = true; } if (cancel) { focusView.requestFocus(); return; } final Budget newBudget = createBudget(); createButtonView.setClickable(false); ApiInterface.getInstance().create(newBudget, new ApiCallback<Long>() { @Override public void onSuccess(Long result) { UBudgetApp app = (UBudgetApp) getApplication(); app.budgetList.add(0, newBudget); finish(); } @Override public void onFailure(String errorMessage) { Toast.makeText(AddBudgetActivity.this, errorMessage, Toast.LENGTH_LONG).show(); createButtonView.setClickable(true); } }); }</code><technical_language>Put a space && - Do double parsing line if statement shorten conditional a bit. a matter of fact, string in previous conditional, store String a variable parse that</technical_language>

Target:
public void attemptAddBudget(){ boolean cancel = false; View focusView = null; mBudgetAmountView.setError(null); mBudgetNameView.setError(null); mBudgetAmount = mBudgetAmountView.getText().toString(); mBudgetName = mBudgetNameView.getText().toString(); if (mBudgetAmount.isEmpty()) { mBudgetAmountView.setError(getString(R.string.error_invalid_amount)); focusView = mBudgetAmountView; cancel = true; } double amount = Double.parseDouble(mBudgetAmountView.getText().toString()); if (!cancel && amount == 0.0) { mBudgetAmountView.setError(getString(R.string.error_zero_amount)); mBudgetAmountView.requestFocus(); focusView = mBudgetAmountView; cancel = true; } if (mBudgetName.isEmpty()) { mBudgetNameView.setError(getString(R.string.error_invalid_budget_name)); focusView = mBudgetNameView; cancel = true; } if (cancel) { focusView.requestFocus(); return; } final Budget newBudget = createBudget(); createButtonView.setClickable(false); ApiInterface.getInstance().create(newBudget, new ApiCallback<Long>() { @Override public void onSuccess(Long result) { UBudgetApp app = (UBudgetApp) getApplication(); app.getBudgetList().add(0, newBudget); finish(); } @Override public void onFailure(String errorMessage) { Toast.makeText(AddBudgetActivity.this, errorMessage, Toast.LENGTH_LONG).show(); createButtonView.setClickable(true); } }); }
Source:
<code>public Result<BpmnNode> convertNode(FlowElement flowElement) { return Match.of(FlowElement.class, Result.class) .when(StartEvent.class, converterFactory.startEventConverter()::convert) .when(EndEvent.class, converterFactory.endEventConverter()::convert) .when(BoundaryEvent.class, converterFactory.intermediateCatchEventConverter()::convertBoundaryEvent) .when(IntermediateCatchEvent.class, converterFactory.intermediateCatchEventConverter()::convert) .when(IntermediateThrowEvent.class, converterFactory.intermediateThrowEventConverter()::convert) .when(Task.class, converterFactory.taskConverter()::convert) .when(Gateway.class, converterFactory.gatewayConverter()::convert) .when(SubProcess.class, converterFactory.subProcessConverter()::convertSubProcess) .when(CallActivity.class, converterFactory.callActivityConverter()::convert) .ignore(DataStore.class) .ignore(DataStoreReference.class) .ignore(DataObjectReference.class) .ignore(DataObject.class) .ignore(TextAnnotation.class) .ignore(Group.class) <START> .defaultValue(Result.ignored("FlowElement not found")) <END> .inputDecorator(BPMNElementDecorators.flowElementDecorator()) .outputDecorator(BPMNElementDecorators.resultBpmnDecorator()) .mode(getMode()) .apply(flowElement) .value() .get(); }</code><technical_language>above, nice pass a messageKey element id parameter</technical_language>

Target:
public Result<BpmnNode> convertNode(FlowElement flowElement) { return Match.of(FlowElement.class, Result.class) .when(StartEvent.class, converterFactory.startEventConverter()::convert) .when(EndEvent.class, converterFactory.endEventConverter()::convert) .when(BoundaryEvent.class, converterFactory.intermediateCatchEventConverter()::convertBoundaryEvent) .when(IntermediateCatchEvent.class, converterFactory.intermediateCatchEventConverter()::convert) .when(IntermediateThrowEvent.class, converterFactory.intermediateThrowEventConverter()::convert) .when(Task.class, converterFactory.taskConverter()::convert) .when(Gateway.class, converterFactory.gatewayConverter()::convert) .when(SubProcess.class, converterFactory.subProcessConverter()::convertSubProcess) .when(CallActivity.class, converterFactory.callActivityConverter()::convert) .ignore(DataStoreReference.class) .ignore(DataObjectReference.class) .ignore(DataObject.class) .ignore(TextAnnotation.class) .defaultValue(Result.ignored("FlowElement not found", getNotFoundMessage(flowElement))) .inputDecorator(BPMNElementDecorators.flowElementDecorator()) .outputDecorator(BPMNElementDecorators.resultBpmnDecorator()) .mode(getMode()) .apply(flowElement) .value(); }
Source:
<code>public static List<Object> sscan(Region<ByteArrayWrapper, RedisSet> region, ByteArrayWrapper key, Pattern matchPattern, int count, int cursor) { RedisSet RedisSet = region.get(key); if (RedisSet != null) { return RedisSet.doSscan(matchPattern, count, cursor); } else { <START> return null; <END> } }</code><technical_language>calling code differentiate null empty collection? If not, return empty collection get rid of upstream null checks</technical_language>

Target:
public static List<Object> sscan(Region<ByteArrayWrapper, RedisSet> region, ByteArrayWrapper key, Pattern matchPattern, int count, int cursor) { RedisSet RedisSet = region.get(key); if (RedisSet != null) { return RedisSet.doSscan(matchPattern, count, cursor); } else { return emptyList(); } }
Source:
<code>public boolean hasLong() { <START> return this.isIntegerCell; <END> }</code><technical_language>range of valid Long is wider Integer</technical_language>

Target:
public boolean hasLong() { return pbCell.hasSint64Value(); }
Source:
<code>public void run() { aclService.assertHasAccess("Insufficient privileges to delete/restore object " + pid.getUUID(), pid, agent.getPrincipals(), markForDeletion); RepositoryObject repoObj = repositoryObjectLoader.getRepositoryObject(pid); if (repoObj instanceof AdminUnit) { <START> aclService.assertHasAccess("Insufficient privileges to delete/restore admin unit " + pid.getUUID(), <END> pid, agent.getPrincipals(), markForDeletionUnit); } if (!(repoObj instanceof ContentObject)) { throw new InvalidOperationForObjectType("Cannot mark object " + pid.getUUID() + " for deletion, objects of type " + repoObj.getClass().getName() + " are not eligible."); } String updateString = createSparqlReplace(pid.getRepositoryPath(), markedForDeletion, true); sparqlUpdateService.executeUpdate(repoObj.getMetadataUri().toString(), updateString); repoObj.getPremisLog().buildEvent(Premis.Deletion) .addImplementorAgent(agent.getUsernameUri()) .addEventDetail("Item marked for deletion and not available without permissions") .write(); }</code><technical_language>separate jobs for restore delete, this assertion "delete"</technical_language>

Target:
public void run() { aclService.assertHasAccess("Insufficient privileges to delete object " + pid.getUUID(), pid, agent.getPrincipals(), markForDeletion); RepositoryObject repoObj = repositoryObjectLoader.getRepositoryObject(pid); if (repoObj instanceof AdminUnit) { aclService.assertHasAccess("Insufficient privileges to delete admin unit " + pid.getUUID(), pid, agent.getPrincipals(), markForDeletionUnit); } if (!(repoObj instanceof ContentObject)) { throw new InvalidOperationForObjectType("Cannot mark object " + pid.getUUID() + " for deletion, objects of type " + repoObj.getClass().getName() + " are not eligible."); } String updateString = createSparqlReplace(pid.getRepositoryPath(), markedForDeletion, true); sparqlUpdateService.executeUpdate(repoObj.getMetadataUri().toString(), updateString); repoObj.getPremisLog().buildEvent(Premis.Deletion) .addImplementorAgent(agent.getUsernameUri()) .addEventDetail("Item marked for deletion and not available without permissions") .write(); }
Source:
<code>public GiveCommand(String name) { super(name, "%nukkit.command.give.description", "%nukkit.command.give.usage"); this.setPermission("nukkit.command.give"); this.commandParameters.clear(); <START> this.commandParameters.put("default", new CommandParameter[]{ <END> new CommandParameter("player", CommandParameter.ARG_TYPE_TARGET, false), new CommandParameter("item", false, CommandParameter.ENUM_TYPE_ITEM_LIST), new CommandParameter("amount", CommandParameter.ARG_TYPE_INT, true), new CommandParameter("meta", CommandParameter.ARG_TYPE_INT, true), new CommandParameter("tags...", CommandParameter.ARG_TYPE_RAW_TEXT, true) }); }</code><technical_language>please return deleted options, item id name</technical_language>

Target:
public GiveCommand(String name) { super(name, "%nukkit.command.give.description", "%nukkit.command.give.usage"); this.setPermission("nukkit.command.give"); this.commandParameters.clear(); this.commandParameters.put("default", new CommandParameter[]{ new CommandParameter("player", CommandParameter.ARG_TYPE_TARGET, false), new CommandParameter("item", false, CommandParameter.ENUM_TYPE_ITEM_LIST), new CommandParameter("amount", CommandParameter.ARG_TYPE_INT, true), new CommandParameter("meta", CommandParameter.ARG_TYPE_INT, true), new CommandParameter("tags...", CommandParameter.ARG_TYPE_RAW_TEXT, true) }); this.commandParameters.put("toPlayerById", new CommandParameter[]{ new CommandParameter("player", CommandParameter.ARG_TYPE_TARGET, false), new CommandParameter("item ID", CommandParameter.ARG_TYPE_INT, false), new CommandParameter("amount", CommandParameter.ARG_TYPE_INT, true), new CommandParameter("tags...", CommandParameter.ARG_TYPE_RAW_TEXT, true) }); this.commandParameters.put("toPlayerByIdMeta", new CommandParameter[]{ new CommandParameter("player", CommandParameter.ARG_TYPE_TARGET, false), new CommandParameter("item ID:meta", CommandParameter.ARG_TYPE_RAW_TEXT, false), new CommandParameter("amount", CommandParameter.ARG_TYPE_INT, true), new CommandParameter("tags...", CommandParameter.ARG_TYPE_RAW_TEXT, true) }); }
Source:
<code>public static String shorten(String s, int len) { s = s.trim(); <START> if (s.length() > 12) { <END> s = s.substring(0, len - 3).trim() + "..."; } return s; }</code><technical_language>Do s.length() > len</technical_language>

Target:
public static String shorten(String s, int len) { s = s.trim(); if (s.length() > len) { s = s.substring(0, len - 3).trim() + "..."; } return s; }
Source:
<code>public void bindViewModel(@NonNull final ProductListViewModel viewModel) { this.viewModel = viewModel; viewModel.fetchDataIfNecessary(); viewModel .state() .observe(this, state -> setRefreshing(state == CollectionListViewModel.State.FETCHING)); viewModel .error() .observe(this, error -> { Snackbar snackbar = Snackbar.make(this, R.string.default_error, Snackbar.LENGTH_LONG); snackbar.getView().setBackgroundResource(R.color.snackbar_error_background); snackbar.show(); }); Transformations .map(viewModel.data(), products -> Util.reduce(products, (viewModels, product) -> { <START> viewModels.add(new ProductListItemViewModel(product)); <END> return viewModels; }, new ArrayList<ListItemViewModel>())) .observe(this, adapter::swapItemsAndNotify); }</code><technical_language>Is reason this transformation done ViewModel side? public class ProductListViewModel extends BasePaginatedListViewModel< ProductListItemViewModel ></technical_language>

Target:
public void bindViewModel(@NonNull final ProductListViewModel viewModel) { this.viewModel = viewModel; viewModel.fetchDataIfNecessary(); viewModel .state() .observe(this, state -> setRefreshing(state == CollectionListViewModel.State.FETCHING)); viewModel .error() .observe(this, error -> { Snackbar snackbar = Snackbar.make(this, R.string.default_error, Snackbar.LENGTH_LONG); snackbar.getView().setBackgroundResource(R.color.snackbar_error_background); snackbar.show(); }); viewModel .items() .observe(this, adapter::swapItemsAndNotify); }
Source:
<code>protected void addItem(String iconClass, String id, String name, String description, Command onClicked) { Element nameEl = onClicked != null ? Document.get().createAnchorElement() : Document.get().createSpanElement(); nameEl.setInnerText(name); nameEl.setClassName(onClicked != null ? "navtree-widget-non-clicked" : "navtree-widget-non-clickable"); if (description != null && !description.equals(name)) { nameEl.setTitle(description); } SpanElement iconSpan = Document.get().createSpanElement(); iconSpan.setClassName("navtree-widget-icon " + iconClass); <START> DivElement div = Document.get().createDivElement(); <END> div.appendChild(iconSpan); div.appendChild(nameEl); navWidget.appendChild((Node) div); itemMap.put(id, nameEl); if (onClicked != null) { Event.sinkEvents(nameEl, Event.ONCLICK); Event.setEventListener(nameEl, event -> { if (Event.ONCLICK == event.getTypeInt()) { onClicked.execute(); } }); } }</code><technical_language>For this type of component, I some of other places, I recommend creating Errai Widgets encapsulate logic</technical_language>

Target:
protected void addItem(String iconClass, String id, String name, String description, Command onClicked) { Element nameEl = onClicked != null ? Document.get().createAnchorElement() : Document.get().createSpanElement(); nameEl.setInnerText(name); nameEl.setClassName(onClicked != null ? "uf-navtree-widget-non-clicked" : "uf-navtree-widget-non-clickable"); if (description != null && !description.equals(name)) { nameEl.setTitle(description); } SpanElement iconSpan = Document.get().createSpanElement(); iconSpan.setClassName("uf-navtree-widget-icon " + iconClass); DivElement div = Document.get().createDivElement(); div.appendChild(iconSpan); div.appendChild(nameEl); navWidget.appendChild((Node) div); itemMap.put(id, nameEl); if (onClicked != null) { Event.sinkEvents(nameEl, Event.ONCLICK); Event.setEventListener(nameEl, event -> { if (Event.ONCLICK == event.getTypeInt()) { onClicked.execute(); } }); } }
Source:
<code>private static ITypedElement createTypedElement(Repository repository, String path, final RevCommit commit, final ObjectId objectId) { <START> if (null != commit) <END> return CompareUtils.getFileRevisionTypedElement(path, commit, repository, objectId); else return new GitCompareFileRevisionEditorInput.EmptyTypedElement(""); }</code><technical_language>style nit: missing braces</technical_language>

Target:
private static ITypedElement createTypedElement(Repository repository, String path, final RevCommit commit, final ObjectId objectId) { if (null != commit) { return CompareUtils.getFileRevisionTypedElement(path, commit, repository, objectId); } else { return new GitCompareFileRevisionEditorInput.EmptyTypedElement(""); } }
Source:
<code>private void prepareInsertExistingPartition(HdfsContext context, PartitionAndMore partitionAndMore) { Partition partition = partitionAndMore.getPartition(); Partition oldPartition = delegate.getPartition(partition.getDatabaseName(), partition.getTableName(), partition.getValues()) .orElseThrow(() -> new PrestoException( TRANSACTION_CONFLICT, <START> format("The partition that this transaction modified was deleted in another transaction. %s %s", partition.getTableName(), partition.getValues()))); <END> Path targetPath = new Path(partition.getStorage().getLocation()); Path currentPath = partitionAndMore.getCurrentLocation(); cleanUpTasksForAbort.add(new DirectoryCleanUpTask(context, targetPath, false)); if (!targetPath.equals(currentPath)) { asyncRename(hdfsEnvironment, renameExecutor, fileRenameCancelled, fileRenameFutures, context, currentPath, targetPath, partitionAndMore.getFileNames()); } replaceParametersOperations.add(new ReplaceParametersOperation( partition.getDatabaseName(), partition.getTableName(), Optional.of(partition.getValues()), partition.getParameters(), oldPartition.getParameters())); }</code><technical_language>Add some punctuation %s %s, Table: %s, partition: '%s' reword "The table %s's partition '%s' this transaction modified deleted in another transaction."</technical_language>

Target:
private void prepareInsertExistingPartition(HdfsContext context, PartitionAndMore partitionAndMore) { deleteOnly = false; Partition partition = partitionAndMore.getPartition(); Path targetPath = new Path(partition.getStorage().getLocation()); Path currentPath = partitionAndMore.getCurrentLocation(); cleanUpTasksForAbort.add(new DirectoryCleanUpTask(context, targetPath, false)); if (!targetPath.equals(currentPath)) { asyncRename(hdfsEnvironment, renameExecutor, fileRenameCancelled, fileRenameFutures, context, currentPath, targetPath, partitionAndMore.getFileNames()); } if (partitionAndMore.getStatisticsUpdate().isPresent()) { updateStatisticsOperations.add( new UpdateStatisticsOperation( new SchemaTableName(partition.getDatabaseName(), partition.getTableName()), Optional.of(partition.getValues()), partitionAndMore.getStatisticsUpdate().get())); } }
Source:
<code>public static Package getUserModel(ExecutionEvent event) { ServiceUtilsForHandlers serviceUtils = ServiceUtilsForHandlers.getInstance(); try { EList<Resource> resources = serviceUtils.getModelSet(event).getResources(); for (int i = 0; i < Math.min(resources.size(), <START> 4); <END> i++) { Resource userResource = resources.get(i); if (userResource.getContents().size() > 0) { EObject topEObj = userResource.getContents().get(0); if ((topEObj instanceof Package) && (!(topEObj instanceof Profile))) { return (Package) topEObj; } } } } catch (ServiceException e) { } return null; }</code><technical_language>a bad id, I think... Ihave idea for that..</technical_language>

Target:
public static Package getUserModel(ExecutionEvent event) { ServiceUtilsForHandlers serviceUtils = ServiceUtilsForHandlers.getInstance(); try { URI uri = serviceUtils.getModelSet(event).getURIWithoutExtension().appendFileExtension(UML_EXT); Resource userResource = serviceUtils.getModelSet(event).getResource(uri, false); if (userResource != null && userResource.getContents().size() > 0) { EObject topEObj = userResource.getContents().get(0); if ((topEObj instanceof Package) && (!(topEObj instanceof Profile))) { return (Package) topEObj; } } } catch (ServiceException e) { Activator.log.error(e); } return null; }
Source:
<code>public void testPerSessionInterpreterCloseOnNoteRemoval() throws IOException, InterpreterException, InterruptedException { Note note1 = notebook.createNote("note1", anonymous); Paragraph p1 = note1.addNewParagraph(AuthenticationInfo.ANONYMOUS); p1.setText("%mock1 getId"); p1.setAuthenticationInfo(anonymous); for (InterpreterSetting setting : note1.getBindedInterpreterSettings(new ArrayList<>())) { setting.getOption().setPerNote(setting.getOption().SCOPED); notebook.getInterpreterSettingManager().restart(setting.getId()); } <START> Thread.sleep(2000); <END> note1.run(p1.getId()); while (p1.getStatus() != Status.FINISHED) Thread.yield(); InterpreterResult result = p1.getReturn(); notebook.removeNote(note1, anonymous); note1 = notebook.createNote("note1", anonymous); p1 = note1.addNewParagraph(AuthenticationInfo.ANONYMOUS); p1.setText("%mock1 getId"); p1.setAuthenticationInfo(anonymous); note1.run(p1.getId()); while (p1.getStatus() != Status.FINISHED) Thread.yield(); assertNotEquals(p1.getReturn().message(), result.message()); notebook.removeNote(note1, anonymous); }</code><technical_language>this change</technical_language>

Target:
public void testPerSessionInterpreterCloseOnNoteRemoval() throws IOException, InterpreterException { Note note1 = notebook.createNote("note1", anonymous); Paragraph p1 = note1.addNewParagraph(AuthenticationInfo.ANONYMOUS); p1.setText("%mock1 getId"); p1.setAuthenticationInfo(anonymous); for (InterpreterSetting setting : note1.getBindedInterpreterSettings(new ArrayList<>())) { setting.getOption().setPerNote(setting.getOption().SCOPED); notebook.getInterpreterSettingManager().restart(setting.getId()); } note1.run(p1.getId()); while (p1.getStatus() != Status.FINISHED) Thread.yield(); InterpreterResult result = p1.getReturn(); notebook.removeNote(note1, anonymous); note1 = notebook.createNote("note1", anonymous); p1 = note1.addNewParagraph(AuthenticationInfo.ANONYMOUS); p1.setText("%mock1 getId"); p1.setAuthenticationInfo(anonymous); note1.run(p1.getId()); while (p1.getStatus() != Status.FINISHED) Thread.yield(); assertNotEquals(p1.getReturn().message(), result.message()); notebook.removeNote(note1, anonymous); }
Source:
<code>public MessageStream<M> sink(SinkFunction<? super M> sinkFn) { String opId = this.streamAppDesc.getNextOpId(OpCode.SINK); SinkOperatorSpec<M> op = OperatorSpecs.createSinkOperatorSpec(sinkFn, opId); this.operatorSpec.registerNextOperatorSpec(op); <START> return new MessageStreamImpl<>(this.streamAppDesc, op); <END> }</code><technical_language>new message stream instead of returning 'this'</technical_language>

Target:
public void sink(SinkFunction<? super M> sinkFn) { String opId = this.streamAppDesc.getNextOpId(OpCode.SINK); SinkOperatorSpec<M> op = OperatorSpecs.createSinkOperatorSpec(sinkFn, opId); this.operatorSpec.registerNextOperatorSpec(op); }
Source:
<code>public void shouldFetchOnlyNonVoidedPatientEncountersIfIncludeAllParamIsSetToFalse() throws Exception { <START> String encounterUuuid = "c59b3942-4fdd-11e5-8c3c-410f8777c163"; <END> String patientUuid = "da7f524f-27ce-4bb2-86d6-6d1d05312bd5"; Patient patient = Context.getPatientService().getPatientByUuid(patientUuid); Encounter enc = Context.getEncounterService().getEncounterByUuid(encounterUuuid); Context.getEncounterService().voidEncounter(enc, "bcbcb"); Context.getEncounterService().saveEncounter(enc); List<Encounter> encs = Context.getEncounterService().getEncountersByPatient(patient.getGivenName()); Assert.assertEquals(1, encs.size()); MockHttpServletRequest req = request(RequestMethod.GET, getURI()); req.addParameter("patient", patientUuid); req.addParameter("includeAll", "false"); SimpleObject result = deserialize(handle(req)); List<Object> encounters = result.get("results"); Assert.assertEquals(1, encounters.size()); }</code><technical_language>this test fail changes</technical_language>

Target:
public void shouldFetchOnlyNonVoidedPatientEncountersIfIncludeAllParamIsSetToFalse() throws Exception { Patient patient = Context.getPatientService().getPatientByUuid(RestTestConstants1_9.PATIENT_WITH_ENCOUNTER_UUID); Encounter enc = Context.getEncounterService().getEncounterByUuid(RestTestConstants1_9.ENCOUNTER_UUID); Context.getEncounterService().voidEncounter(enc, "bcbcb"); Context.getEncounterService().saveEncounter(enc); List<Encounter> encs = Context.getEncounterService().getEncountersByPatient(patient); Assert.assertEquals(1, encs.size()); MockHttpServletRequest req = request(RequestMethod.GET, getURI()); req.addParameter("patient", RestTestConstants1_9.PATIENT_WITH_ENCOUNTER_UUID); req.addParameter("includeAll", "false"); SimpleObject result = deserialize(handle(req)); List<Object> encounters = result.get("results"); Assert.assertEquals(1, encounters.size()); }
Source:
<code>public void testSecondEvent() { CtfTmfEvent event = getEvent(1); <START> assertEquals("Second event type", event.getType().getName()); <END> assertEquals("Second event timestamp" ,1234568, event.getTimestamp().getValue()); assertEquals("Second event int field", 0, ((Long) event.getContent().getField("field_1").getValue()).intValue()); assertEquals("Second event string field", "This is a test", event.getContent().getField("a_string").getValue()); }</code><technical_language>add a message here, changed expected value. Of fail ;)</technical_language>

Target:
public void testSecondEvent() { CtfTmfEvent event = getEvent(1); assertEquals("Second event type", "Spammy_Event", event.getType().getName()); assertEquals("Second event timestamp" ,1234568, event.getTimestamp().getValue()); assertEquals("Second event int field", 0, ((Long) event.getContent().getField("field_1").getValue()).intValue()); assertEquals("Second event string field", "This is a test", event.getContent().getField("a_string").getValue()); }
Source:
<code>private boolean hasStatus(final StatuteType statuteType, final Registration registration) { return registration.getStudent().getStudentStatutesSet().stream() .filter(statute -> statute.getType() == statuteType) <START> .anyMatch(statute -> statute.getBeginExecutionPeriod().isCurrent() || statute.getBeginExecutionPeriod().isCurrent()); <END> }</code><technical_language>this is condition sides</technical_language>

Target:
private boolean hasStatus(final StatuteType statuteType, final Registration registration) { return registration.getStudent().getStudentStatutesSet().stream() .filter(statute -> statute.getType().getCode().equals(statuteType.getCode())) .anyMatch(statute -> statute.getBeginExecutionPeriod().isCurrent() || statute.getEndExecutionPeriod().isCurrent()); }
Source:
<code>public ModelAndView handleRequest(final HttpServletRequest request, final HttpServletResponse response) { val context = new JEEContext(request, response, getOAuthConfigurationContext().getSessionStore()); if (!verifyRevocationRequest(context)) { LOGGER.error("Revocation request verification failed. Request is missing required parameters"); return OAuth20Utils.writeError(response, OAuth20Constants.INVALID_REQUEST); } val manager = new ProfileManager<CommonProfile>(context, context.getSessionStore()); val clientId = OAuth20Utils.getClientIdAndClientSecret(context).getLeft(); val registeredService = getRegisteredServiceByClientId(clientId); <START> if (isServiceNeedAuthentication(registeredService)) { <END> if (manager.get(true).isEmpty()) { LOGGER.error("Service requests authentication", clientId); return OAuth20Utils.writeError(response, OAuth20Constants.ACCESS_DENIED); } } val token = context.getRequestParameter(OAuth20Constants.TOKEN) .map(String::valueOf).orElse(StringUtils.EMPTY); if (isAsupportedTokenType(token)) { return generateRevocationResponse(token, clientId, response); } return OAuth20Utils.writeError(response, OAuth20Constants.INVALID_REQUEST); }</code><technical_language>doesServiceNeedAuthentication()</technical_language>

Target:
public ModelAndView handleRequest(final HttpServletRequest request, final HttpServletResponse response) { val context = new JEEContext(request, response, getOAuthConfigurationContext().getSessionStore()); if (!verifyRevocationRequest(context)) { LOGGER.error("Revocation request verification failed. Request is missing required parameters"); return OAuth20Utils.writeError(response, OAuth20Constants.INVALID_REQUEST); } val manager = new ProfileManager<CommonProfile>(context, context.getSessionStore()); val clientId = OAuth20Utils.getClientIdAndClientSecret(context).getLeft(); val registeredService = getRegisteredServiceByClientId(clientId); if (OAuth20Utils.doesServiceNeedAuthentication(registeredService)) { if (manager.get(true).isEmpty()) { LOGGER.warn("Service requests authentication", clientId); return OAuth20Utils.writeError(response, OAuth20Constants.ACCESS_DENIED); } } else { val service = getOAuthConfigurationContext().getWebApplicationServiceServiceFactory().createService(registeredService.getServiceId()); val audit = AuditableContext.builder() .service(service) .registeredService(registeredService) .build(); val accessResult = getOAuthConfigurationContext().getRegisteredServiceAccessStrategyEnforcer().execute(audit); if (accessResult.isExecutionFailure()) { return OAuth20Utils.writeError(response, OAuth20Constants.INVALID_REQUEST); } } val token = context.getRequestParameter(OAuth20Constants.TOKEN) .map(String::valueOf).orElse(StringUtils.EMPTY); return generateRevocationResponse(token, clientId, response); }
Source:
<code>protected boolean shouldUpdate(final Set<String> changedKeys) { assert changedKeys != null; if (clientConfig.shouldUseDnsForFetchingServiceUrls()) { return false; } if (changedKeys.contains("eureka.client.region")) { return true; } for (final String key : changedKeys) { <START> assert key != null; <END> if (key.startsWith("eureka.client.service-url.") || key.startsWith("eureka.client.serviceUrl.") || key.startsWith("eureka.client.availability-zones.") || key.startsWith("eureka.client.availabilityZones.")) { return true; } } return false; }</code><technical_language>throw exception? if</technical_language>

Target:
protected boolean shouldUpdate(final Set<String> changedKeys) { assert changedKeys != null; if (clientConfig.shouldUseDnsForFetchingServiceUrls()) { return false; } if (changedKeys.contains("eureka.client.region")) { return true; } for (final String key : changedKeys) { if (key.startsWith("eureka.client.service-url.") || key.startsWith("eureka.client.availability-zones.")) { return true; } } return false; }