auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testCheckContainerSizeValid() throws TException { TTransport transport; ThriftBinaryProtocol protocol; transport = getMockTransport(3); <START> replay(transport); <END> protocol = new ThriftBinaryProtocol(transport); protocol.readListBegin(); transport = getMockTransport(3); replay(transport); protocol = new ThriftBinaryProtocol(transport); protocol.readSetBegin(); transport = getMockMapTransport(3); replay(transport); protocol = new ThriftBinaryProtocol(transport); protocol.readMapBegin(); }</code><technical_language>done mock, call verify(mock)</technical_language>

Target:
public void testCheckContainerSizeValid() throws TException { TTransport transport; ThriftBinaryProtocol protocol; transport = getMockTransport(3); replay(transport); protocol = new ThriftBinaryProtocol(transport); protocol.readListBegin(); verify(transport); transport = getMockTransport(3); replay(transport); protocol = new ThriftBinaryProtocol(transport); protocol.readSetBegin(); verify(transport); transport = getMockMapTransport(3); replay(transport); protocol = new ThriftBinaryProtocol(transport); protocol.readMapBegin(); verify(transport); }
Source:
<code>public void afterPropertiesSet() { Assert.notNull(codeListTable, "codeListTable is not initialized!"); if (fallbackTo == null) { fallbackTo = resolveLocale(Locale.getDefault()); Assert.notNull(fallbackTo, "No codelist found for fallback default locale '" + Locale <START> .getDefault().getLanguage() <END> + "', it must be defined."); } else { Assert.isTrue(codeListTable.containsRow(fallbackTo), "No codelist found for fallback locale '" + fallbackTo + "', it must be defined."); } }</code><technical_language>[x] error message is incorrectly. In fact, codelist for Locale.getDefault() Locale.getDefault().getLanguage(). default locale is Locale.getDefault(). I recommend Locale.getDefault() Locale.getDefault().getLanguage()</technical_language>

Target:
public void afterPropertiesSet() { Assert.notNull(codeListTable, "codeListTable is not initialized!"); if (fallbackTo == null) { Locale defaultLocale = Locale.getDefault(); fallbackTo = resolveLocale(defaultLocale); Assert.notNull(fallbackTo, "No codelist for default locale ('" + defaultLocale + "' and '" + defaultLocale.getLanguage() + "'). Please define codelist for default locale or set locale already defined in codelist to fallbackTo."); } else { Assert.isTrue(codeListTable.containsRow(fallbackTo), "No codelist found for fallback locale '" + fallbackTo + "', it must be defined."); } }
Source:
<code>private <R> void checkMatchesIdType(R result) { Class routingResultType = null; <START> if(result instanceof Collection) { <END> Collection asCollection = (Collection) result; Iterator iterator = asCollection.iterator(); if(iterator.hasNext()) { Object element = iterator.next(); routingResultType = element.getClass(); } } else { routingResultType = result.getClass(); } if (routingResultType != null) { Class<I> idClass = idClass(); boolean corresponds = idClass.isAssignableFrom(routingResultType); checkArgument(corresponds, "Message routing failed in `%s` due to the type mismatch. " + "Expected ID type is `%s`, but was `%s`.", getClass().getName(), idClass.getName(), routingResultType.getName()); } }</code><technical_language>Please fix code alignment here</technical_language>

Target:
private <R> void checkMatchesIdType(R result) { Class routingResultType = null; if (result instanceof Collection) { Collection asCollection = (Collection) result; Object element = getFirst(asCollection, null); if (element != null) { routingResultType = element.getClass(); } } else { routingResultType = result.getClass(); } if (routingResultType != null) { Class<I> idClass = idClass(); boolean corresponds = idClass.isAssignableFrom(routingResultType); checkArgument(corresponds, "Message routing failed in `%s` due to the type mismatch. " + "Expected ID type is `%s`, but was `%s`.", getClass().getName(), idClass.getName(), routingResultType.getName()); } }
Source:
<code>public EntityType(String aName, String aLabel, String aType) { this(aName , aType , true , "" , null , null , null , <START> Collections.singletonList(aLabel) , null , null , <END> null ); }</code><technical_language>Again, asList a static import</technical_language>

Target:
public EntityType(String aName, String aLabel, String aType) { this(aName , aType , true , "" , null , null , null , Arrays.asList(aLabel) , null , null , null ); }
Source:
<code>public SexGenotypeDataCollection(@Nonnull final String sexGenotypeDataSourceName, @Nonnull final Reader sexGenotypeDataReader) throws IOException { try (final SexGenotypeTableReader reader = new SexGenotypeTableReader(sexGenotypeDataSourceName, sexGenotypeDataReader)) { sexGenotypeDataList = reader.stream().collect(Collectors.toList()); } catch (final IOException ex) { <START> throw new UserException.CouldNotReadInputFile("Could not reader sex genotype data from " + sexGenotypeDataSourceName); <END> } }</code><technical_language>> **read**</technical_language>

Target:
public SexGenotypeDataCollection(@Nonnull final String sexGenotypeDataSourceName, @Nonnull final Reader sexGenotypeDataReader) throws IOException { try (final SexGenotypeTableReader reader = new SexGenotypeTableReader(sexGenotypeDataSourceName, sexGenotypeDataReader)) { sexGenotypeDataList = reader.stream().collect(Collectors.toList()); } catch (final IOException ex) { throw new UserException.CouldNotReadInputFile("Could not read sex genotype data from " + sexGenotypeDataSourceName); } }
Source:
<code>public Role getRole() { <START> try { <END> return Role.valueOf(roleCombo.get()); } catch (Exception ex) { } return null; }</code><technical_language>Suggest create local variable Role role = null return</technical_language>

Target:
public Role getRole() { Role role = null; try { role = Role.valueOf(roleCombo.get()); } catch (Exception ex) { } return role; }
Source:
<code>private void initialize() { if (isInitialized()) { return; } m_maxThreads = getMaxThreads(); if (m_maxThreads < 1) { exportLog.warn("Parameter \"" + MAX_EXPORT_THREADS + "\" should have a positive value, forcing to default value of 1"); m_maxThreads = 1; } else { int localSitesCount = getLocalSitesCount(); if (localSitesCount == 0) { exportLog.warn("Parameter \"" + MAX_EXPORT_THREADS + "\" cannot be checked, forcing to default value of 1"); m_maxThreads = 1; } else if (m_maxThreads > localSitesCount) { exportLog.warn("Parameter \"" + MAX_EXPORT_THREADS + "\" exceeds local sites count, forcing to default value of 1"); <START> m_maxThreads = 1; <END> } } trace("Export Data Sources running with %d executor threads", m_maxThreads); m_nextAlloc = 0; m_executors = new ArrayList<>(m_maxThreads); m_refCounts = new IdentityHashMap<>(); m_pid2execMap = new HashMap<>(); }</code><technical_language>set m_maxThreads localSiteCount user wanted more threads want limit threads <= localSitesCount</technical_language>

Target:
private void initialize() { if (isInitialized()) { return; } m_maxThreads = getConfigMaxThreads(); int minThreads = getMinThreads(); if (m_maxThreads < 1) { exportLog.warn("Parameter \"" + MAX_EXPORT_THREADS + "\" should have a positive value, forcing to default value of " + minThreads); m_maxThreads = minThreads; } else { int localSitesCount = getLocalSitesCount(); if (localSitesCount == 0) { exportLog.warn("Parameter \"" + MAX_EXPORT_THREADS + "\" cannot be checked, forcing to default value of " + minThreads); m_maxThreads = minThreads; } else if (m_maxThreads > localSitesCount) { exportLog.warn("Parameter \"" + MAX_EXPORT_THREADS + "\" exceeds local sites count, forcing to " + localSitesCount); m_maxThreads = localSitesCount; } } exportLog.info("Export Data Sources running with " + m_maxThreads + " executor threads"); m_nextAlloc = 0; m_executors = new ArrayList<>(m_maxThreads); m_refCounts = new IdentityHashMap<>(); m_pid2execMap = new HashMap<>(); }
Source:
<code>public void stop() { log.debug( "Stopping VM pause monitor" ); <START> worker.interrupt(); <END> try { worker.join(); } catch ( InterruptedException ignore ) { currentThread().interrupt(); } }</code><technical_language>if instead of interruption flag stop kind of flag</technical_language>

Target:
public void stop() { log.debug( "Stopping VM pause monitor" ); checkState( job != null, "VM pause monitor is not started" ); job.cancel( true ); job = null; }
Source:
<code>static void verifyNoAsyncRestTemplateAttributes(Element element, ParserContext parserContext) { for (String attributeName : ASYNC_REST_TEMPLATE_REFERENCE_ATTRIBUTES) { if (element.hasAttribute(attributeName)) { <START> parserContext.getReaderContext().error("When providing a 'rest-template' reference, the '" <END> + attributeName + "' attribute is not allowed.", parserContext.extractSource(element)); } } }</code><technical_language>"When providing 'async-rest-template'... Correct? properly reflect reality</technical_language>

Target:
static void verifyNoAsyncRestTemplateAttributes(Element element, ParserContext parserContext) { for (String attributeName : ASYNC_REST_TEMPLATE_REFERENCE_ATTRIBUTES) { if (element.hasAttribute(attributeName)) { parserContext.getReaderContext().error("When providing an 'async-rest-template' reference, the '" + attributeName + "' attribute is not allowed.", parserContext.extractSource(element)); } } }
Source:
<code>protected void acquireDiskLocks() { <START> if (isImageLockNeeded()) { <END> final DiskImage diskImage = (DiskImage) getDisk(); final ImageStatus imgStatus = diskImage.getImageStatus(); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getCompensationContext().snapshotEntityStatus(diskImage.getImage(), imgStatus); getCompensationContext().stateChanged(); diskImage.setImageStatus(ImageStatus.LOCKED); ImagesHandler.updateImageStatus(diskImage.getImage().getId(), ImageStatus.LOCKED); return null; }}); } }</code><technical_language>I lock acquired for image disk, vdsm call minutes provide user experience</technical_language>

Target:
protected void acquireDiskLocks() { if (isImageLockNeeded()) { final DiskImage diskImage = (DiskImage) getDisk(); final ImageStatus imgStatus = diskImage.getImageStatus(); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getCompensationContext().snapshotEntityStatus(diskImage.getImage(), imgStatus); getCompensationContext().stateChanged(); diskImage.setImageStatus(ImageStatus.LOCKED); ImagesHandler.updateImageStatus(diskImage.getImageId(), ImageStatus.LOCKED); return null; }}); } }
Source:
<code>public String getTournament(Model model, HttpSession session) { Member member = (Member) session.getAttribute("member"); MemberDao memberDao = new MemberDao(); member = memberDao.getMemberById(member.getId()); if (member == null || member.getContext() != UserType.OFFICIAL) { <START> return "redirect/:denied"; <END> } Set<Team> teams = member.getTeams(); model.addAttribute("teams", teams); TournamentDao tournamentDao = new TournamentDao(); List<Tournament> tournaments = tournamentDao.getLastXTournaments(5); model.addAttribute("tournaments", tournaments); return "official"; }</code><technical_language>reason change this? /:denied compared :/denied</technical_language>

Target:
public String getTournament(Model model, HttpSession session) { Member member = (Member) session.getAttribute("member"); MemberDao memberDao = new MemberDao(); member = memberDao.getMemberById(member.getId()); if (member == null || member.getContext() != UserType.OFFICIAL) { return "redirect:/denied"; } Set<Team> teams = member.getTeams(); model.addAttribute("teams", teams); TournamentDao tournamentDao = new TournamentDao(); List<Tournament> tournaments = tournamentDao.getLastXTournaments(5); model.addAttribute("tournaments", tournaments); return "official"; }
Source:
<code>public void verifyPostedReplyWithMessage(String message, int replyNumber) { <START> new WebDriverWait(driver, 30).until(ExpectedConditions.textToBePresentInElement( <END> By.cssSelector("ul.replies li.message[id=\""+replyNumber+"\"] div.msg-body p"), message) ); PageObjectLogging.log("verifyPostedReplyWithMessage", "message with title verified", true); }</code><technical_language>waitForTextToBePresentInElementByElement waitForTextToBePresentInElementByBy create new method for css selector</technical_language>

Target:
public void verifyPostedReplyWithMessage(String message, int replyNumber) { waitForTextToBePresentInElementByBy(By.cssSelector("ul.replies li.message[id=\""+replyNumber+"\"] div.msg-body p") , message); PageObjectLogging.log("verifyPostedReplyWithMessage", "message with title verified", true); }
Source:
<code>private boolean isClusterLevelChange() { Version newVersion = getParameters().getClusterLevelChangeToVersion(); return newVersion != null && getVm().isRunningOrPaused() && <START> (getVm().getCustomCompatibilityVersion() == null || !newVersion.equals(getVm().getCustomCompatibilityVersion())); <END> }</code><technical_language>missing then.. handling case compatibility version of cluster VM is defined in is changed. if is some custom compatibility version for VM, cluster's compatibility version is irrelevant - VM run custom compatibility. therefore, if custom compatibility version is set, method return false. if is custom compatibility version set VM is affected compatibility version of cluster check if new compatibility version of cluster is cluster VM resides in before. no</technical_language>

Target:
private boolean isClusterLevelChange() { Version newVersion = getParameters().getClusterLevelChangeToVersion(); return newVersion != null && getVm().isRunningOrPaused() && getVm().getCustomCompatibilityVersion() == null; }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Clip clip = (Clip) o; return getClipID().equals(clip.getClipID()) && <START> uri.equals(clip.uri); <END> }</code><technical_language>fields for for consistency</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Clip clip = (Clip) o; return getClipID().equals(clip.getClipID()) && getURI().equals(clip.getURI()); }
Source:
<code><START> private DetailAST findChildWithIdent(DetailAST root) { <END> DetailAST curNode = root; while (curNode.findFirstToken(TokenTypes.IDENT) == null) { DetailAST toVisit = curNode.getFirstChild(); while (toVisit == null) { toVisit = curNode.getNextSibling(); if (toVisit == null) { curNode = curNode.getParent(); } } if (curNode == root.getParent()) { curNode = null; break; } curNode = toVisit; } return curNode; }</code><technical_language>static</technical_language>

Target:
private static DetailAST findChildWithIdent(DetailAST root) { return TokenUtils.findFirstTokenByPredicate(root, cur -> { return cur.findFirstToken(TokenTypes.IDENT) != null; }).orElse(null); }
Source:
<code>public String[] getActiveApnTypes() { if <START> (mTransportManager == <END> null || mDcTrackers == null) { Rlog.e(LOG_TAG, "Invalid state for Transport/DcTrackers"); return new String[0]; } Set<String> activeApnTypes = new HashSet<String>(); for (int i = 0; i < mDcTrackers.size(); i++) { activeApnTypes.addAll(Arrays.asList(mDcTrackers.valueAt(i).getActiveApnTypes())); } return activeApnTypes.toArray(new String[activeApnTypes.size()]); }</code><technical_language>remove logic mTransportMgr? also, I prefer mTransportMgr.getAvailableTransport mDcTracker initialized get updated if availabletransport changes</technical_language>

Target:
public String[] getActiveApnTypes() { if (mTransportManager == null || mDcTrackers == null) { Rlog.e(LOG_TAG, "Invalid state for Transport/DcTrackers"); return new String[0]; } Set<String> activeApnTypes = new HashSet<String>(); for (int transportType : mTransportManager.getAvailableTransports()) { DcTracker dct = getDcTracker(transportType); if (dct == null) continue; activeApnTypes.addAll(Arrays.asList(dct.getActiveApnTypes())); } return activeApnTypes.toArray(new String[activeApnTypes.size()]); }
Source:
<code>public void verifyOpeningArticleInNav(int anchorIndex) { waitForElementVisibleByElement(noChevrons.get(anchorIndex)); <START> if (noChevrons.size() != 0) { <END> noChevrons.get(anchorIndex).click(); PageObjectLogging.log("verifyOpeningArticleInNav", "New article opened", true, driver); } }</code><technical_language>is this check necessary noChevrons.get(index) is called prior this</technical_language>

Target:
public void verifyOpeningArticleInNav(int anchorIndex) { waitForElementVisibleByElement(noChevrons.get(anchorIndex)); noChevrons.get(anchorIndex).click(); PageObjectLogging.log("verifyOpeningArticleInNav", "New article opened", true, driver); }
Source:
<code>@Override public void onReceive(Context context, Intent intent) { if (intent == null) { return; } final String action = intent.getAction(); <START> if (ACTION_AIRPLANE_MODE_CHANGED.equals(action)) { <END> dispatchAirplaneModeChange(intent.getBooleanExtra(EXTRA_AIRPLANE_STATE, false)); } else if (CONNECTIVITY_ACTION.equals(action)) { dispatchNetworkStateChange(connectivityManager.getActiveNetworkInfo()); } }</code><technical_language>I I this line of code get in. Terrible</technical_language>

Target:
@Override public void onReceive(Context context, Intent intent) { if (intent == null) { return; } final String action = intent.getAction(); if (ACTION_AIRPLANE_MODE_CHANGED.equals(action)) { if (!intent.hasExtra(EXTRA_AIRPLANE_STATE)) { return; } dispatcher.dispatchAirplaneModeChange(intent.getBooleanExtra(EXTRA_AIRPLANE_STATE, false)); } else if (CONNECTIVITY_ACTION.equals(action)) { ConnectivityManager connectivityManager = getService(context, CONNECTIVITY_SERVICE); dispatcher.dispatchNetworkStateChange(connectivityManager.getActiveNetworkInfo()); } }
Source:
<code>private boolean stopTransferIfNecessary(ImageTransfer entity, long ts) { if <START> (entity.getClientInactivityTimeout() > <END> 0 && (entity.getPhase() == ImageTransferPhase.INITIALIZING || entity.getPhase() == ImageTransferPhase.TRANSFERRING) && (entity.getLastUpdated().getTime() / 1000) + entity.getClientInactivityTimeout() < ts) { if (getParameters().getTransferType() == TransferType.Download) { auditLog(this, AuditLogType.DOWNLOAD_IMAGE_CANCELED_TIMEOUT); updateEntityPhase(ImageTransferPhase.CANCELLED); } else { updateEntityPhaseToPausedBySystem( AuditLogType.UPLOAD_IMAGE_PAUSED_BY_SYSTEM_TIMEOUT); } return true; } return false; }</code><technical_language>if this is null</technical_language>

Target:
private boolean stopTransferIfNecessary(ImageTransfer entity, long ts) { if (shouldAbortOnClientInactivityTimeout(entity, ts)) { if (getParameters().getTransferType() == TransferType.Download) { auditLog(this, AuditLogType.DOWNLOAD_IMAGE_CANCELED_TIMEOUT); updateEntityPhase(ImageTransferPhase.CANCELLED); } else { updateEntityPhaseToPausedBySystem( AuditLogType.UPLOAD_IMAGE_PAUSED_BY_SYSTEM_TIMEOUT); } return true; } return false; }
Source:
<code>public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; SurveyAnswer other = (SurveyAnswer) obj; return (Objects.equals(answeredOn, other.answeredOn) && Objects.equals(answers, other.answers) && Objects.equals(client, other.client) && declined == other.declined); <START> } <END></code><technical_language>questionGuid</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; SurveyAnswer other = (SurveyAnswer) obj; return (Objects.equals(answeredOn, other.answeredOn) && Objects.equals(answers, other.answers) && Objects.equals(questionGuid, other.questionGuid) && Objects.equals(client, other.client) && declined == other.declined); }
Source:
<code>public HttpServerAuthenticationMechanism createAuthenticationMechanism(String mechanismName, Map<String, ?> properties, CallbackHandler callbackHandler) throws HttpAuthenticationException { checkNotNullParam("mechanismName", mechanismName); checkNotNullParam("properties", properties); checkNotNullParam("callbackHandler", callbackHandler); switch (mechanismName) { case BASIC_NAME: return new BasicAuthenticationMechanism(callbackHandler, (String) properties.get(CONFIG_REALM), false); case CLIENT_CERT_NAME: return new ClientCertAuthenticationMechanism(callbackHandler); case DIGEST_NAME: <START> return new DigestAuthenticationMechanism(callbackHandler, nonceManager, (String) properties.get(CONFIG_REALM), (String) properties.get(CONFIG_CONTEXT_PATH), (String) properties.get(CONFIG_ALGORITHM), providers); <END> case FORM_NAME: return new FormAuthenticationMechanism(callbackHandler, properties); case SPNEGO_NAME: return new SpnegoAuthenticationMechanism(callbackHandler, properties); case BEARER_TOKEN: return new BearerTokenAuthenticationMechanism(callbackHandler); } return null; }</code><technical_language>I handle algorithm a single property, problem is want configure environment some clients understand stronger hashes some want mechanism created multiple times for algorithm. need existing DIGEST_NAME unmodified want follow a similar pattern SASL algorithm a part of name - multiple in a preferred order. consider algorithm property a comma separated list if do impossible interleave other mechanisms if desirable for reason</technical_language>

Target:
public HttpServerAuthenticationMechanism createAuthenticationMechanism(String mechanismName, Map<String, ?> properties, CallbackHandler callbackHandler) throws HttpAuthenticationException { checkNotNullParam("mechanismName", mechanismName); checkNotNullParam("properties", properties); checkNotNullParam("callbackHandler", callbackHandler); switch (mechanismName) { case BASIC_NAME: return new BasicAuthenticationMechanism(callbackHandler, (String) properties.get(CONFIG_REALM), false); case CLIENT_CERT_NAME: return new ClientCertAuthenticationMechanism(callbackHandler); case DIGEST_NAME: return new DigestAuthenticationMechanism(callbackHandler, nonceManager, (String) properties.get(CONFIG_REALM), (String) properties.get(CONFIG_CONTEXT_PATH), MD5, providers); case DIGEST_SHA256_NAME: return new DigestAuthenticationMechanism(callbackHandler, nonceManager, (String) properties.get(CONFIG_REALM), (String) properties.get(CONFIG_CONTEXT_PATH), SHA256, providers); case DIGEST_SHA512_256_NAME: return new DigestAuthenticationMechanism(callbackHandler, nonceManager, (String) properties.get(CONFIG_REALM), (String) properties.get(CONFIG_CONTEXT_PATH), SHA512_256, providers); case FORM_NAME: return new FormAuthenticationMechanism(callbackHandler, properties); case SPNEGO_NAME: return new SpnegoAuthenticationMechanism(callbackHandler, properties); case BEARER_TOKEN: return new BearerTokenAuthenticationMechanism(callbackHandler); } return null; }
Source:
<code>public void getAmbryBlobStorageServiceTest() throws Exception { Properties properties = new Properties(); <START> properties.setProperty(HelixPropertyStoreConfig.HELIX_PROPERTY_STORE_PREFIX + "zk.client.connect.string", <END> ZK_CONNECT_STRING); properties.setProperty(HelixPropertyStoreConfig.HELIX_PROPERTY_STORE_PREFIX + "root.path", STORE_ROOT_PATH); VerifiableProperties verifiableProperties = new VerifiableProperties(properties); AmbryBlobStorageServiceFactory ambryBlobStorageServiceFactory = new AmbryBlobStorageServiceFactory(verifiableProperties, new MockClusterMap(), new MockRestRequestResponseHandler(), new InMemoryRouter(verifiableProperties, new MockClusterMap()), new MockNotifier()); BlobStorageService ambryBlobStorageService = ambryBlobStorageServiceFactory.getBlobStorageService(); assertNotNull("No BlobStorageService returned", ambryBlobStorageService); assertEquals("Did not receive an AmbryBlobStorageService instance", AmbryBlobStorageService.class.getCanonicalName(), ambryBlobStorageService.getClass().getCanonicalName()); }</code><technical_language>required ? used</technical_language>

Target:
public void getAmbryBlobStorageServiceTest() throws Exception { Properties properties = new Properties(); VerifiableProperties verifiableProperties = new VerifiableProperties(properties); AmbryBlobStorageServiceFactory ambryBlobStorageServiceFactory = new AmbryBlobStorageServiceFactory(verifiableProperties, new MockClusterMap(), new MockRestRequestResponseHandler(), new InMemoryRouter(verifiableProperties, new MockClusterMap()), new MockNotifier()); BlobStorageService ambryBlobStorageService = ambryBlobStorageServiceFactory.getBlobStorageService(); assertNotNull("No BlobStorageService returned", ambryBlobStorageService); assertEquals("Did not receive an AmbryBlobStorageService instance", AmbryBlobStorageService.class.getCanonicalName(), ambryBlobStorageService.getClass().getCanonicalName()); }
Source:
<code>public void testMultiThreadedCreateWithDuplicateClientAssignedIdsInTransaction() throws Exception { ExecutorService executor = Executors.newFixedThreadPool(20); List<Future<String>> futures = new ArrayList<>(); for (int i = 0; i < 100; i++) { int finalI = i; Callable<String> task = () -> { Bundle input = new Bundle(); input.setType(BundleType.TRANSACTION); Patient p = new Patient(); p.setId("A" + finalI); p.addIdentifier().setValue("A"+finalI); input.addEntry().setResource(p).setFullUrl("Patient/A" + finalI).getRequest().setMethod(HTTPVerb.PUT).setUrl("Patient/A" + finalI); try { ourClient.transaction().withBundle(input).execute(); return null; } catch (ResourceVersionConflictException e) { assertThat(e.toString(), containsString("Error flushing transaction with resource types: [Patient] - The operation has failed with a client-assigned ID constraint failure")); return e.toString(); } }; for (int j = 0; j < 2; j++) { Future<String> future = executor.submit(task); futures.add(future); } } List<String> results = new ArrayList<>(); for (Future<String> next : futures) { String nextOutcome = next.get(); if (isNotBlank(nextOutcome)) { results.add(nextOutcome); } } ourLog.info("Results: {}", results); <START> assertThat(results, not(Matchers.empty())); <END> }</code><technical_language>This feels a weak assert. Is this want assert here</technical_language>

Target:
public void testMultiThreadedCreateWithDuplicateClientAssignedIdsInTransaction() throws Exception { ExecutorService executor = Executors.newFixedThreadPool(20); List<Future<String>> futures = new ArrayList<>(); for (int i = 0; i < 100; i++) { int finalI = i; Callable<String> task = () -> { Bundle input = new Bundle(); input.setType(BundleType.TRANSACTION); Patient p = new Patient(); p.setId("A" + finalI); p.addIdentifier().setValue("A"+finalI); input.addEntry().setResource(p).setFullUrl("Patient/A" + finalI).getRequest().setMethod(HTTPVerb.PUT).setUrl("Patient/A" + finalI); try { ourClient.transaction().withBundle(input).execute(); return null; } catch (ResourceVersionConflictException e) { assertThat(e.toString(), containsString("Error flushing transaction with resource types: [Patient] - The operation has failed with a client-assigned ID constraint failure")); return e.toString(); } }; for (int j = 0; j < 2; j++) { Future<String> future = executor.submit(task); futures.add(future); } } List<String> results = new ArrayList<>(); for (Future<String> next : futures) { String nextOutcome = next.get(); if (isNotBlank(nextOutcome)) { results.add(nextOutcome); } } ourLog.info("Results: {}", results); assertThat(results, not(Matchers.empty())); assertThat(results.get(0), containsString("HTTP 409 Conflict: Error flushing transaction with resource types: [Patient]")); }
Source:
<code>private void setClientOptions(WebClient webClient, String htmlUnitWebClientOptions) { final WebClientOptions webClientOptions = webClient.getOptions(); Map<String, String> clientOptions = new LinkedHashMap<>(); final String[] options = htmlUnitWebClientOptions.split(","); for (String option : options) { final String[] keyValue = option.split("="); if (keyValue.length == 2) { String key = keyValue[0].trim(); key = BROWSER_CAPABILITIES + Character.toUpperCase(key.charAt(0)) + key.substring(1); clientOptions.put(key, keyValue[1].trim()); <START> } <END> } final DesiredCapabilities webClientCapabilities = new DesiredCapabilities(clientOptions); CapabilitiesOptionsMapper.mapCapabilities(webClientOptions, webClientCapabilities, BROWSER_CAPABILITIES); }</code><technical_language>Remember property a multiline string - StringUtils.trimMultiline split for time</technical_language>

Target:
private void setClientOptions(WebClient webClient, String htmlUnitWebClientOptions) { final WebClientOptions webClientOptions = webClient.getOptions(); Map<String, String> clientOptions = new LinkedHashMap<>(); final String multiline = StringUtils.trimMultiline(htmlUnitWebClientOptions); final String[] options = multiline.split(";"); for (String option : options) { final String[] keyValue = option.split("="); if (keyValue.length == 2) { String key = keyValue[0].trim(); if (key.length() > 0) { key = BROWSER_NAME + Character.toUpperCase(key.charAt(0)) + key.substring(1); String value = keyValue[1].trim(); if (value.contains(",")) { value = value.replaceAll("\\s*,\\s*", " "); } clientOptions.put(key, value); } else { logger.info("Excluding option : " + option + "to set for HtmlUnitDriver webClientOptions as it is not as per required format i.e. key=value"); } } } final DesiredCapabilities webClientCapabilities = new DesiredCapabilities(clientOptions); logger.info("Setting HtmlDriver web client options: " + clientOptions); CapabilitiesOptionsMapper.mapCapabilities(webClientOptions, webClientCapabilities, BROWSER_NAME); }
Source:
<code>private boolean transitState(String endpoint, ClientState from, ClientState to) { boolean updated = clientStatus.replace(endpoint, from, to); if(updated) { LOG.debug("Client state update -> {}", endpoint, from, to); } else { <START> LOG.debug("Cannot update Client state -> {}. Current state is {}", <END> endpoint, from, to, clientStatus.get(endpoint)); } return updated; }</code><technical_language>if isDebugEnabled is missing</technical_language>

Target:
private boolean transitState(String endpoint, ClientState from, ClientState to) { boolean updated = clientStatus.replace(endpoint, from, to); if(LOG.isDebugEnabled()) { if (updated) { LOG.debug("Client state update -> {}", endpoint, from, to); } else { LOG.debug("Cannot update Client state -> {}. Current state is {}", endpoint, from, to, clientStatus.get(endpoint)); } } return updated; }
Source:
<code>protected List<OrganizationEntity> getActiveOrganizations() { List<OrganizationEntity> result = new ArrayList<>(); if (StringUtils.isNotBlank(ENABLED_ORGANIZATIONS)) { String[] organizationIdentifiers = StringUtils.split(ENABLED_ORGANIZATIONS, ","); for (String organizationIdentifierStr : organizationIdentifiers) { if (StringUtils.isNotBlank(organizationIdentifierStr)) { SchoolDataIdentifier identifier = SchoolDataIdentifier.fromId(organizationIdentifierStr); if (identifier != null) { <START> OrganizationEntity organizationEntity = organizationEntityController.findByDataSourceAndIdentifier(identifier.getDataSource(), identifier.getIdentifier()); <END> if (organizationEntity != null) { result.add(organizationEntity); } } } } } return result; }</code><technical_language>needs replaced findByDataSourceAndIdentifierAndArchived respective branch</technical_language>

Target:
protected List<OrganizationEntity> getActiveOrganizations() { List<OrganizationEntity> result = new ArrayList<>(); if (StringUtils.isNotBlank(ENABLED_ORGANIZATIONS)) { String[] organizationIdentifiers = StringUtils.split(ENABLED_ORGANIZATIONS, ","); for (String organizationIdentifierStr : organizationIdentifiers) { if (StringUtils.isNotBlank(organizationIdentifierStr)) { SchoolDataIdentifier identifier = SchoolDataIdentifier.fromId(organizationIdentifierStr); if (identifier != null) { OrganizationEntity organizationEntity = organizationEntityController.findByDataSourceAndIdentifierAndArchived( identifier.getDataSource(), identifier.getIdentifier(), Boolean.FALSE); if (organizationEntity != null) { result.add(organizationEntity); } } } } } return result; }
Source:
<code>private SimpleReportEntry createReportEntry( TestIdentifier testIdentifier, TestExecutionResult testExecutionResult, Map<String, String> systemProperties, String reason, Integer elapsedTime ) { String[] classMethodName = toClassMethodName( testIdentifier ); String className = classMethodName[0]; String classText = classMethodName[1]; if ( Objects.equals( className, classText ) ) { classText = null; } boolean isFailedContainer = isFailedContainer( testIdentifier, testExecutionResult ); <START> String methodName = ( isFailedContainer || testIdentifier.isTest() ) ? classMethodName[2] : null; <END> String methodText = ( isFailedContainer || testIdentifier.isTest() ) ? classMethodName[3] : null; if ( Objects.equals( methodName, methodText ) ) { methodText = null; } StackTraceWriter stw = testExecutionResult == null ? null : toStackTraceWriter( className, methodName, testExecutionResult ); return new SimpleReportEntry( className, classText, methodName, methodText, stw, elapsedTime, reason, systemProperties ); }</code><technical_language>do brackets in ( isFailedContainer || testIdentifier.isTest() ). is collision boolean String in this case</technical_language>

Target:
private SimpleReportEntry createReportEntry( TestIdentifier testIdentifier, TestExecutionResult testExecutionResult, Map<String, String> systemProperties, String reason, Integer elapsedTime ) { String[] classMethodName = toClassMethodName( testIdentifier ); String className = classMethodName[0]; String classText = classMethodName[1]; if ( Objects.equals( className, classText ) ) { classText = null; } boolean failed = testExecutionResult != null && testExecutionResult.getStatus() == FAILED; String methodName = failed || testIdentifier.isTest() ? classMethodName[2] : null; String methodText = failed || testIdentifier.isTest() ? classMethodName[3] : null; if ( Objects.equals( methodName, methodText ) ) { methodText = null; } StackTraceWriter stw = testExecutionResult == null ? null : toStackTraceWriter( className, methodName, testExecutionResult ); return new SimpleReportEntry( className, classText, methodName, methodText, stw, elapsedTime, reason, systemProperties ); }
Source:
<code>protected StrategyPriority internalCanHandle(Map<VolumeInfo, DataStore> volumeMap) { if (super.internalCanHandle(volumeMap) == StrategyPriority.CANT_HANDLE) { Set<VolumeInfo> volumeInfoSet = volumeMap.keySet(); for (VolumeInfo volumeInfo : volumeInfoSet) { StoragePoolVO storagePoolVO = _storagePoolDao.findById(volumeInfo.getPoolId()); if (storagePoolVO.getPoolType() != StoragePoolType.Filesystem) { return StrategyPriority.CANT_HANDLE; <START> } <END> } return StrategyPriority.HIGHEST; } return StrategyPriority.CANT_HANDLE; }</code><technical_language>happen if VM a ROOT volume a local disk (FileSystem) more data disks NFS Ceph for example</technical_language>

Target:
protected StrategyPriority internalCanHandle(Map<VolumeInfo, DataStore> volumeMap) { if (super.internalCanHandle(volumeMap) == StrategyPriority.CANT_HANDLE) { Set<VolumeInfo> volumeInfoSet = volumeMap.keySet(); for (VolumeInfo volumeInfo : volumeInfoSet) { StoragePoolVO storagePoolVO = _storagePoolDao.findById(volumeInfo.getPoolId()); if (storagePoolVO.getPoolType() != StoragePoolType.Filesystem && storagePoolVO.getPoolType() != StoragePoolType.NetworkFilesystem) { return StrategyPriority.CANT_HANDLE; } } return StrategyPriority.HYPERVISOR; } return StrategyPriority.CANT_HANDLE; }
Source:
<code>private void parse(String argv) { OptionSet options = buildOptionParser().parse(argv); Properties properties; if (options.has("config")) { properties = parseFile((String) options.valueOf("config"), true); } else { properties = parseFile(DEFAULT_CONFIG_FILE, false); } if (options.has("env_config_prefix")) { String prefix = ((String) options.valueOf("env_config_prefix")).toLowerCase(); System.getenv().entrySet().stream().filter(map -> map.getKey().toLowerCase().startsWith(prefix)) <START> .forEach(config -> properties.put(config.getKey().toLowerCase().replace(prefix, ""), config.getValue())); <END> } if (options.has("help")) usage("Help for Maxwell:"); setup(options, properties); List<?> arguments = options.nonOptionArguments(); if(!arguments.isEmpty()) { usage("Unknown argument(s): " + arguments); } }</code><technical_language>nit: replaceFirst instead of replace</technical_language>

Target:
private void parse(String argv) { OptionSet options = buildOptionParser().parse(argv); Properties properties; if (options.has("config")) { properties = parseFile((String) options.valueOf("config"), true); } else { properties = parseFile(DEFAULT_CONFIG_FILE, false); } String prefix = getEnvConfigPrefix(options, properties); if (prefix != null) { System.getenv().entrySet().stream() .filter(map -> map.getKey().toLowerCase().startsWith(prefix.toLowerCase())) .forEach(config -> properties.put(config.getKey().toLowerCase().replaceFirst(prefix.toLowerCase(), ""), config.getValue())); } if (options.has("help")) usage("Help for Maxwell:"); setup(options, properties); List<?> arguments = options.nonOptionArguments(); if(!arguments.isEmpty()) { usage("Unknown argument(s): " + arguments); } }
Source:
<code>public boolean processMessage(Message message) { switch (message.what) { case CMD_NETWORK_CONNECTED: updateConnectedNetworkAttributes(message); transitionTo(mValidatedState); break; case CMD_EVALUATE_PRIVATE_DNS: transitionTo(mEvaluatingPrivateDnsState); break; case EVENT_DNS_NOTIFICATION: mDnsStallDetector.accumulateConsecutiveDnsTimeoutCount(message.arg1); if (evaluateDataStall()) { transitionTo(mEvaluatingState); } break; case EVENT_POLL_TCPINFO: if (getTcpSocketTracker().pollSocketsInfo() && evaluateDataStall()) { transitionTo(mEvaluatingState); } <START> sendTcpPollingEvent(); <END> break; default: return NOT_HANDLED; } return HANDLED; }</code><technical_language>put this in else ? important messages removed in exit()</technical_language>

Target:
public boolean processMessage(Message message) { switch (message.what) { case CMD_NETWORK_CONNECTED: updateConnectedNetworkAttributes(message); transitionTo(mValidatedState); break; case CMD_EVALUATE_PRIVATE_DNS: transitionTo(mEvaluatingPrivateDnsState); break; case EVENT_DNS_NOTIFICATION: mDnsStallDetector.accumulateConsecutiveDnsTimeoutCount(message.arg1); if (evaluateDataStall()) { transitionTo(mEvaluatingState); } break; case EVENT_POLL_TCPINFO: if (getTcpSocketTracker().pollSocketsInfo() && evaluateDataStall()) { transitionTo(mEvaluatingState); } else { sendTcpPollingEvent(); } break; default: return NOT_HANDLED; } return HANDLED; }
Source:
<code>static <E extends Entity<?, ?>> Map<String, MemoizedValue> extractColumnValues( E entity, Collection<EntityColumn> entityColumns) { checkNotNull(entityColumns); checkNotNull(entity); final Class<? extends Entity> entityClass = entity.getClass(); if (!isPublic(entityClass)) { return Collections.emptyMap(); } final Map<String, MemoizedValue> values = recordColumnValuesToMap(entityColumns, entity); <START> <END> return values; }</code><technical_language>Please kill this empty line</technical_language>

Target:
extractColumnValues(E entity, Collection<EntityColumn> entityColumns) { checkNotNull(entity); checkNotNull(entityColumns); final ColumnValueExtractor columnValueExtractor = ColumnValueExtractor.create(entity, entityColumns); return columnValueExtractor.extractColumnValues(); }
Source:
<code>private static void replaceWord(StringBuilder input, String word, String replace, boolean ignoreCase) { StringBuilder workInput; String workWord = word; if (ignoreCase) { workInput = new StringBuilder(input.toString().toLowerCase(Locale.ENGLISH)); workWord = word.toLowerCase(Locale.ENGLISH); } else { workInput = new StringBuilder(input); } int pos = 0; do { pos = workInput.indexOf(workWord, pos); if (pos == -1) { break; } if (pos > 0) { char prevChar = workInput.charAt(pos - 1); if (Character.isLetterOrDigit(prevChar)) { pos = pos + workWord.length(); continue; } } int nextPos = pos + workWord.length(); if (nextPos < workInput.length()) { char nextChar = workInput.charAt(nextPos); if (Character.isLetterOrDigit(nextChar)) { pos = pos + workWord.length(); continue; } } <START> input.replace(pos, pos + workWord.length(), replace); <END> pos = pos + replace.length(); } while (pos > -1); }</code><technical_language>replacement assigned anywhere</technical_language>

Target:
private static void replaceWord(StringBuilder input, String word, String replace, boolean ignoreCase) { StringBuilder workInput; String workWord; if (ignoreCase) { workInput = new StringBuilder(input.toString().toLowerCase(Locale.ENGLISH)); workWord = word.toLowerCase(Locale.ENGLISH); } else { workInput = new StringBuilder(input); workWord = word; } int pos = 0; do { pos = workInput.indexOf(workWord, pos); if (pos == -1) { break; } if (pos > 0) { char prevChar = workInput.charAt(pos - 1); if (Character.isLetterOrDigit(prevChar)) { pos = pos + workWord.length(); continue; } } int nextPos = pos + workWord.length(); if (nextPos < workInput.length()) { char nextChar = workInput.charAt(nextPos); if (Character.isLetterOrDigit(nextChar)) { pos = pos + workWord.length(); continue; } } input.replace(pos, pos + workWord.length(), replace); pos = pos + replace.length(); } while (pos > -1); }
Source:
<code>public static String unquoteDoubleQuotes(String s) { if (s.length() >= 2) { if (s.charAt(0) == '\"' && s.charAt(s.length() - 1) == '\"') { <START> return s.substring(1, s.length() - 1); <END> } } return s; }</code><technical_language>need double quote unquoting, this suffers issue single quote unquoting above</technical_language>

Target:
public static String unquoteDoubleQuotes(String s) { return unquote(s, '\"'); }
Source:
<code>protected List<TimeLinkEvent> getLinkList(long startTime, long endTime, long resolution, IProgressMonitor monitor) { <START> return new ArrayList<TimeLinkEvent>(fLinkEvents); <END> }</code><technical_language>return null default</technical_language>

Target:
protected List<ILinkEvent> getLinkList(long startTime, long endTime, long resolution, IProgressMonitor monitor) { return new ArrayList<ILinkEvent>(); }
Source:
<code>private void addOrUpdateDayTruncatedActivity(ActivityPayload payload, GoalDTO matchingGoal) { <START> ActivityCacheResult activity = getRegisteredDayActivity(payload, matchingGoal); <END> if (canCombineWithLastRegisteredActivity(payload, activity.content)) { if (isBeyondSkipWindowAfterLastRegisteredActivity(payload, activity.content)) { updateActivityEndTime(payload, matchingGoal, activity); } } else { addActivity(payload, matchingGoal, activity); } }</code><technical_language>rename activity activityCacheResult? confused times activity a cache result. Please do in other methods too</technical_language>

Target:
private void addOrUpdateDayTruncatedActivity(ActivityPayload payload, GoalDTO matchingGoal) { ActivityDTO lastRegisteredActivity = getLastRegisteredActivity(payload, matchingGoal); if (canCombineWithLastRegisteredActivity(payload, lastRegisteredActivity)) { if (isBeyondSkipWindowAfterLastRegisteredActivity(payload, lastRegisteredActivity)) { updateActivityEndTime(payload, matchingGoal, lastRegisteredActivity); } } else { addActivity(payload, matchingGoal, lastRegisteredActivity); } }
Source:
<code>public void shouldThrowExceptionIfNoTypeMappingWasFoundWithoutAccessingDbWithRawQueryBlocking() { final StorIOSQLite storIOSQLite = mock(StorIOSQLite.class); final StorIOSQLite.Internal internal = mock(StorIOSQLite.Internal.class); when(storIOSQLite.get()).thenReturn(new PreparedGet.Builder(storIOSQLite)); when(storIOSQLite.internal()).thenReturn(internal); final PreparedGet<TestItem> preparedGet = storIOSQLite .get() .object(TestItem.class) .withQuery(RawQuery.builder().query("test query").build()) .prepare(); try { preparedGet.executeAsBlocking(); failBecauseExceptionWasNotThrown(StorIOException.class); } catch (StorIOException expected) { assertThat(expected).hasCauseInstanceOf(IllegalStateException.class); <START> } <END> verify(storIOSQLite).get(); verify(storIOSQLite).internal(); verify(internal).typeMapping(TestItem.class); verify(internal, never()).rawQuery(any(RawQuery.class)); verifyNoMoreInteractions(storIOSQLite, internal); }</code><technical_language>(check exception message)</technical_language>

Target:
public void shouldThrowExceptionIfNoTypeMappingWasFoundWithoutAccessingDbWithRawQueryBlocking() { final StorIOSQLite storIOSQLite = mock(StorIOSQLite.class); final StorIOSQLite.Internal internal = mock(StorIOSQLite.Internal.class); when(storIOSQLite.get()).thenReturn(new PreparedGet.Builder(storIOSQLite)); when(storIOSQLite.internal()).thenReturn(internal); final PreparedGet<TestItem> preparedGet = storIOSQLite .get() .object(TestItem.class) .withQuery(RawQuery.builder().query("test query").build()) .prepare(); try { preparedGet.executeAsBlocking(); failBecauseExceptionWasNotThrown(StorIOException.class); } catch (StorIOException expected) { assertThat(expected).hasCauseInstanceOf(IllegalStateException.class); assertThat(expected.getCause()).hasMessage("This type does not have type mapping: " + "type = " + TestItem.class + "," + "db was not touched by this operation, please add type mapping for this type"); } verify(storIOSQLite).get(); verify(storIOSQLite).internal(); verify(internal).typeMapping(TestItem.class); verify(internal, never()).rawQuery(any(RawQuery.class)); verifyNoMoreInteractions(storIOSQLite, internal); }
Source:
<code>public GarruksWarsteed(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{G}{G}"); this.subtype.add(SubType.RHINO); this.power = new MageInt(3); this.toughness = new MageInt(5); this.addAbility(VigilanceAbility.getInstance()); <START> this.addAbility(new EntersBattlefieldTriggeredAbility(new SearchLibraryGraveyardPutInHandEffect(filter, false, true), true)); <END> }</code><technical_language>this need ability effect optional, ability is fine</technical_language>

Target:
public GarruksWarsteed(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{G}{G}"); this.subtype.add(SubType.RHINO); this.power = new MageInt(3); this.toughness = new MageInt(5); this.addAbility(VigilanceAbility.getInstance()); this.addAbility(new EntersBattlefieldTriggeredAbility(new SearchLibraryGraveyardPutInHandEffect(filter, false, true))); }
Source:
<code>public MergeStrategy getPreferredMergeStrategy() { final IEclipsePreferences prefs = InstanceScope.INSTANCE .getNode(Activator.getPluginId()); if <START> (prefs.getBoolean(GitCorePreferences.core_enableLogicalModel, false)) { <END> String preferredMergeStrategyKey = prefs.get( GitCorePreferences.core_preferredModelMergeStrategy, MergeStrategy.RECURSIVE.getName()); if (preferredMergeStrategyKey != null && !preferredMergeStrategyKey.isEmpty()) { MergeStrategy result = MergeStrategy .get(preferredMergeStrategyKey); if (result != null) { return result; } logError(NLS.bind( CoreText.Activator_invalidPreferredModelMergeStrategy, preferredMergeStrategyKey), null); } logError(CoreText.Activator_missingPreferredModelMergeStrategy, null); } return MergeStrategy.RECURSIVE; }</code><technical_language>If this extension point sense for strategies models need this check</technical_language>

Target:
public MergeStrategy getPreferredMergeStrategy() { final IEclipsePreferences prefs = InstanceScope.INSTANCE .getNode(Activator.getPluginId()); String preferredMergeStrategyKey = prefs.get( GitCorePreferences.core_preferredMergeStrategy, null); if (preferredMergeStrategyKey != null && !preferredMergeStrategyKey.isEmpty()) { MergeStrategy result = MergeStrategy.get(preferredMergeStrategyKey); if (result != null) { return result; } logError(NLS.bind(CoreText.Activator_invalidPreferredMergeStrategy, preferredMergeStrategyKey), null); } return null; }