auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>void initialize(PlatformManager platformManager, Platform platform) { BlockRegistry blockRegistry = platform.getRegistries().getBlockRegistry(); for (BlockType type : BlockType.REGISTRY) { for (BlockState state : type.getAllStates()) { BlockStateIdAccess.register(state, blockRegistry.getInternalBlockStateId(state) <START> .orElse(BlockStateIdAccess.invalidId())); <END> } } }</code><technical_language>this return int? orElse</technical_language>

Target:
void initialize(PlatformManager platformManager, Platform platform) { platform.registerGameHooks(); }
Source:
<code>public InstructorAttributes updateInstructorByEmail(InstructorAttributes.UpdateOptionsWithEmail updateOptions) throws InvalidParametersException, EntityDoesNotExistException { Assumption.assertNotNull("Supplied parameter was null", updateOptions); InstructorAttributes originalInstructor = instructorsDb.getInstructorForEmail(updateOptions.getCourseId(), updateOptions.getEmail()); <START> InstructorAttributes updatedInstructor = instructorsDb.updateInstructorByEmail(updateOptions); <END> boolean isOriginalInstructorDisplayed = originalInstructor.isDisplayedToStudents(); verifyAtLeastOneInstructorIsDisplayed(originalInstructor.courseId, isOriginalInstructorDisplayed, updatedInstructor.isDisplayedToStudents()); return instructorsDb.updateInstructorByEmail(updateOptions); }</code><technical_language>This update instructor, meaning check is meaningless</technical_language>

Target:
public InstructorAttributes updateInstructorByEmail(InstructorAttributes.UpdateOptionsWithEmail updateOptions) throws InvalidParametersException, EntityDoesNotExistException { Assumption.assertNotNull("Supplied parameter was null", updateOptions); InstructorAttributes originalInstructor = instructorsDb.getInstructorForEmail(updateOptions.getCourseId(), updateOptions.getEmail()); if (originalInstructor == null) { throw new EntityDoesNotExistException("Trying to update non-existent Entity: " + updateOptions); } InstructorAttributes newInstructor = originalInstructor.getCopy(); newInstructor.update(updateOptions); boolean isOriginalInstructorDisplayed = originalInstructor.isDisplayedToStudents(); verifyAtLeastOneInstructorIsDisplayed(originalInstructor.courseId, isOriginalInstructorDisplayed, newInstructor.isDisplayedToStudents()); return instructorsDb.updateInstructorByEmail(updateOptions); }
Source:
<code>public static SQLException getJdbcSQLException(int errorCode) { <START> return getJdbcSQLException(errorCode, null); <END> }</code><technical_language>getJdbcSQLException(errorCode, (Throwable) null) renaming of methods, this call is ambiguous</technical_language>

Target:
public static SQLException getJdbcSQLException(int errorCode) { return getJdbcSQLException(errorCode, (Throwable)null); }
Source:
<code><START> static BasicLocationDefinition localhost(String id) { <END> return new BasicLocationDefinition(id, "localhost", "localhost", null); }</code><technical_language>Dislike package scope, is needed protected public</technical_language>

Target:
protected static BasicLocationDefinition localhost(String id) { return new BasicLocationDefinition(id, "localhost", "localhost", null); }
Source:
<code>public void testToBuilder() { CloudBigtableConfiguration underTest = new CloudBigtableConfiguration(PROJECT, ZONE, CLUSTER, Collections.singletonMap("somekey", "somevalue")); CloudBigtableConfiguration copy = underTest.toBuilder().build(); <START> Assert.assertTrue(underTest != copy); <END> Assert.assertEquals(underTest, copy); }</code><technical_language>nit: assertNotSame()</technical_language>

Target:
public void testToBuilder() { CloudBigtableConfiguration underTest = new CloudBigtableConfiguration(PROJECT, ZONE, CLUSTER, Collections.singletonMap("somekey", "somevalue")); CloudBigtableConfiguration copy = underTest.toBuilder().build(); Assert.assertNotSame(underTest, copy); Assert.assertEquals(underTest, copy); }
Source:
<code>public void should_call_all_listeners_on_verify() { RememberingListener listener1 = new RememberingListener(); RememberingListener listener2 = new RememberingListener(); MockingProgress mockingProgress = ThreadSafeMockingProgress.mockingProgress(); mockingProgress.addListener(listener1); mockingProgress.addListener(listener2); Foo foo = mock(Foo.class); VerificationMode never = never(); verify(foo, never).doSomething(""); <START> assertThatHasBeenNotified(listener1, foo, never, invocationWanted); <END> assertThatHasBeenNotified(listener2, foo, never, invocationWanted); }</code><technical_language>good methods failing for reasons. assert here</technical_language>

Target:
public void should_call_all_listeners_on_verify() { RememberingListener listener2 = new RememberingListener(); mockitoFramework.addListener(listener2); Foo foo = mock(Foo.class); VerificationMode never = never(); verify(foo, never).doSomething(""); assertThat(listener).is(notifiedFor(foo, never, invocationWanted)); assertThat(listener2).is(notifiedFor(foo, never, invocationWanted)); }
Source:
<code>public Box get(long boxId) throws IOException { Box o = boxStore.get(boxId); if (authorizationManager.readCheck(o)) return o; <START> else throw new IOException("User " + authorizationManager.getCurrentUser().getFullName() + " cannot read Box " + boxId); <END> }</code><technical_language>authorizationManager#throwIfNotReadable</technical_language>

Target:
public Box get(long boxId) throws IOException { Box o = boxStore.get(boxId); authorizationManager.throwIfNotReadable(o); return o; }
Source:
<code>private static double pvbpPayment(PricingEnvironment env, RatePaymentPeriod paymentPeriod) { double df = env.discountFactor(paymentPeriod.getCurrency(), paymentPeriod.getPaymentDate()); ArgChecker.isTrue(!paymentPeriod.getFxReset().isPresent()); double notional = paymentPeriod.getNotional(); <START> ArgChecker.isTrue(paymentPeriod.getAccrualPeriods().size() == 1); <END> RateAccrualPeriod accrualPeriod = paymentPeriod.getAccrualPeriods().get(0); ArgChecker.isTrue(accrualPeriod.getRateObservation() instanceof FixedRateObservation); return df * accrualPeriod.getYearFraction() * notional; }</code><technical_language>arg checkers top of method</technical_language>

Target:
private static double pvbpPayment(PricingEnvironment env, RatePaymentPeriod paymentPeriod) { ArgChecker.isTrue(!paymentPeriod.getFxReset().isPresent()); ArgChecker.isTrue(paymentPeriod.getAccrualPeriods().size() == 1); RateAccrualPeriod accrualPeriod = paymentPeriod.getAccrualPeriods().get(0); ArgChecker.isTrue(accrualPeriod.getRateObservation() instanceof FixedRateObservation); double df = env.discountFactor(paymentPeriod.getCurrency(), paymentPeriod.getPaymentDate()); double notional = paymentPeriod.getNotional(); return df * accrualPeriod.getYearFraction() * notional; }
Source:
<code>public DataBundle generateJsonData() { DataBundle dataBundle = new DataBundle(); dataBundle.accounts = generateAccounts(); dataBundle.courses = generateCourses(); dataBundle.instructors = generateInstructors(); dataBundle.students = generateStudents(); dataBundle.feedbackQuestions = generateFeedbackQuestions(); <START> dataBundle.feedbackSessions = generateFeedbackSessions(); <END> dataBundle.feedbackResponses = generateFeedbackResponses(); dataBundle.feedbackResponseComments = generateFeedbackResponseComments(); dataBundle.profiles = generateProfiles(); return dataBundle; }</code><technical_language>Irrelevant changes</technical_language>

Target:
public DataBundle generateJsonData() { DataBundle dataBundle = new DataBundle(); dataBundle.accounts = generateAccounts(); dataBundle.courses = generateCourses(); dataBundle.instructors = generateInstructors(); dataBundle.students = generateStudents(); dataBundle.feedbackSessions = generateFeedbackSessions(); dataBundle.feedbackQuestions = generateFeedbackQuestions(); dataBundle.feedbackResponses = generateFeedbackResponses(); dataBundle.feedbackResponseComments = generateFeedbackResponseComments(); dataBundle.profiles = generateProfiles(); return dataBundle; }
Source:
<code>public void processTimer(ComputationContext context, String key, long timestamp) { refreshMetricsIfNeeded(); log.debug("start update metrics: " + metrics.size()); <START> List<LatencyMetric> toRemove = metrics.stream() <END> .filter(metric -> metric.update(getManager(), codec)) .collect(Collectors.toList()); toRemove.forEach(LatencyMetric::destroy); toRemove.forEach(metric -> invalidStreams.add(metric.getStream())); metrics.removeAll(toRemove); context.setTimer("tracker", System.currentTimeMillis() + intervalMs); }</code><technical_language>suggestion log.debug("start update metrics: {}", metrics::size);</technical_language>

Target:
public void processTimer(ComputationContext context, String key, long timestamp) { refreshMetricsIfNeeded(); log.debug("start update metrics: {}", metrics::size); List<LatencyMetric> toRemove = metrics.stream() .filter(metric -> metric.update(getManager(), codec)) .collect(Collectors.toList()); toRemove.forEach(LatencyMetric::destroy); toRemove.forEach(metric -> invalidStreams.add(metric.getStream())); metrics.removeAll(toRemove); context.setTimer("tracker", System.currentTimeMillis() + intervalMs); }
Source:
<code>default void bindEntityClass(Class<?> entityClass, EntityDictionary dictionary) { <START> <END> try { dictionary.lookupEntityClass(entityClass); } catch (IllegalArgumentException e) { return; } dictionary.bindEntity(entityClass); dictionary.getAttributes(entityClass) .stream() .forEach((attribute) -> { JPQLFilterFragment annotation = dictionary.getAttributeOrRelationAnnotation(entityClass, JPQLFilterFragment.class, attribute); if (annotation != null) { try { FilterTranslator.registerJPQLGenerator(annotation.operator(), entityClass, attribute, annotation.generator().newInstance()); } catch (InstantiationException | IllegalAccessException e) { throw new IllegalStateException(e); } } }); }</code><technical_language>extra lines</technical_language>

Target:
default void bindEntityClass(Class<?> entityClass, EntityDictionary dictionary) { try { dictionary.lookupEntityClass(entityClass); } catch (IllegalArgumentException e) { return; } dictionary.bindEntity(entityClass); dictionary.getAttributes(entityClass) .stream() .forEach((attribute) -> { JPQLFilterFragment annotation = dictionary.getAttributeOrRelationAnnotation(entityClass, JPQLFilterFragment.class, attribute); if (annotation != null) { try { FilterTranslator.registerJPQLGenerator(annotation.operator(), entityClass, attribute, annotation.generator().newInstance()); } catch (InstantiationException | IllegalAccessException e) { LOGGER.error("Unable to instantiate the JPQL fragment generator: {}", e.getMessage()); throw new IllegalStateException(e); } } }); }
Source:
<code><START> public final int compareTo(final Object other) { <END> final Cookie o = (Cookie) other; int retVal = 0; if (getName() == null && o.getName() != null) return -1; if (getName() != null && o.getName() == null) return 1; retVal = (getName() == null && o.getName() == null) ? 0 : getName().compareTo(o.getName()); if (retVal != 0) return retVal; if (getPath() == null && o.getPath() != null) return -1; if (getPath() != null && o.getPath() == null) return 1; retVal = (getPath() == null && o.getPath() == null) ? 0 : getPath().compareTo(o.getPath()); if (retVal != 0) return retVal; if (getDomain() == null && o.getDomain() != null) return -1; if (getDomain() != null && o.getDomain() == null) return 1; retVal = (getDomain() == null && o.getDomain() == null) ? 0 : getDomain().compareTo(o.getDomain()); if (retVal != 0) return retVal; return 0; }</code><technical_language>@ropalka @fl4via this default impl in interface? AFAICT calls interface methods, a default impl. avoids making incompatible change in a public interface</technical_language>

Target:
public final int compareTo(final Object other) { return Cookie.super.compareTo(other); }
Source:
<code>public void recordEventAsync(StramEvent ev) { <START> if (apexPluginManager != null) { <END> apexPluginManager.dispatch(STRAM_EVENT, ev); } if (eventBus != null) { eventBus.publishAsync(ev); } }</code><technical_language>plugin manager listen event bus, get event bus it? able get access other types of events listening bus</technical_language>

Target:
public void recordEventAsync(StramEvent ev) { apexPluginDispatcher.dispatch(STRAM_EVENT, ev); if (eventBus != null) { eventBus.publishAsync(ev); } }
Source:
<code>public void testBindingCteAssociationToEntity() { transactional(new TxVoidWork() { @Override <START> public void work(EntityManager em) { <END> CriteriaBuilder<MyEntity> select = cbf.create(em, MyEntity.class) .withRecursive(Cte.class) .from(MyEntity.class, "a") .bind("myEntity").select("a") .bind("id").select("1") .unionAll() .from(MyEntity.class, "a") .where("a.attribute").eq("bogus") .bind("myEntity").select("a") .bind("id").select("1") .end() .from(Cte.class) .select("myEntity"); List<MyEntity> resultList = select .getResultList(); String sql = ((CustomSQLTypedQuery) select.getQuery()).getQuerySpecification().getSql(); String cteBase = sql.substring(sql.indexOf("\nselect") + 1, sql.lastIndexOf("UNION ALL") - 1); String cteRecursivePart = sql.substring(sql.indexOf("UNION ALL")+10, sql.lastIndexOf("select")-3); String queryPart = sql.substring(sql.lastIndexOf("select")); assertEquals("Recursive base part should project 2 columns separated by a single comma", cteBase.indexOf(","), cteBase.lastIndexOf(",")); assertEquals("Recursive part should project 2 columns separated by a single comma", cteRecursivePart.indexOf(","), cteRecursivePart.lastIndexOf(",")); assertEquals("Final query should project 2 columns separated by a single comma", queryPart.indexOf(","), queryPart.lastIndexOf(",")); } }); }</code><technical_language>Please add a note MySQL, Oracle Hibernate 4.2 4.3 supported</technical_language>

Target:
public void testBindingCteAssociationToEntity() { transactional(new TxVoidWork() { @Override public void work(EntityManager em) { CriteriaBuilder<MyEntity> select = cbf.create(em, MyEntity.class) .withRecursive(Cte.class) .from(MyEntity.class, "a") .bind("myEntity").select("a") .bind("id").select("1") .unionAll() .from(MyEntity.class, "a") .where("a.attribute").eq("bogus") .bind("myEntity").select("a") .bind("id").select("1") .end() .from(Cte.class) .select("myEntity"); select.getResultList(); String sql = ((CustomSQLTypedQuery) select.getQuery()).getQuerySpecification().getSql(); String cteBase = sql.substring(sql.indexOf("\nselect") + 1, sql.lastIndexOf("UNION ALL") - 1); String cteRecursivePart = sql.substring(sql.indexOf("UNION ALL")+10, sql.lastIndexOf("select")-3); String queryPart = sql.substring(sql.lastIndexOf("select")); assertEquals("Recursive base part should project 2 columns separated by a single comma", cteBase.indexOf(","), cteBase.lastIndexOf(",")); assertEquals("Recursive part should project 2 columns separated by a single comma", cteRecursivePart.indexOf(","), cteRecursivePart.lastIndexOf(",")); assertEquals("Final query should project 2 columns separated by a single comma", queryPart.indexOf(","), queryPart.lastIndexOf(",")); } }); }
Source:
<code>public ResponseEntity<CustomPageImpl<UserLicensesDTO>> getLicenses( @ModelAttribute PageDTO pageDTO, @RequestParam(name = "queryUser", defaultValue = "") String query, @RequestParam(name = "pendingOnly", defaultValue = "false") Boolean pendingOnly) { PageRequest pageRequest = new PageRequest(pageDTO.getPage() - 1, pageDTO.getPageSize()); final Page<AthenaUser> users = userService.getUsersWithLicenses(pageRequest, query, pendingOnly); List<UserLicensesDTO> dtos = converterUtils.convertList(users.getContent(), UserLicensesDTO.class); CustomPageImpl<UserLicensesDTO> resultPage = new CustomPageImpl<>(dtos, pageRequest, users.getTotalElements()); <START> return ResponseEntity.ok(resultPage); <END> }</code><technical_language>entity</technical_language>

Target:
public Page<UserLicensesDTO> getLicenses( @ModelAttribute PageDTO pageDTO, @RequestParam(name = "queryUser", defaultValue = "") String query, @RequestParam(name = "pendingOnly", defaultValue = "false") Boolean pendingOnly) { PageRequest pageRequest = new PageRequest(pageDTO.getPage() - 1, pageDTO.getPageSize()); final Page<AthenaUser> users = userService.getUsersWithLicenses(pageRequest, query, pendingOnly); List<UserLicensesDTO> dtos = converterUtils.convertList(users.getContent(), UserLicensesDTO.class); return new CustomPageImpl(dtos, pageRequest, users.getTotalElements()); }
Source:
<code>protected boolean isVersion21OrHigher() { String version = null; if (getTargetObject() != null) { URI uri = getTargetObject().eResource().getURI(); <START> IFile tempFile = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(uri.toPlatformString(true))); <END> IProject project = tempFile.getProject(); version = SwitchYardModelUtils.getSwitchYardProjectRuntimeVersion(project); } if (version != null && (version.startsWith("2.0") || version.startsWith("1"))) { return false; } return true; }</code><technical_language>a project stored of workspace location</technical_language>

Target:
protected boolean isVersion21OrHigher() { String version = null; if (getTargetObject() != null) { URI uri = getTargetObject().eResource().getURI(); IFile tempFile = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(uri.toPlatformString(true))); if (tempFile != null) { IProject project = tempFile.getProject(); version = SwitchYardModelUtils.getSwitchYardProjectRuntimeVersion(project); } } if (version != null && (version.startsWith("2.0") || version.startsWith("1"))) { return false; } return true; }
Source:
<code>public String getSqlOrder() { <START> return "SELECT ST_Transform(the_geom, targetCRSCode [or 'EPSG:4326']) from myTable"; <END> }</code><technical_language>I replace targetCRSCode [or 'EPSG:4326'] targetCRSCode | 'EPSG:4326'. capitalize FROM</technical_language>

Target:
public String getSqlOrder() { return "SELECT ST_Transform(the_geom, targetCRSCode | 'EPSG:4326') from myTable"; }
Source:
<code>public void shouldSetJettyBaseToValueOfJettyHome() { when(systemEnvironment.getPropertyImpl("jetty.home")).thenReturn("foo"); <START> JettyWorkDirValidator jettyWorkDirValidator = new JettyWorkDirValidator(systemEnvironment); <END> Validation val = new Validation(); jettyWorkDirValidator.validate(val); assertThat(val.isSuccessful(), is(true)); verify(systemEnvironment).setProperty("jetty.base", "foo"); }</code><technical_language>Pull this out a field initialise setup</technical_language>

Target:
public void shouldSetJettyBaseToValueOfJettyHome() { when(systemEnvironment.getPropertyImpl("jetty.home")).thenReturn("foo"); Validation val = new Validation(); jettyWorkDirValidator.validate(val); assertThat(val.isSuccessful(), is(true)); verify(systemEnvironment).setProperty("jetty.base", "foo"); }
Source:
<code>public void doSetup() throws Exception { final byte[] password = "password".getBytes("UTF-8"); crc32 = DigestManager.instantiate(ThreadLocalRandom.current().nextLong(0, Long.MAX_VALUE), password, DigestType.CRC32); crc32c = DigestManager.instantiate(ThreadLocalRandom.current().nextLong(0, Long.MAX_VALUE), password, DigestType.CRC32C); mac = DigestManager.instantiate(ThreadLocalRandom.current().nextLong(0, Long.MAX_VALUE), password, DigestType.MAC); digestBuf = Unpooled.buffer(getDigestManager(digest).getMacCodeLength()); <START> final int entrySizeKb = 64; <END> arrayBackedBuffer = Unpooled.wrappedBuffer(randomBytes(entrySizeKb * 1024)); final int headerSize = 32 + getDigestManager(digest).getMacCodeLength(); notArrayBackedBuffer = DoubleByteBuf.get(Unpooled.wrappedBuffer(randomBytes(headerSize)), Unpooled.wrappedBuffer((randomBytes(entrySizeKb * 1024 - headerSize)))); byteBufDefaultAlloc = ByteBufAllocator.DEFAULT.buffer(entrySizeKb * 1024, entrySizeKb * 1024); byteBufDefaultAlloc.writeBytes(randomBytes(entrySizeKb * 1024)); if (!arrayBackedBuffer.hasArray() || notArrayBackedBuffer.hasArray()) { throw new IllegalStateException("buffers in invalid state"); } }</code><technical_language>worth comparing entry sizes</technical_language>

Target:
public void doSetup() throws Exception { final byte[] password = "password".getBytes("UTF-8"); crc32 = DigestManager.instantiate(ThreadLocalRandom.current().nextLong(0, Long.MAX_VALUE), password, DigestType.CRC32); crc32c = DigestManager.instantiate(ThreadLocalRandom.current().nextLong(0, Long.MAX_VALUE), password, DigestType.CRC32C); mac = DigestManager.instantiate(ThreadLocalRandom.current().nextLong(0, Long.MAX_VALUE), password, DigestType.MAC); digestBuf = Unpooled.buffer(getDigestManager(digest).getMacCodeLength()); arrayBackedBuffer = Unpooled.wrappedBuffer(randomBytes(entrySize)); final int headerSize = 32 + getDigestManager(digest).getMacCodeLength(); notArrayBackedBuffer = DoubleByteBuf.get(Unpooled.wrappedBuffer(randomBytes(headerSize)), Unpooled.wrappedBuffer((randomBytes(entrySize - headerSize)))); byteBufDefaultAlloc = ByteBufAllocator.DEFAULT.buffer(entrySize, entrySize); byteBufDefaultAlloc.writeBytes(randomBytes(entrySize)); if (!arrayBackedBuffer.hasArray() || notArrayBackedBuffer.hasArray()) { throw new IllegalStateException("buffers in invalid state"); } }
Source:
<code>public static void check( LogTailScanner tailScanner, Config config ) throws UpgradeNotAllowedByConfigurationException { if ( !config.get( GraphDatabaseSettings.allow_upgrade ) ) { LogEntryVersion latestLogEntryVersion = tailScanner.getTailInformation().latestLogEntryVersion; if ( latestLogEntryVersion != null && LogEntryVersion.moreRecentVersionExists( latestLogEntryVersion ) ) { <START> String message = "The version your upgrading to is using a new transaction log format. This is a " + <END> "non-reversible upgrade and you wont be able to downgrade after starting"; throw new UpgradeNotAllowedByConfigurationException( message ); } } }</code><technical_language>-></technical_language>

Target:
public static void check( LogTailScanner tailScanner, Config config ) throws UpgradeNotAllowedByConfigurationException { if ( !config.get( GraphDatabaseSettings.allow_upgrade ) ) { LogEntryVersion latestLogEntryVersion = tailScanner.getTailInformation().latestLogEntryVersion; if ( latestLogEntryVersion != null && LogEntryVersion.moreRecentVersionExists( latestLogEntryVersion ) ) { String message = "The version you're upgrading to is using a new transaction log format. This is a " + "non-reversible upgrade and you wont be able to downgrade after starting"; throw new UpgradeNotAllowedByConfigurationException( message ); } } }
Source:
<code>public void execute() throws ServerApiException { try { <START> LinkDomainToLdapResponse response = _ldapManager.linkDomainToLdap(domainId, type, name, accountType); <END> if(admin!=null) { try { LdapUser ldapUser = _ldapManager.getUser(admin, type, name); if(!ldapUser.isDisabled()) { Account account = _accountService.getActiveAccountByName(admin, domainId); if (account == null) { UserAccount userAccount = _accountService.createUserAccount(admin, "", ldapUser.getFirstname(), ldapUser.getLastname(), ldapUser.getEmail(), null, admin, Account.ACCOUNT_TYPE_DOMAIN_ADMIN, domainId, admin, null, UUID.randomUUID().toString(), UUID.randomUUID().toString(), User.Source.LDAP); response.setAdminId(String.valueOf(userAccount.getAccountId())); s_logger.info("created an account with name " + admin + " in the given domain " + domainId); } else { s_logger.debug("an account with name " + admin + " already exists in the domain " + domainId); } } else { s_logger.debug("ldap user with username "+admin+" is disabled in the given group/ou"); } } catch (NoLdapUserMatchingQueryException e) { s_logger.debug("no ldap user matching username " + admin + " in the given group/ou"); } } response.setObjectName("LinkDomainToLdap"); response.setResponseName(getCommandName()); setResponseObject(response); } catch (final InvalidParameterValueException e) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.toString()); } }</code><technical_language>linkDomainToAdmin() createUserAccount() involves DB updates. in a tx? if call succeeds call fails</technical_language>

Target:
public void execute() throws ServerApiException { try { LinkDomainToLdapResponse response = _ldapManager.linkDomainToLdap(domainId, type, name, accountType); if(admin!=null) { LdapUser ldapUser = null; try { ldapUser = _ldapManager.getUser(admin, type, name); } catch (NoLdapUserMatchingQueryException e) { s_logger.debug("no ldap user matching username " + admin + " in the given group/ou", e); } if (ldapUser != null && !ldapUser.isDisabled()) { Account account = _accountService.getActiveAccountByName(admin, domainId); if (account == null) { try { UserAccount userAccount = _accountService.createUserAccount(admin, "", ldapUser.getFirstname(), ldapUser.getLastname(), ldapUser.getEmail(), null, admin, Account.ACCOUNT_TYPE_DOMAIN_ADMIN, domainId, admin, null, UUID.randomUUID().toString(), UUID.randomUUID().toString(), User.Source.LDAP); response.setAdminId(String.valueOf(userAccount.getAccountId())); s_logger.info("created an account with name " + admin + " in the given domain " + domainId); } catch (Exception e) { s_logger.info("an exception occurred while creating account with name " + admin +" in domain " + domainId, e); } } else { s_logger.debug("an account with name " + admin + " already exists in the domain " + domainId); } } else { s_logger.debug("ldap user with username "+admin+" is disabled in the given group/ou"); } } response.setObjectName("LinkDomainToLdap"); response.setResponseName(getCommandName()); setResponseObject(response); } catch (final InvalidParameterValueException e) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.toString()); } }
Source:
<code>public void destroy(String name) throws CachePersistenceException { <START> if(!started) <END> internalStart(); PersistenceSpace space = knownPersistenceSpaces.remove(name); if (space == null) { destroy(name, new DefaultPersistenceSpaceIdentifier(getDirectoryFor(name)), true); } else { destroy(name, space.identifier, true); } }</code><technical_language>{ } please</technical_language>

Target:
public void destroy(String name) throws CachePersistenceException { boolean wasStarted = false; if (!started) { internalStart(); wasStarted = true; } try { PersistenceSpace space = knownPersistenceSpaces.remove(name); if (space == null) { destroy(name, new DefaultPersistenceSpaceIdentifier(getDirectoryFor(name)), true); } else { destroy(name, space.identifier, true); } } finally { if (wasStarted) { stop(); } } }
Source:
<code>private List<VDS> getGlusterPeers(Guid upServerId) { List<VDS> glusterServers = new ArrayList<VDS>(); VDSReturnValue returnValue = Backend.getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.GlusterHostsList, new VdsIdVDSCommandParametersBase(upServerId)); <START> setSucceeded(returnValue.getSucceeded()); <END> if (getSucceeded()) { glusterServers = (List<VDS>) returnValue.getReturnValue(); } else { getReturnValue().getFault().setError(returnValue.getVdsError().getCode()); getReturnValue().getFault().setMessage(returnValue.getVdsError().getMessage()); AuditLogDirector.log(new AuditLogableBase(upServerId), AuditLogType.GLUSTER_HOST_LIST_FAILED); } return glusterServers; }</code><technical_language>please dont set commands succeeded here, is set true end of command</technical_language>

Target:
private List<VDS> getGlusterPeers(Guid upServerId) { List<VDS> glusterServers = new ArrayList<VDS>(); VDSReturnValue returnValue = Backend.getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.GlusterHostsList, new VdsIdVDSCommandParametersBase(upServerId)); if (!returnValue.getSucceeded()) { getReturnValue().getFault().setError(returnValue.getVdsError().getCode()); getReturnValue().getFault().setMessage(returnValue.getVdsError().getMessage()); AuditLogDirector.log(new AuditLogableBase(upServerId), AuditLogType.GLUSTER_HOST_LIST_FAILED); } return (List<VDS>) returnValue.getReturnValue(); }
Source:
<code>static public void assertNotEquals(String message, double unexpected, double actual, double delta) { if (!doubleIsDifferent(unexpected, actual, delta)) { <START> failEquals(message, actual); <END> } }</code><technical_language>Similarly here, Double.valueOf(actual)</technical_language>

Target:
static public void assertNotEquals(String message, double unexpected, double actual, double delta) { if (!doubleIsDifferent(unexpected, actual, delta)) { failEquals(message, Double.valueOf(actual)); } }
Source:
<code>public void shouldMakeTripletsUpToTen() { final Map<String, Integer> searchData = new HashMap<>(); <START> searchData.put(PythagoreanTriplet.MAX_FACTOR, 10); <END> final List<Long> actual = PythagoreanTriplet.createTripletsList(searchData) .stream() .map(t -> t.calculateProduct()) .sorted((p1, p2) -> Double.compare(p1, p2)) .collect(Collectors.toList()); final List<Long> expected = Arrays.asList(60l, 480l); assertEquals(expected, actual); }</code><technical_language>referencing a constant defined in example code... code practitioner exercise is fetched. legit include a starter class includes constants</technical_language>

Target:
public void shouldMakeTripletsUpToTen() { final List<Long> actual = PythagoreanTriplet .makeTripletsList() .withFactorsLessThanOrEqualTo(10) .build() .stream() .map(t -> t.calculateProduct()) .sorted() .collect(Collectors.toList()); final List<Long> expected = Arrays.asList(60l, 480l); assertEquals(expected, actual); }
Source:
<code>public Linkifier(GitilesUrls urls, Config config) { this.urls = checkNotNull(urls, "urls"); List<CommentLinkInfo> list = new ArrayList<>(); list.add(new CommentLinkInfo(HTTP_URL_PATTERN, "$0")); Set<String> subsections = config.getSubsections(COMMENTLINK); List<String> patterns = new ArrayList<>(); patterns.add(HTTP_URL_PATTERN.pattern()); patterns.add(CHANGE_ID_PATTERN.pattern()); for (String subsection : subsections) { String match = config.getString("commentlink", subsection, "match"); String link = config.getString("commentlink", subsection, "link"); String html = config.getString("commentlink", subsection, "html"); <START> if (html != null) log.warn( "Beware: html in commentlinks is unsupported in gitiles; " + "Did you copy it from a gerrit config?"); <END> checkArgument(!Strings.isNullOrEmpty(match), "invalid commentlink.%s.match", subsection); Pattern compiledPattern = Pattern.compile(match); list.add(new CommentLinkInfo(compiledPattern, link)); patterns.add(match); } this.commentLinks = Collections.unmodifiableList(list); allPattern = Pattern.compile(Joiner.on('|').join(patterns)); }</code><technical_language>Please put 'if' body a separate line, surrounded braces: if (html != null) { log.warn(...)</technical_language>

Target:
public Linkifier(GitilesUrls urls, Config config) { this.urls = checkNotNull(urls, "urls"); List<CommentLinkInfo> list = new ArrayList<>(); list.add(new CommentLinkInfo(HTTP_URL_PATTERN, "$0")); Set<String> subsections = config.getSubsections(COMMENTLINK); List<String> patterns = new ArrayList<>(); patterns.add(HTTP_URL_PATTERN.pattern()); patterns.add(CHANGE_ID_PATTERN.pattern()); for (String subsection : subsections) { String match = config.getString("commentlink", subsection, "match"); String link = config.getString("commentlink", subsection, "link"); String html = config.getString("commentlink", subsection, "html"); if (html != null) log.warn("Beware: html in commentlinks is unsupported in gitiles; " + "Did you copy it from a gerrit config?"); if (Strings.isNullOrEmpty(match)) { log.warn("invalid commentlink.%s.match", subsection); } Pattern compiledPattern = Pattern.compile(match); list.add(new CommentLinkInfo(compiledPattern, link)); patterns.add(match); } this.commentLinks = Collections.unmodifiableList(list); allPattern = Pattern.compile(Joiner.on('|').join(patterns)); }
Source:
<code>public void shouldCreateFutureFromCompletedJavaCompletableFuture() { <START> CompletableFuture<Integer> jFuture = CompletableFuture.completedFuture(1); <END> final Future<Integer> future = Future.fromCompletableFuture(jFuture); assertCompleted(future, 1); }</code><technical_language>minor: final</technical_language>

Target:
public void shouldCreateFutureFromCompletedJavaCompletableFuture() { final CompletableFuture<Integer> jFuture = CompletableFuture.completedFuture(1); final Future<Integer> future = Future.fromCompletableFuture(jFuture); assertCompleted(future, 1); }
Source:
<code>private boolean consoleEditorHadFocusLast() { <START> AceEditor editor = editorFocusTracker_.getLastFocusedEditor(); <END> if (editor == null) return false; String id = editor.getWidget().getElement().getId(); return "rstudio_console_input".equals(id); }</code><technical_language>this need work source windows? (If so, DocFocusedEvent SourceWindowManager.getLastFocusedSourceWindowId)</technical_language>

Target:
private boolean consoleEditorHadFocusLast() { String id = MainWindowObject.get(MainWindowObject.LAST_FOCUSED_EDITOR); return "rstudio_console_input".equals(id); }
Source:
<code>private static Repository[] getRepositories(boolean warn, @NonNull IStructuredSelection selection, Shell shell) { <START> List<Repository> repositories = new ArrayList<>(); <END> IPath[] locations = getSelectedLocations(selection); if (GitTraceLocation.SELECTION.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.SELECTION.getLocation(), "selection=" + selection + ", locations=" + Arrays.toString(locations)); for (IPath location : locations) { RepositoryMapping mapping = RepositoryMapping.getMapping(location); Repository repo; if (mapping != null) { repo = mapping.getRepository(); } else { repo = org.eclipse.egit.core.Activator.getDefault() .getRepositoryCache().getRepository(location); } if (repo != null) { repositories.add(repo); } } if (repositories.size() == 0) { for (Object o : selection.toArray()) { Repository nextRepo = AdapterUtils.adapt(o, Repository.class); if (nextRepo != null) { repositories.add(nextRepo); } } } if (repositories.size() == 0) { if (warn) MessageDialog.openError(shell, UIText.RepositoryAction_errorFindingRepoTitle, UIText.RepositoryAction_errorFindingRepo); return null; } return repositories.toArray(new Repository[repositories.size()]); }</code><technical_language>This a Set avoid duplicates</technical_language>

Target:
private static Repository[] getRepositories(boolean warn, @NonNull IStructuredSelection selection, Shell shell) { Set<Repository> repositories = new HashSet<>(); Set<Object> elements = getSelectionContents(selection); if (GitTraceLocation.SELECTION.isActive()) { GitTraceLocation.getTrace().trace( GitTraceLocation.SELECTION.getLocation(), "selection=" + selection + ", elements=" + elements.toString()); } for (Object location : elements) { Repository repo = null; if (location instanceof Repository) { repo = (Repository) location; } else if (location instanceof IResource) { repo = ResourceUtil.getRepository((IResource) location); } else if (location instanceof IPath) { repo = ResourceUtil.getRepository((IPath) location); } if (repo != null) { repositories.add(repo); } } if (repositories.size() == 0) { for (Object o : selection.toArray()) { Repository nextRepo = AdapterUtils.adapt(o, Repository.class); if (nextRepo != null) { repositories.add(nextRepo); } } } if (repositories.isEmpty()) { if (warn) { MessageDialog.openError(shell, UIText.RepositoryAction_errorFindingRepoTitle, UIText.RepositoryAction_errorFindingRepo); } return null; } return repositories.toArray(new Repository[repositories.size()]); }
Source:
<code>private boolean executeRequest(HttpGet request) { request.setConfig(config); try { HttpResponse response = client.execute(request); return response.getStatusLine().getStatusCode() == STATUS_OK; } catch (Exception e) { <START> return false; <END> } }</code><technical_language>A suggestion: extend verification class error message. API users</technical_language>

Target:
private Verification executeRequest(HttpGet request) { request.setConfig(config); try { HttpResponse response = client.execute(request); int status = response.getStatusLine().getStatusCode(); if (status == STATUS_OK) { return new Verification(true); } else { return new Verification(false, Integer.toString(status)); } } catch (Exception e) { LOGGER.error("Error verifying connection", e); return new Verification(false, e.toString()); } }
Source:
<code>private void slaveWithPlainMechanism() throws Exception { getDomainMasterClient().execute(changePresentedMechanisms("master", new HashSet<>(Arrays.asList("PLAIN")))); getDomainSlaveClient().execute(changeSaslMechanism("slave", "PLAIN")); reloadSlave(); testSupport.getDomainSlaveLifecycleUtil().awaitHostController(System.currentTimeMillis()); readHostControllerStatus(getDomainMasterClient()); getDomainMasterClient().execute(changePresentedMechanisms("master", new HashSet<>(Arrays.asList("DIGEST-MD5")))); getDomainSlaveClient().execute(changeSaslMechanism("slave", "DIGEST-MD5")); reloadSlave(); testSupport.getDomainSlaveLifecycleUtil().awaitHostController(System.currentTimeMillis()); assertTrue("Host \"slave\" did not reconnect to master with plain mechanism.", hostRunning(FAILED_RELOAD_TIMEOUT_MILLIS)); <START> readHostControllerStatus(domainMasterClient); <END> }</code><technical_language>L129 L130 redundant. This is OT this PR other of hostRunning in this class kind of sucks. AIUI basically means test wait for 10 secs waiting for slave *not* reauth. need more clever</technical_language>

Target:
private void slaveWithPlainMechanism() throws Exception { getDomainMasterClient().execute(changePresentedMechanisms("master", new HashSet<>(Arrays.asList("PLAIN")))); getDomainSlaveClient().execute(changeSaslMechanism("slave", "PLAIN")); reloadSlave(); testSupport.getDomainSlaveLifecycleUtil().awaitHostController(System.currentTimeMillis()); readHostControllerStatus(getDomainMasterClient()); getDomainMasterClient().execute(changePresentedMechanisms("master", new HashSet<>(Arrays.asList("DIGEST-MD5")))); getDomainSlaveClient().execute(changeSaslMechanism("slave", "DIGEST-MD5")); reloadSlave(); testSupport.getDomainSlaveLifecycleUtil().awaitHostController(System.currentTimeMillis()); assertTrue("Host \"slave\" did not reconnect to master with plain mechanism.", hostRunning(FAILED_RELOAD_TIMEOUT_MILLIS)); }
Source:
<code>private final void logAndRaiseIssue(List<PomIssue> issues, String message) { <START> LoggerFactory.getLogger(getClass()).info(message); <END> issues.add((new PomIssue(KEY, message))); }</code><technical_language>need log here, logging is done in MavenSensor class. responsibility of this class is collect PomIssues return in Iterable. I guess this method call issues.add() in places</technical_language>

Target:
private final void logAndRaiseIssue(List<PomIssue> issues, String message) { issues.add((new PomIssue(KEY, message))); }
Source:
<code>public DistStageAck executeOnSlave() { if (!isServiceRunning()) { return errorResponse("Service is not runnning", null); } if (slaveState.getSlaveIndex() == 0) { DistStageAck result = null; Object prevResult = null; <START> Statistics stats = new DefaultStatistics(new DataOperationStats()); <END> stats.begin(); for (int i = 0; i < numExecutions; i++) { prevResult = streamTaskResult; result = executeStreamTask(stats); if (prevResult != null) { if (prevResult.equals(streamTaskResult)) { log.info(i + ": Got the same results for two Stream tasks runs"); } else { log.error(i + ": Did not get the same results for two Stream tasks runs"); break; } } if (result.isError() && exitOnFailure) { break; } } stats.end(); if (storeResultInCache) { try { if (streamTaskResult != null) { basicOperations.getCache(cacheName).put(STREAM_RESULT_KEY, streamTaskResult); } } catch (Exception e) { log.error("Failed to put result object into cache", e); } } log.info("Executed stream stage on slave"); return result; } else { return new StreamStageAck(slaveState); } }</code><technical_language>Stats configurable, too</technical_language>

Target:
public DistStageAck executeOnSlave() { if (!isServiceRunning()) { return errorResponse("Service is not runnning", null); } DistStageAck result = null; Object prevResult = null; Statistics stats = statisticsPrototype.copy(); stats.begin(); for (int i = 0; i < numExecutions; i++) { prevResult = streamTaskResult; result = executeStreamTask(stats); if (prevResult != null) { if (prevResult.equals(streamTaskResult)) { log.info(i + ": Got the same results for two Stream tasks runs"); } else { log.error(i + ": Did not get the same results for two Stream tasks runs"); break; } } if (result.isError() && exitOnFailure) { break; } } stats.end(); log.info("Executed stream stage on slave"); return result; }
Source:
<code>public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException { try { String symbol = null; if (params instanceof TradeHistoryParamCurrencyPair && ((TradeHistoryParamCurrencyPair) params).getCurrencyPair() != null) { symbol = BitfinexAdapters.adaptCurrencyPair( ((TradeHistoryParamCurrencyPair) params).getCurrencyPair()); } long startTime = 0; Long endTime = null; Long limit = 50L; if (params instanceof TradeHistoryParamsTimeSpan) { TradeHistoryParamsTimeSpan paramsTimeSpan = (TradeHistoryParamsTimeSpan) params; startTime = DateUtils.toMillisNullSafe(paramsTimeSpan.getStartTime()); endTime = DateUtils.toMillisNullSafe(paramsTimeSpan.getEndTime()); } <START> if (params instanceof TradeHistoryParamPaging) { <END> TradeHistoryParamPaging pagingParams = (TradeHistoryParamPaging) params; Integer pageLength = pagingParams.getPageLength(); Integer pageNum = pagingParams.getPageNumber(); limit = (pageLength != null && pageNum != null) ? pageLength * (pageNum + 1) : 50L; } if (params instanceof TradeHistoryParamLimit) { TradeHistoryParamLimit tradeHistoryParamLimit = (TradeHistoryParamLimit) params; limit = Long.valueOf(tradeHistoryParamLimit.getLimit()); } final List<Trade> trades = getBitfinexTradesV2(symbol, startTime, endTime, limit); return BitfinexAdapters.adaptTradeHistoryV2(trades); } catch (BitfinexException e) { throw BitfinexErrorAdapter.adapt(e); } }</code><technical_language>I remove this entire if pageNumber BitfinexTradeHistoryParams this implementation in common actual paging</technical_language>

Target:
public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException { try { String symbol = null; if (params instanceof TradeHistoryParamCurrencyPair && ((TradeHistoryParamCurrencyPair) params).getCurrencyPair() != null) { symbol = BitfinexAdapters.adaptCurrencyPair( ((TradeHistoryParamCurrencyPair) params).getCurrencyPair()); } long startTime = 0; Long endTime = null; Long limit = 50L; Long sort = null; if (params instanceof TradeHistoryParamsTimeSpan) { TradeHistoryParamsTimeSpan paramsTimeSpan = (TradeHistoryParamsTimeSpan) params; startTime = DateUtils.toMillisNullSafe(paramsTimeSpan.getStartTime()); endTime = DateUtils.toMillisNullSafe(paramsTimeSpan.getEndTime()); } if (params instanceof TradeHistoryParamLimit) { TradeHistoryParamLimit tradeHistoryParamLimit = (TradeHistoryParamLimit) params; limit = Long.valueOf(tradeHistoryParamLimit.getLimit()); } if (params instanceof TradeHistoryParamsSorted) { TradeHistoryParamsSorted tradeHistoryParamsSorted = (TradeHistoryParamsSorted) params; sort = tradeHistoryParamsSorted.getOrder() == TradeHistoryParamsSorted.Order.asc ? 1L : -1L; } final List<Trade> trades = getBitfinexTradesV2(symbol, startTime, endTime, limit, sort); return BitfinexAdapters.adaptTradeHistoryV2(trades); } catch (BitfinexException e) { throw BitfinexErrorAdapter.adapt(e); } }
Source:
<code>public TkWithAliasHeader(final Base base, final Take take) { this.base = base; this.take = take; this.header = <START> String.format("%s: %s", "X-Netbout-Alias", "%s"); <END> }</code><technical_language>@kujtimiihoxha "X-Netbout-Alias: %s"</technical_language>

Target:
public TkWithAliasHeader(final Base base, final Take take) { this.base = base; this.take = take; }
Source:
<code>ZKUpdater(Collection<Account> accounts) { this.accounts = accounts; Pair<String, Path> backupPrefixAndPath = null; if (accountService.backupDirPath != null) { try { backupPrefixAndPath = accountService.reserveBackupFile(); } catch (IOException e) { <START> logger.error("Error reserving backup file", e); <END> } } this.backupPrefixAndPath = backupPrefixAndPath; }</code><technical_language>if backup file created? skip backups</technical_language>

Target:
ZKUpdater(Collection<Account> accounts) { this.accounts = accounts; Pair<String, Path> backupPrefixAndPath = null; try { backupPrefixAndPath = backup.reserveBackupFile(); } catch (IOException e) { logger.error("Error reserving backup file", e); } this.backupPrefixAndPath = backupPrefixAndPath; }
Source:
<code>public GrpcCallTracker(StreamObserver<?> streamObserver) { if (!(streamObserver instanceof ServerCallStreamObserver)) { <START> throw new IllegalStateException("Call tacking is supported for server streams."); <END> } mStreamObserver = (ServerCallStreamObserver) streamObserver; }</code><technical_language>"tacking" -> "tracking" "is supported" => "is supported" Also, include instance type of streamObserver in message</technical_language>

Target:
public GrpcCallTracker(StreamObserver<?> streamObserver) { if (!(streamObserver instanceof ServerCallStreamObserver)) { throw new IllegalStateException(String.format( "Call tracking is only supported for server streams. Passed stream type: %s", streamObserver.getClass().getSimpleName())); } mStreamObserver = (ServerCallStreamObserver) streamObserver; }
Source:
<code>public void recognizePiiEntity() { String document = "My SSN is 555-55-5555"; textAnalyticsClient.recognizePiiEntities(document).forEach(piiEntity -> <START> System.out.printf("Recognized Personally Identifiable Information entity: %s, category: %s, subCategory: %s, score: %f.%n", <END> piiEntity.getText(), piiEntity.getCategory(), piiEntity.getSubcategory(), piiEntity.getConfidenceScore())); }</code><technical_language>including offset length again. print too</technical_language>

Target:
public void recognizePiiEntity() { String document = "My SSN is 859-98-0987"; textAnalyticsClient.recognizePiiEntities(document).forEach(entity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, entity category: %s, entity subcategory: %s," + " confidence score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore())); }
Source:
<code>protected static boolean tableExists(TableReference tableReference) { <START> Iterator<TableReference> it = NodesDownTestSetup.db.getAllTableNames().iterator(); <END> while (it.hasNext()) { if (it.next().equals(tableReference)) { return true; } } return false; }</code><technical_language>This replaced with: return NodesDownTestSetup.db.getAllTableNames().contains(tableReference);</technical_language>

Target:
protected static boolean tableExists(TableReference tableReference) { return NodesDownTestSetup.kvs.getAllTableNames().contains(tableReference); }
Source:
<code>private void initProgressIndicator() { progressIndicator = new SimplePanel(); getContainer().insert(progressIndicator, 0); getDetailModel().getPropertyChangedEvent().addListener((ev, sender, args) -> progressIndicator.getElement().setInnerSafeHtml(getDetailModel().isNetworkOperationInProgress() ? templates.networkUpdatingSpinner(constants.networkUpdating()) : <START> templates.noHtml() <END> ) ); }</code><technical_language>replace with: SafeHtmlUtils.fromTrustedString("")</technical_language>

Target:
private void initProgressIndicator() { progressIndicator = new SimplePanel(); getContainer().insert(progressIndicator, 0); getDetailModel().getPropertyChangedEvent().addListener((ev, sender, args) -> progressIndicator.getElement().setInnerSafeHtml(getDetailModel().isNetworkOperationInProgress() ? templates.networkUpdatingSpinner(constants.networkUpdating()) : SafeHtmlUtils.fromTrustedString("") ) ); }