auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void validatePartitionAssignmentSupported(Datastream datastream) throws DatastreamValidationException { try { String connectorName = datastream.getConnectorName(); ConnectorInfo connectorInfo = _connectors.get(connectorName); if (connectorInfo == null) { throw new DatastreamValidationException("Invalid connector: " + connectorName); } <START> if (!(connectorInfo.getAssignmentStrategy() instanceof StickyPartitionAssignmentStrategy)) { <END> throw new DatastreamValidationException("Invalid Partition assignment strategy " + connectorName); } } catch (Exception e) { _dynamicMetricsManager.createOrUpdateMeter(MODULE, "isPartitionAssignmentSupported", NUM_ERRORS, 1); throw e; } }</code><technical_language>This leaking type of Assignmentstrategies coordinator. Coordinator agnostic type of AssignmentStrategies, I need a figure out Strategy supports partitionMovement</technical_language>

Target:
public void validatePartitionAssignmentSupported(Datastream datastream) throws DatastreamValidationException { try { String connectorName = datastream.getConnectorName(); ConnectorInfo connectorInfo = _connectors.get(connectorName); if (connectorInfo == null) { throw new DatastreamValidationException("Invalid connector: " + connectorName); } Connector connectorInstance = connectorInfo.getConnector().getConnectorInstance(); if (!(connectorInstance.getDatastreamPartitions().containsKey(DatastreamUtils.getGroupName(datastream)))) { String msg = String.format("Partition assignment is not managed by connector, datastream %s", datastream.getName()); _log.error(msg); throw new DatastreamValidationException(msg); } } catch (Exception e) { _dynamicMetricsManager.createOrUpdateMeter(MODULE, "isPartitionAssignmentSupported", NUM_ERRORS, 1); throw e; } }
Source:
<code>protected void handleMessage(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessage responseMessage, final OsgpException osgpException) throws FunctionalException { <START> if (responseMessage.getDataObject() instanceof ArrayList) { <END> @SuppressWarnings("unchecked") final List<FirmwareVersionDto> firmwareVersionList = (List<FirmwareVersionDto>) responseMessage .getDataObject(); this.configurationService.handleUpdateFirmwareResponse(deviceMessageMetadata, responseMessage.getResult(), osgpException, firmwareVersionList); } else { throw new FunctionalException(FunctionalExceptionType.VALIDATION_ERROR, ComponentType.DOMAIN_SMART_METERING, new OsgpException(ComponentType.DOMAIN_SMART_METERING, "DataObject for response message should be of type ArrayList")); } }</code><technical_language>a problem, is reason type check is done ArrayList instead of List interface, data is cast</technical_language>

Target:
protected void handleMessage(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessage responseMessage, final OsgpException osgpException) throws FunctionalException { if (responseMessage.getDataObject() instanceof List) { @SuppressWarnings("unchecked") final List<FirmwareVersionDto> firmwareVersionList = (List<FirmwareVersionDto>) responseMessage .getDataObject(); this.configurationService.handleUpdateFirmwareResponse(deviceMessageMetadata, responseMessage.getResult(), osgpException, firmwareVersionList); } else { throw new FunctionalException(FunctionalExceptionType.VALIDATION_ERROR, ComponentType.DOMAIN_SMART_METERING, new OsgpException(ComponentType.DOMAIN_SMART_METERING, "DataObject for response message should be of type ArrayList")); } }
Source:
<code>private Message getOldUOMAnnouncement() { boolean mainJarAvailable = transitionMainJarFetcher == null ? false : transitionMainJarFetcher.fetched(); <START> return DMT.createUOMAnnouncement(updateURI.toString(), revocationURI <END> .toString(), revocationChecker.hasBlown(), mainJarAvailable ? TRANSITION_VERSION : -1, revocationChecker.lastSucceededDelta(), revocationChecker .getRevocationDNFCounter(), revocationChecker .getBlobSize(), mainJarAvailable ? transitionMainJarFetcher.getBlobSize() : -1, (int) node.nodeStats.getNodeAveragePingTime(), (int) node.nodeStats.getBwlimitDelayTime()); }</code><technical_language>Oh. updateURI remain transitionMainJarURIAsUSK. fix</technical_language>

Target:
private Message getOldUOMAnnouncement() { boolean mainJarAvailable = transitionMainJarFetcher == null ? false : transitionMainJarFetcher.fetched(); return DMT.createUOMAnnouncement(transitionMainJarURIAsUSK.toString(), revocationURI .toString(), revocationChecker.hasBlown(), mainJarAvailable ? TRANSITION_VERSION : -1, revocationChecker.lastSucceededDelta(), revocationChecker .getRevocationDNFCounter(), revocationChecker .getBlobSize(), mainJarAvailable ? transitionMainJarFetcher.getBlobSize() : -1, (int) node.nodeStats.getNodeAveragePingTime(), (int) node.nodeStats.getBwlimitDelayTime()); }
Source:
<code>public ZooKeeperInstance(UUID instanceId, String zooKeepers) { <START> this(null, instanceId.toString(), zooKeepers, -1, new ZooCacheFactory()); <END> }</code><technical_language>Some of methods deprecated. If point of altering implementation, remove them, maintain them. In 2.0, drop deprecated in 1.9.0 previous</technical_language>

Target:
public ZooKeeperInstance(UUID instanceId, String zooKeepers) { this(ClientConfiguration.loadDefault().withInstance(instanceId).withZkHosts(zooKeepers)); }
Source:
<code>void verifyTimeDurationComputationWithSecondsRemaining() { final Instant banExpiry = CURRENT_TIME.plus(20, ChronoUnit.SECONDS); final String result = PlayerIsMutedMessage.muteDurationRemainingToString.apply( <START> Clock.fixed(CURRENT_TIME, ZoneOffset.UTC), banExpiry); <END> assertThat(result, is("20 seconds")); }</code><technical_language>1 is a tight time window. hope run issues that</technical_language>

Target:
void verifyTimeDurationComputationWithSecondsRemaining() { final Instant banExpiry = CURRENT_TIME.plus(20, ChronoUnit.SECONDS); final String result = formattingFunction.apply(banExpiry); assertThat(result, is("20 seconds")); }
Source:
<code>protected void initInternal() throws LifecycleException { super.initInternal(); if (traceDelay == 0) { throw new LifecycleException("The delay for trace must be greater than 0"); } if (projectId.isEmpty()) { throw new LifecycleException("You must specify a project to store the traces"); } try { traceService = TraceGrpcApiService.builder() .setScheduledDelay(traceDelay) .setProjectId(projectId) .build(); Trace.init(traceService); <START> log.trace("Trace service initialized for project: " + projectId); <END> } catch (IOException e) { log.error("An error occurred during the initialization of the Trace valve", e); throw new LifecycleException(e); } }</code><technical_language>info log level more imo</technical_language>

Target:
protected void initInternal() throws LifecycleException { super.initInternal(); initTraceService(); }
Source:
<code>public void cssChrome_004_verifyEditSummaryAppearsAndWorks() { WikiBasePageObject wiki = new WikiBasePageObject(driver); wiki.openWikiPage(); CommonFunctions.logInCookie(Properties.userNameStaff, Properties.passwordStaff); SpecialCssPageObject specialCss = wiki.openSpecialCss(); String randomText = specialCss.generateRandomString(); specialCss.sendEditSummaryText(randomText); specialCss.saveCssContent(randomText, wiki); wiki.openArticle(URLsContent.buildUrl(URLsContent.mediaWikiCss, URLsContent.historyAction)); String editSummary = wiki.getFirstCssRevision(); <START> randomText = "(" + randomText + ")"; <END> Assertion.assertEquals(randomText, editSummary); }</code><technical_language>do a quick regex check instead of concatenating brackets random text. if change of presenting summary text</technical_language>

Target:
public void cssChrome_004_verifyEditSummaryAppearsAndWorks() { WikiBasePageObject wiki = new WikiBasePageObject(driver); wiki.openWikiPage(); CommonFunctions.logInCookie(Properties.userNameStaff, Properties.passwordStaff); SpecialCssPageObject specialCss = wiki.openSpecialCss(); String currentTimestamp = specialCss.getTimeStamp(); specialCss.sendEditSummaryText(currentTimestamp); specialCss.saveCssContent(currentTimestamp, wiki); wiki.openArticle(URLsContent.buildUrl(URLsContent.mediaWikiCss, URLsContent.historyAction)); String editSummary = wiki.getFirstCssRevision(); Assertion.assertStringContains(editSummary, currentTimestamp); }
Source:
<code>public boolean isHealthy() { <START> Set<State> unhealthyStates = ImmutableSet.of( <END> UNHEALTHY_SUPERVISOR, UNHEALTHY_TASKS, UNABLE_TO_CONNECT_TO_STREAM, LOST_CONTACT_WITH_STREAM ); return !unhealthyStates.contains(this); }</code><technical_language>This list is created time check is done; suggestion making a static. Alternatively, error prone encode this information constructor (so add a future state, miss adding this list)</technical_language>

Target:
public boolean isHealthy() { return healthy; }
Source:
<code>public void checkSourceVideoContent(String desiredContent) { <START> Assertion.assertEquals(getSourceContent().substring(1, 38) + getSourceContent().substring(48), <END> desiredContent.substring(1, 38) + desiredContent.substring(48) ); }</code><technical_language>Well, necessarily own, if understand this works does, means this part of code needs fixing git blame is friend quest reach author :D</technical_language>

Target:
public void checkSourceVideoContent(String desiredContent) { int fileNameLength = 38; int fileParametersBeginIndex = 48; Assertion.assertEquals(getSourceContent().substring(1, fileNameLength) + getSourceContent().substring(fileParametersBeginIndex), desiredContent.substring(1, fileNameLength) + desiredContent.substring(fileParametersBeginIndex) ); }
Source:
<code>StreamProcessor(String sdkKey, LDConfig config, FeatureRequestor requestor) { this.store = config.featureStore; this.config = config; this.sdkKey = sdkKey; this.requestor = requestor; <START> this.heartbeatDetectorService = Executors.newScheduledThreadPool(1); <END> heartbeatDetectorService.scheduleAtFixedRate(new HeartbeatDetector(), 1, 1, TimeUnit.MINUTES); }</code><technical_language>named threadpools this: ThreadFactory threadFactory = new ThreadFactoryBuilder() .setNameFormat("LaunchDarkly-HeartbeatDetector-%d") .build(); this. heartbeatDetectorService = Executors.newSingleThreadScheduledExecutor(threadFactory); This for easier debugging reading of log statements. Also, I want this a single threaded executor, practically matter much</technical_language>

Target:
StreamProcessor(String sdkKey, LDConfig config, FeatureRequestor requestor) { this.store = config.featureStore; this.config = config; this.sdkKey = sdkKey; this.requestor = requestor; ThreadFactory threadFactory = new ThreadFactoryBuilder() .setNameFormat("LaunchDarkly-HeartbeatDetector-%d") .build(); this.heartbeatDetectorService = Executors.newSingleThreadScheduledExecutor(threadFactory); heartbeatDetectorService.scheduleAtFixedRate(new HeartbeatDetector(), 1, 1, TimeUnit.MINUTES); }
Source:
<code>public Map<String, Optional<GameProfile>> lookupByNames(Iterable<String> names) { checkNotNull(names, "names"); Map<String, Optional<GameProfile>> result = Maps.newHashMap(); this.getServer().getGameProfileRepository().findProfilesByNames(Iterables.toArray(names, String.class), Agent.MINECRAFT, new MapProfileLookupCallback(result)); if (!result.isEmpty()) { <START> for (Map.Entry<String, Optional<GameProfile>> entry : result.entrySet()) { <END> if (entry.getValue().isPresent()) { this.addEntry((com.mojang.authlib.GameProfile) entry.getValue().get(), null); } } return ImmutableMap.copyOf(result); } else { return ImmutableMap.of(); } }</code><technical_language>iterate values here</technical_language>

Target:
public Map<String, Optional<GameProfile>> lookupByNames(Iterable<String> names) { checkNotNull(names, "names"); Map<String, Optional<GameProfile>> result = Maps.newHashMap(); this.getServer().getGameProfileRepository().findProfilesByNames(Iterables.toArray(names, String.class), Agent.MINECRAFT, new MapProfileLookupCallback(result)); if (!result.isEmpty()) { for (Optional<GameProfile> entry : result.values()) { if (entry.isPresent()) { this.addEntry((com.mojang.authlib.GameProfile) entry.get(), null); } } return ImmutableMap.copyOf(result); } else { return ImmutableMap.of(); } }
Source:
<code>public void testFetchWithBlobLimitFilter() throws Exception { InMemoryRepository server2 = newRepo("server2"); try (TestRepository<InMemoryRepository> remote2 = new TestRepository<>( server2)) { RevBlob longBlob = remote2.blob("foobar"); RevBlob shortBlob = remote2.blob("fooba"); RevTree tree = remote2.tree(remote2.file("1", longBlob), remote2.file("2", shortBlob)); RevCommit commit = remote2.commit(tree); remote2.update("master", commit); server2.getConfig().setBoolean("uploadpack", null, "allowfilter", true); testProtocol = new TestProtocol<>(new UploadPackFactory<Object>() { @Override public UploadPack create(Object req, Repository db) throws ServiceNotEnabledException, ServiceNotAuthorizedException { UploadPack up = new UploadPack(db); return up; } }, null); uri = testProtocol.register(ctx, server2); try (Transport tn = testProtocol.open(uri, client, "server2")) { <START> tn.setFilterSpec(FilterSpec.withBlobLimit((5))); <END> tn.fetch(NullProgressMonitor.INSTANCE, Collections.singletonList(new RefSpec(commit.name()))); assertFalse( client.getObjectDatabase().has(longBlob.toObjectId())); assertTrue( client.getObjectDatabase().has(shortBlob.toObjectId())); } } }</code><technical_language>(and for rest)</technical_language>

Target:
public void testFetchWithBlobLimitFilter() throws Exception { InMemoryRepository server2 = newRepo("server2"); try (TestRepository<InMemoryRepository> remote2 = new TestRepository<>( server2)) { RevBlob longBlob = remote2.blob("foobar"); RevBlob shortBlob = remote2.blob("fooba"); RevTree tree = remote2.tree(remote2.file("1", longBlob), remote2.file("2", shortBlob)); RevCommit commit = remote2.commit(tree); remote2.update("master", commit); server2.getConfig().setBoolean("uploadpack", null, "allowfilter", true); testProtocol = new TestProtocol<>(new UploadPackFactory<Object>() { @Override public UploadPack create(Object req, Repository db) throws ServiceNotEnabledException, ServiceNotAuthorizedException { UploadPack up = new UploadPack(db); return up; } }, null); uri = testProtocol.register(ctx, server2); try (Transport tn = testProtocol.open(uri, client, "server2")) { tn.setFilterSpec(FilterSpec.withBlobLimit(5)); tn.fetch(NullProgressMonitor.INSTANCE, Collections.singletonList(new RefSpec(commit.name()))); assertFalse( client.getObjectDatabase().has(longBlob.toObjectId())); assertTrue( client.getObjectDatabase().has(shortBlob.toObjectId())); } } }
Source:
<code><START> Account(Short id, String name, AccountStatus status, Collection<Container> containers) { <END> this.id = id; this.name = name; this.status = status; checkRequiredFieldsForBuild(); if (containers != null) { for (Container container : containers) { updateContainerMap(container); } checkAccountIdInContainers(); checkDuplicateContainerNameOrId(containers); } }</code><technical_language>this private. I mean, move AccountBuilder this file this constructor private else construct Account instance builder</technical_language>

Target:
Account(Short id, String name, AccountStatus status, Collection<Container> containers) throws JSONException { this.id = id; this.name = name; this.status = status; checkRequiredFieldsForBuild(); if (containers != null) { for (Container container : containers) { checkParentAccountIdInContainers(container); checkDuplicateContainerNameOrId(container); updateContainerMap(container); } } }
Source:
<code>public Application edit(Application applicationForLeave, Person person, Optional<String> comment) { if (applicationForLeave.getStatus().compareTo(WAITING) != 0) { <START> throw new EditApplicationForLeaveNotAllowedException("Cannot edit application for leave " + <END> "with id " + applicationForLeave.getId() + " because the status is " + applicationForLeave.getStatus() + " and not waiting."); } applicationForLeave.setStatus(ApplicationStatus.WAITING); applicationForLeave.setEditedDate(LocalDate.now(clock)); final Application savedApplication = applicationService.save(applicationForLeave); commentService.create(savedApplication, ApplicationAction.EDITED, comment, person); applicationMailService.sendEditedApplicationNotification(savedApplication, person); return savedApplication; }</code><technical_language>String.format()</technical_language>

Target:
public Application edit(Application applicationForLeave, Person person, Optional<String> comment) { if (applicationForLeave.getStatus().compareTo(WAITING) != 0) { throw new EditApplicationForLeaveNotAllowedException(String.format("Cannot edit application for leave " + "with id %d because the status is %s and not waiting.", applicationForLeave.getId(), applicationForLeave.getStatus())); } applicationForLeave.setStatus(ApplicationStatus.WAITING); applicationForLeave.setEditedDate(LocalDate.now(clock)); final Application savedApplication = applicationService.save(applicationForLeave); commentService.create(savedApplication, ApplicationAction.EDITED, comment, person); applicationMailService.sendEditedApplicationNotification(savedApplication, person); return savedApplication; }
Source:
<code><START> public NormalizationBolt(String normalizationProcessorJson) { <END> this(Utils.getObjectFromJson(normalizationProcessorJson, NormalizationProcessor.class)); }</code><technical_language>Do need this constructor ? NormalizationBolt(NormalizationProcessor normalizationProcessor)</technical_language>

Target:
public NormalizationBolt(String normalizationProcessorJson) { this(Utils.createObjectFromJson(normalizationProcessorJson, NormalizationProcessor.class)); }
Source:
<code>public void start() { ClientConfig clientConfig = new ClientConfig(); <START> clientConfig.getGroupConfig().setName("dev").setPassword("dev-pass"); <END> clientConfig.getNetworkConfig().addAddress(servers.split(";")); hazelcastInstance = HazelcastClient.newHazelcastClient(clientConfig); MembershipListener listener = new MembershipListener() { @Override public void memberAdded(MembershipEvent membershipEvent) { updateMembers(membershipEvent.getMembers()); } @Override public void memberRemoved(MembershipEvent membershipEvent) { updateMembers(membershipEvent.getMembers()); } @Override public void memberAttributeChanged(MemberAttributeEvent memberAttributeEvent) { } }; synchronized (this) { addMembershipListener(listener); updateMembers(hazelcastInstance.getCluster().getMembers()); } }</code><technical_language>credentials configurable</technical_language>

Target:
public void start() { ClientConfig clientConfig = new ClientConfig(); clientConfig.getGroupConfig().setName(groupName).setPassword(groupPass); clientConfig.getNetworkConfig().addAddress(servers); hazelcastInstance = HazelcastClient.newHazelcastClient(clientConfig); }
Source:
<code>public File execute(SelenideElement proxy, WebElementSource linkWithHref, Object[] args) throws IOException { WebElement link = linkWithHref.findAndAssertElementIsVisible(); long timeout = getTimeout(args); if (Configuration.fileDownload == HTTPGET) { LOG.config("selenide.fileDownload = " + System.getProperty("selenide.fileDownload") + " download file via http get"); return downloadFileWithHttpRequest.download(link, timeout); } <START> else if (!Configuration.proxyEnabled) { <END> throw new IllegalStateException("Cannot download file: proxy server is not enabled. Setup Configuration.proxyEnabled"); } else if (webdriverContainer.getProxyServer() == null) { throw new IllegalStateException("Cannot download file: proxy server is not started"); } else { return downloadFileWithProxyServer.download(linkWithHref, link, webdriverContainer.getProxyServer(), timeout); } }</code><technical_language>else if is redundant in this place branch do a return throw</technical_language>

Target:
public File execute(SelenideElement proxy, WebElementSource linkWithHref, Object[] args) throws IOException { WebElement link = linkWithHref.findAndAssertElementIsVisible(); long timeout = getTimeout(args); if (Configuration.fileDownload == HTTPGET) { LOG.config("selenide.fileDownload = " + System.getProperty("selenide.fileDownload") + " download file via http get"); return downloadFileWithHttpRequest.download(link, timeout); } if (!Configuration.proxyEnabled) { throw new IllegalStateException("Cannot download file: proxy server is not enabled. Setup Configuration.proxyEnabled"); } if (webdriverContainer.getProxyServer() == null) { throw new IllegalStateException("Cannot download file: proxy server is not started"); } return downloadFileWithProxyServer.download(linkWithHref, link, webdriverContainer.getProxyServer(), timeout); }
Source:
<code>protected ToStringBuilder appendAttributes(ToStringBuilder tsb) { return super.appendAttributes(tsb) .append("operations", getOperations()) .append("size", getSize()) .append("url", getUrl()) .append("filename", getFilename()) <START> .append("sparse", isSparse()); <END> }</code><technical_language>add tansferId here</technical_language>

Target:
protected ToStringBuilder appendAttributes(ToStringBuilder tsb) { return super.appendAttributes(tsb) .append("operations", getOperations()) .append("size", getSize()) .append("url", getUrl()) .append("filename", getFilename()) .append("sparse", isSparse()) .append("transferId", getTransferId()); }
Source:
<code>private Iterable<Volume> collectVolumes(MachineType input) { ImmutableSet.Builder<Volume> volumes = ImmutableSet.builder(); for (MachineType.ScratchDisk disk : input.getScratchDisks()) { <START> volumes.add(new VolumeImpl(null, Volume.Type.LOCAL, new Integer(disk.getDiskGb()).floatValue(), null, true, <END> false)); } return volumes.build(); }</code><technical_language>new VolumeImpl? builder other factory for this</technical_language>

Target:
private Iterable<Volume> collectVolumes(MachineType input) { ImmutableSet.Builder<Volume> volumes = ImmutableSet.builder(); for (MachineType.ScratchDisk disk : input.getScratchDisks()) { volumes.add(new VolumeBuilder() .type(Volume.Type.LOCAL) .size(new Integer(disk.getDiskGb()).floatValue()) .bootDevice(true) .durable(false).build()); } return volumes.build(); }
Source:
<code>public void emailConsentAgreementDoesNotSuppressEmailNotification() { account.setConsentSignatureHistory(SUBPOP_GUID, ImmutableList.of(CONSENT_SIGNATURE)); consentService.resendConsentAgreement(study, SUBPOP_GUID, PARTICIPANT); <START> verify(sendMailService).sendEmail(emailCaptor.capture()); <END> Set<String> recipients = emailCaptor.getValue().getRecipientEmails(); assertEquals(1, recipients.size()); assertTrue(recipients.contains(PARTICIPANT.getEmail())); }</code><technical_language>This defeats purpose of test, is verify turning suppression flag suppress if user explicitly asks for consent email. merge emailConsentAgreementNoConsentAdministratorEmail() verify subpopulation.isAutoSendConsentSuppressed() is called</technical_language>

Target:
public void emailConsentAgreementDoesNotSuppressEmailNotification() { account.setConsentSignatureHistory(SUBPOP_GUID, ImmutableList.of(CONSENT_SIGNATURE)); consentService.resendConsentAgreement(study, SUBPOP_GUID, PARTICIPANT); verify(subpopulation, never()).isAutoSendConsentSuppressed(); verify(sendMailService).sendEmail(emailCaptor.capture()); Set<String> recipients = emailCaptor.getValue().getRecipientEmails(); assertEquals(1, recipients.size()); assertTrue(recipients.contains(PARTICIPANT.getEmail())); }
Source:
<code>private Promise<Channel> acquireUploadChannel() { Promise<Channel> channelReady = eventLoop.next().newPromise(); channelPool .acquire() .addListener( (Future<Channel> channelAcquired) -> { if (!channelAcquired.isSuccess()) { channelReady.setFailure(channelAcquired.cause()); return; } try { Channel ch = channelAcquired.getNow(); <START> ChannelPipeline p = ch.pipeline(); <END> if (!isChannelPipelineEmpty(p)) { channelReady.setFailure( new IllegalStateException("Channel pipeline is not empty.")); return; } p.addFirst( "timeout-handler", new IdleTimeoutHandler(timeoutSeconds, WriteTimeoutException.INSTANCE)); p.addLast(new HttpResponseDecoder()); p.addLast(new HttpObjectAggregator(10 * 1024)); p.addLast(new HttpRequestEncoder()); p.addLast(new ChunkedWriteHandler()); synchronized (credentialsLock) { p.addLast(new HttpUploadHandler(creds, extraHttpHeaders)); } if (!ch.eventLoop().inEventLoop()) { ch.eventLoop().execute(() -> channelReady.setSuccess(ch)); } else { channelReady.setSuccess(ch); } } catch (Throwable t) { channelReady.setFailure(t); } }); return channelReady; }</code><technical_language>nit: please change p pipeline (or similar)</technical_language>

Target:
private Promise<Channel> acquireUploadChannel() { Promise<Channel> channelReady = eventLoop.next().newPromise(); channelPool .acquire() .addListener( (Future<Channel> channelAcquired) -> { if (!channelAcquired.isSuccess()) { channelReady.setFailure(channelAcquired.cause()); return; } try { Channel channel = channelAcquired.getNow(); ChannelPipeline pipeline = channel.pipeline(); if (!isChannelPipelineEmpty(pipeline)) { channelReady.setFailure( new IllegalStateException("Channel pipeline is not empty.")); return; } pipeline.addFirst( "timeout-handler", new IdleTimeoutHandler(timeoutSeconds, WriteTimeoutException.INSTANCE)); pipeline.addLast(new HttpResponseDecoder()); pipeline.addLast(new HttpObjectAggregator(10 * 1024)); pipeline.addLast(new HttpRequestEncoder()); pipeline.addLast(new ChunkedWriteHandler()); synchronized (credentialsLock) { pipeline.addLast(new HttpUploadHandler(creds, extraHttpHeaders)); } if (!channel.eventLoop().inEventLoop()) { channel.eventLoop().execute(() -> channelReady.setSuccess(channel)); } else { channelReady.setSuccess(channel); } } catch (Throwable t) { channelReady.setFailure(t); } }); return channelReady; }
Source:
<code>private StorageLocation loadSegmentWithRetry(DataSegment segment, String storageDirStr) throws SegmentLoadingException { Iterator<StorageLocation> locations = strategy.getLocations(segment, storageDirStr); int numLocationsToTry = this.locations.size(); <START> while (locations.hasNext() && numLocationsToTry > 0) { <END> StorageLocation loc = locations.next(); numLocationsToTry--; File storageDir = loc.reserve(storageDirStr, segment); if (null != storageDir) { try { loadInLocationWithStartMarker(segment, storageDir); return loc; } catch (SegmentLoadingException e) { try { log.makeAlert( e, "Failed to load segment in current location %s, try next location if any", loc.getPath().getAbsolutePath() ).addData("location", loc.getPath().getAbsolutePath()).emit(); } finally { loc.removeSegmentDir(storageDir, segment); cleanupCacheFiles(loc.getPath(), storageDir); } } } } throw new SegmentLoadingException("Failed to load segment %s in all locations.", segment.getId()); }</code><technical_language>numLocationsToTry check moved RoundRobinStorageLocationSelectorStrategy</technical_language>

Target:
private StorageLocation loadSegmentWithRetry(DataSegment segment, String storageDirStr) throws SegmentLoadingException { Iterator<StorageLocation> locationsIterator = strategy.getLocations(); while (locationsIterator.hasNext()) { StorageLocation loc = locationsIterator.next(); File storageDir = loc.reserve(storageDirStr, segment); if (storageDir != null) { try { loadInLocationWithStartMarker(segment, storageDir); return loc; } catch (SegmentLoadingException e) { try { log.makeAlert( e, "Failed to load segment in current location [%s], try next location if any", loc.getPath().getAbsolutePath() ).addData("location", loc.getPath().getAbsolutePath()).emit(); } finally { loc.removeSegmentDir(storageDir, segment); cleanupCacheFiles(loc.getPath(), storageDir); } } } } throw new SegmentLoadingException("Failed to load segment %s in all locations.", segment.getId()); }
Source:
<code>protected LockProperties getLockingPropertiesSettings() { <START> return new LockProperties().setObtainLock(false); <END> }</code><technical_language>I expect this false default... return new LockProperties(); if want lock you: return new LockProperties.setObtainLock(true);</technical_language>

Target:
protected LockProperties getLockingPropertiesSettings() { return new LockProperties(); }
Source:
<code>public void onCreateButtonClicked() { Set<String> mods = modManagerController.apply().stream() .map(ModVersion::getUid) .collect(Collectors.toSet()); <START> int minRating = 0; <END> int maxRating = 3000; boolean enforceRating = false; if (!minRankingTextField.getText().isEmpty()) { minRating = Integer.parseInt(minRankingTextField.getText()); } if(!maxRankingTextField.getText().isEmpty()) { maxRating = Integer.parseInt(maxRankingTextField.getText()); } enforceRating = enforceRankingCheckBox.isSelected(); NewGameInfo newGameInfo = new NewGameInfo( titleTextField.getText(), Strings.emptyToNull(passwordTextField.getText()), featuredModListView.getSelectionModel().getSelectedItem(), mapListView.getSelectionModel().getSelectedItem().getFolderName(), mods, onlyForFriendsCheckBox.isSelected() ? GameVisibility.PRIVATE : GameVisibility.PUBLIC, minRating, maxRating, enforceRating); gameService.hostGame(newGameInfo).exceptionally(throwable -> { log.warn("Game could not be hosted", throwable); notificationService.addNotification( new ImmediateErrorNotification( i18n.get("errorTitle"), i18n.get("game.create.failed"), throwable, i18n, reportingService )); return null; }); onCloseButtonClicked(); }</code><technical_language>negative Ratings</technical_language>

Target:
public void onCreateButtonClicked() { Set<String> mods = modManagerController.apply().stream() .map(ModVersion::getUid) .collect(Collectors.toSet()); Integer minRating = null; Integer maxRating = null; boolean enforceRating; if (!minRankingTextField.getText().isEmpty()) { minRating = Integer.parseInt(minRankingTextField.getText()); } if(!maxRankingTextField.getText().isEmpty()) { maxRating = Integer.parseInt(maxRankingTextField.getText()); } enforceRating = enforceRankingCheckBox.isSelected(); NewGameInfo newGameInfo = new NewGameInfo( titleTextField.getText(), Strings.emptyToNull(passwordTextField.getText()), featuredModListView.getSelectionModel().getSelectedItem(), mapListView.getSelectionModel().getSelectedItem().getFolderName(), mods, onlyForFriendsCheckBox.isSelected() ? GameVisibility.PRIVATE : GameVisibility.PUBLIC, minRating, maxRating, enforceRating); gameService.hostGame(newGameInfo).exceptionally(throwable -> { log.warn("Game could not be hosted", throwable); notificationService.addImmediateErrorNotification(throwable, "game.create.failed"); return null; }); onCloseButtonClicked(); }
Source:
<code>private Map<String, String> getActivatedParcels(Stack stack) { <START> if (stack.isDatalake()) { <END> Set<ClusterComponent> components = clusterComponentConfigProvider.getComponentsByClusterId(stack.getCluster().getId()); ClusterComponent stackComponent = components.stream() .filter(clusterComponent -> clusterComponent.getName().equals(StackType.CDH.name())) .findFirst().orElse(null); if (Objects.isNull(stackComponent)) { throw new NotFoundException("Runtime component not found!"); } ClouderaManagerProduct stackProduct = stackComponent.getAttributes().getSilent(ClouderaManagerProduct.class); return Map.of(stackProduct.getName(), stackProduct.getVersion()); } else { ClusterApi connector = clusterApiConnectors.getConnector(stack); return connector.gatherInstalledParcels(stack.getName()); } }</code><technical_language>Add logs</technical_language>

Target:
private Map<String, String> getActivatedParcels(Stack stack) { if (stack.isDatalake()) { Set<ClusterComponent> components = clusterComponentConfigProvider.getComponentsByClusterId(stack.getCluster().getId()); ClusterComponent stackComponent = components.stream() .filter(clusterComponent -> clusterComponent.getName().equals(StackType.CDH.name())) .findFirst().orElseThrow(() -> new NotFoundException("Runtime component not found!")); ClouderaManagerProduct stackProduct = stackComponent.getAttributes().getSilent(ClouderaManagerProduct.class); LOGGER.debug("For datalake clusters only the CDH parcel is activated in CM: {}", stackProduct); return Map.of(stackProduct.getName(), stackProduct.getVersion()); } else { ClusterApi connector = clusterApiConnectors.getConnector(stack); Map<String, String> installedParcels = connector.gatherInstalledParcels(stack.getName()); LOGGER.debug("The activated parcels for the datahub cluster: {}", installedParcels); return installedParcels; } }
Source:
<code>public void waitSafely(Runnable o) { try { o.run(); <START> } catch (TimeoutException e) { <END> PageObjectLogging.log("Timed out waiting", e.getMessage(), true); } }</code><technical_language>Create a ticket improve Sonar rules</technical_language>

Target:
public void waitSafely(Runnable o) { try { o.run(); } catch (TimeoutException e) { PageObjectLogging.log("Timed out waiting", e, true); } }
Source:
<code>public Properties getDataNucleusPropertiesForInternalInfrastructure() { Properties properties = new Properties(); properties.putAll(coreConfigurationService.loadDatanucleusConfig()); properties.remove("javax.jdo.option.Optimistic"); properties.remove("datanucleus.flush.mode"); addBeanValidationFactoryProperty(properties); <START> properties.put("javax.jdo.option.ConnectionURL", getSchemaConnectionURL(properties)); <END> return properties; }</code><technical_language>constant defined earlier (moreover, jdo connection options some sort of options class)</technical_language>

Target:
public Properties getDataNucleusPropertiesForInternalInfrastructure() { Properties properties = new Properties(); properties.putAll(coreConfigurationService.loadDatanucleusSchemaConfig()); addBeanValidationFactoryProperty(properties); return properties; }
Source:
<code>public RegionLocations locateMeta(byte[] row, RegionLocateType locateType) throws IOException { if (locateType == RegionLocateType.AFTER) { row = Arrays.copyOf(row, row.length + 1); locateType = RegionLocateType.CURRENT; } Scan scan = MetaTableAccessor.createLocateRegionScan(TableName.META_TABLE_NAME, row, locateType, 1); try (RegionScanner scanner = masterRegion.getScanner(scan)) { boolean moreRows; List<Cell> cells = new ArrayList<>(); do { moreRows = scanner.next(cells); if (cells.isEmpty()) { continue; } Result result = Result.create(cells); cells.clear(); RegionLocations locs = MetaTableAccessor.getRegionLocations(result); if (locs == null || locs.getDefaultRegionLocation() == null) { LOG.warn("No location found when locating meta region with row='{}', locateType={}", Bytes.toStringBinary(row), locateType); return null; } HRegionLocation loc = locs.getDefaultRegionLocation(); RegionInfo info = loc.getRegion(); <START> if (info == null) { <END> LOG.warn("HRegionInfo is null when locating meta region with row='{}', locateType={}", Bytes.toStringBinary(row), locateType); return null; } if (info.isSplitParent()) { continue; } return locs; } while (moreRows); LOG.warn("No location available when locating meta region with row='{}', locateType={}", Bytes.toStringBinary(row), locateType); return null; } }</code><technical_language>understand</technical_language>

Target:
public RegionLocations locateMeta(byte[] row, RegionLocateType locateType) throws IOException { if (locateType == RegionLocateType.AFTER) { row = Arrays.copyOf(row, row.length + 1); locateType = RegionLocateType.CURRENT; } Scan scan = CatalogFamilyFormat.createRegionLocateScan(TableName.META_TABLE_NAME, row, locateType, 1); try (RegionScanner scanner = masterRegion.getScanner(scan)) { boolean moreRows; List<Cell> cells = new ArrayList<>(); do { moreRows = scanner.next(cells); if (cells.isEmpty()) { continue; } Result result = Result.create(cells); cells.clear(); RegionLocations locs = CatalogFamilyFormat.getRegionLocations(result); if (locs == null || locs.getDefaultRegionLocation() == null) { LOG.warn("No location found when locating meta region with row='{}', locateType={}", Bytes.toStringBinary(row), locateType); return null; } HRegionLocation loc = locs.getDefaultRegionLocation(); RegionInfo info = loc.getRegion(); if (info == null) { LOG.warn("HRegionInfo is null when locating meta region with row='{}', locateType={}", Bytes.toStringBinary(row), locateType); return null; } if (info.isSplitParent()) { continue; } return locs; } while (moreRows); LOG.warn("No location available when locating meta region with row='{}', locateType={}", Bytes.toStringBinary(row), locateType); return null; } }
Source:
<code>public void test_create_tag() throws Exception { w.init(); String gitDir = w.repoPath() + File.separator + ".git"; w.commitEmpty("init"); ObjectId init = w.git.revParse("HEAD"); w.git.tag("test", "this is a tag"); ObjectId testTag = w.git.getHeadRev(gitDir, "test"); if (w.git instanceof JGitAPIImpl) { assertEquals("Annotated tag does not match SHA1", init, testTag); } else { <START> assertNull("Annotated tag unexpectedly not null", testTag); <END> } ObjectId testTagCommit = w.git.getHeadRev(gitDir, "refs/tags/test"); assertEquals("Annotated tag doesn't match queried commit SHA1", init, testTagCommit); assertEquals(init, w.git.revParse("test")); assertEquals(init, w.git.revParse("refs/tags/test")); assertTrue("test tag not created", w.cmd("git tag").contains("test")); String message = w.cmd("git tag -l -n1"); assertTrue("unexpected test tag message : " + message, message.contains("this is a tag")); assertNull(w.git.getHeadRev(gitDir, "not-a-valid-tag")); }</code><technical_language>Is current cli git behaviour intended? is due -h option provided git ls-remote in CliGitAPIImpl [line 2851](<LINK_0> option -t (for tags) added. ^{} appended (to unpeel tag) is clear if refspec provided is a tag not. implement returning commit shas for types of tags some more logic required. big question is: method getHeadRev() about? is branches longer. extractBranchNameFromBranchSpec() more complicated</technical_language>

Target:
public void test_create_tag() throws Exception { w.init(); String gitDir = w.repoPath() + File.separator + ".git"; w.commitEmpty("init"); ObjectId commitId = w.git.revParse("HEAD"); w.git.tag("test", "this is an annotated tag"); String shortTagRef = "test"; ObjectId tagHeadIdByShortRef = w.git.getHeadRev(gitDir, shortTagRef); if (w.git instanceof JGitAPIImpl) { assertEquals("annotated tag does not match commit SHA1", commitId, tagHeadIdByShortRef); } else { assertNull("annotated tag unexpectedly not null", tagHeadIdByShortRef); } assertEquals("annotated tag does not match commit SHA1", commitId, w.git.revParse(shortTagRef)); String longTagRef = "refs/tags/test"; assertEquals("annotated tag does not match commit SHA1", commitId, w.git.getHeadRev(gitDir, longTagRef)); assertEquals("annotated tag does not match commit SHA1", commitId, w.git.revParse(longTagRef)); String tagNames = w.cmd("git tag -l").trim(); assertEquals("tag not created", "test", tagNames); String tagNamesWithMessages = w.cmd("git tag -l -n1"); assertTrue("unexpected tag message : " + tagNamesWithMessages, tagNamesWithMessages.contains("this is an annotated tag")); ObjectId invalidTagId = w.git.getHeadRev(gitDir, "not-a-valid-tag"); assertNull("did not expect reference for invalid tag but got : " + invalidTagId, invalidTagId); }
Source:
<code>public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable { ComposedCompletionStage<Void> composedCompletionStage = null; if (cacheNotifier.hasListener(CacheEntryRemoved.class)) { composedCompletionStage = CompletionStages.composedCompletionStage(); for (InternalCacheEntry e : dataContainer) { composedCompletionStage.dependsOn(cacheNotifier.notifyCacheEntryRemoved(e.getKey(), e.getValue(), e.getMetadata(), true, ctx, command)); } <START> composedCompletionStage.freeze(); <END> } return stageOrNullSyncValue(composedCompletionStage); }</code><technical_language>This work... I suggest keeping sync in phase adding batching later</technical_language>

Target:
public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable { AggregateCompletionStage<Void> aggregateCompletionStage = null; if (cacheNotifier.hasListener(CacheEntryRemoved.class)) { aggregateCompletionStage = CompletionStages.aggregateCompletionStage(); for (InternalCacheEntry e : dataContainer) { aggregateCompletionStage.dependsOn(cacheNotifier.notifyCacheEntryRemoved(e.getKey(), e.getValue(), e.getMetadata(), true, ctx, command)); } } return delayedNull(aggregateCompletionStage != null ? aggregateCompletionStage.freeze() : null); }
Source:
<code>public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.isEmpty()) { <START> throw new IllegalArgumentException("function 'timestampFromEpoch' needs at least 1 argument"); <END> } ExprEval value = args.get(0).eval(bindings); if (value.type() != ExprType.STRING) { throw new IllegalArgumentException("first argument should be string type but got " + value.type() + " type"); } DateFormat formatter = ISO8601; if (args.size() > 1) { ExprEval format = args.get(1).eval(bindings); if (format.type() != ExprType.STRING) { throw new IllegalArgumentException("first argument should be string type but got " + format.type() + " type"); } formatter = new SimpleDateFormat(format.stringValue()); } Date date; try { date = formatter.parse(value.stringValue()); } catch (ParseException e) { throw new IllegalArgumentException("invalid value " + value.stringValue()); } return toValue(date); }</code><technical_language>I this function 'timestamp', 'timestampFromEpoch'</technical_language>

Target:
public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() != 1 && args.size() != 2) { throw new IAE("function '%s' needs 1 or 2 arguments", name()); } ExprEval value = args.get(0).eval(bindings); if (value.type() != ExprType.STRING) { throw new IAE("first argument should be string type but got %s type", value.type()); } DateTimeFormatter formatter = ISODateTimeFormat.dateOptionalTimeParser(); if (args.size() > 1) { ExprEval format = args.get(1).eval(bindings); if (format.type() != ExprType.STRING) { throw new IAE("second argument should be string type but got %s type", format.type()); } formatter = DateTimeFormat.forPattern(format.asString()); } DateTime date; try { date = DateTime.parse(value.asString(), formatter); } catch (IllegalArgumentException e) { throw new IAE(e, "invalid value %s", value.asString()); } return toValue(date); }
Source:
<code>public void testNotEqualsSql() { final TestDao dao = getDao(); <START> Expression notEqualsExpression = RootTable.FIELD_TEST.not().eq("1"); <END> assertThat(notEqualsExpression.buildSql(dao).first, is("(NOT (root.test) == ?)")); }</code><technical_language>so, while this test is valid, this happen in normal usage. expression for is: FIELD_TEST.eq("1").not() FIELD_TEST.ne("1")</technical_language>

Target:
public void testNotEqualsSql() { final TestDao dao = getDao(); Expression notEqualsExpression = RootTable.FIELD_TEST.ne("1"); assertThat(notEqualsExpression.buildSql(dao).first, is("(root.test != ?)")); }
Source:
<code>public Image(Device device, ImageDataProvider imageDataProvider) { super(device); this.imageDataProvider = imageDataProvider; currentDeviceZoom = getDeviceZoom (); boolean[] found = new boolean[1]; ImageData data = DPIUtil.validateAndGetImageDataAtZoom(imageDataProvider, currentDeviceZoom, found); if (found[0]) { init(data); } else { float scaleFactor = currentDeviceZoom / 100; <START> ImageData resizedData = data.scaledTo((int)(data.width * scaleFactor), (int)(data.height * scaleFactor)); <END> init (resizedData); } init(); }</code><technical_language>refactor this a utility method places in Image class, for win & gtk? Idea is scaling code in place for easy modification & maintenance</technical_language>

Target:
public Image(Device device, ImageDataProvider imageDataProvider) { super(device); this.imageDataProvider = imageDataProvider; currentDeviceZoom = getDeviceZoom (); boolean[] found = new boolean[1]; ImageData data = DPIUtil.validateAndGetImageDataAtZoom(imageDataProvider, currentDeviceZoom, found); if (found[0]) { init(data); } else { ImageData resizedData = DPIUtil.autoScaleImageData(data, currentDeviceZoom); init (resizedData); } init(); }
Source:
<code>protected void newStreamOpenWaitForFeaturesSequence(String waitFor) throws InterruptedException, SmackException, XMPPException { prepareToWaitForFeaturesReceived(); StreamOpenFactory streamOpenFactory = activeTransport.getStreamOpenFactory(); <START> sendStreamOpen(streamOpenFactory.getStreamOpen()); <END> waitForFeaturesReceived(waitFor); }</code><technical_language>Please add a new line declaration of StreamOpen streamOpen =</technical_language>

Target:
protected void newStreamOpenWaitForFeaturesSequence(String waitFor) throws InterruptedException, SmackException, XMPPException { prepareToWaitForFeaturesReceived(); StreamOpenAndCloseFactory streamOpenAndCloseFactory = activeTransport.getStreamOpenAndCloseFactory(); CharSequence from = null; CharSequence localpart = connectionInternal.connection.getConfiguration().getUsername(); DomainBareJid xmppServiceDomain = getXMPPServiceDomain(); if (localpart != null) { from = XmppStringUtils.completeJidFrom(localpart, xmppServiceDomain); } StreamOpen streamOpen = streamOpenAndCloseFactory.createStreamOpen(xmppServiceDomain, from, getStreamId(), getConfiguration().getXmlLang()); sendStreamOpen(streamOpen); waitForFeaturesReceived(waitFor); }
Source:
<code>private static File createFileFromInputStream(InputStream inputStream, String encoding) { final File file; final File tempDir = FileHelper.getTempDir(); File fileCandidate = null; boolean usableName = false; int index = 0; while (!usableName) { index++; fileCandidate = new File(tempDir, "metamodel" + index + ".csv"); usableName = !fileCandidate.exists(); } file = fileCandidate; final BufferedWriter writer = FileHelper.getBufferedWriter(file, encoding); <START> final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(encoding))); <END> try { file.createNewFile(); file.deleteOnExit(); boolean firstLine = true; for (String line = reader.readLine(); line != null; line = reader.readLine()) { if (firstLine) { firstLine = false; } else { writer.write('\n'); } writer.write(line); } } catch (IOException e) { throw new IllegalStateException(e); } finally { FileHelper.safeClose(writer, reader); } return file; }</code><technical_language>For sake of consistency, nicer FileHelper.getBufferedReader(inputStream, encoding)</technical_language>

Target:
private static File createFileFromInputStream(InputStream inputStream, String encoding) { final File file; final File tempDir = FileHelper.getTempDir(); File fileCandidate = null; boolean usableName = false; int index = 0; while (!usableName) { index++; fileCandidate = new File(tempDir, "metamodel" + index + ".csv"); usableName = !fileCandidate.exists(); } file = fileCandidate; final BufferedWriter writer = FileHelper.getBufferedWriter(file, encoding); final BufferedReader reader = FileHelper.getBufferedReader(inputStream, encoding); try { file.createNewFile(); file.deleteOnExit(); boolean firstLine = true; for (String line = reader.readLine(); line != null; line = reader.readLine()) { if (firstLine) { firstLine = false; } else { writer.write('\n'); } writer.write(line); } } catch (IOException e) { throw new IllegalStateException(e); } finally { FileHelper.safeClose(writer, reader); } return file; }