auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ImportVmTemplateCommand(ImportVmTemplateParameters parameters) { super(parameters); setVmTemplate(parameters.getVmTemplate()); parameters.setEntityInfo(new EntityInfo(VdcObjectType.VmTemplate, getVmTemplateId())); setStoragePoolId(parameters.getStoragePoolId()); setVdsGroupId(parameters.getVdsGroupId()); setStorageDomainId(parameters.getStorageDomainId()); <START> ImportUtils.updateGraphicsDevices(getVmTemplate(), getVmTemplate().getCompatibilityVersion()); <END> }</code><technical_language>verify flow? if cluster is set template get in parameters</technical_language>

Target:
public ImportVmTemplateCommand(ImportVmTemplateParameters parameters) { super(parameters); setVmTemplate(parameters.getVmTemplate()); parameters.setEntityInfo(new EntityInfo(VdcObjectType.VmTemplate, getVmTemplateId())); setStoragePoolId(parameters.getStoragePoolId()); setClusterId(parameters.getClusterId()); setStorageDomainId(parameters.getStorageDomainId()); setEffectiveCompatibilityVersion(CompatibilityVersionUtils.getEffective(getVmTemplate(), this::getCluster)); ImportUtils.updateGraphicsDevices(getVmTemplate(), getEffectiveCompatibilityVersion()); }
Source:
<code>private void isConsentCookieSetToAccepted() { <START> final String cookieValue = driver.manage().getCookieNamed("euconsent").getValue(); <END> Assertion.assertEquals(cookieValue.length(), 48, "Incorrect length of accepted euconsent value"); }</code><technical_language>If extract part in get cookie length a separate method (for example getEuConsentCookieLength()), able re-use in isConsentCookieSetToAccepted() isConsentCookieSetToRejected() shorter</technical_language>

Target:
private void isConsentCookieSetToAccepted() { Assertion.assertEquals( getEuConsentCookieValue().length(), 48, "Incorrect length of accepted euconsent value" ); }
Source:
<code>public String getImageURLFromGallery(String articleName) { for (WebElement page : categoryGalleryItems) { if (page.findElement(By.cssSelector("a")).getAttribute("title").equals(articleName)) { <START> return page.findElement(By.cssSelector("img")).getAttribute("src"); <END> } } return null; }</code><technical_language>if is element image</technical_language>

Target:
public String getImageURLFromGallery(String articleName) { for (WebElement page : categoryGalleryItems) { if (page.findElement(By.cssSelector("a")).getAttribute("title").equals(articleName)) { return page.findElement(By.cssSelector("img")).getAttribute("src"); } } throw new NoSuchElementException( String.format("Could not find article with name %s", articleName)); }
Source:
<code>public void shouldThrowConflictExceptionWhenCreatingAccountWithExistingName() throws Exception { AccountImpl account = accounts[0]; account.setName(accounts[1].getName()); <START> accountDao.create(account); <END> }</code><technical_language>try create user existing name id. ensure conflict is thrown of names conflct is needed rewrite this test AccountImpl account = new AccountImpl(NameGenerator.generate("account", 5), accounts[0].getName(), "test"); accountDao.create(account);</technical_language>

Target:
public void shouldThrowConflictExceptionWhenCreatingAccountWithExistingName() throws Exception { AccountImpl account = new AccountImpl(NameGenerator.generate("account", 5), accounts[0].getName(), "test"); accountDao.create(account); }
Source:
<code><START> public void searchExternalGroups(final String searchFilter, <END> final AsyncCallback<List<AccountGroup.ExternalNameKey>> callback) { final Collection<GroupReference> groups = groupBackend.suggest("ldapgroup/" + searchFilter); final List<AccountGroup.ExternalNameKey> matches = Lists.newArrayListWithCapacity(groups.size()); for (GroupReference ref : groups) { int index = ref.getUUID().get().indexOf(':'); if ((index >= 0) && !internalGroupBackend.handles(ref.getUUID())) { matches.add(new AccountGroup.ExternalNameKey( ref.getUUID().get().substring(index + 1))); } } Collections.sort(matches); callback.onSuccess(matches); }</code><technical_language>imho this die part of change, UI code related it. this is merged new ldap group references new ldap backend directly, mirrored internal group backend</technical_language>

Target:
public void searchExternalGroups(final String searchFilter, final AsyncCallback<List<AccountGroup.ExternalNameKey>> callback) { String prefix; switch (authConfig.getAuthType()) { case HTTP_LDAP: case LDAP: case LDAP_BIND: case CLIENT_SSL_CERT_LDAP: prefix = "ldapgroup/"; break; default: callback.onSuccess(Collections.<AccountGroup.ExternalNameKey>emptyList()); return; } final Collection<GroupReference> groups = groupBackend.suggest(prefix + searchFilter); final List<AccountGroup.ExternalNameKey> matches = Lists.newArrayListWithCapacity(groups.size()); for (GroupReference ref : groups) { int index = ref.getUUID().get().indexOf(':'); if ((index >= 0) && !internalGroupBackend.handles(ref.getUUID())) { matches.add(new AccountGroup.ExternalNameKey( ref.getUUID().get().substring(index + 1))); } } Collections.sort(matches); callback.onSuccess(matches); }
Source:
<code>public boolean matches(@Nonnull InventoryCrafting inv, @Nonnull World world) { List<ItemStack> items = Lists.newArrayListWithCapacity(inv.getSizeInventory()); for (int i = 0; i < inv.getSizeInventory(); ++i) { ItemStack itemstack = inv.getStackInSlot(i); if (!itemstack.isEmpty()) { items.add(itemstack); } } int size = items.size(); <START> if (size > 0) <END> { int[] stackSelectedItem = new int[size + 1], stackSelectedIngredient = new int[size + 1]; boolean[] isItemSelected = new boolean[size], isIngredientSelected = new boolean[this.input.size()]; int pointer = 1; while (pointer > 0) { for (int i = stackSelectedItem[pointer]; i < size; ++i) { if (!isItemSelected[i]) { ItemStack itemstack = items.get(i); for (int j = this.input.size() - 1; j >= 0; --j) { if (!isIngredientSelected[j] && this.input.get(j).apply(itemstack)) { stackSelectedIngredient[pointer] = j; stackSelectedItem[pointer++] = i; isIngredientSelected[j] = true; isItemSelected[i] = true; i = -1; break; } } if (pointer > size) { return size == this.input.size(); } } } isIngredientSelected[stackSelectedIngredient[--pointer]] = false; isItemSelected[stackSelectedItem[pointer]++] = false; } } return false; }</code><technical_language>if (size == input.size())</technical_language>

Target:
public boolean matches(@Nonnull InventoryCrafting inv, @Nonnull World world) { int ingredientCount = 0; RecipeItemHelper recipeItemHelper = new RecipeItemHelper(); for (int i = 0; i < inv.getSizeInventory(); ++i) { ItemStack itemstack = inv.getStackInSlot(i); if (!itemstack.isEmpty()) { ++ingredientCount; recipeItemHelper.accountStack(itemstack); } } return ingredientCount == this.input.size() && recipeItemHelper.canCraft(this, null); }
Source:
<code>LocalPaxosComponents(TimelockPaxosMetrics metrics, PaxosUseCase paxosUseCase, Path legacyLogDirectory, Path sqliteLogDirectory, UUID leaderUuid, boolean canCreateNewClients) { this.metrics = metrics; this.paxosUseCase = paxosUseCase; this.baseLogDirectory = legacyLogDirectory; <START> this.sqliteLogDirectory = paxosUseCase.logDirectoryRelativeToDataDirectory(sqliteLogDirectory).toAbsolutePath(); <END> this.leaderUuid = leaderUuid; this.memoizedBatchAcceptor = Suppliers.memoize(this::createBatchAcceptor); this.memoizedBatchLearner = Suppliers.memoize(this::createBatchLearner); this.memoizedBatchPingableLeader = Suppliers.memoize(this::createBatchPingableLeader); this.canCreateNewClients = canCreateNewClients; }</code><technical_language>This sqliteLogDirectory: need separate SQLite instances for of cases</technical_language>

Target:
LocalPaxosComponents(TimelockPaxosMetrics metrics, PaxosUseCase paxosUseCase, Path legacyLogDirectory, Path sqliteLogDirectory, UUID leaderUuid, boolean canCreateNewClients) { this.metrics = metrics; this.paxosUseCase = paxosUseCase; this.baseLogDirectory = legacyLogDirectory; this.sqliteLogDirectory = sqliteLogDirectory; this.leaderUuid = leaderUuid; this.memoizedBatchAcceptor = Suppliers.memoize(this::createBatchAcceptor); this.memoizedBatchLearner = Suppliers.memoize(this::createBatchLearner); this.memoizedBatchPingableLeader = Suppliers.memoize(this::createBatchPingableLeader); this.canCreateNewClients = canCreateNewClients; }
Source:
<code>public ActionForward createDEAStandaloneGratuityPR(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws FenixServiceException { final DegreeCurricularPlan degreeCurricularPlan = getDegreeCurricularPlan(request); InstallmentBean installment = getInstallment(); StandaloneInstallmentBean standaloneInstallment = null; <START> if (installment instanceof StandaloneInstallmentBean) { <END> standaloneInstallment = (StandaloneInstallmentBean) installment; if (!installment.hasRequiredInformation()) { addActionMessage("installment", request, "label.payments.postingRules.paymentPlan.information.to.create.installment.is.all.required"); return createDEAGratuityPRInvalid(mapping, form, request, response); } } try { PostingRulesManager.createDEAStandaloneGratuityPostingRule(standaloneInstallment, degreeCurricularPlan); } catch (DomainException e) { addActionMessage(request, e.getKey(), e.getArgs()); return createDEAGratuityPRInvalid(mapping, form, request, response); } return showPostGraduationDegreeCurricularPlanPostingRules(mapping, form, request, response); }</code><technical_language>is necessary verify class type? this method called create a Standalone Gratuity</technical_language>

Target:
public ActionForward createDEAStandaloneGratuityPR(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws FenixServiceException { final DegreeCurricularPlan degreeCurricularPlan = getDegreeCurricularPlan(request); InstallmentBean installment = getInstallment(); StandaloneInstallmentBean standaloneInstallment = (StandaloneInstallmentBean) installment; if (!installment.hasRequiredInformation()) { addActionMessage("installment", request, "label.payments.postingRules.paymentPlan.information.to.create.installment.is.all.required"); return createDEAGratuityPRInvalid(mapping, form, request, response); } try { PostingRulesManager.createDEAStandaloneGratuityPostingRule(standaloneInstallment, degreeCurricularPlan); } catch (DomainException e) { PaymentPlanBean paymentPlanEditor = new PaymentPlanBean(ExecutionYear.readCurrentExecutionYear()); request.setAttribute("degreeCurricularPlan", degreeCurricularPlan); request.setAttribute("paymentPlanEditor", paymentPlanEditor); request.setAttribute("installmentEditor", installment); addActionMessage(request, e.getKey(), e.getArgs()); return mapping.findForward("createDEAGratuityPR"); } return showPostGraduationDegreeCurricularPlanPostingRules(mapping, form, request, response); }
Source:
<code>public void setOnTitleClickListener(final OnClickListener listener) { if (listener != null) { <START> title.setOnClickListener(listener); <END> } }</code><technical_language>wrong setting listener null if guarding for null listeners</technical_language>

Target:
public void setOnTitleClickListener(final OnClickListener listener) { title.setOnClickListener(listener); }
Source:
<code>public String validateSchema(FormDataMultiPart multiPart) { Schema schema = getSchemaFromMultiPart(multiPart); try { <START> List<TableConfig> tableConfigs = getTableConfigsForSchema(schema.getSchemaName()); <END> SchemaUtils.validate(schema, tableConfigs); } catch (Exception e) { throw new ControllerApplicationException(LOGGER, "Invalid schema: " + schema.getSchemaName() + ". Reason: " + e.getMessage(), Response.Status.BAD_REQUEST, e); } return schema.toPrettyJsonString(); }</code><technical_language>I if this (along getTableConfigsForSchema function) moved validate ? caller do this single time (and done implicitly)</technical_language>

Target:
public String validateSchema(FormDataMultiPart multiPart) { Schema schema = getSchemaFromMultiPart(multiPart); try { List<TableConfig> tableConfigs = _pinotHelixResourceManager.getTableConfigsForSchema(schema.getSchemaName()); SchemaUtils.validate(schema, tableConfigs); } catch (Exception e) { throw new ControllerApplicationException(LOGGER, "Invalid schema: " + schema.getSchemaName() + ". Reason: " + e.getMessage(), Response.Status.BAD_REQUEST, e); } return schema.toPrettyJsonString(); }
Source:
<code>public void init(FilterConfig filterConfig) throws ServletException { <START> dirAllowed = Context.getConfig().getBoolean("media.dirAllowed"); <END> }</code><technical_language>I prefer full words. For example directoryAllow</technical_language>

Target:
public void init(FilterConfig filterConfig) throws ServletException { }
Source:
<code>@Override public Integer exitStatus(FilePath workspace, Launcher launcher) throws IOException, InterruptedException { Integer status = super.exitStatus(workspace, launcher); if (status != null) { LOGGER.log(Level.FINE, "found exit code {0} in {1}", new Object[] {status, controlDir}); return status; } long now = System.nanoTime(); if (lastCheck == 0) { LOGGER.log(Level.FINE, "starting check in {0}", controlDir); lastCheck = now; } else if (now > lastCheck + TimeUnit.SECONDS.toNanos(HEARTBEAT_CHECK_INTERVAL)) { lastCheck = now; long currentTimestamp = getLogFile(workspace).lastModified(); if (currentTimestamp == 0) { LOGGER.log(Level.FINE, "apparently never started in {0}", controlDir); return recordExitStatus(workspace, -2); <START> } else if (checkedTimestamp > 0 && currentTimestamp < checkedTimestamp + TimeUnit.SECONDS.toMillis(HEARTBEAT_MINIMUM_DELTA)) { <END> LOGGER.log(Level.FINE, "heartbeat touches apparently not running in {0}", controlDir); return recordExitStatus(workspace, -1); } else { checkedTimestamp = currentTimestamp; LOGGER.log(Level.FINE, "seeing recent log file modifications in {0}", controlDir); } } return null; }</code><technical_language>Need check absolute of timestamp differences -- covered if agent clock skewed NTP runs reset clocks (possible earlier time). more (have introduce production issues in distributed systems timestamps). skew a build report report HEARTBEAT_MINIMUM valid skews order of a *OR* large -- this cover clock skew case better</technical_language>

Target:
@Override public Integer exitStatus(FilePath workspace, Launcher launcher) throws IOException, InterruptedException { Integer status = super.exitStatus(workspace, launcher); if (status != null) { LOGGER.log(Level.FINE, "found exit code {0} in {1}", new Object[] {status, controlDir}); return status; } long now = System.nanoTime(); if (lastCheck == 0) { LOGGER.log(Level.FINE, "starting check in {0}", controlDir); lastCheck = now; } else if (now > lastCheck + TimeUnit.SECONDS.toNanos(HEARTBEAT_CHECK_INTERVAL)) { lastCheck = now; long currentTimestamp = getLogFile(workspace).lastModified(); if (currentTimestamp == 0) { LOGGER.log(Level.FINE, "apparently never started in {0}", controlDir); return recordExitStatus(workspace, -2); } else if (checkedTimestamp > 0) { if (currentTimestamp < checkedTimestamp) { LOGGER.log(Level.WARNING, "apparent clock skew in {0}", controlDir); } else if (currentTimestamp < checkedTimestamp + TimeUnit.SECONDS.toMillis(HEARTBEAT_MINIMUM_DELTA)) { FilePath pidFile = pidFile(workspace); if (pidFile.exists()) { LOGGER.log(Level.FINE, "still have {0} so heartbeat checks unreliable; process may or may not be alive", pidFile); } else { LOGGER.log(Level.FINE, "heartbeat touches apparently not running in {0}", controlDir); return recordExitStatus(workspace, -1); } } } else { LOGGER.log(Level.FINE, "seeing recent log file modifications in {0}", controlDir); } checkedTimestamp = currentTimestamp; } return null; }
Source:
<code>public void shouldGetEncountersByEncounterTypeAndPatient() throws Exception { executeDataSet("EncountersForDifferentTypesWithObservations.xml"); SimpleObject result = deserialize(handle(newGetRequest(getURI(), new Parameter("s","default"),new Parameter("patient", "41c6b35e-c093-11e3-be87-005056821db0"), new Parameter("encounterType", "ff7397ea-c090-11e3-be87-005056821db0")))); <START> Assert.assertEquals(1,((ArrayList)result.get("results")).size()); <END> }</code><technical_language>if assert a property ensure right</technical_language>

Target:
public void shouldGetEncountersByEncounterTypeAndPatient() throws Exception { executeDataSet("EncountersForDifferentTypesWithObservations.xml"); SimpleObject result = deserialize(handle(newGetRequest(getURI(), new Parameter("s","default"),new Parameter("patient", "41c6b35e-c093-11e3-be87-005056821db0"), new Parameter("encounterType", "ff7397ea-c090-11e3-be87-005056821db0")))); ArrayList encounters = (ArrayList) result.get("results"); Assert.assertEquals(1, encounters.size()); String encounterUuid = (String) PropertyUtils.getProperty(encounters.get(0), "uuid"); Assert.assertEquals("62967e68-96bb-11e0-8d6b-9b9415a91465", encounterUuid); }
Source:
<code>private <T> T tryExecuteTransactionLoop(SessionWork<T> sessionWork, boolean readWriteTransaction, boolean readOnlyEntities) { Throwable lastException = null; int dampingFactor = PASchedulerProperties.SCHEDULER_DB_TRANSACTION_DAMPING_FACTOR.getValueAsInt(); int delay = PASchedulerProperties.SCHEDULER_DB_TRANSACTION_SLEEP_DELAY.getValueAsInt(); int maximumNumberOfRetries = Math.max(PASchedulerProperties.SCHEDULER_DB_TRANSACTION_MAXIMUM_RETRIES.getValueAsInt(), 0); for (int i = 0; i <= maximumNumberOfRetries; i++) { try { return tryExecuteTransaction(sessionWork, readWriteTransaction, readOnlyEntities); <START> } catch (DatabaseManagerException e) { <END> throw e; } catch (Throwable exception) { lastException = exception; logger.warn(String.format("Database operation failed. Automatic retry in %d ms (attempt %d)", delay, i), exception); new Sleeper(delay, logger).sleep(); delay *= dampingFactor; } } logger.warn("Maximum number of transaction retries exceeded, giving up. Last exception is: ", lastException); throw new DatabaseManagerException(lastException); }</code><technical_language>I IllegalArgumentException thrown well, check if other expected exception</technical_language>

Target:
private <T> T tryExecuteTransactionLoop(SessionWork<T> sessionWork, boolean readWriteTransaction, boolean readOnlyEntities) { Throwable lastException = null; int dampingFactor = PASchedulerProperties.SCHEDULER_DB_TRANSACTION_DAMPING_FACTOR.getValueAsInt(); int delay = PASchedulerProperties.SCHEDULER_DB_TRANSACTION_SLEEP_DELAY.getValueAsInt(); int maximumNumberOfRetries = Math.max(PASchedulerProperties.SCHEDULER_DB_TRANSACTION_MAXIMUM_RETRIES.getValueAsInt(), 0); for (int i = 0; i <= maximumNumberOfRetries; i++) { try { return tryExecuteTransaction(sessionWork, readWriteTransaction, readOnlyEntities); } catch (DatabaseManagerException | IllegalArgumentException e) { throw e; } catch (Throwable exception) { lastException = exception; logger.warn(String.format("Database operation failed. Automatic retry in %d ms (attempt %d)", delay, i), exception); new Sleeper(delay, logger).sleep(); delay *= dampingFactor; } } logger.warn("Maximum number of transaction retries exceeded, giving up. Last exception is: ", lastException); throw new DatabaseManagerException(lastException); }
Source:
<code>public static String creationDateFormat( final Date date ) { <START> return CREATION_DATE_FORMAT.format(date); <END> }</code><technical_language>SimpleDateFormat is thread safe, share threads. static instance _can_ threads this method is static, safe this change</technical_language>

Target:
public static String creationDateFormat( final Date date ) { return CREATION_DATE_FORMAT.format(date.toInstant()); }
Source:
<code>protected BufferedImage readImage(Blob blob) { try { <START> return readImage(blob.getStream()); <END> } catch (IOException e) { throw new UncheckedIOException(e); } }</code><technical_language>Blob''s stream closed right</technical_language>

Target:
protected BufferedImage readImage(Blob blob) { try (InputStream is = blob.getStream()) { return readImage(is); } catch (IOException e) { throw new UncheckedIOException(e); } }
Source:
<code>private static String _getNight(final long time) { final Calendar cal = GregorianCalendar.getInstance(); cal.setTimeInMillis(time); final int ampm = cal.get(Calendar.AM_PM); final Calendar endCal; final int startDay; final int endDay; if (ampm == Calendar.AM) { endCal = (Calendar) cal.clone(); endDay = cal.get(Calendar.DAY_OF_MONTH); cal.add(Calendar.DAY_OF_MONTH, -1); startDay = cal.get(Calendar.DAY_OF_MONTH); } else { startDay = cal.get(Calendar.DAY_OF_MONTH); cal.add(Calendar.DAY_OF_MONTH, 1); endCal = cal; endDay = cal.get(Calendar.DAY_OF_MONTH); } final StringBuilder buf = new StringBuilder(); buf.append(startDay).append("/").append(endDay).append(" "); <START> final DateFormat f = new SimpleDateFormat("yyyy-MMM-dd"); <END> buf.append(f.format(endCal.getTime())); return buf.toString(); }</code><technical_language>This formatted date escape XML file is written. I if parses String else. I leave this one</technical_language>

Target:
private static String _getNight(final long time) { final Calendar cal = GregorianCalendar.getInstance(); cal.setTimeInMillis(time); final int ampm = cal.get(Calendar.AM_PM); final Calendar endCal; final int startDay; final int endDay; if (ampm == Calendar.AM) { endCal = (Calendar) cal.clone(); endDay = cal.get(Calendar.DAY_OF_MONTH); cal.add(Calendar.DAY_OF_MONTH, -1); startDay = cal.get(Calendar.DAY_OF_MONTH); } else { startDay = cal.get(Calendar.DAY_OF_MONTH); cal.add(Calendar.DAY_OF_MONTH, 1); endCal = cal; endDay = cal.get(Calendar.DAY_OF_MONTH); } final StringBuilder buf = new StringBuilder(); buf.append(startDay).append("/").append(endDay).append(" "); final DateFormat f = new SimpleDateFormat("MMM yyyy"); buf.append(f.format(endCal.getTime())); return buf.toString(); }
Source:
<code>public void testGetEmailInfo() throws MessagingException { String email = "receiver@gmail.tmt"; String from = "sender@gmail.tmt"; String subject = "email subject"; <START> if (Config.isUsingSendgrid()) { <END> Sendgrid message = new Sendgrid(Config.SENDGRID_USERNAME, Config.SENDGRID_PASSWORD); message.addTo(email); message.setFrom(from); message.setSubject(subject); message.setHtml("<h1>email body</h1>"); assertEquals("[Email sent]to=receiver@gmail.tmt|from=sender@gmail.tmt|subject=email subject", Emails.getEmailInfo(message)); } else { Session session = Session.getDefaultInstance(new Properties(), null); MimeMessage message = new MimeMessage(session); message.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); message.setFrom(new InternetAddress(from)); message.setSubject(subject); message.setContent("<h1>email body</h1>", "text/html"); assertEquals("[Email sent]to=receiver@gmail.tmt|from=sender@gmail.tmt|subject=email subject", Emails.getEmailInfo(message)); } }</code><technical_language>do need this if-else branch here? test irrespective of email service is used</technical_language>

Target:
public void testGetEmailInfo() throws MessagingException, JSONException { String email = "receiver@gmail.tmt"; String from = "sender@gmail.tmt"; String subject = "email subject"; ______TS("Sendgrid message"); Sendgrid message = new Sendgrid(Config.SENDGRID_USERNAME, Config.SENDGRID_PASSWORD); message.addTo(email); message.setFrom(from); message.setSubject(subject); message.setHtml("<h1>email body</h1>"); assertEquals("[Email sent]to=receiver@gmail.tmt|from=sender@gmail.tmt|subject=email subject", Emails.getEmailInfo(message)); ______TS("MimeMessage"); Session session = Session.getDefaultInstance(new Properties(), null); MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setSubject(subject); mimeMessage.setContent("<h1>email body</h1>", "text/html"); assertEquals("[Email sent]to=receiver@gmail.tmt|from=sender@gmail.tmt|subject=email subject", Emails.getEmailInfo(mimeMessage)); }
Source:
<code>private Optional<String> getNormalizedAssetPath(NinjaProperties ninjaProperties){ Optional<String> assetBaseDir = Optional.absent(); String baseDir = ninjaProperties.get( "application.static.asset.basedir"); if(baseDir != null){ <START> String pathSeparator = baseDir.substring( baseDir.length() - 1 ); <END> if(!pathSeparator.matches( "[/\\\\]" )){ baseDir += File.separator; } assetBaseDir = Optional.of(baseDir); } return assetBaseDir; }</code><technical_language>Guava's Files.simplifyPath. Saves some lines..</technical_language>

Target:
private Optional<String> getNormalizedAssetPath(NinjaProperties ninjaProperties){ String baseDir = ninjaProperties.get( NinjaConstant.APPLICATION_STATIC_ASSET_BASEDIR ); return Optional.fromNullable(FilenameUtils.normalizeNoEndSeparator(baseDir)); }
Source:
<code>public ServerCnxnFactory getServerCnxnFactory() { if (secureServerCnxnFactory != null) { return secureServerCnxnFactory; <START> } <END> return serverCnxnFactory; }</code><technical_language>to, instead of mix secureServerCnxnFactory in getServerCnxnFactory, add a separate method getSecureServerCnxnFactory? This maps existing set method setSecureServerCnxnFactory. Caller explicitly call both, is more work, semantics more clear</technical_language>

Target:
public ServerCnxnFactory getServerCnxnFactory() { return serverCnxnFactory; }
Source:
<code>void reallocate(PooledByteBuf<T> buf, int newCapacity, boolean freeOldMemory) { assert newCapacity >= 0 && newCapacity <= buf.maxCapacity(); int oldCapacity = buf.length; if (oldCapacity == newCapacity) { return; } PoolChunk<T> oldChunk = buf.chunk; ByteBuffer oldNioBuffer = buf.tmpNioBuf; long oldHandle = buf.handle; T oldMemory = buf.memory; int oldOffset = buf.offset; int oldMaxLength = buf.maxLength; allocate(parent.threadCache(), buf, newCapacity); int bytesToCopy; if (newCapacity > oldCapacity) { bytesToCopy = oldCapacity; } else { buf.trimIndicesToCapacity(newCapacity); bytesToCopy = newCapacity; } if (bytesToCopy > 0) { <START> oldNioBuffer = memoryCopy(oldMemory, oldNioBuffer, oldOffset, buf, bytesToCopy); <END> } if (freeOldMemory) { free(oldChunk, oldNioBuffer, oldHandle, oldMaxLength, buf.cache); } }</code><technical_language>hmm is this correct ? This duplicate is passed free(...)</technical_language>

Target:
void reallocate(PooledByteBuf<T> buf, int newCapacity, boolean freeOldMemory) { assert newCapacity >= 0 && newCapacity <= buf.maxCapacity(); int oldCapacity = buf.length; if (oldCapacity == newCapacity) { return; } PoolChunk<T> oldChunk = buf.chunk; ByteBuffer oldNioBuffer = buf.tmpNioBuf; long oldHandle = buf.handle; T oldMemory = buf.memory; int oldOffset = buf.offset; int oldMaxLength = buf.maxLength; allocate(parent.threadCache(), buf, newCapacity); int bytesToCopy; if (newCapacity > oldCapacity) { bytesToCopy = oldCapacity; } else { buf.trimIndicesToCapacity(newCapacity); bytesToCopy = newCapacity; } memoryCopy(oldMemory, oldOffset, buf, bytesToCopy); if (freeOldMemory) { free(oldChunk, oldNioBuffer, oldHandle, oldMaxLength, buf.cache); } }
Source:
<code><START> public Map<String, ?> exportUsers() { <END> Map<String, Object> exportMap = new HashMap<>(); Map<Long, List<Seat>> seatMap = seatService.getAllSeats().stream(). collect(Collectors.groupingBy(seat -> seat.getUser().getId())); exportMap.put("users", ticketService.getAllTickets().stream().map(Ticket::getOwner) .map(user -> new UserExportDTO(user.getEmail(), user.getPassword(), user.getId(), seatMap.get(user.getId()))).collect(Collectors.toList())); exportMap.put("teams", teamService.getAllTeams().stream() .map(team -> new TeamExportDTO(team.getTeamName(), team.getCaptain().getId(), team.getMembers().stream().map(User::getId).collect(Collectors.toList())))); return exportMap; }</code><technical_language>This function horribly formatted here, needs improve</technical_language>

Target:
public Map<String, ?> exportUsers() { Map<String, Object> exportMap = new HashMap<>(); Map<Long, List<Seat>> seatMap = seatService.getAllSeats().stream() .filter(Seat::isTaken) .collect(Collectors.groupingBy(seat -> seat.getUser().getId())); exportMap.put("users", ticketService.getAllTickets().stream() .filter(Ticket::isValid) .map(Ticket::getOwner) .map(user -> new UserExportDTO(user.getEmail(), user.getPassword(), user.getProfile().getDisplayName(), user.getId(), seatMap.get(user.getId()).stream() .map(Seat::toString).collect(Collectors.toList()))) .collect(Collectors.toList())); exportMap.put("teams", teamService.getAllTeams().stream() .map(team -> new TeamExportDTO(team.getTeamName(), team.getCaptain().getId(), team.getMembers().stream() .map(User::getId).collect(Collectors.toList())))); return exportMap; }
Source:
<code>public String importUserSkill(ImportUserSkillTO importUserSkills, User user) throws InternalServerErrorException, BadRequestException { List<String> failTechnologies = new ArrayList<>(); for (UserSkillTO userSkill : importUserSkills.getUserSkill()) { String email = userSkill.getEmail(); TechGalleryUser techGalleryUser; try { techGalleryUser = userService.getUserSyncedWithProvider(email.split("@")[0]); for (String techSkill : userSkill.getTechSkill()) { String[] split = techSkill.split(";"); if (!failTechnologies.contains(split[0])) { Technology technology = recoverTechnologyById(split[0]); if (technology != null) { Skill skillEntity = skillDao.findByUserAndTechnology(techGalleryUser, technology); if (skillEntity != null) { log.info("Inactivating skill: " + skillEntity.getId()); skillEntity.setInactivatedDate(new Date()); skillEntity.setActive(Boolean.FALSE); skillDao.update(skillEntity); } Skill skill = new Skill(); skill.setValue(Integer.parseInt(split[1])); addNewSkill(skill, techGalleryUser, technology); } else { failTechnologies.add(split[0]); } } } } catch (NotFoundException e) { <START> log.info(e.getMessage()); <END> } } return null; }</code><technical_language>@felipeaziz I handle this in a more way. thrown? Is logging correct behaviour</technical_language>

Target:
public String importUserSkill(ImportUserSkillTO importUserSkills, User user) throws InternalServerErrorException, BadRequestException { List<String> failTechnologies = new ArrayList<>(); for (UserSkillTO userSkill : importUserSkills.getUserSkill()) { String email = userSkill.getEmail(); TechGalleryUser techGalleryUser; try { techGalleryUser = userService.getUserSyncedWithProvider(email.split("@")[0]); for (String techSkill : userSkill.getTechSkill()) { String[] splitedTechSkill = techSkill.split(";"); if (!failTechnologies.contains(splitedTechSkill[0])) { Technology technology = recoverTechnologyById(splitedTechSkill[0]); if (technology != null) { Skill skillEntity = skillDao.findByUserAndTechnology(techGalleryUser, technology); if (skillEntity != null) { log.info("Inactivating skill: " + skillEntity.getId()); skillEntity.setInactivatedDate(new Date()); skillEntity.setActive(Boolean.FALSE); skillDao.update(skillEntity); } Skill skill = new Skill(); skill.setValue(Integer.parseInt(splitedTechSkill[1])); addNewSkill(skill, techGalleryUser, technology); } else { failTechnologies.add(splitedTechSkill[0]); } } } } catch (NotFoundException e) { log.log(Level.INFO, "User " + userSkill.getEmail() + " not found during import. Row ignored.", e); } } return null; }
Source:
<code>public String toString() { return MoreObjects.toStringHelper(this) .add("_uri", _uri) <START> .add("_version", _version) <END> .add("_name", _name) .toString(); }</code><technical_language>match conventional toString implementation</technical_language>

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("Uri", _uri) .add("Version", _version) .add("Name", _name) .toString(); }
Source:
<code>private void buildSdk(String projectId, ProjectDataType dataType, ClientMessageOutputStream outStream, Project project, FileData sdkFileData) throws IOException, SandboxServiceException { <START> outStream.println("Successfully got SDK."); <END> File rootDir = createTempDirectory("demo-project"); try { outStream.println("Processing project archive..."); String sourceArchiveFile = Environment.getServerHomeDir() + "/" + DEMO_PROJECTS_FOLDER + "/" + project.getSourceArchive(); String rootProjectDir = rootDir.getAbsolutePath(); executeCommand(outStream, new String[]{"tar", "-C", rootProjectDir, "-xzvf", sourceArchiveFile}, null); File sdkFile = new File(rootProjectDir + "/" + project.getSdkLibDir() + "/" + sdkFileData.getFileName()); FileOutputStream fos = FileUtils.openOutputStream(sdkFile); fos.write(sdkFileData.getFileData()); fos.flush(); fos.close(); ProjectDataKey dataKey = new ProjectDataKey(projectId, dataType); if (dataType == ProjectDataType.SOURCE) { buildSdkSource(outStream, rootDir, sourceArchiveFile, rootProjectDir, dataKey); } else { buildBinary(outStream, project, rootDir, dataKey); } } finally { FileUtils.deleteDirectory(rootDir); } }</code><technical_language>This line moved line 501. After: FileData sdkFileData = cacheService.getSdk(project.getId());</technical_language>

Target:
private void buildSdk(String projectId, ProjectDataType dataType, ClientMessageOutputStream outStream, Project project, FileData sdkFileData) throws IOException, SandboxServiceException { File rootDir = createTempDirectory("demo-project"); try { outStream.println("Processing project archive..."); String sourceArchiveFile = Environment.getServerHomeDir() + "/" + DEMO_PROJECTS_FOLDER + "/" + project.getSourceArchive(); String rootProjectDir = rootDir.getAbsolutePath(); executeCommand(outStream, new String[]{"tar", "-C", rootProjectDir, "-xzvf", sourceArchiveFile}, null); File sdkFile = new File(rootProjectDir + "/" + project.getSdkLibDir() + "/" + sdkFileData.getFileName()); FileOutputStream fos = FileUtils.openOutputStream(sdkFile); fos.write(sdkFileData.getFileData()); fos.flush(); fos.close(); ProjectDataKey dataKey = new ProjectDataKey(projectId, dataType); if (dataType == ProjectDataType.SOURCE) { buildSdkSource(outStream, rootDir, sourceArchiveFile, rootProjectDir, dataKey); } else { buildBinary(outStream, project, rootDir, dataKey); } } finally { FileUtils.deleteDirectory(rootDir); } }
Source:
<code>public void testRefFilter() throws Exception { SubscribedRepository r = new SubscribedRepository(publisherConfig .getSubscriber("origin", db.getDirectory().getAbsolutePath())); r.setUpRefs(); Map<String, Ref> refs = r.getRemoteRefs(); <START> assertTrue(refs.containsKey("refs/heads/master")); <END> assertTrue(refs.containsKey("refs/tags/A")); Map<String, Ref> pubsubRefs = r.getPubSubRefs(); assertTrue(pubsubRefs.containsKey("refs/heads/master")); assertTrue(pubsubRefs.containsKey("refs/tags/A")); }</code><technical_language>Assertions keySet</technical_language>

Target:
public void testRefFilter() throws Exception { SubscribedRepository r = new SubscribedRepository(publisherConfig .getSubscriber("origin", db.getDirectory().getAbsolutePath())); r.setUpRefs(); Set<String> refs = r.getRemoteRefs().keySet(); assertEquals(13, refs.size()); assertTrue(refs.contains("refs/heads/master")); assertTrue(refs.contains("refs/tags/A")); Set<String> pubsubRefs = r.getPubSubRefs().keySet(); assertEquals(13, pubsubRefs.size()); assertTrue(pubsubRefs.contains("refs/heads/master")); assertTrue(pubsubRefs.contains("refs/tags/A")); }
Source:
<code>private void initBanner(Context context, ChartboostParams params, ChartboostBannerListener bannerListener) { String location = params.getLocation(); <START> LinearLayout bannerContainer = new LinearLayout(context); LinearLayout.LayoutParams paramsLayout = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); paramsLayout.gravity = Gravity.CENTER_HORIZONTAL; <END> mChartboostBanner = new ChartboostBanner(context, location, params.getBannerSize(), bannerListener); mChartboostBanner.setAutomaticallyRefreshesContent(false); bannerContainer.addView(mChartboostBanner, paramsLayout); }</code><technical_language>Is a reason LinearLayout is preferred banner container? Is FrameLayout a single view (the mChartboostBanner)</technical_language>

Target:
private ChartboostBanner initBanner(Context context, ChartboostParams params, ChartboostBannerListener bannerListener) { String location = params.getLocation(); mBannerContainer = new FrameLayout(context); FrameLayout.LayoutParams paramsLayout = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT); paramsLayout.gravity = Gravity.CENTER_HORIZONTAL; mChartboostBanner = new ChartboostBanner(context, location, params.getBannerSize(), bannerListener); mChartboostBanner.setAutomaticallyRefreshesContent(false); mBannerContainer.addView(mChartboostBanner, paramsLayout); return mChartboostBanner; }
Source:
<code>private void beginLog() throws IOException { if (logs == null) { <START> finishRef(); <END> out.flushFileHeader(); out.setBlockSize(logBlockSize); logs = new Section(LOG_BLOCK_TYPE); } }</code><technical_language>Rename "finishRefAndObjSections" closing index block section index</technical_language>

Target:
private void beginLog() throws IOException { if (logs == null) { finishRefAndObjSections(); out.flushFileHeader(); out.setBlockSize(logBlockSize); logs = new Section(LOG_BLOCK_TYPE); } }
Source:
<code><START> public void initializeSelectorMetrics(final AtomicLong activeConnections) { <END> numActiveConnections = new Gauge<Long>() { @Override public Long getValue() { return activeConnections.get(); } }; }</code><technical_language>this need public</technical_language>

Target:
void initializeSelectorMetrics(final AtomicLong activeConnections) { numActiveConnections = new Gauge<Long>() { @Override public Long getValue() { return activeConnections.get(); } }; }
Source:
<code>public KieServerTypePermission(Set<Class<?>> classes) { super(patterns()); <START> this.classes = classes; <END> }</code><technical_language>@mswiderski if want prevent a NPE creating a new Set in case passed a null one. I a good idea declare Set classes final</technical_language>

Target:
public KieServerTypePermission(Set<Class<?>> classes) { super(patterns()); this.classes = classes == null ? new HashSet<>() : classes; }
Source:
<code>public void sendPhoneVerificationToken() throws Exception { when(service.getNextToken()).thenReturn("012345"); service.sendPhoneVerificationToken(study, USER_ID, TestConstants.PHONE); <START> verify(mockNotificationsService).sendSMSMessage(smsMessageProviderCaptor.capture()); <END> SmsMessageProvider provider = smsMessageProviderCaptor.getValue(); Map<String,String> tokens = provider.getTokenMap(); assertEquals("012-345", tokens.get("sptoken")); assertEquals("2 hours", tokens.get("phoneVerificationExpirationPeriod")); String message = provider.getSmsRequest().getMessage(); assertTrue(message.contains("012-345")); }</code><technical_language>This test verify save token Redis. (Incidentally, this realize I neglected do for email verification.)</technical_language>

Target:
public void sendPhoneVerificationToken() throws Exception { when(service.getNextToken()).thenReturn("012345"); service.sendPhoneVerificationToken(study, USER_ID, TestConstants.PHONE); verify(mockNotificationsService).sendSMSMessage(smsMessageProviderCaptor.capture()); verify(mockCacheProvider).setObject(eq("012345"), stringCaptor.capture(), eq(AccountWorkflowService.VERIFY_OR_RESET_EXPIRE_IN_SECONDS)); String string = stringCaptor.getValue(); JsonNode node = BridgeObjectMapper.get().readTree(string); assertEquals("api", node.get("studyId").textValue()); assertEquals("userId", node.get("userId").textValue()); SmsMessageProvider provider = smsMessageProviderCaptor.getValue(); Map<String,String> tokens = provider.getTokenMap(); assertEquals("012-345", tokens.get("sptoken")); assertEquals("2 hours", tokens.get("phoneVerificationExpirationPeriod")); String message = provider.getSmsRequest().getMessage(); assertTrue(message.contains("012-345")); verifyNoMoreInteractions(mockCacheProvider); }
Source:
<code>Optional<AggregateStateRecord> perform() { Iterator<AggregateEventRecord> historyBackward = storage.historyBackward(request); if (!historyBackward.hasNext()) { return Optional.absent(); } <START> while (historyBackward.hasNext() <END> && snapshot == null) { AggregateEventRecord record = historyBackward.next(); switch (record.getKindCase()) { case EVENT: history.addFirst(record.getEvent()); break; case SNAPSHOT: snapshot = record.getSnapshot(); break; case KIND_NOT_SET: default: throw newIllegalStateException("Event or snapshot missing in record: \"%s\"", shortDebugString(record)); } } AggregateStateRecord result = buildRecord(); return Optional.of(result); }</code><technical_language>Please extract loop a separate method</technical_language>

Target:
Optional<AggregateStateRecord> perform() { Iterator<AggregateEventRecord> historyBackward = storage.historyBackward(request); if (!historyBackward.hasNext()) { return Optional.absent(); } while (historyBackward.hasNext() && snapshot == null) { AggregateEventRecord record = historyBackward.next(); handleRecord(record); } AggregateStateRecord result = buildRecord(); return Optional.of(result); }
Source:
<code>public final LogicalPageKey getLogicalPage( final int page ) { if ( isPaginationFinished() == false ) { throw new IllegalStateException(); } try { return logicalPages.get( page ); } catch ( IndexOutOfBoundsException e ) { throw e; <START> } <END> }</code><technical_language>extra handling IndexOutOfBoundsException is caught, new code behaves way: exception thrown logicalPages.get( page ) thrown back! so, try-catch is dispensable leave code was</technical_language>

Target:
public final LogicalPageKey getLogicalPage( final int page ) { if ( isPaginationFinished() == false ) { throw new IllegalStateException(); } return logicalPages.get( page ); }
Source:
<code>protected void writeBinaryStorageConfiguration( String repositoryName, OperationContext context, ModelNode model, EditableDocument binaries ) throws OperationFailedException { binaries.set(FieldName.TYPE, FieldValue.BINARY_STORAGE_TYPE_S3); String username = ModelAttributes.S3_USERNAME.resolveModelAttribute(context, model).asString(); binaries.setString(FieldName.USER_NAME, username); String password = ModelAttributes.S3_PASSWORD.resolveModelAttribute(context, model).asString(); binaries.setString(FieldName.USER_PASSWORD, password); String bucketName = ModelAttributes.S3_BUCKET_NAME.resolveModelAttribute(context, model).asString(); binaries.setString(FieldName.BUCKET_NAME, bucketName); <START> String endPoint = ModelAttributes.S3_ENDPOINT_URL.resolveModelAttribute(context, model).asString(); <END> binaries.setString(FieldName.ENDPOINT_URL, endPoint); }</code><technical_language>this work correctly if ModelAttributes.S3_ENDPOINT_URL is defined (the asString() part). return undefined instead of null. correct code like: ModelNode node = resolveModelAttribute(); String endpoint = node.isDefined() ? node.asString() : null</technical_language>

Target:
protected void writeBinaryStorageConfiguration( String repositoryName, OperationContext context, ModelNode model, EditableDocument binaries ) throws OperationFailedException { binaries.set(FieldName.TYPE, FieldValue.BINARY_STORAGE_TYPE_S3); String username = ModelAttributes.S3_USERNAME.resolveModelAttribute(context, model).asString(); binaries.setString(FieldName.USER_NAME, username); String password = ModelAttributes.S3_PASSWORD.resolveModelAttribute(context, model).asString(); binaries.setString(FieldName.USER_PASSWORD, password); String bucketName = ModelAttributes.S3_BUCKET_NAME.resolveModelAttribute(context, model).asString(); binaries.setString(FieldName.BUCKET_NAME, bucketName); ModelNode node = ModelAttributes.S3_ENDPOINT_URL.resolveModelAttribute(context, model); String endPoint = node.isDefined() ? node.asString() : null; binaries.setString(FieldName.ENDPOINT_URL, endPoint); }
Source:
<code>public void testReviewArtifactIsFiltered() { ITask task = mock(ITask.class); when(task.getAttribute("ARTIFACT")).thenReturn("true"); TaskReviewArtifactFilter filter = new TaskReviewArtifactFilter(); boolean wasFiltered = !filter.select(null, task); <START> Assert.assertTrue(wasFiltered); <END> }</code><technical_language>static import for Assert.* methods</technical_language>

Target:
public void testReviewArtifactIsFiltered() { ITask task = mock(ITask.class); when(task.getAttribute("ARTIFACT")).thenReturn("true"); TaskReviewArtifactFilter filter = new TaskReviewArtifactFilter(); boolean wasFiltered = !filter.select(null, task); assertTrue(wasFiltered); }
Source:
<code>private void addSupportedGroups(List<SupportedGroup> defaultGroups, PublicKey publicKey) { if (publicKey != null) { SupportedGroup group = SupportedGroup.fromPublicKey(publicKey); if (group != null && group.isUsable() && !defaultGroups.contains(group)) { <START> if (!config.recommendedSupportedGroupsOnly || !group.isRecommended()) { <END> defaultGroups.add(group); } } } }</code><technical_language>suggestion if (!config.recommendedSupportedGroupsOnly || group.isRecommended()) {</technical_language>

Target:
private void addSupportedGroups(List<SupportedGroup> defaultGroups, PublicKey publicKey) { if (publicKey != null) { SupportedGroup group = SupportedGroup.fromPublicKey(publicKey); if (group != null && group.isUsable() && !defaultGroups.contains(group)) { if (!config.recommendedSupportedGroupsOnly || group.isRecommended()) { defaultGroups.add(group); } } } }
Source:
<code>public boolean hasTaskReadyToRun() { TaskContainer nextExecuteTask = executeQueue.peek(); if (nextExecuteTask != null) { if (! nextExecuteTask.running) { return true; <START> } else if (executeQueue.size() > 1) { <END> return true; } } Iterator<TaskContainer> it = scheduledQueue.iterator(); while (it.hasNext()) { TaskContainer scheduledTask = it.next(); if (scheduledTask.getDelayInMillis() <= 0 && ! scheduledTask.running) { return true; } } return false; }</code><technical_language>couldnt this edge case running finished removed is 1 left, ran yet</technical_language>

Target:
public boolean hasTaskReadyToRun() { synchronized (executeQueueRemoveLock) { TaskContainer nextExecuteTask = executeQueue.peek(); if (nextExecuteTask != null) { if (! nextExecuteTask.running) { return true; } else if (executeQueue.size() > 1) { return true; } } } synchronized (scheduledQueue.getModificationLock()) { Iterator<TaskContainer> it = scheduledQueue.iterator(); while (it.hasNext()) { TaskContainer scheduledTask = it.next(); if (scheduledTask.getDelayInMillis() <= 0 && ! scheduledTask.running) { return true; } } } return false; }