auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>void walkInnerSymbols(ObjectType type, String innerNamespace) { for (String propName : getSortedPublicPropertyNames(type)) { String qualifiedName = innerNamespace + '.' + propName; if (provides.contains(qualifiedName)) continue; JSType pType = type.getPropertyType(propName); <START> Set<JSType> incompatibleTypes = new LinkedHashSet<>(); <END> incompatibleTypes.add(pType); collectIncompatibleSuperTypes(type, propName, incompatibleTypes); incompatibleTypes.remove(pType); if (!pType.isEnumType() && !incompatibleTypes.isEmpty()) { errors.add(JSError.make(currentSymbol.getNode(), CLUTZ_OVERRIDDEN_STATIC_FIELD, innerNamespace, propName)); continue; } if (pType.isEnumType()) { visitEnumType(propName, (EnumType) pType, incompatibleTypes); } else if (isTrueConstructor(pType)) { visitClassOrInterface(propName, (FunctionType) pType); } else if (isTypedef(pType)) { JSType registryType = typeRegistry.getType(qualifiedName); visitTypeAlias(registryType, propName); } } }</code><technical_language>I calling visitProperty instead of repeating code, change painfully clear. Add a TODO for if agree is duplicated code</technical_language>

Target:
void walkInnerSymbols(ObjectType type, String innerNamespace) { for (String propName : getSortedPublicPropertyNames(type)) { String qualifiedName = innerNamespace + '.' + propName; if (provides.contains(qualifiedName)) continue; JSType pType = type.getPropertyType(propName); Set<JSType> incompatibleTypes = getIncompatibleSuperTypes(type, propName, pType); if (!pType.isEnumType() && !incompatibleTypes.isEmpty()) { errors.add(JSError.make(currentSymbol.getNode(), CLUTZ_OVERRIDDEN_STATIC_FIELD, innerNamespace, propName)); continue; } if (pType.isEnumType()) { visitEnumType(propName, (EnumType) pType, incompatibleTypes); } else if (isClassLike(pType)) { visitClassOrInterface(propName, (FunctionType) pType); } else if (isTypedef(pType)) { JSType registryType = typeRegistry.getType(qualifiedName); visitTypeAlias(registryType, propName); } } }
Source:
<code>private void reportPurityError(String msgKeyPrefix, Pair<Tree, String> r) { String reason = r.second; @SuppressWarnings("compilermessages") @CompilerMessageKey String msgKey = msgKeyPrefix + reason; if (reason.equals("call")) { <START> if (r.first instanceof MethodInvocationTree) { <END> MethodInvocationTree mitree = (MethodInvocationTree) r.first; checker.reportError(r.first, msgKey, mitree.getMethodSelect()); } else { NewClassTree nctree = (NewClassTree) r.first; checker.reportError(r.first, msgKey, nctree.getIdentifier()); } } else { checker.reportError(r.first, msgKey); } }</code><technical_language>This r.first.getKind() == Kind.METHOD_INVOCATION</technical_language>

Target:
private void reportPurityError(String msgKeyPrefix, Pair<Tree, String> r) { String reason = r.second; @SuppressWarnings("compilermessages") @CompilerMessageKey String msgKey = msgKeyPrefix + reason; if (reason.equals("call")) { if (r.first.getKind() == Tree.Kind.METHOD_INVOCATION) { MethodInvocationTree mitree = (MethodInvocationTree) r.first; checker.reportError(r.first, msgKey, mitree.getMethodSelect()); } else { NewClassTree nctree = (NewClassTree) r.first; checker.reportError(r.first, msgKey, nctree.getIdentifier()); } } else { checker.reportError(r.first, msgKey); } }
Source:
<code>public void testHashCode() { String rawText = "some raw text"; int position = 1; List<TypedId> identifiers = Lists.newArrayList(new TypedId("someValue", "someType", 0.9f)); BlobCitationEntry blobCitationEntry = new BlobCitationEntry(rawText); blobCitationEntry.setPosition(position); blobCitationEntry.setIdentifiers(identifiers); <START> assertNotEquals(null, blobCitationEntry); <END> assertNotEquals("string", blobCitationEntry); BlobCitationEntry otherBlobCitationEntry = new BlobCitationEntry("other raw text"); otherBlobCitationEntry.setPosition(position); otherBlobCitationEntry.setIdentifiers(identifiers); assertNotSame(blobCitationEntry.hashCode(), otherBlobCitationEntry.hashCode()); otherBlobCitationEntry = new BlobCitationEntry(rawText); otherBlobCitationEntry.setPosition(2); otherBlobCitationEntry.setIdentifiers(identifiers); assertNotSame(blobCitationEntry.hashCode(), otherBlobCitationEntry.hashCode()); otherBlobCitationEntry = new BlobCitationEntry(rawText); otherBlobCitationEntry.setPosition(position); otherBlobCitationEntry.setIdentifiers(Lists.newArrayList(new TypedId("someOtherValue", "someType", 0.9f))); assertNotSame(blobCitationEntry.hashCode(), otherBlobCitationEntry.hashCode()); otherBlobCitationEntry = new BlobCitationEntry(rawText); otherBlobCitationEntry.setPosition(position); otherBlobCitationEntry.setIdentifiers(identifiers); assertEquals(blobCitationEntry.hashCode(), otherBlobCitationEntry.hashCode()); }</code><technical_language>If change this code anyway: assertNotNull more readable</technical_language>

Target:
public void testHashCode() { String rawText = "some raw text"; int position = 1; List<TypedId> identifiers = Lists.newArrayList(new TypedId("someValue", "someType", 0.9f)); BlobCitationEntry blobCitationEntry = new BlobCitationEntry(rawText); blobCitationEntry.setPosition(position); blobCitationEntry.setIdentifiers(identifiers); assertNotNull(blobCitationEntry); assertNotEquals("string", blobCitationEntry); BlobCitationEntry otherBlobCitationEntry = new BlobCitationEntry("other raw text"); otherBlobCitationEntry.setPosition(position); otherBlobCitationEntry.setIdentifiers(identifiers); assertNotEquals(blobCitationEntry.hashCode(), otherBlobCitationEntry.hashCode()); otherBlobCitationEntry = new BlobCitationEntry(rawText); otherBlobCitationEntry.setPosition(2); otherBlobCitationEntry.setIdentifiers(identifiers); assertNotEquals(blobCitationEntry.hashCode(), otherBlobCitationEntry.hashCode()); otherBlobCitationEntry = new BlobCitationEntry(rawText); otherBlobCitationEntry.setPosition(position); otherBlobCitationEntry.setIdentifiers(Lists.newArrayList(new TypedId("someOtherValue", "someType", 0.9f))); assertNotEquals(blobCitationEntry.hashCode(), otherBlobCitationEntry.hashCode()); otherBlobCitationEntry = new BlobCitationEntry(rawText); otherBlobCitationEntry.setPosition(position); otherBlobCitationEntry.setIdentifiers(identifiers); assertEquals(blobCitationEntry.hashCode(), otherBlobCitationEntry.hashCode()); }
Source:
<code>public void scanForRepoChanges() throws IOException { refs.refresh(); <START> getAllRefs(); END> if (!isBare()) getIndex(); }</code><technical_language>This necessary anymore. RefDirectory.refresh() trigger event listener if more refs detected modified, means drop getAllRefs() call here</technical_language>

Target:
public void scanForRepoChanges() throws IOException { getAllRefs(); if (!isBare()) getIndex(); }
Source:
<code>public DAnalysisSessionImpl(DAnalysis mainDAnalysis) { Preconditions.checkNotNull(mainDAnalysis); this.sessionResource = mainDAnalysis.eResource(); Preconditions.checkNotNull(this.sessionResource, Messages.DAnalysisSessionImpl_noRessourceErrorMsg); this.transactionalEditingDomain = Preconditions.checkNotNull(TransactionUtil.getEditingDomain(mainDAnalysis), Messages.DAnalysisSessionImpl_noEditingDomainErrorMsg); this.mainDAnalysis = mainDAnalysis; this.saver = new Saver(this); this.interpreter = new SessionInterpreter(); this.representationsChangeAdapter = new RepresentationsChangeAdapter(this); super.getAnalyses().add(mainDAnalysis); super.getResources().add(sessionResource); setAnalysisSelector(DAnalysisSelectorService.getSelector(this)); setResourceCollector(new LocalResourceCollector(getTransactionalEditingDomain().getResourceSet())); setDeferSaveToPostCommit(true); setSaveInExclusiveTransaction(true); <START> getTransactionalEditingDomain().addResourceSetListener(new DRepresentationChangeListener(this)); <END> }</code><technical_language>this is removed</technical_language>

Target:
public DAnalysisSessionImpl(DAnalysis mainDAnalysis) { Preconditions.checkNotNull(mainDAnalysis); this.sessionResource = mainDAnalysis.eResource(); Preconditions.checkNotNull(this.sessionResource, Messages.DAnalysisSessionImpl_noRessourceErrorMsg); this.transactionalEditingDomain = Preconditions.checkNotNull(TransactionUtil.getEditingDomain(mainDAnalysis), Messages.DAnalysisSessionImpl_noEditingDomainErrorMsg); this.mainDAnalysis = mainDAnalysis; this.saver = new Saver(this); this.interpreter = new SessionInterpreter(); this.representationsChangeAdapter = new RepresentationsChangeAdapter(this); super.getAnalyses().add(mainDAnalysis); super.getResources().add(sessionResource); setAnalysisSelector(DAnalysisSelectorService.getSelector(this)); setResourceCollector(new LocalResourceCollector(getTransactionalEditingDomain().getResourceSet())); setDeferSaveToPostCommit(true); setSaveInExclusiveTransaction(true); dRepresentationChangeListener = new DRepresentationChangeListener(this); getTransactionalEditingDomain().addResourceSetListener(dRepresentationChangeListener); }
Source:
<code><START> public Translation enchantment$getTranslation() { <END> return this.translation; }</code><technical_language>this</technical_language>

Target:
public Translation getTranslation() { if (this.translation == null) { this.translation = new SpongeTranslation(shadow$getName()); } return this.translation; }
Source:
<code>public void setSearchFilter(int index, SearchFilter searchFilter) { if (index < 0 || index >= this.getCount()) { <START> throw new IllegalArgumentException("index is out of range." <END> + ":" + index); } this.searchFilters.add(index, searchFilter); }</code><technical_language>please provide a hint is current index, this more helpful I think</technical_language>

Target:
public void setSearchFilter(int index, SearchFilter searchFilter) { if (index < 0 || index >= this.getCount()) { throw new IllegalArgumentException( String.format("index %d is out of range [0..%d[.", index, this.getCount()) ); } this.searchFilters.add(index, searchFilter); }
Source:
<code>public long getModificationDate() { <START> if (getResource().isAccessible()) { <END> return super.getModificationDate(); } return timestamp; }</code><technical_language>do need this ? type a non-workspace typed element ... assume instances resources of super-class type</technical_language>

Target:
public long getModificationDate() { return timestamp; }
Source:
<code>public void deleteProjectFeatureFlag() throws Exception { final ProjectFeatureFlag featureFlag = gd.getFeatureFlagService().createProjectFeatureFlag(project, new ProjectFeatureFlag("settingName1")); gd.getFeatureFlagService().deleteProjectFeatureFlag(featureFlag); <START> gd.getFeatureFlagService().getProjectFeatureFlag(project, "settingName1"); <END> }</code><technical_language>I replace expectedExceptions try-catch surrounding this call - prevent successful test in case e.g. deleteProjectFeatureFlag throws exception ;)</technical_language>

Target:
public void deleteProjectFeatureFlag() throws Exception { final ProjectFeatureFlag featureFlag = gd.getFeatureFlagService().createProjectFeatureFlag(project, new ProjectFeatureFlag("settingName1")); gd.getFeatureFlagService().deleteProjectFeatureFlag(featureFlag); try { gd.getFeatureFlagService().getProjectFeatureFlag(project, "settingName1"); fail(); } catch (GoodDataException e) { assertThat(e.getMessage(), containsString("Unable to get project feature flag:")); } }
Source:
<code>public Entity getEntity() { <START> return entity; <END> }</code><technical_language>this</technical_language>

Target:
public Entity getEntity() { return this.entity; }
Source:
<code><START> public MemberDescription(String memberId, <END> Optional<String> groupInstanceId, String clientId, String host, MemberAssignment assignment) { this.memberId = memberId == null ? "" : memberId; this.groupInstanceId = groupInstanceId; this.clientId = clientId == null ? "" : clientId; this.host = host == null ? "" : host; this.assignment = assignment == null ? new MemberAssignment(Collections.<TopicPartition>emptySet()) : assignment; }</code><technical_language>mentioned above, this constructor default access</technical_language>

Target:
MemberDescription(String memberId, Optional<String> groupInstanceId, String clientId, String host, MemberAssignment assignment) { this.memberId = memberId == null ? "" : memberId; this.groupInstanceId = groupInstanceId; this.clientId = clientId == null ? "" : clientId; this.host = host == null ? "" : host; this.assignment = assignment == null ? new MemberAssignment(Collections.emptySet()) : assignment; }
Source:
<code>public boolean performNextOperation(int completedChildren) { if (completedChildren == getParameters().getDiskUpdatePhases().size()) { return false; } UpdateVmDiskParameters.Phase nextPhase = getParameters().getDiskUpdatePhases().get(completedChildren); switch (nextPhase) { case EXTEND_DISK: <START> log.info("Start extend disk"); <END> executeDiskExtend(); break; case AMEND_DISK: log.info("Start amend disk"); amendDiskImage(); break; case UPDATE_DISK: default: log.info("Start DB update disk"); performDiskUpdate(); if (getParameters().getDiskUpdatePhases().size() == completedChildren + 1) { return false; } } return true; }</code><technical_language>logs helpful (either remove add disk id)</technical_language>

Target:
public boolean performNextOperation(int completedChildren) { if (completedChildren == getParameters().getDiskUpdatePhases().size()) { return false; } UpdateVmDiskParameters.Phase nextPhase = getParameters().getDiskUpdatePhases().get(completedChildren); switch (nextPhase) { case EXTEND_DISK: log.info("Start to extend disk id '{}')", getOldDisk().getId()); executeDiskExtend(); break; case AMEND_DISK: log.info("Start to amend disk id '{}')", getOldDisk().getId()); amendDiskImage(); break; case UPDATE_DISK: log.info("Start to update general fields of disk id '{}')", getOldDisk().getId()); performDiskUpdate(); return false; } return true; }
Source:
<code><START> public synchronized TransactionalRequestResult initializeTransactions() { <END> boolean isEpochBump = this.producerIdAndEpoch != ProducerIdAndEpoch.NONE; return handleCachedTransactionRequestResult(() -> { transitionTo(State.INITIALIZING); InitProducerIdRequestData requestData = new InitProducerIdRequestData() .setTransactionalId(transactionalId) .setTransactionTimeoutMs(transactionTimeoutMs) .setProducerId(this.producerIdAndEpoch.producerId) .setProducerEpoch(this.producerIdAndEpoch.epoch); InitProducerIdHandler handler = new InitProducerIdHandler(new InitProducerIdRequest.Builder(requestData), isEpochBump); enqueueRequest(handler); return handler.result; }, State.INITIALIZING); }</code><technical_language>This method is invoked KafkaProducer.initializeTransactions. Previously, producer support call this API subsequent call fail. If want preserve this, need bring overloaded method</technical_language>

Target:
public synchronized TransactionalRequestResult initializeTransactions() { return initializeTransactions(ProducerIdAndEpoch.NONE); }
Source:
<code>private Layout correctWrongEpochs(PollReport pollReport, Layout layout) { Map<String, Long> wrongEpochs = pollReport.getWrongEpochs(); if (wrongEpochs.isEmpty()) { return layout; } log.debug("Correct wrong epochs. Poll report: {}", pollReport); try { final Layout oldLayout = layout; Map<String, CompletableFuture<Layout>> layoutCompletableFutureMap = layout .getLayoutServers() .stream() .collect(Collectors.toMap(Function.identity(), server -> getLayoutFromServer(oldLayout, server)) ); Optional<Layout> latestLayout = fetchLatestLayout(layoutCompletableFutureMap); if (!latestLayout.isPresent()) { log.error("Can't get a layout from any server in the cluster. Layout servers: {}, wrong epochs: {}", layout.getLayoutServers(), wrongEpochs ); throw new IllegalStateException("Error in correcting server epochs. Local node is disconnected"); } Layout newManagementLayout = latestLayout.get(); <START> serverContext.saveManagementLayout(newManagementLayout); <END> sealMinServerSet(wrongEpochs, newManagementLayout); updateTrailingLayoutServers(newManagementLayout, layoutCompletableFutureMap); return newManagementLayout; } catch (QuorumUnreachableException e) { log.error("Error in correcting server epochs", e); } return serverContext.copyManagementLayout(); }</code><technical_language>This guarantee newManagementLayout is latest layout. Consider following. - fetch quorum layout - latestLayout. receive a response layout servers latest committed layout. Hence, latestLayout old. - save management layout. This save this layout observed a newer layout. This statement this: newManagementLayout = serverContext.copyManagementLayout() This is optimization waste current detection round. If do get latest layout, sealing fail this poll fail. Also, passing this updateTrailingServers. layout server checks discard commits epoch, do want attempt commit layout</technical_language>

Target:
private Layout correctWrongEpochs(PollReport pollReport, Layout layout) { Map<String, Long> wrongEpochs = pollReport.getWrongEpochs(); if (wrongEpochs.isEmpty()) { return layout; } log.debug("Correct wrong epochs. Poll report: {}", pollReport); try { final Layout oldLayout = layout; Map<String, CompletableFuture<Layout>> layoutCompletableFutureMap = layout .getLayoutServers() .stream() .collect(Collectors.toMap(Function.identity(), server -> getLayoutFromServer(oldLayout, server)) ); Optional<Layout> latestLayout = fetchLatestLayout(layoutCompletableFutureMap); if (!latestLayout.isPresent()) { log.error("Can't get a layout from any server in the cluster. Layout servers: {}, wrong epochs: {}", layout.getLayoutServers(), wrongEpochs ); throw new IllegalStateException("Error in correcting server epochs. Local node is disconnected"); } Layout newManagementLayout = serverContext.saveManagementLayout(latestLayout.get()); sealWithLatestLayout(wrongEpochs, newManagementLayout); updateTrailingLayoutServers(newManagementLayout, layoutCompletableFutureMap); return newManagementLayout; } catch (QuorumUnreachableException e) { log.error("Error in correcting server epochs", e); } return serverContext.copyManagementLayout(); }
Source:
<code>public synchronized void close() throws IOException { if (closed) { return; } try { flushInternal(true); threadExecutor.shutdown(); } catch (IOException e) { throw wrapException(path, e.getMessage(), e); } finally { lastError = new IOException(FSExceptionMessages.STREAM_IS_CLOSED); buffer = null; bufferIndex = 0; closed = true; writeOperations.clear(); if (!threadExecutor.isShutdown()) { threadExecutor.shutdownNow(); } } <START> LOG.debug("Closing AbfsOutputStream ", toString()); <END> }</code><technical_language>guard this a LOG.isDebugEnabled(), toString() operation is enough work. Or, this argument SLF4J Call this.toString() if is printing log entry</technical_language>

Target:
public synchronized void close() throws IOException { if (closed) { return; } try { flushInternal(true); threadExecutor.shutdown(); } catch (IOException e) { throw wrapException(path, e.getMessage(), e); } finally { lastError = new IOException(FSExceptionMessages.STREAM_IS_CLOSED); buffer = null; bufferIndex = 0; closed = true; writeOperations.clear(); if (!threadExecutor.isShutdown()) { threadExecutor.shutdownNow(); } } if (LOG.isDebugEnabled()) { LOG.debug("Closing AbfsOutputStream ", toString()); } }
Source:
<code>protected void joinTestJobs() { try { PlatformUI.getWorkbench().getProgressService().busyCursorWhile( monitor -> Job.getJobManager().join(TestJob.FAMILY_TEST_JOB, monitor)); <START> } catch (InterruptedException | InvocationTargetException e) { <END> e.printStackTrace(); } }</code><technical_language>Example get more readable, format</technical_language>

Target:
protected void joinTestJobs() { try { PlatformUI.getWorkbench().getProgressService().busyCursorWhile( monitor -> Job.getJobManager().join(TestJob.FAMILY_TEST_JOB, monitor)); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }
Source:
<code>public StapNewWizardPage(ISelection selection) { <START> super("wizardPage"); <END> setTitle("Systemtap Script"); setDescription("This wizard creates a new systemtap script."); this.selection = selection; }</code><technical_language>Strings externalized. else in code base for examples of this</technical_language>

Target:
public StapNewWizardPage(ISelection selection) { super(Messages.getString("StapNewWizardPage.WizardPage")); setTitle(Messages.getString("StapNewWizardPage.Title")); setDescription(Messages.getString("StapNewWizardPage.setDescription")); this.selection = selection; }
Source:
<code>public void addColumnFamily(TableName tableName, ColumnFamilyDescriptor columnFamilyDesc) throws IOException { <START> com.google.cloud.bigtable.admin.v2.models.ModifyColumnFamiliesRequest modifyColumnRequest = <END> com.google.cloud.bigtable.admin.v2.models.ModifyColumnFamiliesRequest .of(tableName.getNameAsString()); modifyColumnRequest.addFamily(columnFamilyDesc.getNameAsString(), buildGarbageCollectionRule(TableAdapter2x.toHColumnDescriptor(columnFamilyDesc))); modifyColumns(modifyColumnRequest); }</code><technical_language>Please com.google.cloud.bigtable.admin.v2.models.ModifyColumnFamiliesRequest import, change of proto ModifyColumnFamiliesRequest model well</technical_language>

Target:
public void addColumnFamily(TableName tableName, ColumnFamilyDescriptor columnFamilyDesc) throws IOException { ModifyColumnFamiliesRequest request = ModifyColumnFamiliesRequest.of(tableName.getNameAsString()); request.addFamily(columnFamilyDesc.getNameAsString(), buildGarbageCollectionRule(TableAdapter2x.toHColumnDescriptor(columnFamilyDesc))); modifyColumns(request); }
Source:
<code>private void runImpl() throws IOException { Transport tn = Transport.open(git, uri); PushResult res; try { res = pushVia(tn); } finally { try { tn.close(); } catch (Throwable e2) { log.warn("Unexpected error while closing " + uri, e2); } } for (RemoteRefUpdate u : res.getRemoteUpdates()) { switch (u.getStatus()) { case OK: case UP_TO_DATE: case NON_EXISTING: break; case NOT_ATTEMPTED: case AWAITING_REPORT: case REJECTED_NODELETE: case REJECTED_NONFASTFORWARD: case REJECTED_REMOTE_CHANGED: log.error(String.format("Failed replicate of %s to %s: status %s", u.getRemoteName(), uri, u.getStatus())); break; case REJECTED_OTHER_REASON: if ("non-fast-forward".equals(u.getMessage())) { log.error(String.format("Failed replicate of %s to %s" + ", remote rejected non-fast-forward push." + " Check receive.denyNonFastForwards variable in config file" + " of destination repository.", u.getRemoteName(), uri)); } else if ("failed to lock".equals(u.getMessage())) { <START> throw new RemoteRepositoryException(uri, u.getMessage()); <END> } else { log.error(String.format( "Failed replicate of %s to %s, reason: %s", u.getRemoteName(), uri, u.getMessage())); } break; } } }</code><technical_language>[optional] a LockFailureException subclass of RemoteRepositoryException simply check instanceof need check message</technical_language>

Target:
private void runImpl() throws IOException { Transport tn = Transport.open(git, uri); PushResult res; try { res = pushVia(tn); } finally { try { tn.close(); } catch (Throwable e2) { log.warn("Unexpected error while closing " + uri, e2); } } for (RemoteRefUpdate u : res.getRemoteUpdates()) { switch (u.getStatus()) { case OK: case UP_TO_DATE: case NON_EXISTING: break; case NOT_ATTEMPTED: case AWAITING_REPORT: case REJECTED_NODELETE: case REJECTED_NONFASTFORWARD: case REJECTED_REMOTE_CHANGED: log.error(String.format("Failed replicate of %s to %s: status %s", u.getRemoteName(), uri, u.getStatus())); break; case REJECTED_OTHER_REASON: if ("non-fast-forward".equals(u.getMessage())) { log.error(String.format("Failed replicate of %s to %s" + ", remote rejected non-fast-forward push." + " Check receive.denyNonFastForwards variable in config file" + " of destination repository.", u.getRemoteName(), uri)); } else if ("failed to lock".equals(u.getMessage())) { throw new LockFailureException(uri, u.getMessage()); } else { log.error(String.format( "Failed replicate of %s to %s, reason: %s", u.getRemoteName(), uri, u.getMessage())); } break; } } }
Source:
<code>static RuntimeException launderCacheLoaderException(Exception e) { if (!(e instanceof javax.cache.integration.CacheLoaderException)) { return new javax.cache.integration.CacheLoaderException("Exception in CacheLoader", e); } else { <START> return new PersistenceException(e); <END> } }</code><technical_language>this logic is a bit confusing me: if exception is CacheLoaderException force be. if is, change type PersistenceException</technical_language>

Target:
static RuntimeException launderCacheLoaderException(Exception e) { if (!(e instanceof CacheLoaderException)) { return new CacheLoaderException("Exception in CacheLoader", e); } else { return new PersistenceException(e); } }
Source:
<code>private SafeHtml createBondTooltipMessage(HostInterfaceLineModel lineModel, InterfaceStatus interfaceStatus) { Bond bond = (Bond) lineModel.getInterface(); StringBuilder bondProperties = new StringBuilder(messages.bondStatus(interfaceStatus.toString())); boolean isBond4 = BondMode.BOND4.equals(BondMode.parseBondMode(bond.getBondOptions())); if (InterfaceStatus.UP.equals(interfaceStatus) && isBond4) { bondProperties.append("\n").append(createActiveBondTooltipMessage(bond, lineModel)); } if ((bond.getActiveSlave() != null) && (bond.getActiveSlave().length() > 0)) { bondProperties.append("\n"); <START> bondProperties.append(messages.bondActiveSlave(bond.getActiveSlave())); <END> } return new SafeHtmlBuilder().appendEscapedLines(bondProperties.toString()).toSafeHtml(); }</code><technical_language>squash this line: .append().append()</technical_language>

Target:
private SafeHtml createBondTooltipMessage(HostInterfaceLineModel lineModel, InterfaceStatus interfaceStatus) { Bond bond = (Bond) lineModel.getInterface(); StringBuilder bondProperties = new StringBuilder(messages.bondStatus(interfaceStatus.toString())); boolean isBond4 = BondMode.BOND4.equals(BondMode.parseBondMode(bond.getBondOptions())); if (InterfaceStatus.UP.equals(interfaceStatus) && isBond4) { bondProperties.append("\n").append(createActiveBondTooltipMessage(bond, lineModel)); } if ((bond.getActiveSlave() != null) && (bond.getActiveSlave().length() > 0)) { bondProperties.append("\n").append(messages.bondActiveSlave(bond.getActiveSlave())); } return new SafeHtmlBuilder().appendEscapedLines(bondProperties.toString()).toSafeHtml(); }
Source:
<code>public void run() { try { synchronized (lock) { final LeaderLatch latch = leaderLatch.get(); if (latch == null || !latch.hasLeadership()) { log.info("LEGGO MY EGGO. [%s] is leader.", latch == null ? null : latch.getLeader().getId()); stopBeingLeader(); return; } } List<Boolean> allStarted = Arrays.asList( databaseSegmentManager.isStarted(), serverInventoryView.isStarted() ); for (Boolean aBoolean : allStarted) { if (!aBoolean) { log.error("InventoryManagers not started[%s]", allStarted); stopBeingLeader(); return; } } BalancerStrategyFactory factory= null; <START> if (COST.equals(config.getCoordinatorBalancerStrategy())) <END> factory = new CostBalancerStrategyFactory(); else if (RANDOM.equals(config.getCoordinatorBalancerStrategy())) factory= new RandomBalancerStrategyFactory(); else if (COST_MULTI.equals(config.getCoordinatorBalancerStrategy())) factory = new CostBalancerMultithreadStrategyFactory(config.getCostBalancerStrategyThreadCount()); DruidCoordinatorRuntimeParams params = DruidCoordinatorRuntimeParams.newBuilder() .withStartTime(startTime) .withDatasources(databaseSegmentManager.getInventory()) .withDynamicConfigs(getDynamicConfigs()) .withEmitter(emitter) .withBalancerStrategyFactory(factory) .build(); for (DruidCoordinatorHelper helper : helpers) { params = helper.run(params); } } catch (Exception e) { log.makeAlert(e, "Caught exception, ignoring so that schedule keeps going.").emit(); } }</code><technical_language>balancer strategy put dynamic config</technical_language>

Target:
public void run() { try { synchronized (lock) { final LeaderLatch latch = leaderLatch.get(); if (latch == null || !latch.hasLeadership()) { log.info("LEGGO MY EGGO. [%s] is leader.", latch == null ? null : latch.getLeader().getId()); stopBeingLeader(); return; } } List<Boolean> allStarted = Arrays.asList( databaseSegmentManager.isStarted(), serverInventoryView.isStarted() ); for (Boolean aBoolean : allStarted) { if (!aBoolean) { log.error("InventoryManagers not started[%s]", allStarted); stopBeingLeader(); return; } } BalancerStrategyFactory factory = new CostBalancerStrategyFactory(getDynamicConfigs().getBalancerComputeThreads()); DruidCoordinatorRuntimeParams params = DruidCoordinatorRuntimeParams.newBuilder() .withStartTime(startTime) .withDatasources(databaseSegmentManager.getInventory()) .withDynamicConfigs(getDynamicConfigs()) .withEmitter(emitter) .withBalancerStrategyFactory(factory) .build(); for (DruidCoordinatorHelper helper : helpers) { params = helper.run(params); } } catch (Exception e) { log.makeAlert(e, "Caught exception, ignoring so that schedule keeps going.").emit(); } }
Source:
<code>public void testFail() { final boolean[] flags = new boolean[4]; TmfEventRequest request = setupTestRequest(flags); <START> request.fail(null); <END> assertTrue("isCompleted", request.isCompleted()); assertTrue("isFailed", request.isFailed()); assertFalse("isCancelled", request.isCancelled()); assertTrue("handleCompleted", flags[0]); assertFalse("handleSuccess", flags[1]); assertTrue("handleFailure", flags[2]); assertFalse("handleCancel", flags[3]); }</code><technical_language>Provide exception assert test for it</technical_language>

Target:
public void testFail() { final boolean[] flags = new boolean[4]; TmfEventRequest request = setupTestRequest(flags); request.fail(new IllegalArgumentException("Bad argument")); final Throwable failCause = request.getFailCause(); assertTrue("isCompleted", request.isCompleted()); assertTrue("isFailed", request.isFailed()); assertFalse("isCancelled", request.isCancelled()); assertNotNull("Cause of failure", failCause); assertEquals("Cause of failure message", "Bad argument", failCause.getCause().getMessage()); assertTrue("handleCompleted", flags[0]); assertFalse("handleSuccess", flags[1]); assertTrue("handleFailure", flags[2]); assertFalse("handleCancel", flags[3]); }
Source:
<code>public AsyncFuture<Void> sendBatches(Collection<Batch> batches) { final ArrayList<Metric> metrics = new ArrayList<>(); batches.forEach(batch -> batch.getPoints().forEach( <START> point -> metrics.add(convertBatchMetric(batch, point)))); <END> return sendMetrics(metrics); }</code><technical_language>this is a nested forEach, I more readable formatted batch -> { batch.getPoints().forEach(point -> { metrics.add(convertBatchMetric(batch, point)); } }</technical_language>

Target:
public AsyncFuture<Void> sendBatches(Collection<Batch> batches) { final ArrayList<Metric> metrics = new ArrayList<>(); batches.forEach(batch -> { batch.getPoints().forEach(point -> { metrics.add(convertBatchMetric(batch, point)); }); }); return sendMetrics(metrics); }
Source:
<code>static <T> Try<T> ofSupplier(Supplier<? extends T> supplier) { <START> try { <END> return new Success<>(supplier.get()); } catch (Throwable t) { return new Failure<>(t); } }</code><technical_language>return of(supplier::get) reduce duplicate code. compiler translate method reference a simple method call - additional overhead. Please do this for other static factory methods introduce in this PR, too</technical_language>

Target:
static <T> Try<T> ofSupplier(Supplier<? extends T> supplier) { Objects.requireNonNull(supplier, "supplier is null"); return of(supplier::get); }
Source:
<code><START> public DesignProcessDefinition getDesignProcessDefinition(long processDefinitionId) throws SProcessDefinitionNotFoundException { <END> try { return processDefinitionBARContribution.convertXmlToProcess(getProcessDeploymentInfo(processDefinitionId).getDesignContent().getContent()); } catch (SProcessDefinitionReadException | IOException | XMLParseException e) { throw new SProcessDefinitionNotFoundException(e, processDefinitionId); } }</code><technical_language>Leave **SProcessDefinitionReadException** pass, add in method signature. Convert IOException XMLParseException **SProcessDefinitionReadException**</technical_language>

Target:
public DesignProcessDefinition getDesignProcessDefinition(long processDefinitionId) throws SProcessDefinitionNotFoundException, SProcessDefinitionReadException { try { return processDefinitionBARContribution.convertXmlToProcess(getProcessDeploymentInfo(processDefinitionId).getDesignContent().getContent()); } catch (IOException | XMLParseException e) { throw new SProcessDefinitionReadException(e); } }
Source:
<code>public Array createArrayOf(String typeName, Object[] elements) throws SQLException { checkClosed(); <START> int oid = getTypeInfo().getPGArrayType(typeName.toLowerCase()); <END> if (oid == Oid.UNSPECIFIED) throw new PSQLException(GT.tr("Unable to find server array type for provided name {0}.", typeName), PSQLState.INVALID_NAME); char delim = getTypeInfo().getArrayDelimiter(oid); StringBuilder sb = new StringBuilder(); appendArray(sb, elements, delim); return makeArray(oid, sb.toString()); }</code><technical_language>is this a part of "use UTF-8 instead of US-ASCII for initial encoding" PR</technical_language>

Target:
public Array createArrayOf(String typeName, Object[] elements) throws SQLException { checkClosed(); int oid = getTypeInfo().getPGArrayType(typeName); if (oid == Oid.UNSPECIFIED) throw new PSQLException(GT.tr("Unable to find server array type for provided name {0}.", typeName), PSQLState.INVALID_NAME); char delim = getTypeInfo().getArrayDelimiter(oid); StringBuilder sb = new StringBuilder(); appendArray(sb, elements, delim); return makeArray(oid, sb.toString()); }
Source:
<code><START> public Response invoke(String application, String entityToken, String effectorName, <END> String timeout, Map<String, String> parameters) { final EntityLocal entity = brooklyn().getEntity(application, entityToken); Maybe<Effector<?>> effector = EffectorUtils.findEffectorDeclared(entity, effectorName); if (effector.isAbsentOrNull()) throw WebResourceUtils.notFound("Entity '%s' has no effector with name '%s'", entityToken, effectorName); log.info("REST invocation of " + entity + "." + effector.get() + " " + parameters); Task<?> t = entity.invoke(effector.get(), parameters); try { Object result = null; if (timeout == null || timeout.isEmpty() || "never".equalsIgnoreCase(timeout)) { result = t.get(); } else { long timeoutMillis = "always".equalsIgnoreCase(timeout) ? 0 : Time.parseTimeString(timeout); try { if (timeoutMillis == 0) throw new TimeoutException(); result = t.get(timeoutMillis, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { return Response.status(Response.Status.ACCEPTED).entity(TaskTransformer.taskSummary(t)).build(); } } return Response.status(Response.Status.ACCEPTED).entity(result).build(); } catch (Exception e) { throw Exceptions.propagate(e); } }</code><technical_language>I invoke checks Entitlements.isEntitled - is missing</technical_language>

Target:
public Response invoke(String application, String entityToken, String effectorName, String timeout, Map<String, String> parameters) { final EntityLocal entity = brooklyn().getEntity(application, entityToken); Maybe<Effector<?>> effector = EffectorUtils.findEffectorDeclared(entity, effectorName); if (effector.isAbsentOrNull()) throw WebResourceUtils.notFound("Entity '%s' has no effector with name '%s'", entityToken, effectorName); if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.INVOKE_EFFECTOR, Entitlements.EntityAndItem.of(entity, effector.get().getName()))) { throw WebResourceUtils.unauthorized("User '%s' is not authorized to invoke effector %s on entity %s", Entitlements.getEntitlementContext().user(), effector.get().getName(), entity); } log.info("REST invocation of " + entity + "." + effector.get() + " " + parameters); Task<?> t = entity.invoke(effector.get(), parameters); try { Object result = null; if (timeout == null || timeout.isEmpty() || "never".equalsIgnoreCase(timeout)) { result = t.get(); } else { long timeoutMillis = "always".equalsIgnoreCase(timeout) ? 0 : Time.parseTimeString(timeout); try { if (timeoutMillis == 0) throw new TimeoutException(); result = t.get(timeoutMillis, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { return Response.status(Response.Status.ACCEPTED).entity(TaskTransformer.taskSummary(t)).build(); } } return Response.status(Response.Status.ACCEPTED).entity(result).build(); } catch (Exception e) { throw Exceptions.propagate(e); } }
Source:
<code>private Object getFromMetricsMessage(String groupName, String metricName) { <START> if (metricsMessage.containsKey(groupName)) { <END> return metricsMessage.get(groupName).get(metricName); } else { return null; } }</code><technical_language>careful map entries a of null</technical_language>

Target:
private Object getFromMetricsMessage(String groupName, String metricName) { if (metricsMessage.containsKey(groupName) && metricsMessage.get(groupName) != null) { return metricsMessage.get(groupName).get(metricName); } else { return null; } }
Source:
<code>default P getClosestPointTo(Triangle2afp<?, ?, ?, ?, ?, ?> triangle) { assert triangle != null : AssertMessages.notNullParameter(); final double[] segments = new double[] { triangle.getX1(), triangle.getY1(), triangle.getX2(), triangle.getY2(), triangle.getX2(), triangle.getY2(), triangle.getX3(), triangle.getY3(), triangle.getX3(), triangle.getY3(), triangle.getX1(), triangle.getY1(), }; final P point = getGeomFactory().newPoint(); final P tmp = getGeomFactory().newPoint(); double minDistance = Double.POSITIVE_INFINITY; final double ox1 = getX1(); final double oy1 = getY1(); final double ox2 = getX2(); final double oy2 = getY2(); <START> final int magicFour = 4; <END> for (int i = 0; i < segments.length; i += magicFour) { final double x1 = segments[i]; final double y1 = segments[i + 1]; final double x2 = segments[i + 2]; final double y2 = segments[i + 3]; final double distance = computeClosestPointToSegment(ox1, oy1, ox2, oy2, x1, y1, x2, y2, tmp); if (distance < minDistance) { minDistance = distance; point.set(tmp); } } return point; }</code><technical_language>This local variable removed provide readability code more efficient</technical_language>

Target:
default P getClosestPointTo(Triangle2afp<?, ?, ?, ?, ?, ?> triangle) { assert triangle != null : AssertMessages.notNullParameter(); final double[] segments = new double[] { triangle.getX1(), triangle.getY1(), triangle.getX2(), triangle.getY2(), triangle.getX2(), triangle.getY2(), triangle.getX3(), triangle.getY3(), triangle.getX3(), triangle.getY3(), triangle.getX1(), triangle.getY1(), }; final P point = getGeomFactory().newPoint(); final P tmp = getGeomFactory().newPoint(); double minDistance = Double.POSITIVE_INFINITY; final double ox1 = getX1(); final double oy1 = getY1(); final double ox2 = getX2(); final double oy2 = getY2(); for (int i = 0; i < segments.length;) { final double x1 = segments[i++]; final double y1 = segments[i++]; final double x2 = segments[i++]; final double y2 = segments[i++]; final double distance = computeClosestPointToSegment(ox1, oy1, ox2, oy2, x1, y1, x2, y2, tmp); if (distance < minDistance) { minDistance = distance; point.set(tmp); } } return point; }
Source:
<code>private static boolean attemptToCreateKeyspaceOnHost(InetSocketAddress host, CassandraKeyValueServiceConfig config) throws TException { try { CassandraClient client = CassandraClientFactory.getClientInternal(host, config); KsDef ksDef = createKsDefForFresh(client, config); client.system_add_keyspace(ksDef); <START> log.info("Created keyspace: {}", UnsafeArg.of("keyspace", config.getKeyspaceOrThrow())); <END> CassandraKeyValueServices.waitForSchemaVersions(config, client, "after adding the initial empty keyspace"); return true; } catch (InvalidRequestException e) { return keyspaceAlreadyExists(host, config); } }</code><technical_language>a reason changed this Unsafe? In practice strings feature a bit in logs metric collection</technical_language>

Target:
private static boolean attemptToCreateKeyspaceOnHost(InetSocketAddress host, CassandraKeyValueServiceConfig config) throws TException { try { CassandraClient client = CassandraClientFactory.getClientInternal(host, config); KsDef ksDef = createKsDefForFresh(client, config); client.system_add_keyspace(ksDef); log.info("Created keyspace: {}", SafeArg.of("keyspace", config.getKeyspaceOrThrow())); CassandraKeyValueServices.waitForSchemaVersions(config, client, "after adding the initial empty keyspace"); return true; } catch (InvalidRequestException e) { return keyspaceAlreadyExists(host, config); } }
Source:
<code>private void onBoardNew() { logger.info("Menu: Boards > New"); promptToSaveCurrentBoard(); List<PanelInfo> currentPanelInfos = panels.getCurrentPanelInfos(); panels.closeAllPanels(); <START> boolean aborted = !onBoardSaveAs(); <END> if (aborted) { panels.openPanels(currentPanelInfos); } }</code><technical_language>boolean variable is named a boolean</technical_language>

Target:
private void onBoardNew() { logger.info("Menu: Boards > New"); if (isCurrentBoardDirty() && isUserAgreeableToSavingBorad()) { saveBoard(); logger.info("Changes to the current board saved."); } else { logger.info("User abandoned unsaved changes."); } newBoard(); }
Source:
<code>private static String mapFlagsToStringUsingAnnotation( int value, @Nullable ViewDebug.ExportedProperty annotation) { if (!canFlagsBeMappedToString(annotation)) { throw new IllegalStateException("Cannot map using this annotation"); } <START> StringBuilder stringBuilder = new StringBuilder(); <END> boolean atLeastOneFlag = false; for (ViewDebug.FlagToString flagToString : annotation.flagMapping()) { if (flagToString.outputIf() == ((value & flagToString.mask()) == flagToString.equals())) { if (atLeastOneFlag) { stringBuilder.append(" | "); } stringBuilder.append(flagToString.name()); atLeastOneFlag = true; } } if (atLeastOneFlag) { return stringBuilder.toString(); } else { return NONE_MAPPING; } }</code><technical_language>optimize allocation of a StringBuilder in case atLeastOneFlag ends false. do this initializing stringBuilder null here, lazily instantiating in loop if null</technical_language>

Target:
private static String mapFlagsToStringUsingAnnotation( int value, @Nullable ViewDebug.ExportedProperty annotation) { if (!canFlagsBeMappedToString(annotation)) { throw new IllegalStateException("Cannot map using this annotation"); } StringBuilder stringBuilder = null; boolean atLeastOneFlag = false; for (ViewDebug.FlagToString flagToString : annotation.flagMapping()) { if (flagToString.outputIf() == ((value & flagToString.mask()) == flagToString.equals())) { if (stringBuilder == null) { stringBuilder = new StringBuilder(); } if (atLeastOneFlag) { stringBuilder.append(" | "); } stringBuilder.append(flagToString.name()); atLeastOneFlag = true; } } if (atLeastOneFlag) { return stringBuilder.toString(); } else { return NONE_MAPPING; } }
Source:
<code>private ContextServiceResourceDefinition() { super(new SimpleResourceDefinition.Parameters(PathElement.pathElement(EESubsystemModel.CONTEXT_SERVICE), EeExtension.getResourceDescriptionResolver(EESubsystemModel.CONTEXT_SERVICE)) .setAddHandler(ContextServiceAdd.INSTANCE) <START> .setRemoveHandler(ContextServiceRemove.INSTANCE) <END> .addCapabilities(CAPABILITY)); }</code><technical_language>setRemoveHandler(new ServiceRemoveStepHandler(ContextServiceAdd.INSTANCE))</technical_language>

Target:
private ContextServiceResourceDefinition() { super(new SimpleResourceDefinition.Parameters(PathElement.pathElement(EESubsystemModel.CONTEXT_SERVICE), EeExtension.getResourceDescriptionResolver(EESubsystemModel.CONTEXT_SERVICE)) .setAddHandler(ContextServiceAdd.INSTANCE) .setRemoveHandler(new ServiceRemoveStepHandler(ContextServiceAdd.INSTANCE)) .addCapabilities(CAPABILITY)); }
Source:
<code>protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); newChildDescriptors.add(createChildParameter(VControlgridPackage.Literals.CONTROL_GRID_CELL__CONTROL, VViewFactory.eINSTANCE.createControl())); <START> newChildDescriptors.add(createChildParameter(VControlgridPackage.Literals.CONTROL_GRID_CELL__CONTROL, VTableFactory.eINSTANCE.createTableControl())); newChildDescriptors.add(createChildParameter(VControlgridPackage.Literals.CONTROL_GRID_CELL__CONTROL, VCompoundcontrolFactory.eINSTANCE.createCompoundControl())); <END> }</code><technical_language>need a guard calls optional bundle is present. get ClassNotFoundExceptions</technical_language>

Target:
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); newChildDescriptors.add(createChildParameter(VControlgridPackage.Literals.CONTROL_GRID_CELL__CONTROL, VViewFactory.eINSTANCE.createControl())); try { Class.forName("org.eclipse.emf.ecp.view.spi.table.model.VTableFactory"); newChildDescriptors.add(createChildParameter(VControlgridPackage.Literals.CONTROL_GRID_CELL__CONTROL, VTableFactory.eINSTANCE.createTableControl())); } catch (final ClassNotFoundException ex) { } try { Class.forName("org.eclipse.emf.ecp.view.spi.compoundcontrol.model.VCompoundcontrolFactory"); newChildDescriptors.add(createChildParameter(VControlgridPackage.Literals.CONTROL_GRID_CELL__CONTROL, VCompoundcontrolFactory.eINSTANCE.createCompoundControl())); } catch (final ClassNotFoundException ex) { } }
Source:
<code>public void doCreateFirstAccount(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { boolean inSetup = !Jenkins.getInstance().getInstallState().isSetupComplete(); if(!inSetup && hasSomeUser()) { rsp.sendError(SC_UNAUTHORIZED,"First user was already created"); return; } String view = "firstUser.jelly"; User admin = null; if(inSetup) { admin = getUser(SetupWizard.initialSetupAdminUserName); view = "setupWizardFirstUser.jelly"; } User u = createAccount(req, rsp, false, view); if (u!=null) { tryToMakeAdmin(u); if(admin != null) { <START> admin.delete(); <END> } Jenkins.getInstance().setInstallState(InstallState.CREATE_ADMIN_USER.getNextState()); loginAndTakeBack(req, rsp, u); } }</code><technical_language>@jglick I intention is a temporary admin account for setup only, a complete user registration (with email, full name, custom password) afterwards. This advantage of invalidating generated password in case log storage is insecure</technical_language>

Target:
public void doCreateFirstAccount(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { boolean inSetup = !Jenkins.getInstance().getInstallState().isSetupComplete(); if(!inSetup && hasSomeUser()) { rsp.sendError(SC_UNAUTHORIZED,"First user was already created"); return; } User admin = null; try { String view = "firstUser.jelly"; if(inSetup) { admin = getUser(SetupWizard.initialSetupAdminUserName); if(admin != null) { admin.delete(); } view = "setupWizardFirstUser.jelly"; } User u = createAccount(req, rsp, false, view); if (u!=null) { tryToMakeAdmin(u); if(admin != null) { admin = null; } Jenkins.getInstance().setInstallState(InstallState.CREATE_ADMIN_USER.getNextState()); loginAndTakeBack(req, rsp, u); } } finally { if(admin != null) { admin.save(); } } }