auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void flushErrorReport(File errorFile) { try { Report report; if (config.getBeforeSendTasks().isEmpty()) { report = new Report(config.getApiKey(), errorFile); } else { Error error = ErrorReader.readError(config, errorFile); report = new Report(config.getApiKey(), error); for (BeforeSend beforeSend : config.getBeforeSendTasks()) { try { if (!beforeSend.run(report)) { deleteStoredFiles(Collections.singleton(errorFile)); Logger.info("Deleting cancelled error file " + errorFile.getName()); return; } } catch (Throwable ex) { Logger.warn("BeforeSend threw an Exception", ex); } } } config.getDelivery().deliver(report, config); deleteStoredFiles(Collections.singleton(errorFile)); Logger.info("Deleting sent error file " + errorFile.getName()); } catch (DeliveryFailureException exception) { cancelQueuedFiles(Collections.singleton(errorFile)); Logger.warn("Could not send previously saved error(s)" + " to Bugsnag, will try again later", exception); } catch (Exception exception) { <START> if (delegate != null && !(exception instanceof FileNotFoundException)) { <END> delegate.onErrorReadFailure(exception, errorFile); } deleteStoredFiles(Collections.singleton(errorFile)); } }</code><technical_language>instanceof, a separate catch block for FileNotFoundException warns? need attempt a delete in this case either</technical_language>

Target:
private void flushErrorReport(File errorFile) { try { Report report; if (config.getBeforeSendTasks().isEmpty()) { report = new Report(config.getApiKey(), errorFile); } else { Error error = ErrorReader.readError(config, errorFile); report = new Report(config.getApiKey(), error); for (BeforeSend beforeSend : config.getBeforeSendTasks()) { try { if (!beforeSend.run(report)) { deleteStoredFiles(Collections.singleton(errorFile)); Logger.info("Deleting cancelled error file " + errorFile.getName()); return; } } catch (Throwable ex) { Logger.warn("BeforeSend threw an Exception", ex); } } } config.getDelivery().deliver(report, config); deleteStoredFiles(Collections.singleton(errorFile)); Logger.info("Deleting sent error file " + errorFile.getName()); } catch (DeliveryFailureException exception) { cancelQueuedFiles(Collections.singleton(errorFile)); Logger.warn("Could not send previously saved error(s)" + " to Bugsnag, will try again later", exception); } catch (FileNotFoundException exc) { Logger.warn("Ignoring empty file - oldest report on disk was deleted", exc); } catch (Exception exception) { if (delegate != null) { delegate.onErrorIOFailure(exception, errorFile, "Crash Report Deserialization"); } deleteStoredFiles(Collections.singleton(errorFile)); } }
Source:
<code>private void setUpSeekBar() { seekBar.setMax(elementCount); seekBar.setProgress(progress); seekBar.setOnSeekBarChangeListener(this); if (isRTL()) { float rotate = seekBar.getRotation(); <START> if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { <END> seekBar.setRotation(180 - rotate); } else { seekBar.setRotation(360 - rotate); } } seekBar.setOnTouchListener(new SeekBar.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { seekBar.getThumb().mutate().setAlpha(255); int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: v.getParent().requestDisallowInterceptTouchEvent(true); break; case MotionEvent.ACTION_UP: v.getParent().requestDisallowInterceptTouchEvent(false); if (actualValue == null) { actualValue = rangeStart; setUpActualValueLabel(); } break; } v.onTouchEvent(event); return true; } }); }</code><technical_language>is wrong here, KITKAT supported need this check</technical_language>

Target:
private void setUpSeekBar() { seekBar.setMax(elementCount); seekBar.setProgress(progress); seekBar.setOnSeekBarChangeListener(this); if (isRTL()) { float rotate = seekBar.getRotation(); seekBar.setRotation(360 - rotate); } seekBar.setOnTouchListener(new SeekBar.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { seekBar.getThumb().mutate().setAlpha(255); int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: v.getParent().requestDisallowInterceptTouchEvent(true); break; case MotionEvent.ACTION_UP: v.getParent().requestDisallowInterceptTouchEvent(false); if (actualValue == null) { actualValue = rangeStart; setUpActualValueLabel(); } break; } v.onTouchEvent(event); return true; } }); }
Source:
<code>public void testVerseThree() { String expectedVerseThree = "On the third day of Christmas my true love gave to me, " + "three French Hens, " + "two Turtle Doves, " + "and a Partridge in a Pear Tree.\n"; <START> assertEquals(expectedVerseThree, twelveDays.verse(3)); <END> }</code><technical_language>for this change</technical_language>

Target:
public void testVerseThree() { String expectedVerseThree = "On the third day of Christmas my true love gave to me, three French Hens, " + "two Turtle Doves, and a Partridge in a Pear Tree.\n"; assertEquals(expectedVerseThree, twelveDays.verse(3)); }
Source:
<code>public MultipleStorageDomainsValidator(NGuid spId, Collection<Guid> sdIds) { this.spId = spId; domainValidators = new HashMap<Guid, StorageDomainValidator>(sdIds.size()); for (Guid id : sdIds) { <START> domainValidators.put(id, null); <END> } }</code><technical_language>a matter of taste, filling a map null values is cup of tea. put a member set of storage domain ids, code is called get a storage domain validator, add entry map</technical_language>

Target:
public MultipleStorageDomainsValidator(NGuid spId, Collection<Guid> sdIds) { this.storagePoolId = spId; domainValidators = new HashMap<Guid, StorageDomainValidator>(sdIds.size()); for (Guid id : sdIds) { domainValidators.put(id, null); } }
Source:
<code>public void testCheckWithDescription() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(JavadocTagContinuationIndentationCheck.class); final String[] expected = { <START> "8: " + getCheckMessage(MSG_KEY, 4), <END> "10: " + getCheckMessage(MSG_KEY, 4), "9: " + getCheckMessage(MSG_KEY, 4), }; verify(checkConfig, getPath("InputJavadocTagContinuationIndentationDescription.java"), expected); }</code><technical_language>Please order lines</technical_language>

Target:
public void testCheckWithDescription() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(JavadocTagContinuationIndentationCheck.class); final String[] expected = { "9: " + getCheckMessage(MSG_KEY, 4), "10: " + getCheckMessage(MSG_KEY, 4), "11: " + getCheckMessage(MSG_KEY, 4), "40: " + getCheckMessage(MSG_KEY, 4), "42: " + getCheckMessage(MSG_KEY, 4), "43: " + getCheckMessage(MSG_KEY, 4), }; verify(checkConfig, getPath("InputJavadocTagContinuationIndentationDescription.java"), expected); }
Source:
<code>@Test public void testDuplicatesWithLocation() { Policy p; ArrayList<Notice> notices = new ArrayList<>(); p = ParserWithLocation.parse("img-src a ;;; img-src b", "<LINK_0>", notices); assertEquals(1, notices.size()); <START> assertEquals("1:23: Policy contains more than one img-src directive. All but the first instance will be ignored.", notices.get(0).show()); <END> }</code><technical_language>This position info is off</technical_language>

Target:
@Test public void testDuplicatesWithLocation() { Policy p; ArrayList<Notice> notices = new ArrayList<>(); p = ParserWithLocation.parse("img-src a ;;; img-src b", "<LINK_0>", notices); assertEquals(1, notices.size()); assertEquals("1:15: Policy contains more than one img-src directive. All but the first instance will be ignored.", notices.get(0).show()); }
Source:
<code>public void testPageOrderingBefore() { initOnePageProvider(PositioningKind.BEFORE, DefaultSessionEditorPage.PAGE_ID, PAGE2_ID); List<IFormPage> pagesOrdered = sessionEditor.getPages(); <START> assertEquals("The page order is wrong.", idToPageMap.get(PAGE2_ID), pagesOrdered.get(0)); assertTrue("The page order is wrong.", pagesOrdered.get(1) instanceof DefaultSessionEditorPage); assertEquals("The number of page in the editor is wrong.", 2, pagesOrdered.size()); <END> }</code><technical_language>hesitate create custom assertXXX and/or helper methods reduce code duplication</technical_language>

Target:
public void testPageOrderingBefore() { initOnePageProvider(PositioningKind.BEFORE, DefaultSessionEditorPage.PAGE_ID, PAGE2_ID); assertRightPageOrdering(2, PAGE2_ID, DefaultSessionEditorPage.PAGE_ID); }
Source:
<code>private void testBrokerNamedQueue(AbstractMessageListenerContainer container, CountDownLatch latch1, CountDownLatch latch2, Queue queue) throws Exception { container.start(); String firstDeclaredName = queue.getDeclaredName(); this.template.convertAndSend(firstDeclaredName, "foo"); assertThat(latch1.await(10, TimeUnit.SECONDS)).isTrue(); <START> assertThat(this.message.get().getBody()).isEqualTo("foo".getBytes()); <END> final CountDownLatch newConnectionLatch = new CountDownLatch(2); cf.addConnectionListener(c -> newConnectionLatch.countDown()); cf.resetConnection(); assertThat(newConnectionLatch.await(10, TimeUnit.SECONDS)).isTrue(); String secondDeclaredName = queue.getDeclaredName(); assertThat(secondDeclaredName).isNotEqualTo(firstDeclaredName); this.template.convertAndSend(secondDeclaredName, "bar"); assertThat(latch2.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(this.message.get().getBody()).isEqualTo("bar".getBytes()); container.stop(); }</code><technical_language>reset this AtomicReference in tests: some stale data remain</technical_language>

Target:
private void testBrokerNamedQueue(AbstractMessageListenerContainer container, CountDownLatch latch1, CountDownLatch latch2, Queue queue) throws Exception { container.start(); String firstActualName = queue.getActualName(); this.message.set(null); this.template.convertAndSend(firstActualName, "foo"); assertThat(latch1.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(this.message.get().getBody()).isEqualTo("foo".getBytes()); final CountDownLatch newConnectionLatch = new CountDownLatch(2); cf.addConnectionListener(c -> newConnectionLatch.countDown()); cf.resetConnection(); assertThat(newConnectionLatch.await(10, TimeUnit.SECONDS)).isTrue(); String secondActualName = queue.getActualName(); assertThat(secondActualName).isNotEqualTo(firstActualName); this.message.set(null); this.template.convertAndSend(secondActualName, "bar"); assertThat(latch2.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(this.message.get().getBody()).isEqualTo("bar".getBytes()); container.stop(); }
Source:
<code>public boolean isEmpty(Node compartment) { boolean empty = true; if (compartment != null) { for (Object property : compartment.getChildren()) { if (isStereotypeProperty(property) || isStereotypeBraceProperty(property)) { if (isDisplayed((Node) property)) { <START> empty &= false; <END> } } } } return empty; }</code><technical_language>I this variable get out of for-loop 'empty' variable false affectation</technical_language>

Target:
public boolean isEmpty(Node compartment) { boolean empty = true; if (compartment != null) { Iterator<?> childrenIterator = compartment.getChildren().iterator(); while (childrenIterator.hasNext() && empty) { Object property = childrenIterator.next(); if (isStereotypeProperty(property) || isStereotypeBraceProperty(property)) { if (isDisplayed((Node) property)) { empty &= false; } } } } return empty; }
Source:
<code>public boolean tryLock(long time, TimeUnit unit, String... names) throws InterruptedException { long start = System.nanoTime(); boolean result = false; while (!(result = db.lockForWriting(names)) && TimeUnit.MILLISECONDS.convert((System.nanoTime() - start), TimeUnit.NANOSECONDS) < time) { <START> Thread.sleep(1000); <END> } return result; }</code><technical_language>Do want sleep for 1 sec? Also, a constant sleep time is thread starved of locks, if other threads jumping in. worth sleeping for a random amount of time, 50 300 ms. Also, converting time ns here</technical_language>

Target:
public boolean tryLock(long time, TimeUnit unit, String... names) throws InterruptedException { long start = System.nanoTime(); boolean result = false; long timeInMills = TimeUnit.MILLISECONDS.convert(time, unit); while (!(result = db.lockForWriting(names)) && TimeUnit.MILLISECONDS.convert((System.nanoTime() - start), TimeUnit.NANOSECONDS) < timeInMills) { long sleepDurationMillis = 50 + RANDOM.nextInt(251); Thread.sleep(sleepDurationMillis); } return result; }
Source:
<code>public synchronized int joinLRA(StringBuilder recoveryUrl, URL lra, long timeLimit, String compensatorUrl, String linkHeader, String recoveryUrlBase, String compensatorData) { if (lra == null) lraTrace(null, "Error missing LRA header in join request"); lraTrace(lra, "join LRA"); Transaction transaction = getTransaction(lra); if (timeLimit < 0) timeLimit = 0; if (!transaction.isActive()) return Response.Status.PRECONDITION_FAILED.getStatusCode(); LRARecord participant; try { participant = transaction.enlistParticipant(lra, linkHeader != null ? linkHeader : compensatorUrl, recoveryUrlBase, timeLimit, compensatorData); } catch (GenericLRAException e) { LRALogger.logger.infof(e, e.getMessage()); <START> throw new GenericLRAException(lra, Response.Status.PRECONDITION_FAILED.getStatusCode(), e.getMessage(), e.getCause()); <END> } catch (UnsupportedEncodingException e) { return Response.Status.PRECONDITION_FAILED.getStatusCode(); } if (participant == null || participant.getRecoveryCoordinatorURL() == null) return Response.Status.PRECONDITION_FAILED.getStatusCode(); String recoveryURL = participant.getRecoveryCoordinatorURL().toExternalForm(); updateRecoveryURL(lra, participant.getParticipantURL(), recoveryURL, false); recoveryUrl.append(recoveryURL); return Response.Status.OK.getStatusCode(); }</code><technical_language>I strange hide stack trace of original exception. construct GenericLRAException LRARecord exception pass caller LRAService call? other point I mind is GenericLRAException is WebApplicationException in LRARecord expected thrown out of application a client. throwsome genereic exception rethrow stacktrace GenericLRAException in LRAService</technical_language>

Target:
public synchronized int joinLRA(StringBuilder recoveryUrl, URL lra, long timeLimit, String compensatorUrl, String linkHeader, String recoveryUrlBase, String compensatorData) { if (lra == null) lraTrace(null, "Error missing LRA header in join request"); lraTrace(lra, "join LRA"); Transaction transaction = getTransaction(lra); if (timeLimit < 0) timeLimit = 0; if (!transaction.isActive()) return Response.Status.PRECONDITION_FAILED.getStatusCode(); LRARecord participant; try { participant = transaction.enlistParticipant(lra, linkHeader != null ? linkHeader : compensatorUrl, recoveryUrlBase, timeLimit, compensatorData); } catch (UnsupportedEncodingException e) { return Response.Status.PRECONDITION_FAILED.getStatusCode(); } if (participant == null || participant.getRecoveryCoordinatorURL() == null) return Response.Status.PRECONDITION_FAILED.getStatusCode(); String recoveryURL = participant.getRecoveryCoordinatorURL().toExternalForm(); updateRecoveryURL(lra, participant.getParticipantURL(), recoveryURL, false); recoveryUrl.append(recoveryURL); return Response.Status.OK.getStatusCode(); }
Source:
<code>public boolean enlistResource(final XAResource xaRes) throws RollbackException, IllegalStateException, SystemException { Assert.checkNotNullParam("xaRes", xaRes); final int estimatedRemainingTime = getEstimatedRemainingTime(); <START> if(estimatedRemainingTime == 0) throw Log.log.cannotEnlistToTimeoutedTransaction(xaRes, this); <END> try { xaRes.setTransactionTimeout(estimatedRemainingTime); } catch (XAException e) { throw Log.log.setTimeoutFailed(estimatedRemainingTime, e); } return transaction.enlistResource(xaRes); }</code><technical_language>TimedOut Timeouted</technical_language>

Target:
public boolean enlistResource(final XAResource xaRes) throws RollbackException, IllegalStateException, SystemException { Assert.checkNotNullParam("xaRes", xaRes); final int estimatedRemainingTime = getEstimatedRemainingTime(); if(estimatedRemainingTime == 0) throw Log.log.cannotEnlistToTimeOutTransaction(xaRes, this); try { xaRes.setTransactionTimeout(estimatedRemainingTime); } catch (XAException e) { throw Log.log.setTimeoutFailed(estimatedRemainingTime, e); } return transaction.enlistResource(xaRes); }
Source:
<code>public BlobDetail call() throws Exception { Blob blob = storage.blobBuilder(toBeUploadedBlobDetail.getRemoteBlobName()) .payload(toBeUploadedBlobDetail.getLocalFile()) <START> .contentType("") <END> .build(); String eTag = storage.putBlob(container, blob); BlobDetail uploadedBlobDetail = new BlobDetail( toBeUploadedBlobDetail.getRemoteBlobName(), toBeUploadedBlobDetail.getLocalFile(), eTag); return uploadedBlobDetail; }</code><technical_language>Hmm...will this allow files render correctly? need preserve content types</technical_language>

Target:
public BlobDetail call() throws Exception { Blob blob = storage.blobBuilder(toBeUploadedBlobDetail.getRemoteBlobName()) .payload(toBeUploadedBlobDetail.getLocalFile()) .build(); String eTag = storage.putBlob(container, blob); BlobDetail uploadedBlobDetail = new BlobDetail( toBeUploadedBlobDetail.getRemoteBlobName(), toBeUploadedBlobDetail.getLocalFile(), eTag); return uploadedBlobDetail; }
Source:
<code>public void addAccount(final Account account) { final SqlSession session = sessions.openSession(); try { session.insert(namespace + "addAccount", toMap(account)); session.commit(); } finally { session.close(); } Iterator<AuthToken> iterator = account.getAuthToken().iterator(); while(iterator.hasNext()){ AuthToken token = iterator.next(); <START> System.out.println("Adding Account tokens token:"+token); <END> addAuthToken(new AuthToken(account.getSid(), token.getAuthToken(), token.getDescription())); } }</code><technical_language>Need pull this logging. System.outs..</technical_language>

Target:
public void addAccount(final Account account) { final SqlSession session = sessions.openSession(); try { session.insert(namespace + "addAccount", toMap(account)); session.commit(); } finally { session.close(); } Iterator<AuthToken> iterator = account.getAuthToken().iterator(); while(iterator.hasNext()){ AuthToken token = iterator.next(); addAuthToken(new AuthToken(account.getSid(), token.getAuthToken(), token.getDescription())); } }
Source:
<code>private String createPKCEStateNonce() { <START> return String.format("oauth2code:%s:%s:%s", <END> mPKCEManager.getCodeChallenge(), DbxPKCEManager.CODE_CHALLENGE_METHODS, mTokenAccessType.toString()); }</code><technical_language>pass in a locale extra safe. String.format("oauth2code:%s:%s:%s", -> String.format(Locale.US, "oauth2code:%s:%s:%s",</technical_language>

Target:
private String createPKCEStateNonce() { return String.format(Locale.US, "oauth2code:%s:%s:%s", mPKCEManager.getCodeChallenge(), DbxPKCEManager.CODE_CHALLENGE_METHODS, mTokenAccessType.toString()); }
Source:
<code>public boolean isApplicable() throws CoreException { if (fElements.length == 0) return false; if (fElements.length != fResources.length + fJavaElements.length) return false; for (IResource <START> fResource : <END> fResources) { if (!RefactoringAvailabilityTester.isDeleteAvailable(fResource)) { return false; } } for (IJavaElement fJavaElement : fJavaElements) { if (!RefactoringAvailabilityTester.isDeleteAvailable(fJavaElement)) { return false; } } return true; }</code><technical_language>rename resource</technical_language>

Target:
public boolean isApplicable() throws CoreException { if (fElements.length == 0) return false; if (fElements.length != fResources.length + fJavaElements.length) return false; for (IResource resource : fResources) { if (!RefactoringAvailabilityTester.isDeleteAvailable(resource)) { return false; } } for (IJavaElement javaElement : fJavaElements) { if (!RefactoringAvailabilityTester.isDeleteAvailable(javaElement)) { return false; } } return true; }
Source:
<code>private void updatePostFormatKeysAndNames() { final SiteModel site = getSite(); <START> if (!isAdded() || site == null) { <END> return; } mPostFormatKeys = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.post_format_keys))); mPostFormatNames = new ArrayList<>(Arrays.asList(getResources() .getStringArray(R.array.post_format_display_names))); List<PostFormatModel> postFormatModels = mSiteStore.getPostFormats(site); for (PostFormatModel postFormatModel : postFormatModels) { if (!mPostFormatKeys.contains(postFormatModel.getSlug())) { mPostFormatKeys.add(postFormatModel.getSlug()); mPostFormatNames.add(postFormatModel.getDisplayName()); } } }</code><technical_language>I care fragment is currently added view manipulation. a site null check enough getSite() check for activity null. suggestion if (site == null) {</technical_language>

Target:
private void updatePostFormatKeysAndNames() { final SiteModel site = getSite(); if (site == null) { return; } mPostFormatKeys = new ArrayList<>(mDefaultPostFormatKeys); mPostFormatNames = new ArrayList<>(mDefaultPostFormatNames); List<PostFormatModel> postFormatModels = mSiteStore.getPostFormats(site); for (PostFormatModel postFormatModel : postFormatModels) { if (!mPostFormatKeys.contains(postFormatModel.getSlug())) { mPostFormatKeys.add(postFormatModel.getSlug()); mPostFormatNames.add(postFormatModel.getDisplayName()); } } }
Source:
<code>public void onRevokeLeadership() { synchronized (lock) { if (running) { if (LOG.isDebugEnabled()) { LOG.debug( "Revoke leadership of ({}@{}).", leaderContender.getDescription(), confirmedLeaderSessionID, confirmedLeaderAddress); } issuedLeaderSessionID = null; clearConfirmedLeaderInformation(); <START> leaderContender.revokeLeadership(); <END> leaderElectionDriver.writeLeaderInformation(LeaderInformation.empty()); } else { if (LOG.isDebugEnabled()) { LOG.debug("Ignoring the revoke leadership notification since the " + "has already been closed.", leaderElectionDriver); } } } }</code><technical_language>lock</technical_language>

Target:
public void onRevokeLeadership() { synchronized (lock) { if (running) { if (LOG.isDebugEnabled()) { LOG.debug( "Revoke leadership of ({}@{}).", leaderContender.getDescription(), confirmedLeaderSessionID, confirmedLeaderAddress); } issuedLeaderSessionID = null; clearConfirmedLeaderInformation(); } else { if (LOG.isDebugEnabled()) { LOG.debug("Ignoring the revoke leadership notification since the " + "has already been closed.", leaderElectionDriver); } return; } } leaderContender.revokeLeadership(); synchronized (lock) { if (running) { if (issuedLeaderSessionID == null) { if (LOG.isDebugEnabled()) { LOG.debug("Clearing the leader information on {}.", leaderElectionDriver); } leaderElectionDriver.writeLeaderInformation(LeaderInformation.empty()); } } } }
Source:
<code>@Override public Pair<RelTraitSet, List<RelTraitSet>> deriveTraits( final RelTraitSet childTraits, final int childId) { RelCollation collation = childTraits.getCollation(); if (collation == null || collation.getFieldCollations().size() == 0) { return null; } <START> return Pair.of(getTraitSet().replace(collation), ImmutableList.of(childTraits)); <END> }</code><technical_language>This is correct. select distinct a, b*2, c (select a, b, c foo order a, b, c limit 100) t;</technical_language>

Target:
@Override public Pair<RelTraitSet, List<RelTraitSet>> deriveTraits( final RelTraitSet childTraits, final int childId) { RelCollation collation = childTraits.getCollation(); if (collation == null || childTraits.isDefaultSansConvention()) { return null; } int maxField = Math.max(getInput().getRowType().getFieldCount(), getProjects().size()); Mappings.TargetMapping mapping = Mappings .create(MappingType.FUNCTION, maxField, maxField); for (Ord<RexNode> node : Ord.zip(getProjects())) { if (node.e instanceof RexInputRef) { mapping.set(((RexInputRef) node.e).getIndex(), node.i); } else if (node.e.isA(SqlKind.CAST)) { final RexNode operand = ((RexCall) node.e).getOperands().get(0); if (operand instanceof RexInputRef) { mapping.set(((RexInputRef) operand).getIndex(), node.i); } } } List<RelFieldCollation> collationFieldsToDerive = new ArrayList<>(); for (RelFieldCollation rc : collation.getFieldCollations()) { if (isCollationOnTrivialExpr(mapping, rc, false)) { collationFieldsToDerive.add(rc); } else { break; } } if (collationFieldsToDerive.size() > 0) { final RelCollation newCollation = RelCollations.of(collationFieldsToDerive).apply(mapping); return Pair.of(traitSet.replace(newCollation), ImmutableList.of(childTraits)); } else { return null; } }
Source:
<code>public int updateStars(int stars , String uuid) throws ApplicationManagementException { if (log.isDebugEnabled()) { log.debug("Stars are received for the application " + uuid); } int newStars=0; try { ConnectionManagerUtil.beginDBTransaction(); int ratedUsers = ApplicationManagementDAOFactory.getCommentDAO().getRatedUser(uuid); int oldStars = ApplicationManagementDAOFactory.getCommentDAO().getStars(uuid); <START> if(ratedUsers==0){ <END> newStars=ApplicationManagementDAOFactory.getCommentDAO().updateStars(stars,uuid); return newStars; }else { int avgStars = ((oldStars*ratedUsers)+stars) / (ratedUsers+1); newStars = ApplicationManagementDAOFactory.getCommentDAO().updateStars(avgStars, uuid); ConnectionManagerUtil.commitDBTransaction(); return newStars; } } catch (ApplicationManagementDAOException e) { ConnectionManagerUtil.rollbackDBTransaction(); log.error("Application Management Exception occurs.", e); } catch (DBConnectionException e) { log.error("DB Connection Exception occurs.", e); } finally { ConnectionManagerUtil.closeDBConnection(); } return newStars; }</code><technical_language>Apply WSO2 code format</technical_language>

Target:
public int updateStars(int stars, String uuid) throws ApplicationManagementException { if (log.isDebugEnabled()) { log.debug("Stars are received for the application " + uuid); } int newStars = 0; try { ConnectionManagerUtil.beginDBTransaction(); int ratedUsers = commentDAO.getRatedUser(uuid); int oldStars = commentDAO.getStars(uuid); if (ratedUsers == 0) { newStars = commentDAO.updateStars(stars, uuid); return newStars; } else { int avgStars = ((oldStars * ratedUsers) + stars) / (ratedUsers + 1); newStars = commentDAO.updateStars(avgStars, uuid); ConnectionManagerUtil.commitDBTransaction(); return newStars; } } catch (ApplicationManagementDAOException e) { ConnectionManagerUtil.rollbackDBTransaction(); throw new ApplicationManagementException( "Updated average stars of the Application with UUID " + uuid + " can not get.", e); } finally { ConnectionManagerUtil.closeDBConnection(); } }
Source:
<code>public List<String> getYarnRecommendedDecommissionHostsForHostGroup(String clusterCrn, YarnScalingServiceV1Response yarnResponse, Map<String, String> hostFqdnsToInstanceId, int maxAllowedDownScale, Optional<Integer> mandatoryDownScaleCount) { Set<String> consideredNodeIds = new HashSet<>(); Integer allowedDownscale = Math.max(maxAllowedDownScale, mandatoryDownScaleCount.orElse(0)); List<String> decommissionNodes = yarnResponse.getScaleDownCandidates().orElse(List.of()).stream() <START> .sorted(Comparator.comparingInt(YarnScalingServiceV1Response.DecommissionCandidate::getAmCount)) <END> .map(YarnScalingServiceV1Response.DecommissionCandidate::getNodeId) .map(nodeFqdn -> nodeFqdn.split(":")[0]) .filter(s -> hostFqdnsToInstanceId.keySet().contains(s)) .map(nodeFqdn -> hostFqdnsToInstanceId.get(nodeFqdn)) .limit(allowedDownscale) .map(nodeId -> { consideredNodeIds.add(nodeId); return nodeId; }) .collect(Collectors.toList()); int forcedCandidatesCount = mandatoryDownScaleCount.orElse(0) - decommissionNodes.size(); if (forcedCandidatesCount > 0) { List forcedCandidates = hostFqdnsToInstanceId.keySet().stream() .filter(nodeId -> !consideredNodeIds.contains(nodeId)) .limit(forcedCandidatesCount).collect(Collectors.toList()); LOGGER.info("Forced downscaling candidates count '{}', candidates '{}' in cluster '{}' to achieve mandatory " + "downscaletarget '{}'.", forcedCandidates.size(), forcedCandidates, clusterCrn, mandatoryDownScaleCount.orElse(0)); decommissionNodes.addAll(forcedCandidates); } return decommissionNodes; }</code><technical_language>Is this needed if YARN is processing this</technical_language>

Target:
public List<String> getYarnRecommendedDecommissionHostsForHostGroup(String clusterCrn, YarnScalingServiceV1Response yarnResponse, Map<String, String> hostFqdnsToInstanceId, int maxAllowedDownScale, Optional<Integer> mandatoryDownScaleCount) { Set<String> consideredNodeIds = new HashSet<>(); Integer allowedDownscale = Math.max(maxAllowedDownScale, mandatoryDownScaleCount.orElse(0)); List<String> decommissionNodes = yarnResponse.getScaleDownCandidates().orElse(List.of()).stream() .map(YarnScalingServiceV1Response.DecommissionCandidate::getNodeId) .map(nodeFqdn -> nodeFqdn.split(":")[0]) .filter(s -> hostFqdnsToInstanceId.keySet().contains(s)) .map(nodeFqdn -> hostFqdnsToInstanceId.get(nodeFqdn)) .limit(allowedDownscale) .map(nodeId -> { consideredNodeIds.add(nodeId); return nodeId; }) .collect(Collectors.toList()); int forcedCandidatesCount = mandatoryDownScaleCount.orElse(0) - decommissionNodes.size(); if (forcedCandidatesCount > 0) { List forcedCandidates = hostFqdnsToInstanceId.keySet().stream() .filter(nodeId -> !consideredNodeIds.contains(nodeId)) .limit(forcedCandidatesCount).collect(Collectors.toList()); LOGGER.info("Forced downscaling candidates count '{}', candidates '{}' in cluster '{}' to achieve mandatory " + "downscaletarget '{}'.", forcedCandidates.size(), forcedCandidates, clusterCrn, mandatoryDownScaleCount.orElse(0)); decommissionNodes.addAll(forcedCandidates); } return decommissionNodes; }
Source:
<code><START> protected boolean validateInputs() { <END> boolean result = super.validateInputs(); if (result) { returnValue.setExceptionString(""); try { String hostName = getParameters().getVdsHostName(); if (StringUtils.isBlank(hostName)) { returnValue.setExceptionString("Cannot register Host - no Hostname address specified."); result = false; } else { List<VDS> vdssByUniqueId = getVdssByUniqueId(); if (vdssByUniqueId.size() > 1) { returnValue.setExceptionString("Cannot register Host - unique id is ambigious."); result = false; } else if (vdssByUniqueId.size() == 1) { VDS vds = vdssByUniqueId.get(0); if (!VdsHandler.isPendingOvirt(vds)) { returnValue.setExceptionString(VdcBllMessages.VDS_STATUS_NOT_VALID_FOR_UPDATE.name()); result = false; } else { Long otp = getParameters().getOtp(); if (otp != null && !isValidOtp(vds, otp)) { returnValue.setExceptionString(String.format("Invalid OTP for host %s", hostName)); result = false; } } } } } catch (RuntimeException ex) { log.error("RegisterVdsQuery::CanDoAction: An exception has been thrown.", ex); returnValue.setExceptionString(String.format("Cannot register Host - An exception has been thrown: %1$s", ex.getMessage())); result = false; } } return result; }</code><technical_language>optional: consider replacing "result=false" "return false" get rid of if-elses</technical_language>

Target:
protected boolean validateInputs() { boolean result = super.validateInputs(); if (result) { VdcQueryReturnValue returnValue = getQueryReturnValue(); returnValue.setExceptionString(""); try { String hostName = getParameters().getVdsHostName(); if (StringUtils.isBlank(hostName)) { returnValue.setExceptionString("Cannot register Host - no Hostname address specified."); result = false; } else { List<VDS> vdssByUniqueId = getVdssByUniqueId(); if (vdssByUniqueId.size() > 1) { returnValue.setExceptionString("Cannot register Host - unique id is ambigious."); result = false; } else if (vdssByUniqueId.size() == 1) { VDS vds = vdssByUniqueId.get(0); if (!VdsHandler.isPendingOvirt(vds)) { returnValue.setExceptionString(VdcBllMessages.VDS_STATUS_NOT_VALID_FOR_UPDATE.name()); result = false; } else { Long otp = getParameters().getOtp(); if (otp != null && !isValidOtp(vds, otp)) { returnValue.setExceptionString(String.format("Invalid OTP for host %s", hostName)); result = false; } } } } } catch (RuntimeException ex) { log.error("RegisterVdsQuery::CanDoAction: An exception has been thrown.", ex); returnValue.setExceptionString(String.format("Cannot register Host - An exception has been thrown: %1$s", ex.getMessage())); result = false; } } return result; }
Source:
<code>private void throwIfErrorResponse(Response response, String metricsPrefix) throws GatewayClientException, DownstreamException { if (CLIENT_ERROR == response.getStatusInfo().getFamily()) { metricRegistry.counter(metricsPrefix + ".failures").inc(); throw new GatewayClientException( "Unexpected HTTP status code " + response.getStatus() + " from gateway", response); } if (SERVER_ERROR == response.getStatusInfo().getFamily()) { metricRegistry.counter(metricsPrefix + ".failures").inc(); String responseMessage = response.readEntity(String.class); logger.error("Unexpected HTTP status code from gateway, error=[{}]", response.getStatus(), responseMessage); throw new DownstreamException(response.getStatus(), responseMessage); } <START> logger.error("Other unexpected HTTP status code from gateway=[stripe]", response.getStatus()); <END> }</code><technical_language>useful log response body well</technical_language>

Target:
private void throwIfErrorResponse(Response response, String metricsPrefix) throws GatewayClientException, DownstreamException { switch (response.getStatusInfo().getFamily()) { case SUCCESSFUL: break; case CLIENT_ERROR: metricRegistry.counter(metricsPrefix + ".failures").inc(); throw new GatewayClientException("Unexpected HTTP status code " + response.getStatus() + " from gateway", response); case SERVER_ERROR: metricRegistry.counter(metricsPrefix + ".failures").inc(); String responseMessage = response.readEntity(String.class); logger.error("Unexpected HTTP status code from gateway, error=[{}]", response.getStatus(), responseMessage); throw new DownstreamException(response.getStatus(), responseMessage); default: logger.error("Other HTTP status from gateway=[stripe], response=[]", response); } }
Source:
<code>public CategoryView findCategory(CategoryView parentCategoryView, String category) throws IOException { String cacheKey = "singleCategory:" <START> + CacheParams.createKeyHash(category + parentCategoryView.hashCode()); <END> return CacheUtil.getOrCompute(cache, cacheKey, () -> findCategoryWithoutCache(parentCategoryView, category)); }</code><technical_language>CategoryView.hashCode() returns hashCode of name field, String.hashCode() is collision-resistant. Meaning, is a small chance (but astronomically small SHA-1) cache key collide another parent of category. CacheParams provides a a collision-resistant key out of strings. I recommend java String cacheKey = "singleCategory:" + CacheParams.createKeyHash(category, parentCategoryView.getName());</technical_language>

Target:
public CategoryView findCategory(CategoryView parentCategoryView, String category) throws IOException { String cacheKey = "singleCategory:" + CacheParams.createKeyHash(category, parentCategoryView.getName()); return CacheUtil.getOrCompute(cache, cacheKey, () -> findCategoryWithoutCache(parentCategoryView, category)); }
Source:
<code><START> public SDVariable tile(SDVariable iX, int[] repeat) { return tile(iX, repeat);} <END></code><technical_language>a lot return tile(null, iX, repeat) meant this create infinite recursion / stack overflow instead</technical_language>

Target:
public SDVariable tile(SDVariable iX, int[] repeat) { return tile(null, iX, repeat);}
Source:
<code>private TaskConfigurer getDefaultConfigurer() { verifyEnvironment(); int configurers = this.context.getBeanNamesForType(TaskConfigurer.class).length; if (configurers < 1) { TaskConfigurer taskConfigurer; if(!CollectionUtils.isEmpty(this.dataSources) && this.dataSources.size() == 1) { taskConfigurer = new DefaultTaskConfigurer(this.dataSources.iterator().next()); } else { <START> taskConfigurer = new DefaultTaskConfigurer(null); <END> } this.context.getBeanFactory().registerSingleton("taskConfigurer", taskConfigurer); return taskConfigurer; } else { if(configurers == 1) { return this.context.getBean(TaskConfigurer.class); } else { throw new IllegalStateException("Expected one TaskConfigurer but found " + configurers); } } }</code><technical_language>Do want add a default constructor DefaultTaskConfigurer for this case (instead of passing null)</technical_language>

Target:
private TaskConfigurer getDefaultConfigurer() { verifyEnvironment(); int configurers = this.context.getBeanNamesForType(TaskConfigurer.class).length; if (configurers < 1) { TaskConfigurer taskConfigurer; if(!CollectionUtils.isEmpty(this.dataSources) && this.dataSources.size() == 1) { taskConfigurer = new DefaultTaskConfigurer(this.dataSources.iterator().next()); } else { taskConfigurer = new DefaultTaskConfigurer(); } this.context.getBeanFactory().registerSingleton("taskConfigurer", taskConfigurer); return taskConfigurer; } else { if(configurers == 1) { return this.context.getBean(TaskConfigurer.class); } else { throw new IllegalStateException("Expected one TaskConfigurer but found " + configurers); } } }
Source:
<code>public void widgetSelected(SelectionEvent e) { IStructuredSelection selection = viewer.getStructuredSelection(); <START> if (selection != null) { <END> viewer.editElement(selection.getFirstElement(), 0); } }</code><technical_language>I apply a patch for proposed bug report</technical_language>

Target:
public void widgetSelected(SelectionEvent e) { IStructuredSelection selection = viewer.getStructuredSelection(); if (!selection.isEmpty()) { viewer.editElement(selection.getFirstElement(), 0); } }
Source:
<code>public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); <START> final AwsCredentials awsCredential = <END> (AwsCredentials) AwsCredentials.newBuilder(AWS_CREDENTIAL) .setTokenUrl(transportFactory.transport.getStsUrl()) .setHttpTransportFactory(transportFactory) .setCredentialSource(buildAwsCredentialSource(transportFactory)) .build(); AccessToken accessToken = awsCredential.refreshAccessToken(); assertThat(accessToken.getTokenValue()).isEqualTo(transportFactory.transport.getAccessToken()); }</code><technical_language>final local variables required, Google style</technical_language>

Target:
public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException { MockExternalAccountCredentialsTransportFactory transportFactory = new MockExternalAccountCredentialsTransportFactory(); AwsCredentials awsCredential = (AwsCredentials) AwsCredentials.newBuilder(AWS_CREDENTIAL) .setTokenUrl(transportFactory.transport.getStsUrl()) .setHttpTransportFactory(transportFactory) .setCredentialSource(buildAwsCredentialSource(transportFactory)) .build(); AccessToken accessToken = awsCredential.refreshAccessToken(); assertEquals(transportFactory.transport.getAccessToken(), accessToken.getTokenValue()); }
Source:
<code>public void saveShowInMruPartIdsList() { if (!mruPartIds.isEmpty()) { StringBuilder mruList = new StringBuilder(); for (Iterator<String> it = mruPartIds.iterator(); it.hasNext();) { mruList.append(it.next()); if (it.hasNext()) <START> mruList.append(MRU_LIST_SEPARATOR); <END> } getWindowModel().getPersistedState().put(IWorkbenchConstants.TAG_MRU_LIST, mruList.toString()); } }</code><technical_language>Slightly more flexible is move this statement line 2799 condition mruList.length() != 0. This change allow of enhanced 'for' loop</technical_language>

Target:
public void saveShowInMruPartIdsList() { if (!mruPartIds.isEmpty()) { StringBuilder mruList = new StringBuilder(); for (String partId : mruPartIds) { if (mruList.length() != 0) mruList.append(MRU_LIST_SEPARATOR); mruList.append(partId); } getWindowModel().getPersistedState().put(IWorkbenchConstants.TAG_MRU_LIST, mruList.toString()); } }
Source:
<code><START> private Pair<ByteBuffer, BlobProperties> getPutMessage(StoreKey id, short accountId, short containerId) <END> throws MessageFormatException, IOException { int blobSize = TestUtils.RANDOM.nextInt(500) + 501; int userMetadataSize = TestUtils.RANDOM.nextInt(blobSize / 2); byte[] blob = new byte[blobSize]; byte[] usermetadata = new byte[userMetadataSize]; TestUtils.RANDOM.nextBytes(blob); TestUtils.RANDOM.nextBytes(usermetadata); BlobProperties blobProperties = new BlobProperties(blobSize, "test", accountId, containerId); MessageFormatInputStream stream = new PutMessageFormatInputStream(id, blobProperties, ByteBuffer.wrap(usermetadata), new ByteBufferInputStream(ByteBuffer.wrap(blob)), blobSize); byte[] message = Utils.readBytesFromStream(stream, (int) stream.getSize()); return new Pair(ByteBuffer.wrap(message), blobProperties); }</code><technical_language>right do is return ByteBuffer MessageInfo</technical_language>

Target:
private Pair<ByteBuffer, MessageInfo> getPutMessage(StoreKey id, short accountId, short containerId) throws MessageFormatException, IOException { int blobSize = TestUtils.RANDOM.nextInt(500) + 501; int userMetadataSize = TestUtils.RANDOM.nextInt(blobSize / 2); byte[] blob = new byte[blobSize]; byte[] usermetadata = new byte[userMetadataSize]; TestUtils.RANDOM.nextBytes(blob); TestUtils.RANDOM.nextBytes(usermetadata); BlobProperties blobProperties = new BlobProperties(blobSize, "test", accountId, containerId); MessageFormatInputStream stream = new PutMessageFormatInputStream(id, blobProperties, ByteBuffer.wrap(usermetadata), new ByteBufferInputStream(ByteBuffer.wrap(blob)), blobSize); byte[] message = Utils.readBytesFromStream(stream, (int) stream.getSize()); return new Pair(ByteBuffer.wrap(message), new MessageInfo(id, message.length, Utils.Infinite_Time, accountId, containerId, blobProperties.getCreationTimeInMs())); }
Source:
<code>public List<IBaseEventInfo> getKernelProvider(IProgressMonitor monitor) throws ExecutionException { List<String> command = createCommand(LTTngControlServiceConstants.COMMAND_LIST, LTTngControlServiceConstants.OPTION_KERNEL); ICommandResult result = executeCommand(command, monitor, false); List<IBaseEventInfo> events = new ArrayList<>(); <START> if (result.getErrorOutput().size() > 0) { <END> if (ignoredPattern(result.getErrorOutput(), LTTngControlServiceConstants.LIST_KERNEL_NO_KERNEL_PROVIDER_PATTERN)) { return events; } } if (isError(result)) { throw new ExecutionException(Messages.TraceControl_CommandError + " " + toCommandString(command) + "\n" + result.toString()); } getProviderEventInfo(result.getOutput(), 0, events); return events; }</code><technical_language>!isEmpty</technical_language>

Target:
public List<IBaseEventInfo> getKernelProvider(IProgressMonitor monitor) throws ExecutionException { List<String> command = createCommand(LTTngControlServiceConstants.COMMAND_LIST, LTTngControlServiceConstants.OPTION_KERNEL); ICommandResult result = executeCommand(command, monitor, false); List<IBaseEventInfo> events = new ArrayList<>(); if (ignoredPattern(result.getErrorOutput(), LTTngControlServiceConstants.LIST_KERNEL_NO_KERNEL_PROVIDER_PATTERN)) { return events; } if (isError(result)) { throw new ExecutionException(Messages.TraceControl_CommandError + " " + toCommandString(command) + "\n" + result.toString()); } getProviderEventInfo(result.getOutput(), 0, events); return events; }
Source:
<code>public TupleDomainFilter toCoercingFilter(TupleDomainFilter filter, Subfield subfield) { if (filter == IS_NULL || filter == IS_NOT_NULL) { return filter; } if (subfield.getPath().size() > 0) { String fieldName = ((Subfield.NestedField) subfield.getPath().get(0)).getName(); for (int i = 0; i < toFieldNames.size(); i++) { if (fieldName.equals(toFieldNames.get(i))) { return coercers[i].toCoercingFilter(filter, subfield.tail(fieldName)); } } <START> verify(false, "Unexpected struct field: " + fieldName); <END> } throw new UnsupportedOperationException("Range filers on struct types are not supported"); }</code><technical_language>throw exception instead</technical_language>

Target:
public TupleDomainFilter toCoercingFilter(TupleDomainFilter filter, Subfield subfield) { if (filter == IS_NULL || filter == IS_NOT_NULL) { return filter; } if (subfield.getPath().size() > 0) { String fieldName = ((Subfield.NestedField) subfield.getPath().get(0)).getName(); for (int i = 0; i < toFieldNames.size(); i++) { if (fieldName.equals(toFieldNames.get(i))) { HiveCoercer coercer = coercers[i]; if (coercer == null) { return filter; } return coercer.toCoercingFilter(filter, subfield.tail(fieldName)); } } throw new IllegalArgumentException("Struct field not found: " + fieldName); } throw new UnsupportedOperationException("Range filers on struct types are not supported"); }
Source:
<code>protected void put(final String key, final Object value, final T element) { Map<Object, Set<T>> keyMap = this.index.get(key); if (null == keyMap) { <START> Map<Object, Set<T>> tmpMap = new ConcurrentHashMap<>(); <END> this.index.putIfAbsent(key, tmpMap); keyMap = this.index.get(key); } Set<T> objects = keyMap.get(value); if (null == objects) { Set<T> tmpObjects = ConcurrentHashMap.newKeySet(); keyMap.putIfAbsent(value, tmpObjects); objects = keyMap.get(value); } objects.add(element); }</code><technical_language>add a final please</technical_language>

Target:
protected void put(final String key, final Object value, final T element) { Map<Object, Set<T>> keyMap = this.index.get(key); if (null == keyMap) { this.index.putIfAbsent(key, new ConcurrentHashMap<Object, Set<T>>()); keyMap = this.index.get(key); } Set<T> objects = keyMap.get(value); if (null == objects) { keyMap.putIfAbsent(value, ConcurrentHashMap.newKeySet()); objects = keyMap.get(value); } objects.add(element); }
Source:
<code>private String uriWithoutExtension(String requestUri) { int suffixStart = requestUri.lastIndexOf("."); if (suffixStart >= 0) { return requestUri.substring(0, suffixStart); } <START> return null; <END> }</code><technical_language>If find extension, return requestUri</technical_language>

Target:
private String uriWithoutExtension(String requestUri) { int suffixStart = requestUri.lastIndexOf("."); if (suffixStart >= 0) { return requestUri.substring(0, suffixStart); } return requestUri; }