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:main.java.miro.browser.browser.widgets.browser.display.HeightModifier.java

@Override
public void handleEvent(Event event) {

    GC gc;//from   www .j a  va  2s  . com
    String textString = null;
    Text s = (Text) event.widget;
    int lineHeight = s.getLineHeight();

    Rectangle cd = s.getClientArea();
    int lineWidth = s.getClientArea().width;
    if (event.widget instanceof Text) {
        textString = s.getText();
        gc = new GC(s);
    } else if (event.widget instanceof Link) {
        Link l = (Link) event.widget;
        textString = l.getText();
        gc = new GC(l);
    } else {
        return;
    }

    int newLineCount = StringUtils.countMatches(textString, "\n");
    if (newLineCount > 0) {
        //         textString = textString.replace("\n", " ");
        //         s.setText(textString);
    }

    newLineCount = StringUtils.countMatches(textString, "\n");
    if (textString == null | textString.length() == 0) {
        textString = "None";

        if (event.widget instanceof Text) {
            ((Text) event.widget).setText(textString);
        } else {
            ((Link) event.widget).setText(textString);
        }
    }

    RowData rowData = (RowData) field.getLayoutData();

    // Calculate new height, based on strinWidth
    int stringWidth = gc.stringExtent(textString).x;

    // Divide by our width, factor is how many lines we expect from this
    // input
    double factor = stringWidth / (double) (lineWidth);

    int minLines = field.getMinLines();
    int lines = Math.max((int) factor, minLines);

    // Calculate our new preferred height
    int height = (int) (Math.ceil(lines) * lineHeight);
    for (int i = 0; i < newLineCount; i++) {
        height += lineHeight;
    }
    //      rowData.height = height;

    //      if (height == 0 | height >= minLines) {
    //         rowData.height = height;
    //      } else if (height < minLines) {
    //         rowData.height = minLines;
    //      }
    //      field.setLayoutData(rowData);

    Composite c = field.getParent();
    while (!(c instanceof DisplayWidget)) {
        c = c.getParent();
    }

    DisplayWidget dw = (DisplayWidget) c;
    dw.getParent().layout();
    dw.getParent().getParent().layout();
    Point size = dw.computeSize(dw.getSize().x, SWT.DEFAULT);
    //      Point size = dw.computeSize(SWT.DEFAULT, SWT.DEFAULT);
    Point wat = dw.getParent().computeSize(SWT.DEFAULT, SWT.DEFAULT);

    ScrolledComposite scroller = (ScrolledComposite) dw.getParent();
    scroller.setMinHeight(size.y);
    dw.layout(true);
    dw.pack();
}

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

@Override
public List<Partition> partition() {

    Validate.notNull(this.items);

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

    // 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++;
        }//  w  w  w  .  j  a  va2s .  c  o  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 {

        // Mix of First Fit Decreasing (FFD) strategy and Full Bin strategy
        for (int i = 0; i < this.numberOfBins; i++) {
            Partition bin = new Partition();
            bins.add(bin);

            // check if we have ran out of items
            if (!items.isEmpty()) {

                Item largestItem = items.get(0);

                bin.add(largestItem);
                items.remove(largestItem);

                Long currentSum = bin.sum();

                if (currentSum < max) {
                    Long diff = max - currentSum;
                    List<Item> toRemove = new ArrayList<>();

                    for (Item item : items) {
                        //Item item = items.get(j);
                        if (item.getWeight() <= diff) {

                            bin.add(item);
                            toRemove.add(item);

                            if (item.getWeight() == diff) {
                                break;
                            } else {
                                // look for an even small number to fill the gap
                                diff = max - bin.sum();
                            }
                        }
                    }

                    items.removeAll(toRemove);

                }
            }
            bin.calculateScale();
        }

        /*if(!items.isEmpty()) {
        bins.get(bins.size() - 1).addAll(items);
        items.clear();
        }*/

        // 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);

            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++;

            } while (!items.isEmpty());

            items.clear();
        }

    }

    return bins;

}

From source file:edu.stanford.cfuller.imageanalysistools.filter.Kernel.java

public void formatTransformFrom1DInput(int size0, int size1) {

    int ydimPowOfTwo = size0;
    int xdimPowOfTwo = size1;

    if (!org.apache.commons.math3.util.ArithmeticUtils.isPowerOfTwo(ydimPowOfTwo)
            || !org.apache.commons.math3.util.ArithmeticUtils.isPowerOfTwo(xdimPowOfTwo)) {

        xdimPowOfTwo = (int) Math.pow(2, Math.ceil(Math.log(size1) / Math.log(2)));
        ydimPowOfTwo = (int) Math.pow(2, Math.ceil(Math.log(size0) / Math.log(2)));
    }//from   w ww  .  j  a v a  2 s . c o m

    Complex[][] colMajorImage = new Complex[xdimPowOfTwo][ydimPowOfTwo];

    int counter = 0;

    for (int i = 0; i < colMajorImage.length; i++) {
        for (int j = 0; j < colMajorImage[0].length; j++) {

            colMajorImage[i][j] = new Complex(this.weights[counter++], this.weights[counter++]);

        }

    }

    this.transform = colMajorImage;
}

From source file:ar.com.zauber.commons.dao.Paging.java

/**
 * Retorna el nmero de la ltima pgina.// w w  w  .j a v a2  s. co m
 * 
 * @return the last page number
 */
public final int getLastPageNumber() {
    if (resultSize == null) {
        throw new IllegalStateException("No se sete el tamao del " + "resultado");
    }

    return Math.round(new Float(Math.ceil((double) resultSize / resultsPerPage)));
}

From source file:com.aliyun.fs.oss.nat.BufferReader.java

private void prepareBeforeFetch() throws IOException {
    if (algorithmVersion == 1) {
        this.fileContentLength = store.retrieveMetadata(key).getLength();
        this.lengthToFetch = fileContentLength - pos;
        this.bufferSize = lengthToFetch < 16 * 1024 * 1024 ? 1024 * 1024
                : (lengthToFetch > 1024 * 1024 * 1024 ? 64 * 1024 * 1024 : (int) (lengthToFetch / 16));
        if (Math.log(bufferSize) / Math.log(2) != 0) {
            int power = (int) Math.ceil(Math.log(bufferSize) / Math.log(2));
            this.bufferSize = (int) Math.pow(2, power);
        }//from  ww w  .j a  va2 s.c  om

        if (buffer == null) {
            buffer = new byte[bufferSize];
        }
        this.concurrentStreams = conf.getInt("fs.oss.reader.concurrent.number", 4);
        if ((Math.log(concurrentStreams) / Math.log(2)) != 0) {
            int power = (int) Math.ceil(Math.log(concurrentStreams) / Math.log(2));
            this.concurrentStreams = (int) Math.pow(2, power);
        }
        this.readers = new ConcurrentReader[concurrentStreams];
        this.splitContentSize = new int[concurrentStreams * 2];
        this.splitSize = bufferSize / concurrentStreams / 2;

        initializeTaskEngine();
    } else {
        in = store.retrieve(key, pos);
    }
}

From source file:edu.uga.cs.fluxbuster.clustering.hierarchicalclustering.DistanceMatrix.java

/**
 * Populate distance matrix from a list of matrix values specified in row
 * major order.//from   ww  w . j av  a  2s  .c  o  m
 * 
 * @param vals
 *            the matrix values
 */
private void populateDistanceMatrix(Vector<Float> vals) {
    int matrixdim = (int) Math.ceil(Math.sqrt(2 * vals.size()));

    int length = matrixdim - 1;
    int start = 0;
    for (int i = 0; i < matrixdim - 1; i++) {
        Vector<Float> row = new Vector<Float>();
        row.addAll(vals.subList(start, start + length));
        distMatrix.add(row);
        start += length;
        length--;
    }
}

From source file:com.googlecode.psiprobe.jsp.VisualScoreTag.java

StringBuffer calculateSuffix(String body) {
    if (value < minValue) {
        log.info("value " + value + " is less than min value " + minValue);
        value = minValue;//  ww  w.ja va2s.co m
    }
    if (value > maxValue) {
        log.info("value " + value + " is greater than max value " + maxValue);
        value = maxValue;
    }
    if (value + value2 < minValue || value2 < 0) {
        log.info("value2 " + value2 + " is less than min value");
        value2 = 0;
    }
    if (value + value2 > maxValue) {
        log.info("value2 " + value2 + " is greater than max value");
        value2 = maxValue - value;
    }

    double unitSize = (maxValue - minValue) / (fullBlocks * partialBlocks);
    double blockWidth = unitSize * partialBlocks;

    int fullRedBlockCount = (int) Math.floor(value / blockWidth);
    int partialRedBlockIndex = (int) Math.floor((value - fullRedBlockCount * blockWidth) / unitSize);
    int partialBlueBlockIndex1 = (partialRedBlockIndex > 0
            ? Math.min((int) Math.floor(value2 / unitSize), partialBlocks - partialRedBlockIndex)
            : 0);
    int fullBlueBlockCount = Math.max(0,
            (int) Math.ceil(value2 / blockWidth) - (partialRedBlockIndex > 0 ? 1 : 0));
    int partialBlueBlockIndex2 = (int) Math.floor(
            (value2 - (fullBlueBlockCount * blockWidth) - (partialBlueBlockIndex1 * unitSize)) / unitSize);

    StringBuffer buf = new StringBuffer();

    // Beginning
    if (showA) {
        String format = WHITE_LEFT_BORDER;
        if (fullRedBlockCount > 0 || partialRedBlockIndex > 0) {
            format = RED_LEFT_BORDER;
        } else if (partialBlueBlockIndex1 == 0 && (fullBlueBlockCount > 0 || partialBlueBlockIndex2 > 0)) {
            format = BLUE_LEFT_BORDER;
        }
        buf.append(MessageFormat.format(body, new Object[] { format }));
    }

    // Full red blocks
    String fullRedBody = MessageFormat.format(body, new Object[] { partialBlocks + "+0" });
    for (int i = 0; i < fullRedBlockCount; i++) {
        buf.append(fullRedBody);
    }

    // Mixed red/blue block (mid-block transition)
    if (partialRedBlockIndex > 0) {
        String partialBody = MessageFormat.format(body,
                new Object[] { partialRedBlockIndex + "+" + partialBlueBlockIndex1 });
        buf.append(partialBody);
    }

    // Full blue blocks
    String fullBlueBody = MessageFormat.format(body, new Object[] { "0+" + partialBlocks });
    for (int i = 0; i < fullBlueBlockCount; i++) {
        buf.append(fullBlueBody);
    }

    // Partial blue block
    if (partialBlueBlockIndex2 > 0) {
        String partialBody = MessageFormat.format(body, new Object[] { "0+" + partialBlueBlockIndex2 });
        buf.append(partialBody);
    }

    // Empty blocks
    int emptyBlocks = showEmptyBlocks ? fullBlocks - (fullRedBlockCount + fullBlueBlockCount
            + (partialRedBlockIndex > 0 ? 1 : 0) + (partialBlueBlockIndex2 > 0 ? 1 : 0)) : 0;
    if (emptyBlocks > 0) {
        String emptyBody = MessageFormat.format(body, new Object[] { "0+0" });
        for (int i = 0; i < emptyBlocks; i++) {
            buf.append(emptyBody);
        }
    }

    // End
    if (showB) {
        String format = WHITE_RIGHT_BORDER;
        if (fullRedBlockCount == fullBlocks) {
            format = RED_RIGHT_BORDER;
        } else if (fullRedBlockCount + (partialRedBlockIndex + partialBlueBlockIndex1 == partialBlocks ? 1 : 0)
                + fullBlueBlockCount == fullBlocks) {
            format = BLUE_RIGHT_BORDER;
        }
        buf.append(MessageFormat.format(body, new Object[] { format }));
    }

    return buf;
}

From source file:info.raack.appliancedetection.evaluation.model.appliance.SineWaveDevice.java

protected int powerDrawAtOnCycleTimestep(int totalSeconds, int secondIndex, int globalTimestep) {
    return (int) (Math.sin((2 * Math.PI) * (float) secondIndex / wavelength) * maxAmplitude)
            + (int) Math.ceil(maxAmplitude);
}

From source file:ldbc.snb.datagen.generator.PostGenerator.java

public long createPosts(RandomGeneratorFarm randomFarm, final Forum forum,
        final ArrayList<ForumMembership> memberships, long numPosts, long startId,
        PersonActivityExporter exporter) throws IOException {
    long postId = startId;
    Properties prop = new Properties();
    prop.setProperty("type", "post");
    ArrayList<Post> result = new ArrayList<Post>();
    for (ForumMembership member : memberships) {
        double numPostsMember = numPosts / (double) memberships.size();
        if (numPostsMember < 1.0) {
            double prob = randomFarm.get(RandomGeneratorFarm.Aspect.NUM_POST).nextDouble();
            if (prob < numPostsMember)
                numPostsMember = 1.0;/*w ww .  jav a  2  s  .co m*/
        } else {
            numPostsMember = Math.ceil(numPostsMember);
        }
        for (int i = 0; i < (int) (numPostsMember); ++i) {
            PostInfo postInfo = generatePostInfo(randomFarm.get(RandomGeneratorFarm.Aspect.TAG),
                    randomFarm.get(RandomGeneratorFarm.Aspect.DATE), forum, member);
            if (postInfo != null) {

                String content = "";

                // crear properties class para passar
                content = this.generator_.generateText(member.person(), postInfo.tags, prop);
                post_.initialize(SN.formId(SN.composeId(postId++, postInfo.date)), postInfo.date,
                        member.person(), forum.id(), content, postInfo.tags,
                        Dictionaries.ips.getIP(randomFarm.get(RandomGeneratorFarm.Aspect.IP),
                                randomFarm.get(RandomGeneratorFarm.Aspect.DIFF_IP),
                                randomFarm.get(RandomGeneratorFarm.Aspect.DIFF_IP_FOR_TRAVELER),
                                member.person().ipAddress(), postInfo.date),
                        Dictionaries.browsers.getPostBrowserId(
                                randomFarm.get(RandomGeneratorFarm.Aspect.DIFF_BROWSER),
                                randomFarm.get(RandomGeneratorFarm.Aspect.BROWSER),
                                member.person().browserId()),
                        forum.language());
                if (richRdf) {
                    post_.richRdf(true);
                    if (randomFarm.get(RandomGeneratorFarm.Aspect.POST_MENTIONED).nextDouble() > 0.6) {
                        TreeSet<Long> t = new TreeSet<Long>();
                        // The user mentions one or more (up to 4) members of the forum                                                                                                
                        t.add(memberships
                                .get(randomFarm.get(RandomGeneratorFarm.Aspect.MEMBERSHIP_INDEX_POST_MENTIONED)
                                        .nextInt(memberships.size()))
                                .person().accountId());
                        double probabilityForNumberOfMentions = randomFarm
                                .get(RandomGeneratorFarm.Aspect.POST_MENTIONED_NUM).nextDouble();
                        if (probabilityForNumberOfMentions > 0.5)
                            t.add(memberships.get(
                                    randomFarm.get(RandomGeneratorFarm.Aspect.MEMBERSHIP_INDEX_POST_MENTIONED)
                                            .nextInt(memberships.size()))
                                    .person().accountId());
                        if (probabilityForNumberOfMentions > 0.75)
                            t.add(memberships.get(
                                    randomFarm.get(RandomGeneratorFarm.Aspect.MEMBERSHIP_INDEX_POST_MENTIONED)
                                            .nextInt(memberships.size()))
                                    .person().accountId());
                        if (probabilityForNumberOfMentions > 0.95)
                            t.add(memberships.get(
                                    randomFarm.get(RandomGeneratorFarm.Aspect.MEMBERSHIP_INDEX_POST_MENTIONED)
                                            .nextInt(memberships.size()))
                                    .person().accountId());
                        post_.mentioned(t);
                    }
                    if (randomFarm.get(RandomGeneratorFarm.Aspect.POST_VISIBILITY).nextDouble() > 0.95) {
                        if (post_.mentioned() == null || randomFarm
                                .get(RandomGeneratorFarm.Aspect.POST_VISIBILITY_TF).nextDouble() > 0.5)
                            post_.setPublic(true);
                        else
                            post_.setPublic(false);
                    }
                    if (randomFarm.get(RandomGeneratorFarm.Aspect.POST_LINK).nextDouble() > 0.57) {
                        post_.link("http://ld.bc/" + RandomStringUtils.random(6, true, false));
                    }
                }
                if (richRdf && randomFarm.get(RandomGeneratorFarm.Aspect.POST_COUNTRY).nextDouble() > 0.02)
                    post_.countryKnown(false);
                exporter.export(post_);

                if (randomFarm.get(RandomGeneratorFarm.Aspect.NUM_LIKE).nextDouble() <= 0.1) {
                    likeGenerator_.generateLikes(randomFarm.get(RandomGeneratorFarm.Aspect.NUM_LIKE), forum,
                            post_, Like.LikeType.POST, exporter);
                }

                //// generate comments
                int numComments = randomFarm.get(RandomGeneratorFarm.Aspect.NUM_COMMENT)
                        .nextInt(DatagenParams.maxNumComments + 1);
                postId = commentGenerator_.createComments(randomFarm, forum, post_, numComments, postId,
                        exporter);
            }
        }
    }
    return postId;
}

From source file:io.github.apfelcreme.Guilds.UUIDFetcher.java

public Map<String, UUID> call() throws Exception {
    Map<String, UUID> uuidMap = new HashMap<String, UUID>();
    int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST);
    for (int i = 0; i < requests; i++) {
        HttpURLConnection connection = createConnection();
        String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size())));
        writeBody(connection, body);//  www .j  ava2 s .c om
        JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
        for (Object profile : array) {
            JSONObject jsonProfile = (JSONObject) profile;
            String id = (String) jsonProfile.get("id");
            String name = (String) jsonProfile.get("name");
            UUID uuid = UUIDFetcher.getUUID(id);
            uuidMap.put(name, uuid);
        }
        if (rateLimiting && i != requests - 1) {
            Thread.sleep(10L);
        }
    }
    return uuidMap;
}