auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Collection<AbstractNodeTemplate> getDeployableSubgraph(Collection<AbstractNodeTemplate> nodeTemplates, Map<String, Collection<Long>> nodeIds2situationIds) { Set<AbstractNodeTemplate> validDeploymentSubgraph = new HashSet<AbstractNodeTemplate>(nodeTemplates); Collection<AbstractNodeTemplate> toRemove = new HashSet<AbstractNodeTemplate>(); for (AbstractNodeTemplate nodeTemplate : nodeTemplates) { Collection<AbstractRelationshipTemplate> hostingRelations = this.getOutgoingHostedOnRelations(nodeTemplate); if (!hostingRelations.isEmpty()) { boolean foundValidHost = false; for (AbstractRelationshipTemplate relationshipTemplate : hostingRelations) { AbstractNodeTemplate hostingNode = relationshipTemplate.getTarget(); <START> if (this.isValidUnderSituations(hostingNode, nodeIds2situationIds) <END> && nodeTemplates.contains(hostingNode)) { foundValidHost = true; } if (foundValidHost) { break; } } if (!foundValidHost) { toRemove.add(nodeTemplate); } } } if (toRemove.isEmpty()) { return validDeploymentSubgraph; } else { validDeploymentSubgraph.removeAll(toRemove); return getDeployableSubgraph(validDeploymentSubgraph, nodeIds2situationIds); } }</code><technical_language>break in this if statement</technical_language>

Target:
private Collection<AbstractNodeTemplate> getDeployableSubgraph(Collection<AbstractNodeTemplate> nodeTemplates, Map<String, Collection<Long>> nodeIds2situationIds) { Set<AbstractNodeTemplate> validDeploymentSubgraph = new HashSet<AbstractNodeTemplate>(nodeTemplates); Collection<AbstractNodeTemplate> toRemove = new HashSet<AbstractNodeTemplate>(); for (AbstractNodeTemplate nodeTemplate : nodeTemplates) { Collection<AbstractRelationshipTemplate> hostingRelations = this.getOutgoingHostedOnRelations(nodeTemplate); if (!hostingRelations.isEmpty()) { boolean foundValidHost = false; for (AbstractRelationshipTemplate relationshipTemplate : hostingRelations) { AbstractNodeTemplate hostingNode = relationshipTemplate.getTarget(); if (this.isValidUnderSituations(hostingNode, nodeIds2situationIds) && nodeTemplates.contains(hostingNode)) { foundValidHost = true; break; } } if (!foundValidHost) { toRemove.add(nodeTemplate); } } } if (toRemove.isEmpty()) { return validDeploymentSubgraph; } else { validDeploymentSubgraph.removeAll(toRemove); return getDeployableSubgraph(validDeploymentSubgraph, nodeIds2situationIds); } }
Source:
<code>private boolean validateAndSetStorageQuotaHelper(QuotaConsumptionParametersWrapper parameters) { <START> lock.readLock().lock(); <END> try { synchronized (storagePoolQuotaMap.get(parameters.getAuditLogable().getStoragePool().getId())) { if (storagePoolQuotaMap.get(parameters.getAuditLogable().getStoragePool().getId()) == null) { return false; } Map<Guid, Quota> quotaMap = storagePoolQuotaMap.get(parameters.getAuditLogable().getStoragePool().getId()); Map<Guid, Map<Guid, Double>> desiredStorageSizeQuotaMap = new HashMap<Guid, Map<Guid, Double>>(); Map<Guid, Double> newUsedGlobalStorageSize = new HashMap<Guid, Double>(); Map<Guid, Map<Guid, Double>> newUsedSpecificStorageSize = new HashMap<Guid, Map<Guid, Double>>(); generateDesiredStorageSizeQuotaMap(parameters, desiredStorageSizeQuotaMap); for (Guid quotaId : desiredStorageSizeQuotaMap.keySet()) { Quota quota = quotaMap.get(quotaId); if (quota.getGlobalQuotaStorage() != null) { if (checkConsumptionForGlobalStorageQuota(parameters, desiredStorageSizeQuotaMap, newUsedGlobalStorageSize, quotaId, quota)) return false; } else { if (checkConsumptionForSpecificSorageQuota(parameters, desiredStorageSizeQuotaMap, newUsedSpecificStorageSize, quotaId, quota)) return false; } } saveNewConsumptionValues(quotaMap, newUsedGlobalStorageSize, newUsedSpecificStorageSize); } return true; } finally { lock.readLock().unlock(); } }</code><technical_language>modifying stuff - a writeLock somewhere</technical_language>

Target:
private boolean validateAndSetStorageQuotaHelper(QuotaConsumptionParametersWrapper parameters) { Pair<AuditLogType, AuditLogableBase> auditLogPair = new Pair<AuditLogType, AuditLogableBase>(); auditLogPair.setSecond(parameters.getAuditLogable()); lock.readLock().lock(); try { if (storagePoolQuotaMap.get(parameters.getStoragePoolId()) == null) { return false; } synchronized (storagePoolQuotaMap.get(parameters.getStoragePoolId())) { Map<Guid, Quota> quotaMap = storagePoolQuotaMap.get(parameters.getStoragePoolId()); Map<Guid, Map<Guid, Double>> desiredStorageSizeQuotaMap = new HashMap<Guid, Map<Guid, Double>>(); Map<Guid, Double> newUsedGlobalStorageSize = new HashMap<Guid, Double>(); Map<Guid, Map<Guid, Double>> newUsedSpecificStorageSize = new HashMap<Guid, Map<Guid, Double>>(); generateDesiredStorageSizeQuotaMap(parameters, desiredStorageSizeQuotaMap); for (Guid quotaId : desiredStorageSizeQuotaMap.keySet()) { Quota quota = quotaMap.get(quotaId); if (quota.getGlobalQuotaStorage() != null) { if (!checkConsumptionForGlobalStorageQuota(parameters, desiredStorageSizeQuotaMap, newUsedGlobalStorageSize, quotaId, quota, auditLogPair)) return false; } else { if (!checkConsumptionForSpecificSorageQuota(parameters, desiredStorageSizeQuotaMap, newUsedSpecificStorageSize, quotaId, quota, auditLogPair)) return false; } } saveNewConsumptionValues(quotaMap, newUsedGlobalStorageSize, newUsedSpecificStorageSize); } return true; } finally { lock.readLock().unlock(); quotaManagerAuditLogger.auditLog(auditLogPair.getSecond(), auditLogPair.getFirst()); } }
Source:
<code><START> private void setSelectionControlsEnabled(boolean enabled) { <END> copyGraphButton.setEnabled(enabled); removeGraphButton.setEnabled(enabled); }</code><technical_language>'Edit Button' patch is in master, suggest rebasing this patch top of master avoid merge conflicts</technical_language>

Target:
private void setSelectionControlsEnabled(boolean enabled) { copyGraphButton.setEnabled(enabled); editGraphButton.setEnabled(enabled); removeGraphButton.setEnabled(enabled); }
Source:
<code>protected void remove(WorkflowTask task) { <START> if (task != null && task.getWebasset() != null) { <END> cache.remove(this.getKey(task.getWebasset(), task.getLanguageId()), TASK_GROUP); cache.remove(task.getWebasset(), STEP_GROUP); } if (task != null && UtilMethods.isSet(task.getId())) { cache.remove(task.getId(), TASK_GROUP); } }</code><technical_language>Null comparisons replaced UtilMethods.isSet(object)</technical_language>

Target:
protected void remove(WorkflowTask task) { if (UtilMethods.isSet(task) && UtilMethods.isSet(task.getWebasset())) { cache.remove(this.getKey(task.getWebasset(), task.getLanguageId()), TASK_GROUP); cache.remove(task.getWebasset(), STEP_GROUP); } if (UtilMethods.isSet(task) && UtilMethods.isSet(task.getId())) { cache.remove(task.getId(), TASK_GROUP); } }
Source:
<code>private void createKey() { CreateKeyActivity activity = (CreateKeyActivity) getActivity(); if (activity == null) { return; } final boolean createSecurityToken = activity.mCreateSecurityToken; CryptoOperationHelper.Callback<SaveKeyringParcel, EditKeyResult> createKeyCallback = new CryptoOperationHelper.Callback<SaveKeyringParcel, EditKeyResult>() { @Override public SaveKeyringParcel createOperationInput() { return mSaveKeyringParcel; } @Override public void onCryptoOperationSuccess(EditKeyResult result) { <START> BackupNotificationUtil.setBackupReminder(getContext(),result.mMasterKeyId, <END> mNameEdit.getText().toString(), mEmailEdit.getText().toString()); if (createSecurityToken) { moveToCard(result); return; } if (result.mMasterKeyId != null && mUploadCheckbox.isChecked()) { uploadKey(result); return; } finishWithResult(result); } @Override public void onCryptoOperationCancelled() { } @Override public void onCryptoOperationError(EditKeyResult result) { displayResult(result); } @Override public boolean onCryptoSetProgress(String msg, int progress, int max) { return false; } }; mCreateOpHelper = new CryptoOperationHelper<>(1, this, createKeyCallback, R.string.progress_building_key); mCreateOpHelper.cryptoOperation(); }</code><technical_language>result.mMasterKeyId null this point. this is in finishWithResult</technical_language>

Target:
private void createKey() { CreateKeyActivity activity = (CreateKeyActivity) getActivity(); if (activity == null) { return; } final boolean createSecurityToken = activity.mCreateSecurityToken; CryptoOperationHelper.Callback<SaveKeyringParcel, EditKeyResult> createKeyCallback = new CryptoOperationHelper.Callback<SaveKeyringParcel, EditKeyResult>() { @Override public SaveKeyringParcel createOperationInput() { return mSaveKeyringParcel; } @Override public void onCryptoOperationSuccess(EditKeyResult result) { if (result != null && getContext() != null) { BackupNotificationUtil.setBackupReminder(getContext(), result.mMasterKeyId, mNameEdit.getText().toString(), mEmailEdit.getText().toString()); } if (createSecurityToken) { moveToCard(result); return; } if (result.mMasterKeyId != null && mUploadCheckbox.isChecked()) { uploadKey(result); return; } finishWithResult(result); } @Override public void onCryptoOperationCancelled() { } @Override public void onCryptoOperationError(EditKeyResult result) { displayResult(result); } @Override public boolean onCryptoSetProgress(String msg, int progress, int max) { return false; } }; mCreateOpHelper = new CryptoOperationHelper<>(1, this, createKeyCallback, R.string.progress_building_key); mCreateOpHelper.cryptoOperation(); }
Source:
<code>public void testCompileCharSeq() { <START> applyCollection(chars -> CharSeq.of(new String(chars))); <END> }</code><technical_language>I this java applyCollection(CharSeq::of);</technical_language>

Target:
public void testCompileCharSeq() { applyCollection(chars -> CharSeq.ofAll(Iterator.ofAll(chars))); }
Source:
<code>public void collectStaticAnnotatedFields(JClassType type, JClassType typeParameter, Class<? extends Annotation> annotation, List<JField> collection) throws UnableToCompleteException { for (JClassType classType : inspectedClass.getFlattenedSupertypeHierarchy()) { for (JField field : classType.getFields()) { if (field.getAnnotation(annotation) != null) { JParameterizedType parameterizedType = field.getType().isParameterized(); if (!field.isStatic() <START> || (typeParameter != null <END> && (parameterizedType == null || !type.isAssignableFrom(parameterizedType) || !typeParameter.isAssignableFrom(parameterizedType.getTypeArgs()[0])))) { logger.log( TreeLogger.ERROR, "Found the annotation @" + annotation.getSimpleName() + " on the invalid field '" + classType.getName() + "." + field.getName() + "'. Field must be static and its type must be " + type.getName() + "<" + typeParameter.getName() + ">.", null); throw new UnableToCompleteException(); } collection.add(field); } } } }</code><technical_language>Is called a null typeParameter</technical_language>

Target:
public void collectStaticAnnotatedFields(JClassType type, JClassType typeParameter, Class<? extends Annotation> annotation, List<JField> collection) throws UnableToCompleteException { for (JClassType classType : inspectedClass.getFlattenedSupertypeHierarchy()) { for (JField field : classType.getFields()) { if (field.getAnnotation(annotation) != null) { JParameterizedType parameterizedType = field.getType().isParameterized(); if (!field.isStatic() || parameterizedType == null || !type.isAssignableFrom(parameterizedType) || !typeParameter.isAssignableFrom(parameterizedType.getTypeArgs()[0])) { logger.log( TreeLogger.ERROR, "Found the annotation @" + annotation.getSimpleName() + " on the invalid field '" + classType.getName() + "." + field.getName() + "'. Field must be static and its type must be " + type.getName() + "<" + typeParameter.getName() + ">.", null); throw new UnableToCompleteException(); } collection.add(field); } } } }
Source:
<code>public void uninstallPush(@NonNull String installationID) throws ThingIFException { <START> thingIfApi.uninstallPush(installationID); <END> }</code><technical_language>Adding this a field is good manner</technical_language>

Target:
public void uninstallPush(@NonNull String installationID) throws ThingIFException { this.thingIfApi.uninstallPush(installationID); }
Source:
<code>public StatusDTO status() { StatusCache statusCache = candlepinCache.getStatusCache(); StatusDTO cached = statusCache.getStatus(); if (cached != null) { return cached; } CandlepinCapabilities caps = CandlepinCapabilities.getCapabilities(); RulesSourceEnum rulesSource = this.jsProvider.getRulesSource(); boolean good = true; try { rulesCurator.getUpdatedFromDB(); } catch (Exception e) { log.error("Error checking database connection", e); good = false; } Mode mode = this.modeManager.getCurrentMode(); ModeChangeReason mcr = this.getOldestReason(this.modeManager.getModeChangeReasons()); good = good && (mode == Mode.NORMAL); StatusDTO status = new StatusDTO() .result(good) .version(version) .release(release) .standalone(standalone) .rulesVersion(jsProvider.getRulesVersion()) .rulesSource(rulesSource != null ? rulesSource.toString() : null) .mode(mode != null ? mode.toString() : null) .modeReason(mcr != null ? mcr.toString() : null) .modeChangeTime(mcr != null ? mcr.getTime().toInstant().atOffset(ZoneOffset.UTC) : null) .managerCapabilities(caps.stream().collect(Collectors.toList())) <START> .timeUTC(new Date().toInstant().atOffset(ZoneOffset.UTC)); <END> if (keycloakEnabled) { AdapterConfig adapterConfig = keycloakConfig.getAdapterConfig(); status .keycloakResource(adapterConfig.getResource()) .keycloakAuthUrl(adapterConfig.getAuthServerUrl()) .keycloakRealm(adapterConfig.getRealm()); } statusCache.setStatus(status); return status; }</code><technical_language>is need create a Date instance convert OffsetDateTime here. OffsetDateTime.now() do</technical_language>

Target:
public StatusDTO status() { StatusCache statusCache = candlepinCache.getStatusCache(); StatusDTO cached = statusCache.getStatus(); if (cached != null) { return cached; } CandlepinCapabilities caps = CandlepinCapabilities.getCapabilities(); RulesSourceEnum rulesSource = this.jsProvider.getRulesSource(); boolean good = true; try { rulesCurator.getUpdatedFromDB(); } catch (Exception e) { log.error("Error checking database connection", e); good = false; } Mode mode = this.modeManager.getCurrentMode(); ModeChangeReason mcr = this.getOldestReason(this.modeManager.getModeChangeReasons()); good = good && (mode == Mode.NORMAL); StatusDTO status = new StatusDTO() .result(good) .version(version) .release(release) .standalone(standalone) .rulesVersion(jsProvider.getRulesVersion()) .rulesSource(rulesSource != null ? rulesSource.toString() : null) .mode(mode != null ? mode.toString() : null) .modeReason(mcr != null ? mcr.toString() : null) .modeChangeTime(mcr != null ? mcr.getTime().toInstant().atOffset(ZoneOffset.UTC) : null) .managerCapabilities(caps.stream().collect(Collectors.toList())) .timeUTC(OffsetDateTime.now()); if (keycloakEnabled) { AdapterConfig adapterConfig = keycloakConfig.getAdapterConfig(); status .keycloakResource(adapterConfig.getResource()) .keycloakAuthUrl(adapterConfig.getAuthServerUrl()) .keycloakRealm(adapterConfig.getRealm()); } statusCache.setStatus(status); return status; }
Source:
<code>synchronized RuntimeException handleException(InvocationTargetException rethrow) { try { throw rethrow.getCause(); } catch (TransactionLockWatchFailedException e) { throw e; } catch (Throwable t) { <START> if (delegate.equals(fallbackCache)) { <END> throw new RuntimeException(t); } else { log.warn("Unexpected failure occurred when trying to use the default cache. " + "Switching to the fallback implementation", t); fallbackCacheSelectedCounter.inc(); delegate = fallbackCache; throw new TransactionLockWatchFailedException("Unexpected failure in the default lock watch cache", t); } } }</code><technical_language>want equals ==</technical_language>

Target:
synchronized RuntimeException handleException(InvocationTargetException rethrow) { try { throw rethrow.getCause(); } catch (TransactionLockWatchFailedException e) { throw e; } catch (Throwable t) { if (delegate == fallbackCache) { throw new RuntimeException(t); } else { log.warn("Unexpected failure occurred when trying to use the default cache. " + "Switching to the fallback implementation", t); fallbackCacheSelectedCounter.inc(); delegate = fallbackCache; throw new TransactionLockWatchFailedException("Unexpected failure in the default lock watch cache", t); } } }
Source:
<code>public Object apply(RevisionResource revision, Input input) throws AuthException, BadRequestException, ResourceConflictException, Exception { final Change.Id changeId = revision.getChange().getId(); final ChangeControl control = revision.getControl(); if (!control.getProjectControl().controlForRef(input.destination) <START> .canUpload()) { <END> throw new AuthException("Not allowed to cherry pick " + changeId.toString() + " to " + input.destination); } final PatchSet.Id patchSetId = revision.getPatchSet().getId(); try { Change.Id cherryPickedChangeId = cherryPickChange.cherryPick(patchSetId, input.message, input.destination); return json.format(cherryPickedChangeId); } catch (InvalidChangeOperationException e ) { throw new BadRequestException(e.getMessage()); } }</code><technical_language>Is this enough? I check read permission for change cherry-picked</technical_language>

Target:
public Object apply(RevisionResource revision, Input input) throws AuthException, BadRequestException, ResourceConflictException, Exception { final ChangeControl control = revision.getControl(); ReviewDb db = dbProvider.get(); if (!control.isVisible(db)) { throw new AuthException("Cherry pick not permitted"); } if (!control.getProjectControl().controlForRef(input.destination) .canUpload()) { throw new AuthException("Not allowed to cherry pick " + revision.getChange().getId().toString() + " to " + input.destination); } final PatchSet.Id patchSetId = revision.getPatchSet().getId(); try { Change.Id cherryPickedChangeId = cherryPickChange.cherryPick(patchSetId, input.message, input.destination); return json.format(cherryPickedChangeId); } catch (InvalidChangeOperationException e) { throw new BadRequestException(e.getMessage()); } }
Source:
<code><START> public void setCheckbox(WebBrowserConfig webBrowserConfig, String url) throws MalformedURLException { <END> UICheckbox saveHostName = find("saveHostName", UICheckbox.class); if (saveHostName != null && webBrowserConfig != null) { saveHostName.setChecked(false); String hostName = new URL(url).getHost(); saveHostName.subscribe(checkbox -> { boolean isTrustedHostName = saveHostName.isChecked(); if (isTrustedHostName) { webBrowserConfig.addTrustedHostName(hostName); } else { webBrowserConfig.removeTrustedHostName(hostName); } }); UICheckbox saveUrl = find("saveUrl", UICheckbox.class); if (saveUrl != null && webBrowserConfig != null) { saveUrl.setChecked(false); saveUrl.subscribe(checkbox -> { boolean isTrustedUrl = saveUrl.isChecked(); if (isTrustedUrl) { webBrowserConfig.addTrustedUrls(url); } else { webBrowserConfig.removeTrustedUrl(url); } }); } } }</code><technical_language>I this is right. this if statement prior checks for saveHostName. seperate combined statement. I recommend seperate</technical_language>

Target:
public void setCheckbox(WebBrowserConfig webBrowserConfig, String url) { UICheckbox saveUrl = find("saveUrl", UICheckbox.class); if (saveUrl != null && webBrowserConfig != null) { saveUrl.setChecked(false); saveUrl.subscribe(checkbox -> { boolean isTrustedUrl = saveUrl.isChecked(); if (isTrustedUrl) { webBrowserConfig.addTrustedUrls(url); } else { webBrowserConfig.removeTrustedUrl(url); } }); } }
Source:
<code>public boolean matches(@Nullable final String s) { if (s == null) { <START> return prefix == null && (suffixStyle == SuffixStyle.MATCH_ANY <END> || suffixStyle == SuffixStyle.MATCH_EMPTY || suffixPattern.matcher("").matches()); } final String suffix; if (prefix == null) { suffix = s; } else if (s.startsWith(prefix)) { suffix = s.substring(prefix.length()); } else { return false; } if (suffixStyle == SuffixStyle.MATCH_ANY) { return true; } else if (suffixStyle == SuffixStyle.MATCH_EMPTY) { return suffix.isEmpty(); } else { return suffixPattern.matcher(suffix).matches(); } }</code><technical_language>this big expression cached computed matches() call</technical_language>

Target:
public boolean matches(@Nullable final String s) { return pattern.matcher(Strings.nullToEmpty(s)).matches(); }
Source:
<code><START> public String toString(boolean explicit) { <END> if (fFilter instanceof ITmfFilterTreeNode) { return ((ITmfFilterTreeNode) fFilter).toString(explicit); } return fFilter.toString(); }</code><technical_language>Consider 'not'</technical_language>

Target:
public String toString(boolean explicit) { if (fFilter instanceof ITmfFilterTreeNode) { return ((ITmfFilterTreeNode) fFilter).toString(explicit); } if (isNot()) { return "not " + fFilter.toString(); } return fFilter.toString(); }
Source:
<code>private static void insertEventsInTable(int numEvents) { try { Cluster cluster = Cluster.builder().addContactPoint(NODE).build(); Session session = cluster.connect(KEYSPACE); String insert = "INSERT INTO " + KEYSPACE + "." + TABLE_NAME + " (ID,lastname,age)" + " VALUES (?,?,?);"; PreparedStatement stmt = session.prepare(insert); BoundStatement boundStatement = new BoundStatement(stmt); for (int i = 0; i < numEvents; i++) { ids.add(UUID.randomUUID()); <START> mapNames.put(i, "test" + i); <END> mapAge.put(i, i + 10); session.execute(boundStatement.bind(ids.get(i), "test" + i, i + 10)); } } catch (DriverException e) { throw new RuntimeException(e); } }</code><technical_language>mapNames mapAge</technical_language>

Target:
private static void insertEventsInTable(int numEvents) { try { Cluster cluster = Cluster.builder().addContactPoint(NODE).build(); Session session = cluster.connect(KEYSPACE); String insert = "INSERT INTO " + KEYSPACE + "." + TABLE_NAME + " (ID,lastname,age)" + " VALUES (?,?,?);"; PreparedStatement stmt = session.prepare(insert); BoundStatement boundStatement = new BoundStatement(stmt); for (int i = 0; i < numEvents; i++) { ids.add(UUID.randomUUID()); mapNames.put(i, "test" + i); mapAge.put(i, i + 10); session.execute(boundStatement.bind(ids.get(i), mapNames.get(i), mapAge.get(i))); } } catch (DriverException e) { throw new RuntimeException(e); } }
Source:
<code>public void remove(final K key) { <START> removeObserver.begin(); <END> checkNonNull(key); try { store.remove(key); } catch (CacheAccessException e) { } finally { removeObserver.end(RemoveOutcome.SUCCESS); } }</code><technical_language>events follow argument validation, precede - if exception is thrown line below, observer left in state</technical_language>

Target:
public void remove(final K key) { statusTransitioner.checkAvailable(); checkNonNull(key); try { store.remove(key); } catch (CacheAccessException e) { } }
Source:
<code>public List<MySearchResult> search(String query) { query = query.toLowerCase(); List<MySearchResult> results = new ArrayList<>(); for (Task t : getProject().getTaskManager().getTasks()) { String snippet = ""; String snippetText = ""; boolean matched = false; if (isNotEmptyAndContains(t.getName(), query)) { matched = true; } for (CustomProperty c : t.getCustomValues().getCustomProperties()) { if (isNotEmptyAndContains(c.getValueAsString(), query)) { matched = true; snippet = c.getDefinition().getName(); snippetText = c.getValueAsString(); break; } } if (isNotEmptyAndContains(t.getNotes(), query)) { matched = true; snippet = GanttLanguage.getInstance().getText("notes"); snippetText = t.getNotes(); } if (isNotEmptyAndContains(String.valueOf(t.getTaskID()), query)) { matched = true; <START> snippet = "Id"; <END> snippetText = String.valueOf(t.getTaskID()); } if (matched) { results.add(new MySearchResult(t, this, query, snippet, snippetText)); } } return results; }</code><technical_language>Please i18n this also. "id" a good key</technical_language>

Target:
public List<MySearchResult> search(String query) { query = query.toLowerCase(); List<MySearchResult> results = new ArrayList<>(); for (Task t : getProject().getTaskManager().getTasks()) { String snippet = ""; String snippetText = ""; boolean matched = false; if (isNotEmptyAndContains(t.getName(), query)) { matched = true; } for (CustomProperty c : t.getCustomValues().getCustomProperties()) { if (isNotEmptyAndContains(c.getValueAsString(), query)) { matched = true; snippet = c.getDefinition().getName(); snippetText = c.getValueAsString(); break; } } if (isNotEmptyAndContains(t.getNotes(), query)) { matched = true; snippet = GanttLanguage.getInstance().getText("notes"); snippetText = t.getNotes(); } if (isNotEmptyAndContains(String.valueOf(t.getTaskID()), query)) { matched = true; snippet = GanttLanguage.getInstance().getText("id"); snippetText = String.valueOf(t.getTaskID()); } if (matched) { results.add(new MySearchResult(t, this, query, snippet, snippetText)); } } return results; }
Source:
<code>public void run() { logger.info("Participant consistency checker is initiated. Participants count = {}", participants.size()); try { ClusterParticipant clusterParticipant = participants.get(0); Set<String> sealedReplicas1 = new HashSet<>(clusterParticipant.getSealedReplicas()); Set<String> stoppedReplicas1 = new HashSet<>(clusterParticipant.getStoppedReplicas()); for (int i = 1; i < participants.size(); ++i) { <START> logger.info("Checking sealed replica list"); <END> Set<String> sealedReplicas2 = new HashSet<>(participants.get(i).getSealedReplicas()); if (!sealedReplicas1.equals(sealedReplicas2)) { logger.warn("Mismatch in sealed replicas. Set is different from set {}", sealedReplicas1, sealedReplicas2); metrics.sealedReplicasMismatchCount.inc(); } logger.info("Checking stopped replica list"); Set<String> stoppedReplicas2 = new HashSet<>(participants.get(i).getStoppedReplicas()); if (!stoppedReplicas1.equals(stoppedReplicas2)) { logger.warn("Mismatch in stopped replicas. Set is different from set {}", stoppedReplicas1, stoppedReplicas2); metrics.stoppedReplicasMismatchCount.inc(); } } } catch (Throwable t) { logger.error("Exception occurs when running consistency checker ", t); } }</code><technical_language>do need info logs</technical_language>

Target:
public void run() { logger.debug("Participant consistency checker is initiated. Participants count = {}", participants.size()); try { ClusterParticipant clusterParticipant = participants.get(0); Set<String> sealedReplicas1 = new HashSet<>(clusterParticipant.getSealedReplicas()); Set<String> stoppedReplicas1 = new HashSet<>(clusterParticipant.getStoppedReplicas()); for (int i = 1; i < participants.size(); ++i) { logger.debug("Checking sealed replica list"); Set<String> sealedReplicas2 = new HashSet<>(participants.get(i).getSealedReplicas()); if (!sealedReplicas1.equals(sealedReplicas2)) { logger.warn("Mismatch in sealed replicas. Set is different from set {}", sealedReplicas1, sealedReplicas2); metrics.sealedReplicasMismatchCount.inc(); } logger.debug("Checking stopped replica list"); Set<String> stoppedReplicas2 = new HashSet<>(participants.get(i).getStoppedReplicas()); if (!stoppedReplicas1.equals(stoppedReplicas2)) { logger.warn("Mismatch in stopped replicas. Set is different from set {}", stoppedReplicas1, stoppedReplicas2); metrics.stoppedReplicasMismatchCount.inc(); } } } catch (Throwable t) { logger.error("Exception occurs when running consistency checker ", t); } }
Source:
<code>private void paintTextLine(TextGroup textGroup, int lineNum, Map<String, Object> styles) { List<Text> line = textGroup.getLine(lineNum); int leftX = textGroup.getLeftX(); int bottomY = textGroup.getBottomY(lineNum); if (line.isEmpty()) { return; } else if (line.size() == 1) { paintWithMinLabel(line, leftX, bottomY, styles); } else { List<Text> middle = line.subList(1, line.size() - 1); OptionalInt minLabel = paintWithMinLabel(middle, leftX, bottomY, styles); Text first = line.get(0); paintBorderLabel(first, minLabel, leftX, bottomY, styles); Text last = line.get(line.size() - 1); <START> if (first != last) { <END> paintBorderLabel(last, minLabel, leftX, bottomY, styles); } } }</code><technical_language>!= ? is Java, Kotlin. != != equals in Java. in case, is texts equals other in sense if more 1 text in line</technical_language>

Target:
private void paintTextLine(TextGroup textGroup, int lineNum, Map<String, Object> styles) { List<Text> line = textGroup.getLine(lineNum); int leftX = textGroup.getLeftX(); int bottomY = textGroup.getBottomY(lineNum); if (line.isEmpty()) { return; } else if (line.size() == 1) { paintWithMinLabel(line, leftX, bottomY, styles); } else { List<Text> middle = line.subList(1, line.size() - 1); OptionalInt minLabel = paintWithMinLabel(middle, leftX, bottomY, styles); Text first = line.get(0); paintBorderLabel(first, minLabel, leftX, bottomY, styles); Text last = line.get(line.size() - 1); paintBorderLabel(last, minLabel, leftX, bottomY, styles); } }
Source:
<code>public QueryRequest process(QueryRequest input) throws PluginExecutionException, StopProcessingException { <START> return null; <END> }</code><technical_language>return input instead of wiping out query request</technical_language>

Target:
public QueryRequest process(QueryRequest input) throws PluginExecutionException, StopProcessingException { final String subjectIdentifier = getSubjectIdentifier(); final Set<String> roles = new HashSet<>(getSubjectRoles()); if (CollectionUtils.isNotEmpty(Sets.intersection(rolesThatCanSeeEverything, roles))) { LOGGER.debug( "Will not modify filter; subject ({}) had at least one role that was exempt [{}]", subjectIdentifier, roles, rolesThatCanSeeEverything); return input; } final TagAggregationVisitor visitor = new TagAggregationVisitor(); final Query query = input.getQuery(); query.accept(visitor, null); final Set<String> discoveredTags = visitor.getTags(); if (CollectionUtils.isEmpty(discoveredTags)) { LOGGER.debug( "Will not modify filter; subject's ({}) query specified no tags", subjectIdentifier, query); return input; } Set<String> tagsNotInCollaborationSet = Sets.filter(discoveredTags, tag -> !collaborationTags.contains(tag)); if (CollectionUtils.isNotEmpty(tagsNotInCollaborationSet)) { LOGGER.debug( "Will not modify filter; subject's ({}) query referenced tags not in collab set [{}]", subjectIdentifier, query, collaborationTags); return input; } Filter policyBranch = createBakedInSecurityPolicySubset(subjectIdentifier, roles); Filter combined = filterBuilder.allOf(query, policyBranch); return new QueryRequestImpl( new QueryImpl(combined), input.isEnterprise(), input.getSourceIds(), input.getProperties()); }
Source:
<code>public ActivityCommentMessage getSenderCopyMessage() { <START> return (this.senderCopyMessageList == null || this.senderCopyMessageList.isEmpty()) ? null <END> : this.senderCopyMessageList.get(0); }</code><technical_language>Suggestion: extract a util method SingletonUtil.getValue(this.senderCopyMessageList).orElse(null)</technical_language>

Target:
public ActivityCommentMessage getSenderCopyMessage() { return getFromHolder(this.senderCopyMessageHolder); }
Source:
<code>private void readRecoveredChannelState() throws IOException, InterruptedException { SequentialChannelStateReader reader = getEnvironment().getTaskStateManager().getSequentialChannelStateReader(); if (reader.hasChannelStates()) { reader.readOutputData(getEnvironment().getAllWriters()); channelIOExecutor.execute(() -> { try { reader.readInputData(getEnvironment().getAllInputGates()); } catch (Exception e) { asyncExceptionHandler.handleAsyncException("Unable to read channel state", e); } }); for (InputGate inputGate : getEnvironment().getAllInputGates()) { inputGate .getStateConsumedFuture() .thenRun(() -> mainMailboxExecutor.execute(inputGate::requestPartitions, "Input gate request partitions")); } } else { <START> requestPartitions(); <END> } }</code><technical_language>unify code paths for (InputGate inputGate : getEnvironment().getAllInputGates()) { inputGate .getStateConsumedFuture() .thenRun(() -> mainMailboxExecutor.execute(inputGate::requestPartitions, "Input gate request partitions")); } set getStateConsumedFuture done if data is available</technical_language>

Target:
private void readRecoveredChannelState() throws IOException, InterruptedException { SequentialChannelStateReader reader = getEnvironment().getTaskStateManager().getSequentialChannelStateReader(); reader.readOutputData(getEnvironment().getAllWriters()); channelIOExecutor.execute(() -> { try { reader.readInputData(getEnvironment().getAllInputGates()); } catch (Exception e) { asyncExceptionHandler.handleAsyncException("Unable to read channel state", e); } }); for (InputGate inputGate : getEnvironment().getAllInputGates()) { inputGate .getStateConsumedFuture() .thenRun(() -> mainMailboxExecutor.execute(inputGate::requestPartitions, "Input gate request partitions")); } }
Source:
<code>private static String generate(FileText fileText, DetailAST detailAST, int lineNumber, int columnNumber, int tabWidth) { final XpathQueryGenerator queryGenerator = new XpathQueryGenerator(detailAST, lineNumber, columnNumber, fileText, tabWidth); final List<String> suppressions = queryGenerator.generate(); final StringBuilder result = new StringBuilder(256); <START> for (int i = 0; i < suppressions.size(); i++) { <END> if (i > 0) { result.append('\n'); } result.append(suppressions.get(i)); } return result.toString(); }</code><technical_language>Stream API Java 8 Collectors.joining a terminator for stream? Stream API allows simplify logic get rid of conditions. code conditions (linear) is easier read support</technical_language>

Target:
private static String generate(FileText fileText, DetailAST detailAST, int lineNumber, int columnNumber, int tabWidth) { final XpathQueryGenerator queryGenerator = new XpathQueryGenerator(detailAST, lineNumber, columnNumber, fileText, tabWidth); final List<String> suppressions = queryGenerator.generate(); return suppressions.stream().collect(Collectors.joining(LINE_SEPARATOR, "", LINE_SEPARATOR)); }
Source:
<code>private void prepareReplication() { try { if (m_producerDRGateway != null) { m_producerDRGateway.initialize(m_catalogContext.cluster.getDrproducerenabled(), VoltDB.getReplicationPort(m_catalogContext.cluster.getDrproducerport()), VoltDB.getDefaultReplicationInterface()); } if (m_consumerDRGateway != null) { <START> m_consumerDRGateway.initialize(m_config.m_startAction.doesRecover() || m_config.m_startAction.doesRejoin()); <END> } } catch (Exception ex) { MiscUtils.printPortsInUse(hostLog); VoltDB.crashLocalVoltDB("Failed to initialize DR", false, ex); } }</code><technical_language>a check is m_config.m_startAction != StartAction.CREATE, covers elastic join well</technical_language>

Target:
private void prepareReplication() { try { if (m_producerDRGateway != null) { m_producerDRGateway.initialize(m_catalogContext.cluster.getDrproducerenabled(), VoltDB.getReplicationPort(m_catalogContext.cluster.getDrproducerport()), VoltDB.getDefaultReplicationInterface()); } if (m_consumerDRGateway != null) { m_consumerDRGateway.initialize(m_config.m_startAction != StartAction.CREATE); } } catch (Exception ex) { MiscUtils.printPortsInUse(hostLog); VoltDB.crashLocalVoltDB("Failed to initialize DR", false, ex); } }
Source:
<code>public void listTopicsTest() { if(AdminUtils.topicExists(kafka_utils.getZkUtils(),"testList")){ kafka_utils.deleteTopic("testList"); } kafka_utils.createTopic("testList"); kafka_utils.createTopic("testList2"); assertThat(kafka_utils.listTopics()).contains("testList"); <START> System.out.println(kafka_utils.listTopics()); <END> assertThat(kafka_utils.listTopics()).contains("testList2"); kafka_utils.deleteTopic("testList"); kafka_utils.deleteTopic("testList2"); }</code><technical_language>System.out used. A logger is go</technical_language>

Target:
public void listTopicsTest() { if(AdminUtils.topicExists(kafka_utils.getZkUtils(),"testList")){ kafka_utils.deleteTopic("testList"); } kafka_utils.createTopic("testList"); kafka_utils.createTopic("testList2"); assertThat(kafka_utils.listTopics()).contains("testList"); logger.error("Kafka contains next topics: " +Joiner.on(",").join(kafka_utils.listTopics())); assertThat(kafka_utils.listTopics()).contains("testList2"); kafka_utils.deleteTopic("testList"); kafka_utils.deleteTopic("testList2"); }
Source:
<code>private void render(SafeHtmlBuilder sb, int row, ChangeAndCommit info) { sb.openTr(); sb.openTd().setStyleName(FileTable.R.css().pointer()).closeTd(); sb.openTd().addStyleName(Gerrit.RESOURCES.css().relatedChangesSubject()); String url = url(info); if (url != null) { sb.openAnchor().setAttribute("href", url); if (url.startsWith("#")) { sb.setAttribute("onclick", OPEN + "(event," + row + ")"); } <START> sb.append((showBranches ? info.branch() + ": " : "") + info.commit().subject()); <END> sb.closeAnchor(); } else { sb.append(info.commit().subject()); } sb.closeTd(); sb.closeTr(); }</code><technical_language>conditionals avoid string concat subject</technical_language>

Target:
private void render(SafeHtmlBuilder sb, int row, ChangeAndCommit info) { sb.openTr(); sb.openTd().setStyleName(FileTable.R.css().pointer()).closeTd(); sb.openTd().addStyleName(Gerrit.RESOURCES.css().relatedChangesSubject()); String url = url(info); if (url != null) { sb.openAnchor().setAttribute("href", url); if (url.startsWith("#")) { sb.setAttribute("onclick", OPEN + "(event," + row + ")"); } if (showBranches) { sb.append(info.branch()).append(": "); } sb.append(info.commit().subject()); sb.closeAnchor(); } else { sb.append(info.commit().subject()); } sb.closeTd(); sb.closeTr(); }
Source:
<code>public ArrayList<CategoryPill.Data> execute(final CreateCategoryContext context) { String response = null; try { response = remoteOperation.execute(buildUrl(context)); } catch(RemoteException e) { PageObjectLogging.logError("error: ", e); } <START> return getCategories(response, context); <END> }</code><technical_language>+ try { + return remoteOperation.execute(buildUrl(context)); + } catch(RemoteException e) { + PageObjectLogging.logError("error: ", e); + return getCategories(response, context); + }</technical_language>

Target:
public List<CategoryPill.Data> execute(final CreateCategoryContext context) { try { return getCategories(remoteOperation.execute(buildUrl(context)), context); } catch(RemoteException e) { PageObjectLogging.logError("error: ", e); throw new CategoriesNotFetched("Could not fetch categories.", e); } }
Source:
<code>public List<BasicDocumentRevision> getDocumentsWithIds(final List<String> docIds) throws DocumentException { Preconditions.checkState(this.isOpen(), "Database is closed"); Preconditions.checkNotNull(docIds, "Input document id list can not be null"); try { return queue.submit(new SQLQueueCallable<List<BasicDocumentRevision>>(){ @Override public List<BasicDocumentRevision> call(SQLDatabase db) throws Exception { String sql = String.format("SELECT " + FULL_DOCUMENT_COLS + " FROM revs, docs" + " WHERE docid IN ( %1$s ) AND current = 1 AND docs.doc_id = revs.doc_id " + " ORDER BY docs.doc_id ", DatabaseUtils.makePlaceholders(docIds.size())); String[] args = docIds.toArray(new String[docIds.size()]); List<BasicDocumentRevision> docs = getRevisionsFromRawQuery(db,sql, args); return sortDocumentsAccordingToIdList(docIds, docs); } }).get(); } catch (InterruptedException e) { <START> logger.log(Level.SEVERE,"Failed to get documents with ids",e); <END> throw new DocumentException("Failed to get documents with ids", e); } catch (ExecutionException e) { logger.log(Level.SEVERE, "Failed to get documents with ids", e); throw new DocumentException("Failed to get documents with ids", e); } }</code><technical_language>add spaces commas while in this code</technical_language>

Target:
public List<DocumentRevision> getDocumentsWithIds(final List<String> docIds) throws DocumentException { Preconditions.checkState(this.isOpen(), "Database is closed"); Preconditions.checkNotNull(docIds, "Input document id list cannot be null"); try { return queue.submit(new SQLQueueCallable<List<DocumentRevision>>(){ @Override public List<DocumentRevision> call(SQLDatabase db) throws Exception { String sql = String.format("SELECT " + FULL_DOCUMENT_COLS + " FROM revs, docs" + " WHERE docid IN ( %1$s ) AND current = 1 AND docs.doc_id = revs.doc_id " + " ORDER BY docs.doc_id ", DatabaseUtils.makePlaceholders(docIds.size())); String[] args = docIds.toArray(new String[docIds.size()]); List<DocumentRevision> docs = getRevisionsFromRawQuery(db,sql, args); return sortDocumentsAccordingToIdList(docIds, docs); } }).get(); } catch (InterruptedException e) { logger.log(Level.SEVERE, "Failed to get documents with ids", e); throw new DocumentException("Failed to get documents with ids", e); } catch (ExecutionException e) { logger.log(Level.SEVERE, "Failed to get documents with ids", e); throw new DocumentException("Failed to get documents with ids", e); } }
Source:
<code>public void validate(ValidationContext validationContext) { if (isEnabled()) { <START> if (!validationContext.systemEnvironment().get(SystemEnvironment.INBUILT_LDAP_PASSWORD_AUTH_ENABLED)) { <END> errors.add("base", "'ldap' tag has been deprecated in favour of bundled LDAP plugin. Use that instead."); } basesConfig.validateBases(); for (BaseConfig baseConfig : basesConfig) { baseConfig.validateBase(); } } }</code><technical_language>method inbuiltLdapPasswordAuthEnabled SystemEnvironment</technical_language>

Target:
public void validate(ValidationContext validationContext) { if (isEnabled()) { if (!validationContext.systemEnvironment().inbuiltLdapPasswordAuthEnabled()) { errors.add("base", "'ldap' tag has been deprecated in favour of bundled LDAP plugin. Use that instead."); return; } basesConfig.validateBases(); for (BaseConfig baseConfig : basesConfig) { baseConfig.validateBase(); } } }
Source:
<code>public void testResponseIncluded() throws AuthenticationException, InvalidRequestException, APIException, APIConnectionException, CardException { String idempotencyKey = Long.toString(System.currentTimeMillis()); <START> RequestOptions includeResponseRequestOptions = RequestOptions.builder() <END> .setStripeVersion(Stripe.apiVersion) .setIdempotencyKey(idempotencyKey) .build(); Customer cus = Customer.create(defaultCustomerParams, includeResponseRequestOptions); cus = Customer.retrieve(cus.getId(), includeResponseRequestOptions); StripeResponse resp = cus.getLastResponse(); assertThat(resp, instanceOf(StripeResponse.class)); assertEquals(200, resp.code()); assertEquals(idempotencyKey, resp.idempotencyKey()); assertTrue(resp.requestId().startsWith("req_")); assertTrue(resp.body().length() > 0); }</code><technical_language>Mind renaming this requestOptions, removed includeResponse flag</technical_language>

Target:
public void testResponseIncluded() throws AuthenticationException, InvalidRequestException, APIException, APIConnectionException, CardException { String idempotencyKey = Long.toString(System.currentTimeMillis()); RequestOptions requestOptions = RequestOptions.builder() .setStripeVersion(Stripe.apiVersion) .setIdempotencyKey(idempotencyKey) .build(); Customer cus = Customer.create(defaultCustomerParams, requestOptions); cus = Customer.retrieve(cus.getId(), requestOptions); StripeResponse resp = cus.getLastResponse(); assertThat(resp, instanceOf(StripeResponse.class)); assertEquals(200, resp.code()); assertEquals(idempotencyKey, resp.idempotencyKey()); assertTrue(resp.requestId().startsWith("req_")); assertTrue(resp.body().length() > 0); }
Source:
<code><START> public SymbolMetadata metadata() { <END> return new SymbolMetadata() { @Override public List<SymbolMetadata.AnnotationValue> valuesForAnnotation(String fullyQualifiedNameOfAnnotation) { return null; } @Override public boolean isAnnotatedWith(String fullyQualifiedName) { return false; } @Override public List<SymbolMetadata.AnnotationInstance> annotations() { return Collections.emptyList(); } }; }</code><technical_language>I prefer implement methods mandated Symbol interface throw new UnsupportedOperationException(); in order immediately currently call methods</technical_language>

Target:
public SymbolMetadata metadata() { throw new UnsupportedOperationException(); }
Source:
<code>public @NonNull ITmfStateValue getOngoingAggregatedState() { List<ITmfStateValue> potentialValues = getQuarkStream() <START> .map(quark -> { <END> try { return getStateSystem().queryOngoingState(quark.intValue()); } catch (AttributeNotFoundException e) { throw new IllegalStateException("Bad aggregation rule"); } }) .collect(Collectors.toList()); for (ITmfStateValue value : potentialValues) { if (!value.isNull()) { return value; } } return TmfStateValue.nullValue(); }</code><technical_language>return early find a non-null interval map remaining quark for nothing</technical_language>

Target:
public ITmfStateValue getOngoingAggregatedState() { Optional<ITmfStateValue> possibleValue = getQuarkStream() .map(quark -> { try { return getStateSystem().queryOngoingState(quark.intValue()); } catch (AttributeNotFoundException e) { throw new IllegalStateException("Bad aggregation rule"); } }) .filter(value -> !value.isNull()) .findFirst(); return possibleValue.orElse(TmfStateValue.nullValue()); }
Source:
<code>public void test() throws Exception { final AtomicReference<Object> payload = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); <START> this.inbound.addInterceptor(new ChannelInterceptor() { <END> @Override public Message<?> preSend(Message<?> message, MessageChannel channel) { payload.set(message.getPayload()); latch.countDown(); return message; } }); this.mqttOutFlow.getInputChannel().send(new GenericMessage<>("foo")); assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(payload.get()).isEqualTo("foo sent to MQTT, received from MQTT"); }</code><technical_language>I understand leak of VerifyingChannelInterceptor in Testing Framework, a MockIntegration.mockMessageHandler() instead of logger in main flow verify incoming message. WDYT</technical_language>

Target:
public void test() throws Exception { ArgumentCaptor<Message<?>> captor = messageArgumentCaptor(); MessageHandler mockMessageHandler = mockMessageHandler(captor).handleNext(m -> { }); this.mockIntegrationContext .substituteMessageHandlerFor( "mqttInFlow.org.springframework.integration.config.ConsumerEndpointFactoryBean#1", mockMessageHandler); this.mqttOutFlow.getInputChannel().send(new GenericMessage<>("foo")); verify(mockMessageHandler).handleMessage(any()); assertThat(captor.getValue().getPayload()) .isEqualTo("foo sent to MQTT, received from MQTT"); }