Example usage for java.math RoundingMode HALF_UP

List of usage examples for java.math RoundingMode HALF_UP

Introduction

In this page you can find the example usage for java.math RoundingMode HALF_UP.

Prototype

RoundingMode HALF_UP

To view the source code for java.math RoundingMode HALF_UP.

Click Source Link

Document

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.

Usage

From source file:net.sourceforge.fenixedu.presentationTier.Action.directiveCouncil.SummariesControlAction.java

private List<DetailSummaryElement> getExecutionCourseResume(final ExecutionSemester executionSemester,
        Collection<Professorship> professorships) {
    List<DetailSummaryElement> allListElements = new ArrayList<DetailSummaryElement>();
    LocalDate today = new LocalDate();
    LocalDate oneWeekBeforeToday = today.minusDays(8);
    for (Professorship professorship : professorships) {
        BigDecimal summariesGiven = EMPTY, lessonsDeclared = EMPTY;
        BigDecimal givenSumariesPercentage = EMPTY;
        BigDecimal notTaughtSummaries = EMPTY;
        BigDecimal notTaughtSummariesPercentage = EMPTY;
        if (professorship.belongsToExecutionPeriod(executionSemester)
                && !professorship.getExecutionCourse().isMasterDegreeDFAOrDEAOnly()) {
            for (Shift shift : professorship.getExecutionCourse().getAssociatedShifts()) {
                DegreeTeachingService degreeTeachingService = professorship
                        .getDegreeTeachingServiceByShift(shift);
                if (degreeTeachingService != null) {
                    // Get the number of declared lessons
                    lessonsDeclared = getDeclaredLesson(degreeTeachingService.getPercentage(), shift,
                            lessonsDeclared, oneWeekBeforeToday);
                }/*from   w  w w.  j a v  a2s.  co m*/
                // Get the number of summaries given
                summariesGiven = getSummariesGiven(professorship, shift, summariesGiven, oneWeekBeforeToday);
                // Get the number of not taught summaries
                notTaughtSummaries = getNotTaughtSummaries(professorship, shift, notTaughtSummaries,
                        oneWeekBeforeToday);
            }
            summariesGiven = summariesGiven.setScale(1, RoundingMode.HALF_UP);
            notTaughtSummaries = notTaughtSummaries.setScale(1, RoundingMode.HALF_UP);
            lessonsDeclared = lessonsDeclared.setScale(1, RoundingMode.HALF_UP);
            givenSumariesPercentage = getDifference(lessonsDeclared, summariesGiven);
            notTaughtSummariesPercentage = getDifference(lessonsDeclared, notTaughtSummaries);

            Teacher teacher = professorship.getTeacher();
            String categoryName = teacher != null && teacher.getCategory() != null
                    ? teacher.getCategory().getName().getContent()
                    : null;
            String siglas = getSiglas(professorship);

            String teacherEmail = professorship.getPerson().getDefaultEmailAddress() != null
                    ? professorship.getPerson().getDefaultEmailAddress().getPresentationValue()
                    : null;

            DetailSummaryElement listElementDTO = new DetailSummaryElement(professorship.getPerson().getName(),
                    professorship.getExecutionCourse().getNome(),
                    teacher != null ? teacher.getTeacherId() : null, teacherEmail, categoryName,
                    lessonsDeclared, summariesGiven, givenSumariesPercentage, notTaughtSummaries,
                    notTaughtSummariesPercentage, siglas);

            allListElements.add(listElementDTO);
        }
    }
    return allListElements;
}

From source file:org.apache.carbondata.core.scan.executor.util.RestructureUtil.java

/**
 * Method for computing measure default value based on the data type
 *
 * @param columnSchema/*from  w w  w . j  a  va 2s . co m*/
 * @param defaultValue
 * @return
 */
public static Object getMeasureDefaultValue(ColumnSchema columnSchema, byte[] defaultValue) {
    Object measureDefaultValue = null;
    if (!isDefaultValueNull(defaultValue)) {
        String value = null;
        switch (columnSchema.getDataType()) {
        case SHORT:
        case INT:
        case LONG:
            value = new String(defaultValue, Charset.forName(CarbonCommonConstants.DEFAULT_CHARSET));
            measureDefaultValue = Long.parseLong(value);
            break;
        case DECIMAL:
            BigDecimal decimal = DataTypeUtil.byteToBigDecimal(defaultValue);
            if (columnSchema.getScale() > decimal.scale()) {
                decimal = decimal.setScale(columnSchema.getScale(), RoundingMode.HALF_UP);
            }
            measureDefaultValue = decimal;
            break;
        default:
            value = new String(defaultValue, Charset.forName(CarbonCommonConstants.DEFAULT_CHARSET));
            Double parsedValue = Double.valueOf(value);
            if (!Double.isInfinite(parsedValue) && !Double.isNaN(parsedValue)) {
                measureDefaultValue = parsedValue;
            }
        }
    }
    return measureDefaultValue;
}

From source file:org.openbravo.financial.FinancialUtils.java

/**
 * Converts an amount.//w  w w.ja  va2s. c  o m
 * 
 * @param amount
 *          BigDecimal amount to convert.
 * @param curFrom
 *          Currency to convert from.
 * @param curTo
 *          Currency to convert to.
 * @param date
 *          Date conversion is being performed.
 * @param org
 *          Organization of the document that needs to be converted.
 * @param strPrecision
 *          type of precision to be used to round the converted amount.
 * @param rateDocs
 *          list of conversion rates defined on the document of the amount that needs to be
 *          converted.
 * @return a BigDecimal representing the converted amount.
 * @throws OBException
 *           when no Conversion Rate is found for the given parameters.
 */
public static BigDecimal getConvertedAmount(BigDecimal amount, Currency curFrom, Currency curTo, Date date,
        Organization org, String strPrecision, List<ConversionRateDoc> rateDocs) throws OBException {
    Check.isNotNull(rateDocs, OBMessageUtils.messageBD("ParameterMissing") + " (rateDocs)");
    if (curFrom.getId().equals(curTo.getId()) || amount.signum() == 0) {
        return amount;
    }
    BigDecimal rate = null;
    if (rateDocs.size() > 0) {
        for (ConversionRateDoc rateDoc : rateDocs) {
            if (curFrom.getId().equals(rateDoc.getCurrency().getId())
                    && curTo.getId().equals(rateDoc.getToCurrency().getId())) {
                rate = rateDoc.getRate();
                break;
            }
        }
    }
    if (rate == null) {
        ConversionRate cr = getConversionRate(date, curFrom, curTo, org, org.getClient());
        if (cr == null) {
            throw new OBException("@NoCurrencyConversion@ " + curFrom.getISOCode() + " @to@ "
                    + curTo.getISOCode() + " @ForDate@ " + OBDateUtils.formatDate(date)
                    + " @And@ @ACCS_AD_ORG_ID_D@ " + org.getIdentifier());
        }
        rate = cr.getMultipleRateBy();
    }
    Long precision = curTo.getStandardPrecision();
    if (PRECISION_COSTING.equals(strPrecision)) {
        precision = curTo.getCostingPrecision();
    } else if (PRECISION_PRICE.equals(strPrecision)) {
        precision = curTo.getPricePrecision();
    }
    return amount.multiply(rate).setScale(precision.intValue(), RoundingMode.HALF_UP);
}

From source file:org.faster.util.DateTimes.java

private static double format(double value, int scale) {
    return new BigDecimal(value).setScale(scale, RoundingMode.HALF_UP).doubleValue();
}

From source file:org.ethereum.rpc.Web3Impl.java

public String eth_netHashrate() {
    BigInteger hashesPerHour = this.worldManager.getHashRateCalculator().calculateNetHashRate(1L,
            TimeUnit.HOURS);/*from w  w w .  ja va 2 s  . co m*/
    BigDecimal hashesPerSecond = new BigDecimal(hashesPerHour)
            .divide(new BigDecimal(TimeUnit.HOURS.toSeconds(1)), 3, RoundingMode.HALF_UP);

    String result = hashesPerSecond.toString();

    if (logger.isDebugEnabled())
        logger.debug("eth_netHashrate(): " + result);

    return result;
}

From source file:org.kuali.kpme.tklm.leave.transfer.service.BalanceTransferServiceImpl.java

@Override
public BalanceTransfer initializeTransfer(String principalId, String accrualCategoryRule,
        BigDecimal accruedBalance, LocalDate effectiveDate) {
    //Initially, principals may be allowed to edit the transfer amount when prompted to submit this balance transfer, however,
    //a base transfer amount together with a forfeited amount is calculated to bring the balance back to its limit in accordance
    //with transfer limits. This "default" transfer object is used to adjust forfeiture when the user changes the transfer amount.
    BalanceTransfer bt = null;/*w  w w . j  ava  2  s.  c om*/
    AccrualCategoryRule accrualRule = HrServiceLocator.getAccrualCategoryRuleService()
            .getAccrualCategoryRule(accrualCategoryRule);

    if (ObjectUtils.isNotNull(accrualRule) && ObjectUtils.isNotNull(accruedBalance)) {
        bt = new BalanceTransfer();
        //These two objects are essential to balance transfers triggered when the employee submits their leave calendar for approval.
        //Neither of these objects should be null, otherwise this method could not have been called.
        AccrualCategory fromAccrualCategory = HrServiceLocator.getAccrualCategoryService()
                .getAccrualCategory(accrualRule.getLmAccrualCategoryId());
        AccrualCategory toAccrualCategory = HrServiceLocator.getAccrualCategoryService()
                .getAccrualCategory(accrualRule.getMaxBalanceTransferToAccrualCategory(), effectiveDate);
        BigDecimal fullTimeEngagement = HrServiceLocator.getJobService()
                .getFteSumForAllActiveLeaveEligibleJobs(principalId, effectiveDate);

        BigDecimal transferConversionFactor = null;
        if (ObjectUtils.isNotNull(accrualRule.getMaxBalanceTransferConversionFactor()))
            transferConversionFactor = accrualRule.getMaxBalanceTransferConversionFactor();

        // AccrualRule.maxBalance == null -> no balance limit. No balance limit -> no accrual triggered transfer / payout / lose.
        // execution point should not be here if max balance on accrualRule is null, unless there exists an employee override.
        BigDecimal maxBalance = accrualRule.getMaxBalance();
        BigDecimal adjustedMaxBalance = maxBalance.multiply(fullTimeEngagement).setScale(2);

        BigDecimal maxTransferAmount = null;
        BigDecimal adjustedMaxTransferAmount = null;
        if (ObjectUtils.isNotNull(accrualRule.getMaxTransferAmount())) {
            maxTransferAmount = new BigDecimal(accrualRule.getMaxTransferAmount());
            adjustedMaxTransferAmount = maxTransferAmount.multiply(fullTimeEngagement).setScale(2);
        } else {
            // no limit on transfer amount
            maxTransferAmount = new BigDecimal(Long.MAX_VALUE);
            adjustedMaxTransferAmount = maxTransferAmount;
        }

        BigDecimal maxCarryOver = null;
        BigDecimal adjustedMaxCarryOver = null;
        if (ObjectUtils.isNotNull(accrualRule.getMaxCarryOver())) {
            maxCarryOver = new BigDecimal(accrualRule.getMaxCarryOver());
            adjustedMaxCarryOver = maxCarryOver.multiply(fullTimeEngagement).setScale(2);
        } else {
            //no limit to carry over.
            maxCarryOver = new BigDecimal(Long.MAX_VALUE);
            adjustedMaxCarryOver = maxCarryOver;
        }

        List<? extends EmployeeOverrideContract> overrides = LmServiceLocator.getEmployeeOverrideService()
                .getEmployeeOverrides(principalId, effectiveDate);
        for (EmployeeOverrideContract override : overrides) {
            if (StringUtils.equals(override.getAccrualCategory(), fromAccrualCategory.getAccrualCategory())) {
                //Do not pro-rate override values for FTE.
                if (StringUtils.equals(override.getOverrideType(), "MB"))
                    adjustedMaxBalance = new BigDecimal(override.getOverrideValue());
                if (StringUtils.equals(override.getOverrideType(), "MTA"))
                    adjustedMaxTransferAmount = new BigDecimal(override.getOverrideValue());
                if (StringUtils.equals(override.getOverrideType(), "MAC"))
                    adjustedMaxCarryOver = new BigDecimal(override.getOverrideValue());
            }
        }

        BigDecimal transferAmount = accruedBalance.subtract(adjustedMaxBalance);
        if (StringUtils.equals(accrualRule.getActionAtMaxBalance(), HrConstants.ACTION_AT_MAX_BALANCE.LOSE)) {
            //Move all time in excess of employee's fte adjusted max balance to forfeiture.
            bt.setForfeitedAmount(transferAmount);
            //There is no transfer to another accrual category.
            bt.setTransferAmount(BigDecimal.ZERO);
            bt.setAmountTransferred(BigDecimal.ZERO);
            // to accrual category is a required field on maintenance document. Set as from accrual category
            // to remove validation errors when routing, approving, etc.
            bt.setToAccrualCategory(fromAccrualCategory.getAccrualCategory());
        } else {
            // ACTION_AT_MAX_BALANCE = TRANSFER
            bt.setToAccrualCategory(toAccrualCategory.getAccrualCategory());
            if (transferAmount.compareTo(adjustedMaxTransferAmount) > 0) {
                //there's forfeiture.
                //bring transfer amount down to the adjusted maximum transfer amount, and place excess in forfeiture.
                //accruedBalance - adjustedMaxTransferAmount - adjustedMaxBalance = forfeiture.
                //transferAmount = accruedBalance - adjustedMaxBalance; forfeiture = transferAmount - adjustedMaxTransferAmount.
                BigDecimal forfeiture = transferAmount.subtract(adjustedMaxTransferAmount).setScale(2);
                forfeiture = forfeiture.stripTrailingZeros();
                bt.setForfeitedAmount(forfeiture);
                bt.setTransferAmount(adjustedMaxTransferAmount);
            } else {
                bt.setTransferAmount(transferAmount);
                bt.setForfeitedAmount(BigDecimal.ZERO);
            }
        }

        //assert(adjustedMaxBalance.compareTo(accruedBalance.subtract(bt.getTransferAmount().add(bt.getForfeitedAmount()))) == 0);

        // Max Carry Over logic for Year End transfers.
        if (StringUtils.equals(accrualRule.getMaxBalanceActionFrequency(),
                HrConstants.MAX_BAL_ACTION_FREQ.YEAR_END)) {

            //At this point, transfer amount and forfeiture have been set so that the new accrued balance will be the
            //adjusted max balance, so this amount is used to check against carry over.
            if (adjustedMaxBalance.compareTo(adjustedMaxCarryOver) > 0) {
                BigDecimal carryOverDiff = adjustedMaxBalance.subtract(adjustedMaxCarryOver);

                if (StringUtils.equals(accrualRule.getActionAtMaxBalance(),
                        HrConstants.ACTION_AT_MAX_BALANCE.LOSE)) {
                    //add carry over excess to forfeiture.
                    bt.setForfeitedAmount(bt.getForfeitedAmount().add(carryOverDiff));
                } else {
                    //maximize the transfer amount.
                    BigDecimal potentialTransferAmount = bt.getTransferAmount().add(carryOverDiff);

                    //Can this amount be added to the transfer amount without exceeding adjusted max transfer amount??
                    if (potentialTransferAmount.compareTo(adjustedMaxTransferAmount) <= 0) {
                        //yes
                        bt.setTransferAmount(bt.getTransferAmount().add(carryOverDiff));
                    } else {
                        //no
                        BigDecimal carryOverExcess = potentialTransferAmount
                                .subtract(adjustedMaxTransferAmount);
                        //move excess to forfeiture
                        bt.setForfeitedAmount(bt.getForfeitedAmount().add(carryOverExcess));
                        //the remainder (if any) can be added to the transfer amount.
                        bt.setTransferAmount(
                                bt.getTransferAmount().add(carryOverDiff.subtract(carryOverExcess)));

                        assert (bt.getTransferAmount().compareTo(adjustedMaxTransferAmount) == 0);
                        // assert that the new balance will be equal to the adjusted max carry over < adjusted max balance.
                    }
                }
                assert (adjustedMaxCarryOver.compareTo(
                        accruedBalance.subtract(bt.getTransferAmount().add(bt.getForfeitedAmount()))) == 0);
            }
            //otherwise, given balance will be at or under the max annual carry over.
        }

        bt.setEffectiveLocalDate(effectiveDate);
        bt.setAccrualCategoryRule(accrualCategoryRule);
        bt.setFromAccrualCategory(fromAccrualCategory.getAccrualCategory());
        bt.setPrincipalId(principalId);
        bt.setUserPrincipalId(HrContext.getPrincipalId());
        if (ObjectUtils.isNotNull(transferConversionFactor)) {
            bt.setAmountTransferred(bt.getTransferAmount().multiply(transferConversionFactor).setScale(2,
                    RoundingMode.HALF_UP));
        } else {
            bt.setAmountTransferred(bt.getTransferAmount());
        }
    }
    return bt;
}

From source file:org.projectforge.fibu.datev.EmployeeSalaryExportDao.java

/**
 * Exports the filtered list as table with almost all fields.
 *///from ww  w. ja  va 2  s .  c om
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public byte[] export(final List<EmployeeSalaryDO> list) {
    log.info("Exporting employee salary list.");
    Validate.notEmpty(list);
    Collections.sort(list, new Comparator<EmployeeSalaryDO>() {
        public int compare(final EmployeeSalaryDO o1, final EmployeeSalaryDO o2) {
            return (o1.getEmployee().getUser().getFullname())
                    .compareTo(o2.getEmployee().getUser().getFullname());
        }
    });
    final EmployeeFilter filter = new EmployeeFilter();
    filter.setShowOnlyActiveEntries(true);
    filter.setDeleted(false);
    final List<EmployeeDO> employees = employeeDao.getList(filter);
    final List<EmployeeDO> missedEmployees = new ArrayList<EmployeeDO>();
    for (final EmployeeDO employee : employees) {
        boolean found = false;
        for (final EmployeeSalaryDO salary : list) {
            if (salary.getEmployeeId().equals(employee.getId()) == true) {
                found = true;
                break;
            }
        }
        if (found == false) {
            missedEmployees.add(employee);
        }
    }
    if (CollectionUtils.isNotEmpty(missedEmployees) == true) {
        Collections.sort(missedEmployees, new Comparator<EmployeeDO>() {
            public int compare(final EmployeeDO o1, final EmployeeDO o2) {
                return (o1.getUser().getFullname()).compareTo(o2.getUser().getFullname());
            }
        });
    }
    final ExportWorkbook xls = new ExportWorkbook();
    final ContentProvider contentProvider = new MyContentProvider(xls);
    // create a default Date format and currency column
    xls.setContentProvider(contentProvider);

    final EmployeeSalaryDO first = list.get(0);
    final int year = first.getYear();
    final int month = first.getMonth();
    final DayHolder buchungsdatum = new DayHolder();
    buchungsdatum.setDate(year, month, 1);
    final MonthHolder monthHolder = new MonthHolder(buchungsdatum.getDate());
    final BigDecimal numberOfWorkingDays = monthHolder.getNumberOfWorkingDays();
    buchungsdatum.setEndOfMonth();

    final String sheetTitle = DateHelper.formatMonth(year, month);
    final ExportSheet sheet = xls.addSheet(sheetTitle);
    sheet.createFreezePane(0, 1);

    final ExportSheet employeeSheet = xls.addSheet(PFUserContext.getLocalizedString("fibu.employee"));
    employeeSheet.setColumnWidth(0, XlsContentProvider.LENGTH_USER * 256);
    employeeSheet.setColumnWidth(1, 14 * 256);
    employeeSheet.setColumnWidth(2, 12 * 256);
    employeeSheet.setColumnWidth(3, 12 * 256);
    employeeSheet.setColumnWidth(4, 12 * 256);
    final ContentProvider provider = employeeSheet.getContentProvider();
    provider.putFormat("STUNDEN", "0.00;[Red]-0.00");
    final ExportRow employeeRow = employeeSheet.addRow();
    employeeRow.addCell(0, PFUserContext.getLocalizedString("fibu.employee"));
    employeeRow.addCell(1, PFUserContext.getLocalizedString("fibu.employee.wochenstunden"));
    employeeRow.addCell(2, PFUserContext.getLocalizedString("fibu.employee.sollstunden"));
    employeeRow.addCell(3, PFUserContext.getLocalizedString("fibu.employee.iststunden"));
    employeeRow.addCell(4, PFUserContext.getLocalizedString("fibu.common.difference"));

    // build all column names, title, widths from fixed and variable columns
    final int numCols = ExcelColumn.values().length;

    final String[] colNames = new String[numCols];
    final String[] colTitles = new String[numCols];
    final int[] colWidths = new int[numCols];

    int idx = 0;
    for (final ExcelColumn col : EnumSet.range(ExcelColumn.START, ExcelColumn.END)) {
        colNames[idx] = col.name();
        colTitles[idx] = PFUserContext.getLocalizedString(col.theTitle);
        colWidths[idx] = col.width;
        ++idx;
    }

    // column property names
    sheet.setPropertyNames(colNames);

    final ContentProvider sheetProvider = sheet.getContentProvider();
    sheetProvider.putFormat("STUNDEN", "0.00");
    sheetProvider.putFormat("BRUTTO_MIT_AG", "#,##0.00;[Red]-#,##0.00");
    sheetProvider.putFormat("KORREKTUR", "#,##0.00;[Red]-#,##0.00");
    sheetProvider.putFormat("SUMME", "#,##0.00;[Red]-#,##0.00");
    sheetProvider.putFormat("KOST1", "#");
    sheetProvider.putFormat("KOST2", "#");
    sheetProvider.putFormat("KONTO", "#");
    sheetProvider.putFormat("GEGENKONTO", "#");
    sheetProvider.putFormat("DATUM", "dd.MM.yyyy");
    // inform provider of column widths
    for (int ci = 0; ci < colWidths.length; ++ci) {
        sheetProvider.putColWidth(ci, colWidths[ci]);
    }

    final ExportRow headRow = sheet.addRow();
    int i = 0;
    for (final String title : colTitles) {
        headRow.addCell(i++, title);
    }

    for (final EmployeeSalaryDO salary : list) {
        final PropertyMapping mapping = new PropertyMapping();
        final PFUserDO user = userGroupCache.getUser(salary.getEmployee().getUserId());
        Validate.isTrue(year == salary.getYear());
        Validate.isTrue(month == salary.getMonth());
        final MonthlyEmployeeReport report = monthlyEmployeeReportDao.getReport(year, month, user);
        mapping.add(ExcelColumn.MITARBEITER, user.getFullname());
        final Kost1DO kost1 = salary.getEmployee().getKost1();
        final BigDecimal bruttoMitAGAnteil = salary.getBruttoMitAgAnteil();
        final BigDecimal netDuration = new BigDecimal(report.getTotalNetDuration());
        final Map<String, Kost2Row> rows = report.getKost2Rows();
        BigDecimal sum = BigDecimal.ZERO;
        int j = rows.size();
        for (final Kost2Row row : rows.values()) {
            final Kost2DO kost2 = row.getKost2();
            final MonthlyEmployeeReportEntry entry = report.getKost2Durations().get(kost2.getId());
            mapping.add(ExcelColumn.KOST1, kost1.getNummer());
            mapping.add(ExcelColumn.MITARBEITER, user.getFullname());
            mapping.add(ExcelColumn.KOST2, kost2.getNummer());
            final BigDecimal duration = new BigDecimal(entry.getMillis() / 1000); // Seconds
            // duration = duration.divide(new BigDecimal(60 * 60 * 24), 8, RoundingMode.HALF_UP); // Fraction of day (24 hours)
            // mapping.add(ExcelColumn.STUNDEN, duration);
            mapping.add(ExcelColumn.STUNDEN, duration.divide(new BigDecimal(3600), 2, RoundingMode.HALF_UP));
            mapping.add(ExcelColumn.BEZEICHNUNG, kost2.getToolTip());
            final BigDecimal betrag = CurrencyHelper.multiply(bruttoMitAGAnteil,
                    new BigDecimal(entry.getMillis()).divide(netDuration, 8, RoundingMode.HALF_UP));
            sum = sum.add(betrag);
            if (--j == 0) {
                final BigDecimal korrektur = bruttoMitAGAnteil.subtract(sum);
                mapping.add(ExcelColumn.BRUTTO_MIT_AG, betrag.add(korrektur));
                mapping.add(ExcelColumn.KORREKTUR, korrektur);
                if (NumberHelper.isEqual(sum.add(korrektur), bruttoMitAGAnteil) == true) {
                    mapping.add(ExcelColumn.SUMME, bruttoMitAGAnteil);
                } else {
                    mapping.add(ExcelColumn.SUMME, "*** " + sum + " != " + bruttoMitAGAnteil);
                }
            } else {
                mapping.add(ExcelColumn.BRUTTO_MIT_AG, betrag);
                mapping.add(ExcelColumn.KORREKTUR, "");
                mapping.add(ExcelColumn.SUMME, "");
            }
            mapping.add(ExcelColumn.DATUM, buchungsdatum.getCalendar()); // Last day of month
            mapping.add(ExcelColumn.KONTO, KONTO); // constant.
            mapping.add(ExcelColumn.GEGENKONTO, GEGENKONTO); // constant.
            sheet.addRow(mapping.getMapping(), 0);
        }
        addEmployeeRow(employeeSheet, salary.getEmployee(), numberOfWorkingDays, netDuration);
    }
    for (final EmployeeDO employee : missedEmployees) {
        final PFUserDO user = userGroupCache.getUser(employee.getUserId());
        final PropertyMapping mapping = new PropertyMapping();
        mapping.add(ExcelColumn.MITARBEITER, user.getFullname());
        mapping.add(ExcelColumn.SUMME, "***");
        mapping.add(ExcelColumn.BEZEICHNUNG, "*** FEHLT! ***");
        sheet.addRow(mapping.getMapping(), 0);
        final MonthlyEmployeeReport report = monthlyEmployeeReportDao.getReport(year, month, user);
        final BigDecimal netDuration = new BigDecimal(report.getTotalNetDuration());
        addEmployeeRow(employeeSheet, employee, numberOfWorkingDays, netDuration);
    }
    // sheet.setZoom(3, 4); // 75%

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        xls.write(baos);
    } catch (final IOException ex) {
        log.fatal("Exception encountered " + ex, ex);
        throw new RuntimeException(ex);
    }
    return baos.toByteArray();
}

From source file:ch.oakmountain.tpa.solver.TrainPathAllocationProblemStatistics.java

private void compileSummaryTable() throws IOException {
    TablePersistor summaryTable = new TablePersistor("summary", outputDir, "Train Path Allocation Problem",
            getHeader());/*from  ww  w. jav a2 s .  co m*/

    for (TrainPathSlot trainPathSlot : arcNodeUnitCapacityCounts.keySet()) {
        int count = arcNodeUnitCapacityCounts.get(trainPathSlot);
        arcNodeUnitCapacityConstraints += 1;
        arcNodeUnitCapacityConstraintTerms += count;
    }
    for (TrainPathSlot trainPathSlot : pathBasedConflictCounts.keySet()) {
        int count = pathBasedConflictCounts.get(trainPathSlot);
        pathBasedSolutionCandidateConflictConstraints += 1;
        pathBasedSolutionCandidateConflictTerms += count;
    }

    // arc-node
    // - flow constraints: sum of nb verticies of all DAGs (terms per constraint: nb of solution candidates)
    // - unit capacity: nb of slots of all DAGs (terms per constraint: at most one term per application)
    summaryTable.writeRow(Arrays.asList("arc-node/path-based", "feasible requests",
            String.valueOf(feasibleSimpleTrainPathApplications.size())));
    summaryTable.writeRow(Arrays.asList("arc-node/path-based", "infeasible requests",
            String.valueOf(infeasibleSimpleTrainPathApplications.size())));
    summaryTable.writeRow(
            Arrays.asList("arc-node/path-based", "total number of train paths", String.valueOf(totalNbPaths)));
    summaryTable.writeRow(Arrays.asList("arc-node/path-based", "global minimum dwell time",
            PeriodicalTimeFrame.formatDuration(
                    feasibleSimpleTrainPathApplications.get(0).getParams().getHARD_MINIMUM_DWELL_TIME())));
    summaryTable.writeRow(Arrays.asList("arc-node/path-based", "global maximum earlier departure time",
            PeriodicalTimeFrame.formatDuration(feasibleSimpleTrainPathApplications.get(0).getParams()
                    .getHARD_MAXIMUM_EARLIER_DEPARTURE())));
    summaryTable.writeRow(Arrays.asList("arc-node/path-based", "global maximum later arrival time",
            PeriodicalTimeFrame.formatDuration(
                    feasibleSimpleTrainPathApplications.get(0).getParams().getHARD_MAXIMUM_LATER_ARRIVAL())));

    summaryTable.writeRow(
            Arrays.asList("arc-node", "flow constraints", String.valueOf(arcNodeFlowConstraintsCount)));
    summaryTable.writeRow(Arrays.asList("arc-node", "terms in flow constraints",
            String.valueOf(arcNodeFlowConstraintTermsCount)));
    summaryTable.writeRow(Arrays.asList("arc-node", "unit capacity constraints",
            String.valueOf(arcNodeUnitCapacityConstraints)));
    summaryTable.writeRow(Arrays.asList("arc-node", "terms in unit capacity constraints",
            String.valueOf(arcNodeUnitCapacityConstraintTerms)));
    BigInteger arcNodeConstraints = BigInteger
            .valueOf(arcNodeFlowConstraintsCount + arcNodeUnitCapacityConstraints);
    summaryTable.writeRow(Arrays.asList("arc-node", "rows (constraints)", String.valueOf(arcNodeConstraints)));
    summaryTable
            .writeRow(Arrays.asList("arc-node", "columns (variables)", String.valueOf(arcNodeVariablesCount)));
    summaryTable.writeRow(Arrays.asList("arc-node", "train path slots",
            String.valueOf(arcNodeUnitCapacityCounts.keySet().size())));
    BigInteger arcNodeTerms = BigInteger
            .valueOf(arcNodeFlowConstraintTermsCount + arcNodeUnitCapacityConstraintTerms);
    BigInteger arcNodeFlowConstraintMatrixSize = BigInteger.valueOf(arcNodeFlowConstraintTermsCount)
            .multiply(BigInteger.valueOf(arcNodeVariablesCount));
    BigInteger arcNodeUnitCapacityConstraintMatrixSize = BigInteger.valueOf(arcNodeUnitCapacityConstraintTerms)
            .multiply(BigInteger.valueOf(arcNodeVariablesCount));
    BigInteger arcNodeMatrixSize = arcNodeConstraints.multiply(BigInteger.valueOf(arcNodeVariablesCount));
    summaryTable.writeRow(Arrays.asList("arc-node", "sparsity in flow constraints",
            String.valueOf(arcNodeFlowConstraintTermsCount + "/" + arcNodeFlowConstraintMatrixSize + " ("
                    + (new BigDecimal(arcNodeFlowConstraintTermsCount))
                            .divide((new BigDecimal(arcNodeFlowConstraintMatrixSize)), 10, RoundingMode.HALF_UP)
                    + ")")));
    summaryTable.writeRow(Arrays.asList("arc-node", "sparsity in unit capacity constraints",
            String.valueOf(arcNodeUnitCapacityConstraintTerms + "/" + arcNodeUnitCapacityConstraintMatrixSize
                    + " ("
                    + (new BigDecimal(arcNodeUnitCapacityConstraintTerms)).divide(
                            (new BigDecimal(arcNodeUnitCapacityConstraintMatrixSize)), 10, RoundingMode.HALF_UP)
                    + ")")));
    summaryTable
            .writeRow(
                    Arrays.asList("arc-node", "sparsity in all constraints",
                            String.valueOf(arcNodeTerms
                                    + "/" + arcNodeMatrixSize + " (" + (new BigDecimal(arcNodeTerms))
                                            .divide(new BigDecimal(arcNodeMatrixSize), 10, RoundingMode.HALF_UP)
                                    + ")")));

    // path-based
    // - solution candidate choice: nb of applications (terms per constraint: nb of solution canidates)
    // - conflict sets: nb of slots of all DAGs (terms per constraint: possibly many terms per application)
    summaryTable.writeRow(Arrays.asList("path-based", "choice constraints",
            String.valueOf(pathBasedSolutionCandidateChoiceConstraintsCount)));
    summaryTable.writeRow(Arrays.asList("path-based", "terms in choice constraints",
            String.valueOf(pathBasedSolutionCandidateChoiceTermsCount)));
    summaryTable.writeRow(Arrays.asList("path-based", "conflict constraints",
            String.valueOf(pathBasedSolutionCandidateConflictConstraints)));
    summaryTable.writeRow(Arrays.asList("path-based", "terms in conflict constraints",
            String.valueOf(pathBasedSolutionCandidateConflictTerms)));
    summaryTable.writeRow(Arrays.asList("path-based", "enumeration rate ",
            String.valueOf(pathBasedSolutionCandidateChoiceTermsCount + "/" + totalNbPaths + "("
                    + ((double) pathBasedSolutionCandidateChoiceTermsCount / totalNbPaths) + ")")));
    BigInteger pathBasedConstraints = BigInteger.valueOf(pathBasedSolutionCandidateChoiceConstraintsCount)
            .add(BigInteger.valueOf(pathBasedSolutionCandidateConflictConstraints));
    summaryTable
            .writeRow(Arrays.asList("path-based", "rows (constraints)", String.valueOf(pathBasedConstraints)));
    summaryTable.writeRow(
            Arrays.asList("path-based", "columns (variables)", String.valueOf(pathBasedVariablesCount)));
    summaryTable.writeRow(Arrays.asList("path-based", "train path slots",
            String.valueOf(pathBasedConflictCounts.keySet().size())));
    BigInteger pathBasedTerms = BigInteger.valueOf(pathBasedSolutionCandidateConflictTerms)
            .add(BigInteger.valueOf(pathBasedSolutionCandidateChoiceTermsCount));
    BigInteger pathBasedMatrixSize = pathBasedConstraints.multiply(BigInteger.valueOf(pathBasedVariablesCount));
    BigInteger pathBasedSolutionCandidateChoiceMatrixSize = BigInteger
            .valueOf(pathBasedSolutionCandidateChoiceConstraintsCount)
            .multiply(BigInteger.valueOf(pathBasedVariablesCount));
    BigInteger pathBasedSolutionCandidateConflictMatrixSize = BigInteger
            .valueOf(pathBasedSolutionCandidateConflictConstraints)
            .multiply(BigInteger.valueOf(pathBasedVariablesCount));
    summaryTable.writeRow(Arrays.asList("path-based", "sparsity in choice constraints",
            String.valueOf(pathBasedSolutionCandidateChoiceTermsCount + "/"
                    + pathBasedSolutionCandidateChoiceMatrixSize + " ("
                    + (new BigDecimal(pathBasedSolutionCandidateChoiceTermsCount)).divide(
                            new BigDecimal(pathBasedSolutionCandidateChoiceMatrixSize), 10,
                            RoundingMode.HALF_UP)
                    + ")")));
    summaryTable.writeRow(Arrays.asList("path-based", "sparsity in conflict constraints",
            String.valueOf(pathBasedSolutionCandidateConflictTerms + "/"
                    + pathBasedSolutionCandidateConflictMatrixSize + " ("
                    + (new BigDecimal(pathBasedSolutionCandidateConflictTerms)).divide(
                            (new BigDecimal(pathBasedSolutionCandidateConflictMatrixSize)), 10,
                            RoundingMode.HALF_UP)
                    + ")")));
    summaryTable
            .writeRow(
                    Arrays.asList("path-based", "sparsity in all constraints",
                            String.valueOf(pathBasedTerms + "/" + pathBasedMatrixSize + " ("
                                    + (new BigDecimal(pathBasedTerms)).divide(
                                            (new BigDecimal(pathBasedMatrixSize)), 10, RoundingMode.HALF_UP)
                                    + ")")));

    summaryTable.finishTable();

    if (!(arcNodeUnitCapacityCounts.keySet().size() >= pathBasedConflictCounts.keySet().size())) {
        throw new IllegalStateException(
                "nb of train path slots in arc node model has to be larger or equal to the number of train path slots in the path based model (because of partial enumeration)");
    }

    // LaTeX table output
    DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance();
    //DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();

    //symbols.setGroupingSeparator(' ');
    //formatter.setDecimalFormatSymbols(symbols);
    File latexFile = new File(outputDir + File.separator + "computational.tex");
    FileUtils.writeStringToFile(latexFile, "Number of feasible applications:&\\multicolumn{2}{c|}{"
            + formatter.format(feasibleSimpleTrainPathApplications.size()) + "}\\\\\n");
    FileUtils.writeStringToFile(latexFile,
            "Number of variables      &" + formatter.format(arcNodeVariablesCount) + "&"
                    + formatter.format(pathBasedVariablesCount) + "\\\\\n",
            true);
    FileUtils.writeStringToFile(latexFile, "Number of constraints   &" + formatter.format(arcNodeConstraints)
            + "&" + formatter.format(pathBasedConstraints) + "\\\\\n", true);
    FileUtils.writeStringToFile(latexFile, "Number of unit capacity / conflict constraints", true);
    FileUtils.writeStringToFile(latexFile,
            "&" + formatter.format(arcNodeUnitCapacityConstraints)
                    + "                                         &"
                    + formatter.format(pathBasedSolutionCandidateConflictConstraints) + "\\\\\n",
            true);
    FileUtils.writeStringToFile(latexFile, "%    Matrix size                     &"
            + formatter.format(arcNodeMatrixSize) + "&" + formatter.format(pathBasedMatrixSize) + "\\\\\n",
            true);
    FileUtils.writeStringToFile(latexFile, "%Number of terms           &" + formatter.format(arcNodeTerms) + "&"
            + formatter.format(pathBasedTerms) + "\\\\\n", true);
    FileUtils.writeStringToFile(latexFile, "Number of terms in unit capacity/", true);
    FileUtils.writeStringToFile(latexFile,
            "&" + formatter.format(arcNodeUnitCapacityConstraintTerms) + "& \\\\\n", true);
    FileUtils.writeStringToFile(latexFile, "\\hspace{0.5cm}choice constraints", true);
    FileUtils.writeStringToFile(latexFile,
            "&&" + formatter.format(pathBasedSolutionCandidateChoiceTermsCount) + "\\\\\n", true);
    FileUtils.writeStringToFile(latexFile, "Number of terms in flow conservation/", true);
    FileUtils.writeStringToFile(latexFile, "&" + formatter.format(arcNodeFlowConstraintTermsCount) + "& \\\\\n",
            true);
    FileUtils.writeStringToFile(latexFile, "\\hspace{0.5cm}conflict constraints", true);
    FileUtils.writeStringToFile(latexFile,
            "&&" + formatter.format(pathBasedSolutionCandidateConflictTerms) + "\\\\\n", true);
}

From source file:uk.ac.leeds.ccg.andyt.projects.fluvialglacial.SlopeAreaAnalysis.java

protected TreeMap<Integer, Object[]> readAustriaData(File fileIn) {
    TreeMap<Integer, Object[]> result;
    result = new TreeMap<Integer, Object[]>();
    BufferedReader br;/* w  w w  .  j  a  v a 2  s.  co m*/
    br = Generic_StaticIO.getBufferedReader(fileIn);
    StreamTokenizer st;
    st = new StreamTokenizer(br);
    Generic_StaticIO.setStreamTokenizerSyntax5(st);
    st.wordChars('(', '(');
    st.wordChars(')', ')');
    st.wordChars('%', '%');
    Generic_StaticIO.skipline(st);
    int token;
    String line = "";
    String[] fields;
    try {
        token = st.nextToken();
        int ID;
        //int pointID;
        while (token != StreamTokenizer.TT_EOF) {
            switch (token) {
            case StreamTokenizer.TT_EOL:
                //flowacc,area (km2),slope_25_(%),proglac_ID,COUNT
                //12.11111069,0.00756944,32.33880000000,0,250631
                fields = line.split(sComma);
                ID = Double.valueOf(fields[1]).intValue();
                if (ID > 0) {
                    //BigDecimal flowacc;
                    BigDecimal area;
                    BigDecimal slope;
                    Object[] data;
                    BigDecimal maxx;
                    BigDecimal maxy;
                    BigDecimal minx;
                    BigDecimal miny;
                    data = result.get(ID);
                    ArrayList<Generic_XYNumericalData> theGeneric_XYNumericalData;
                    if (data == null) {
                        data = new Object[5];
                        theGeneric_XYNumericalData = new ArrayList<Generic_XYNumericalData>();
                        maxx = BigDecimal.ZERO;
                        maxy = BigDecimal.ZERO;
                        minx = BigDecimal.valueOf(Double.MAX_VALUE);
                        miny = BigDecimal.valueOf(Double.MAX_VALUE);
                        data[0] = theGeneric_XYNumericalData;
                        data[1] = maxx;
                        data[2] = minx;
                        data[3] = maxy;
                        data[4] = miny;
                        result.put(ID, data);
                    } else {
                        theGeneric_XYNumericalData = (ArrayList<Generic_XYNumericalData>) data[0];
                        maxx = (BigDecimal) data[1];
                        minx = (BigDecimal) data[2];
                        maxy = (BigDecimal) data[3];
                        miny = (BigDecimal) data[4];
                    }
                    //pointID = Integer.valueOf(fields[4]);
                    //flowacc = new BigDecimal(fields[0]);
                    area = new BigDecimal(fields[3]);
                    if (area.compareTo(BigDecimal.ZERO) == 1) {
                        area = Generic_BigDecimal.log(10, area, 10, RoundingMode.HALF_UP);
                    } else {
                        area = BigDecimal.ZERO;
                    }
                    slope = new BigDecimal(fields[2]);
                    if (slope.compareTo(BigDecimal.ZERO) == 1) {
                        slope = Generic_BigDecimal.log(10, slope, 10, RoundingMode.HALF_UP);
                    } else {
                        slope = BigDecimal.ZERO;
                    }
                    Generic_XYNumericalData point;
                    point = new Generic_XYNumericalData(slope, area);
                    theGeneric_XYNumericalData.add(point);
                    data[0] = theGeneric_XYNumericalData;
                    data[1] = maxx.max(slope);
                    data[2] = minx.min(slope);
                    data[3] = maxy.max(area);
                    data[4] = miny.min(area);
                }
                break;
            case StreamTokenizer.TT_WORD:
                line = st.sval;
                break;
            }
            token = st.nextToken();
        }
    } catch (IOException ex) {
        Logger.getLogger(SlopeAreaAnalysis.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

From source file:com.addthis.hydra.data.tree.prop.DataReservoir.java

private static long doubleToLong(double value, boolean doubleToLongBits) {
    if (doubleToLongBits) {
        return Double.doubleToLongBits(value);
    } else {// w  w w  .ja  va2 s  . c o m
        return DoubleMath.roundToLong(value, RoundingMode.HALF_UP);
    }
}