Example usage for java.lang Math ceil

List of usage examples for java.lang Math ceil

Introduction

In this page you can find the example usage for java.lang Math ceil.

Prototype

public static double ceil(double a) 

Source Link

Document

Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.

Usage

From source file:com.hm.cal.date.JulianDay.java

/**
 * Returns this Julian Day set to noon./*from   w w w .  j  a v a  2 s. c o m*/
 *
 * @return This Julian Day at noon.
 */
public JulianDay atNoon() {
    return new JulianDay(Math.ceil(_jday - 0.5));
}

From source file:no.met.jtimeseries.marinogram.MarinogramWavePlot.java

private XYPlot createPlot(TimeZone timezone, boolean plotWaveDirection, boolean plotWaveHeight) {
    ChartPlotter plotter = new ChartPlotter();
    // default setting
    plotter.setHeight(this.getHeight());
    plotter.setWidth(this.getWidth());
    plotter.setPlotDefaultProperties("", "");
    Color waveHeightColor = new Color(0, 105, 161);
    Color waveDirectionColor = new Color(0, 105, 161);
    // plot style
    PlotStyle.Builder waveStyleBuilder = new PlotStyle.Builder("Wave");
    PlotStyle plotStyle;/*w w  w  .  j  av a  2  s. c om*/
    NumberPhenomenon waveDirection = getOceanForecastDataModel()
            .getPhenomenen(PhenomenonName.WaveDirection.toString(), NumberPhenomenon.class);
    NumberPhenomenon waveHeight = getOceanForecastDataModel()
            .getPhenomenen(PhenomenonName.WaveHeight.toString(), NumberPhenomenon.class);
    if (waveHeight == null || waveDirection == null) {
        return null;
    }

    double tick = (waveHeight.getMaxValue() - waveHeight.getMinValue()) / 2;
    tick = Math.ceil(tick);
    double lowBound = Math.floor(waveHeight.getMinValue() / (tick)) * (tick);
    //The minimum scale is 0
    lowBound = lowBound < 0 ? 0 : lowBound;
    lowBound = lowBound - tick / 2;
    double upperBound = lowBound + tick * 4;

    // reference the range axis
    NumberAxis leftNumberAxis = new NumberAxis();
    leftNumberAxis.setLabel(messages.getString("parameter.wave") + " (m)");
    leftNumberAxis.setLabelPaint(waveHeightColor);
    leftNumberAxis.setTickLabelPaint(waveHeightColor);
    leftNumberAxis.setLowerBound(lowBound);
    leftNumberAxis.setUpperBound(upperBound);
    leftNumberAxis.setTickUnit(new NumberTickUnit(tick));

    NumberAxis rightNumberAxis = new NumberAxis();
    rightNumberAxis.setLabelPaint(waveHeightColor);
    rightNumberAxis.setTickLabelPaint(waveHeightColor);
    rightNumberAxis.setLowerBound(lowBound);
    rightNumberAxis.setUpperBound(upperBound);
    rightNumberAxis.setTickUnit(new NumberTickUnit(tick));

    List<Date> shortTermTime = this.getShortTermTime(waveDirection.getTime().get(0));

    //set thte plot wave height color to be transparent if show wave height is false
    if (!plotWaveHeight) {
        waveHeightColor = new Color(0, 0, 0, 0);
    }

    // plot style
    plotStyle = waveStyleBuilder.spline(SplineStyle.HYBRID).stroke(new BasicStroke(2.0f))
            .seriesColor(waveHeightColor).numberAxis(leftNumberAxis).nonNegative(true).build();

    //Draw the wave height even if plotWaveHeight is false (but with transparent in such a case)
    //for the purpose to keep the same background grid and tick label on the y-axis 
    //no matter the wave height is shown or not
    plotter.addLineChart(TimeBase.SECOND, waveHeight, plotStyle);

    plotter.getPlot().setRangeAxis(1, rightNumberAxis);
    plotter.getPlot().setOutlineVisible(true);

    // first set domain date format and then add hour based domain grid
    // lines
    // TODO: wrap this inside the addHourBasedDomainGridLines for
    // simplicity

    Date minDate = shortTermTime.get(0);
    Date maxDate = shortTermTime.get(shortTermTime.size() - 1);
    plotter.setDomainRange(minDate, maxDate);
    plotter.setDomainDateFormat(timezone, "HH");
    // set domain range after (must) plot all the data
    plotter.addHourBasedDomainGridLines();
    // invisible domain axis
    plotter.getPlot().getDomainAxis().setTickLabelsVisible(false);
    // add markers
    plotter.addDomainMarkers(shortTermTime, timezone, locale);

    if (plotWaveDirection) {
        List<Date> symbolTimes = Utility.filterMinimumHourInterval(waveDirection.getTime(), 2, 1);
        InListFromDateFilter symbolTimesFilter = new InListFromDateFilter(symbolTimes);
        waveDirection.filter(symbolTimesFilter);
        waveHeight = null;
        if (plotWaveHeight) {
            waveHeight = getOceanForecastDataModel().getPhenomenen(PhenomenonName.WaveHeight.toString(),
                    NumberPhenomenon.class);
            waveHeight.filter(symbolTimesFilter);
        }

        plotStyle = waveStyleBuilder.seriesColor(waveDirectionColor).build();
        plotter.addArrowDirectionPlot(waveDirection, waveHeight, 0.1, plotStyle);
    }
    plotter.getPlot().setRangeZeroBaselineVisible(false);

    return plotter.getPlot();

}

From source file:com.unister.semweb.drums.file.SpecificEnlargmentTest.java

/**
 * Generates {@link TestStorable} in such a way that at most <code>maxBytes</code> will be used by the
 * {@link TestStorable}.//from   www.j a  va2  s.c o  m
 */
private List<TestStorable> generateStorables(int maxBytes) {
    int numberOfStorables = (int) Math.ceil((double) maxBytes / globalParameters.getElementSize());

    List<TestStorable> result = new ArrayList<TestStorable>();
    for (int i = 0; i < numberOfStorables; i++) {
        byte[] newKey = generatePseudoKey(globalParameters.getKeySize());
        TestStorable newElement = new TestStorable();
        newElement.setKey(newKey);
        result.add(newElement);
    }
    return result;
}

From source file:mylife.web.interactionsController.java

/**
 *
 * @param pageid//from www . j av  a  2 s . co m
 * @param request
 * @return
 */
@RequestMapping("/interactions/viewinteractions/{pageid}")
public ModelAndView viewinteractions(@PathVariable int pageid, HttpServletRequest request) {
    int total = 25;
    int start = 1;

    if (pageid != 1) {
        start = (pageid - 1) * total + 1;
    }

    List<interactions> list = dao.getinteractionsByPage(start, total);

    HashMap<String, Object> context = new HashMap<String, Object>();
    context.put("list", list);

    int count = dao.getinteractionsCount();
    context.put("pages", Math.ceil((float) count / (float) total));

    context.put("page", pageid);

    Message msg = (Message) request.getSession().getAttribute("message");

    if (msg != null) {
        context.put("message", msg);
        request.getSession().removeAttribute("message");
    }

    return new ModelAndView("viewinteractions", context);
}

From source file:de.tud.kom.p2psim.impl.overlay.dht.kademlia2.setup.AbstractNodeFactory.java

/**
 * Constructs a new AbstractNodeFactory, the necessary constants are read
 * from {@link KademliaSetup}.//  www .  ja  va 2s.c o  m
 */
public AbstractNodeFactory() {
    config = KademliaSetup.getConfig();
    this.rnd = new RandomAdaptor(Simulator.getRandom());

    final int approxSize = (int) Math.ceil(config.getNumberOfPeers() * 1.02);
    constructedNodes = new HashMap<HKademliaOverlayID, Node<HKademliaOverlayID>>(approxSize, 0.99f);
    constructedNodeValues = new ArrayList<Node<HKademliaOverlayID>>(approxSize);
}

From source file:org.motechproject.mobile.omi.manager.MessageStoreManagerImpl.java

public GatewayRequest constructMessage(MessageRequest messageRequest, Language defaultLang) {

    GatewayRequest gatewayRequest = buildGatewayRequest(messageRequest);
    GatewayRequestDetails gatewayDetails = (GatewayRequestDetails) applicationContext
            .getBean("gatewayRequestDetails", GatewayRequestDetails.class);
    gatewayDetails.setMessageType(messageRequest.getMessageType());

    try {/*from   w w w  .j  a  v  a  2  s  .co m*/

        if (messageRequest.getMessageType() == MessageType.TEXT) {

            String template = fetchTemplate(messageRequest, defaultLang);
            logger.debug("message template fetched");
            logger.debug(template);

            String message = parseTemplate(template, messageRequest.getPersInfos());
            logger.debug("message contructed");
            logger.debug(message);

            int maxLength = (charsPerSMS - concatAllowance) * maxConcat - 1;
            message = message.length() <= maxLength ? message : message.substring(0, maxLength);

            int numPages = (int) Math.ceil(message.length() % (charsPerSMS - concatAllowance));
            gatewayDetails.setNumberOfPages(numPages);

            gatewayRequest.setMessage(message);
            gatewayDetails.setMessage(message);

        }

        gatewayRequest.setMessageStatus(MStatus.SCHEDULED);
        gatewayRequest.setGatewayRequestDetails(gatewayDetails);

    } catch (MotechException ex) {
        logger.error("MotechException: " + ex.getMessage());
        gatewayRequest.setMessageStatus(MStatus.FAILED);
        gatewayRequest.setMessage(null);

        GatewayResponse gwResp = coreManager.createGatewayResponse();
        gwResp.setGatewayRequest(gatewayRequest);
        gwResp.setMessageStatus(MStatus.FAILED);
        gwResp.setResponseText(ex.getMessage());

        gatewayRequest.getResponseDetails().add(gwResp);
    }

    gatewayDetails.getGatewayRequests().add(gatewayRequest);
    logger.debug("GatewayRequest object successfully constructed");
    logger.debug(gatewayDetails);

    return gatewayRequest;
}

From source file:com.datatorrent.lib.bucket.AbstractTimeBasedBucketManager.java

private void recomputeNumBuckets() {
    Calendar calendar = Calendar.getInstance();
    long now = calendar.getTimeInMillis();
    calendar.add(Calendar.DATE, -daysSpan);
    startOfBucketsInMillis = calendar.getTimeInMillis();
    expiryTime = startOfBucketsInMillis;
    noOfBuckets = (int) Math.ceil((now - startOfBucketsInMillis) / (bucketSpanInMillis * 1.0));
    if (bucketStore != null) {
        bucketStore.setNoOfBuckets(noOfBuckets);
        bucketStore.setWriteEventKeysOnly(writeEventKeysOnly);
    }//from  w  ww  .  j  a v a2  s  . c  o m
    maxTimesPerBuckets = new Long[noOfBuckets];
}

From source file:UserInterface.SystemAdmin.ReportsJPanel.java

private void populateTotalBIllGenerated() {
    int total = 0;
    if (system.getNetworkList().size() == 0) {
        totalBillTxt.setText("");
        return;/*from   ww w. jav  a 2s .  c o  m*/
    }
    for (Network network : system.getNetworkList()) {
        for (Enterprise enterprise : network.getEnterpriseDirectory().getEnterpriseList()) {
            if (enterprise instanceof WaterEnterprise) {
                for (Organization organization : enterprise.getOrganizationDirectory().getOrganizationList()) {
                    if (organization instanceof CustomerOrganization) {
                        for (Employee employee : organization.getEmployeeDirectory().getEmployeeList()) {
                            Customer customer = (Customer) employee;
                            total += customer.getTotalBill();
                        }
                    }
                }
            }
        }
    }
    totalBillTxt.setText(String.valueOf(Math.ceil(total)) + "$");
}

From source file:io.cloudex.framework.partition.builtin.BinPackingPartition1.java

@Override
public List<Partition> partition() {

    Validate.notNull(this.items);

    // sort descending
    Collections.sort(items, Collections.reverseOrder());

    /*long seed = System.nanoTime();
    Collections.shuffle(items, new Random(seed));*/

    // have we got a maximum set?, otherwise use the size of the largest item
    Long max = (this.maxBinItems != null) ? this.maxBinItems : items.get(0).getWeight();

    PartitionUtils.setScale(items, max);

    long sum = PartitionUtils.sum(items, max);

    // check if the number of bins have already been set, in which case we have to fit everything in them
    if (this.numberOfBins == null) {
        // lower bound number of bin
        double numBins = (sum / (float) max);
        double numWholeBins = Math.floor(numBins);
        this.numberOfBins = (int) numWholeBins;
        double excess = numBins - numWholeBins;
        if (excess > newBinPercentage) {
            this.numberOfBins++;
        }/*from   ww  w  .  ja v a  2s.co  m*/

    } else {
        max = (long) Math.ceil(sum / (float) this.numberOfBins);
    }

    List<Partition> bins = new ArrayList<>();

    if (this.numberOfBins == 1) {

        Partition bin = new Partition();
        bins.add(bin);
        bin.addAll(items);
        items.clear();

    } else {

        // create all the bins
        for (int i = 0; i < this.numberOfBins; i++) {
            bins.add(new Partition(max));
        }

        List<Item> toRemove = new ArrayList<>();

        int binIndex = 0;

        for (Item item : items) {

            // iterate over bins and try to put the item into the first one it fits into

            Partition startBin = bins.get(binIndex);
            ;
            Partition currentBin = null;
            int count = 0;

            while (!toRemove.contains(item)) { // did we put the item in a bin?

                currentBin = bins.get(binIndex);

                if ((count != 0) && (currentBin == startBin)) {
                    // back where we started item did not fit in last bin. move on
                    break;

                }

                if (currentBin.addIfPossible(item)) {
                    // item fit in bin
                    toRemove.add(item);
                }

                // try next bin
                binIndex++;

                if (binIndex == bins.size()) {
                    // go back to the beginning
                    binIndex = 0;
                }

                count++;

            }
        }

        items.removeAll(toRemove);

        // spread out remaining items, this approximate
        if (!items.isEmpty()) {
            //bins.get(bins.size() - 1).addAll(items);
            //items.clear();

            // items are in descending order
            // sort partitions in ascending order
            Collections.sort(bins);
            //Collections.sort(items, Collections.reverseOrder());

            Partition smallest;
            long largestSum = bins.get(bins.size() - 1).sum();
            int index = 0;
            do {

                smallest = bins.get(index);

                // spread the remaining items into the bins, largest item into smallest bin
                for (int i = 0; i < items.size(); i++) {

                    smallest.add(items.remove(i));

                    if (smallest.sum() > largestSum) {
                        break;
                    }
                }

                index++;
                // there is a large item we can't break
                if (!items.isEmpty() && (index >= bins.size())) {
                    bins.get(index - 1).addAll(items);
                    items.clear();
                }

            } while (!items.isEmpty());

            items.clear();
        }

        for (Partition bin : bins) {
            bin.calculateScale();
        }

    }

    return bins;

}

From source file:net.groupbuy.template.directive.PaginationDirective.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
        throws TemplateException, IOException {
    String pattern = FreemarkerUtils.getParameter(PATTERN_PARAMETER_NAME, String.class, params);
    Integer pageNumber = FreemarkerUtils.getParameter(PAGE_NUMBER_PARAMETER_NAME, Integer.class, params);
    Integer totalPages = FreemarkerUtils.getParameter(TOTAL_PAGES_PARAMETER_NAME, Integer.class, params);
    Integer segmentCount = FreemarkerUtils.getParameter(SEGMENT_COUNT_PARAMETER_NAME, Integer.class, params);

    if (pageNumber == null || pageNumber < 1) {
        pageNumber = 1;/*from   w  w w . j av  a 2s  .c o m*/
    }
    if (totalPages == null || totalPages < 1) {
        totalPages = 1;
    }
    if (segmentCount == null || segmentCount < 1) {
        segmentCount = 5;
    }
    boolean hasPrevious = pageNumber > 1;
    boolean hasNext = pageNumber < totalPages;
    boolean isFirst = pageNumber == 1;
    boolean isLast = pageNumber.equals(totalPages);
    int previousPageNumber = pageNumber - 1;
    int nextPageNumber = pageNumber + 1;
    int firstPageNumber = 1;
    int lastPageNumber = totalPages;
    int startSegmentPageNumber = pageNumber - (int) Math.floor((segmentCount - 1) / 2D);
    int endSegmentPageNumber = pageNumber + (int) Math.ceil((segmentCount - 1) / 2D);
    if (startSegmentPageNumber < 1) {
        startSegmentPageNumber = 1;
    }
    if (endSegmentPageNumber > totalPages) {
        endSegmentPageNumber = totalPages;
    }
    List<Integer> segment = new ArrayList<Integer>();
    for (int i = startSegmentPageNumber; i <= endSegmentPageNumber; i++) {
        segment.add(i);
    }

    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put(PATTERN_VARIABLE_NAME, pattern);
    variables.put(PAGE_NUMBER_VARIABLE_NAME, pageNumber);
    variables.put(PAGE_COUNT_VARIABLE_NAME, totalPages);
    variables.put(SEGMENT_COUNT_VARIABLE_NAME, segmentCount);
    variables.put(HAS_PREVIOUS_VARIABLE_NAME, hasPrevious);
    variables.put(HAS_NEXT_VARIABLE_NAME, hasNext);
    variables.put(IS_FIRST_VARIABLE_NAME, isFirst);
    variables.put(IS_LAST_VARIABLE_NAME, isLast);
    variables.put(PREVIOUS_PAGE_NUMBER_VARIABLE_NAME, previousPageNumber);
    variables.put(NEXT_PAGE_NUMBER_VARIABLE_NAME, nextPageNumber);
    variables.put(FIRST_PAGE_NUMBER_VARIABLE_NAME, firstPageNumber);
    variables.put(LAST_PAGE_NUMBER_VARIABLE_NAME, lastPageNumber);
    variables.put(SEGMENT_VARIABLE_NAME, segment);
    setLocalVariables(variables, env, body);
}