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.eucalyptus.objectstorage.ObjectStorageAvailabilityEventListener.java

@Override
public void fireEvent(final ClockTick event) {
    if (BootstrapArgs.isCloudController() && Bootstrap.isOperational()) {
        try {//from ww  w . j a  v  a  2 s. c o m
            long capacity = 0;
            capacity = ConfigurationCache.getConfiguration(ObjectStorageGlobalConfiguration.class)
                    .getMax_total_reporting_capacity_gb();

            ListenerRegistry.getInstance().fireEvent(new ResourceAvailabilityEvent(StorageWalrus,
                    new Availability(capacity, Math.max(0, capacity - (long) Math
                            .ceil((double) ObjectStorageQuotaUtil.getTotalObjectSize() / FileUtils.ONE_GB)))));
        } catch (Exception ex) {
            logger.error(ex, ex);
        }
    }
}

From source file:umontreal.iro.lecuyer.charts.HistogramSeriesCollection.java

private int calcNumBins(int n) {
    // set the number of bins
    int numbins = (int) Math.ceil(1.0 + Num.log2(n));
    if (n > 5000)
        numbins *= 2;/*from   www . j  a va 2  s.c om*/
    return numbins;
}

From source file:com.l2jfree.gameserver.util.IllegalPlayerAction.java

@Override
public void run() {
    _logAudit.info("AUDIT:" + _message + "," + _actor + " " + _punishment);

    GmListTable.broadcastMessageToGMs(_message);

    switch (_punishment) {
    case PUNISH_BROADCAST:
        return;/*from w  w  w .j a va2 s.  c om*/

    case PUNISH_KICKBAN:
        _actor.setAccountAccesslevel(-100);
        //$FALL-THROUGH$
    case PUNISH_KICK:
        new Disconnection(_actor).defaultSequence(false);
        break;
    case PUNISH_JAIL:
        long duration = Config.DEFAULT_PUNISH_PARAM * 60000;

        if (_actor.isInJail())
            duration = Math.max(duration, _actor.getJailTimer());

        _actor.setInJail(true, (int) Math.ceil(duration / 60000.0));
        break;
    }
}

From source file:com.smithsmodding.armory.api.crafting.blacksmiths.recipe.VanillaAnvilRecipe.java

@Override
public boolean matchesRecipe(ItemStack[] pCraftingSlotContents, ItemStack[] pAdditionalSlotContents,
        int pHammerUsagesLeft, int pTongsUsagesLeft) {
    boolean tCreativePlayerConnected = false;

    for (UUID playerId : iEntity.getWatchingPlayers()) {
        if (PlayerManager.getInstance().getServerSidedJoinedMap().get(playerId).capabilities.isCreativeMode)
            tCreativePlayerConnected = true;
    }// ww w  .j a  v a 2s .  c o m

    if (!tCreativePlayerConnected) {
        float tExperience = XPUtil.getExperienceForLevel(iMaximumCost);
        int tXPPerPlayer = (int) Math.ceil(tExperience / (float) iEntity.getConnectedPlayerCount());

        if (iEntity.getConnectedPlayerCount() == 0)
            return false;

        for (UUID playerId : iEntity.getWatchingPlayers()) {
            if (XPUtil.getPlayerXP(
                    PlayerManager.getInstance().getServerSidedJoinedMap().get(playerId)) < tXPPerPlayer)
                return false;
        }
    }

    return iOutputStack != null;
}

From source file:com.github.parzonka.esa.indexing.IndexInverter.java

public void createInvertedIndex() throws CorruptIndexException, IOException, SimilarityException {

    deleteQuietly(invertedIndexDir);//  w  w w. j  av  a  2s . c om
    invertedIndexDir.mkdirs();

    final IndexReader reader = IndexReader.open(FSDirectory.open(luceneIndexDir));
    final int maxDocumentDistributionCount = (int) Math.ceil(maxCorpusDistribution * reader.numDocs());
    final TermEnum termEnum = reader.terms();
    final Set<String> terms = new HashSet<String>();

    int totalTerms = 0;
    while (termEnum.next()) {
        final String term = termEnum.term().text();
        final int termDocFreq = termEnum.docFreq();
        if (minDocumentFrequency <= termDocFreq && termDocFreq < maxDocumentDistributionCount) {
            terms.add(term);
        }
        totalTerms++;
    }
    reader.close();

    System.out.println("Using " + terms.size() + " terms out of " + totalTerms);
    System.out.println("Input Lucene index: " + luceneIndexDir);
    final LuceneVectorReader luceneVectorReader = new LuceneVectorReader(luceneIndexDir);
    configureLuceneVectorReader(luceneVectorReader);
    System.out.println("Output inverted index: " + invertedIndexDir);
    final VectorIndexWriter vectorIndexWriter = new VectorIndexWriter(invertedIndexDir,
            luceneVectorReader.getConceptCount());

    final ProgressMeter progressMeter = new ProgressMeter(terms.size());
    for (String term : terms) {
        final Vector vector = luceneVectorReader.getVector(term);
        vectorIndexWriter.put(term, vector);
        progressMeter.next();
        System.out.println("[" + term + "] " + progressMeter);
    }
    vectorIndexWriter.close();
}

From source file:divconq.ctp.stream.GzipStream.java

@Override
public ReturnOption handle(FileDescriptor file, ByteBuf data) {
    if (file == FileDescriptor.FINAL)
        return this.downstream.handle(file, data);

    // we don't know what to do with a folder at this stage - gzip is for file content only
    // folder scanning is upstream in the FileSourceStream and partners
    if (file.isFolder())
        return ReturnOption.CONTINUE;

    // init if not set for this round of processing 
    if (this.deflater == null) {
        this.deflater = new Deflater(this.compressionLevel, true);
        this.crc.reset();
        this.writeHeader = true;
    }//from www.j a v  a  2 s .  c  o  m

    ByteBuf in = data;
    ByteBuf out = null;

    if (in != null) {
        byte[] inAry = in.array();

        // always allow for a header (10) plus footer (8) plus extra (12)
        // in addition to content
        int sizeEstimate = (int) Math.ceil(in.readableBytes() * 1.001) + 30;
        out = Hub.instance.getBufferAllocator().heapBuffer(sizeEstimate);

        if (this.writeHeader) {
            this.writeHeader = false;
            out.writeBytes(gzipHeader);
        }

        this.crc.update(inAry, in.arrayOffset(), in.writerIndex());

        this.deflater.setInput(inAry, in.arrayOffset(), in.writerIndex());

        while (!this.deflater.needsInput())
            deflate(out);
    } else
        out = Hub.instance.getBufferAllocator().heapBuffer(30);

    FileDescriptor blk = new FileDescriptor();

    if (StringUtil.isEmpty(this.lastpath)) {
        if (StringUtil.isNotEmpty(this.nameHint))
            this.lastpath = "/" + this.nameHint;
        else if (file.getPath() != null)
            this.lastpath = "/" + GzipUtils.getCompressedFilename(file.path().getFileName());
        else
            this.lastpath = "/" + FileUtil.randomFilename("gz");
    }

    blk.setPath(this.lastpath);

    file.setModTime(System.currentTimeMillis());

    if (file.isEof()) {
        this.deflater.finish();

        while (!this.deflater.finished())
            deflate(out);

        int crcValue = (int) this.crc.getValue();

        out.writeByte(crcValue);
        out.writeByte(crcValue >>> 8);
        out.writeByte(crcValue >>> 16);
        out.writeByte(crcValue >>> 24);

        int uncBytes = this.deflater.getTotalIn();

        out.writeByte(uncBytes);
        out.writeByte(uncBytes >>> 8);
        out.writeByte(uncBytes >>> 16);
        out.writeByte(uncBytes >>> 24);

        this.deflater.end();
        this.deflater = null; // cause a reset for next time we use stream

        blk.setEof(true);
    }

    if (in != null)
        in.release();

    return this.downstream.handle(blk, out);
}

From source file:feedme.controller.SearchRestServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*  w  w w .  jav a2 s.  com*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
    request.setCharacterEncoding("UTF-8");

    String city = request.getParameter("where");//get the city
    int category = Integer.parseInt(request.getParameter("what"));//get the category

    int page = 1;
    int recordsPerPage = 6;

    if (request.getParameter("page") != null) {
        page = Integer.parseInt(request.getParameter("page"));
    }

    List<Restaurant> restaurants = new DbRestaurantsManagement().getNextRecentRestaurantsByCatAndCity(0,
            recordsPerPage, category, city);//getting a list of restaurants by category and cities
    int noOfRecords = restaurants.size();

    int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);

    if (isAjaxRequest(request)) {
        try {
            restaurants = new DbRestaurantsManagement().getNextRecentRestaurantsByCatAndCity(
                    (page - 1) * recordsPerPage, recordsPerPage, category, city);//getting a list of restaurants by category and cities
            JSONObject restObj = new JSONObject();
            JSONArray restArray = new JSONArray();
            for (Restaurant rest : restaurants) {
                restArray.put(new JSONObject().put("resturent", rest.toJson()));
            }
            restObj.put("resturent", restArray);
            restObj.put("noOfPages", noOfPages);
            restObj.put("currentPage", page);
            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            writer.print(restObj);
            response.getWriter().flush();
            return;
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    request.setAttribute("noOfPages", noOfPages);
    request.setAttribute("currentPage", page);
    request.setAttribute("restaurants", restaurants);//return the restaurants to the client

    RequestDispatcher dispatcher = request.getRequestDispatcher("website/search_rest.jsp");
    dispatcher.forward(request, response);

}

From source file:io.cloudex.framework.cloud.entities.VmInstance.java

/**
 * Get the approximate usage cost of this VM
 * @return the usage cost so far of this VM instance
 *//*from  w  w w  . jav a 2  s  .com*/
public double getCost() {
    double cost = 0.0;

    if (this.start != null) {

        Validate.notNull(this.vmConfig);

        Date endDate = this.end;

        if (endDate == null) {
            endDate = new Date();
        }

        double elapsed = endDate.getTime() - this.start.getTime();
        Long minUsage = this.vmConfig.getMinUsage();
        if ((minUsage != null) && (minUsage > elapsed)) {
            elapsed = minUsage;

        } else {
            elapsed = elapsed / 1000;

            // elapsed is in seconds, round up to the nearest minute
            double mins = Math.ceil(elapsed / 60);
            elapsed = (long) (mins * 60);
        }

        Double hourlyCost = this.vmConfig.getCost();

        if (hourlyCost != null) {
            cost = hourlyCost * elapsed / SECONDS_IN_HOUR;
        }

    }

    return cost;
}

From source file:SwiftWork.java

/**
 * Generate and store the file, make everything ready a pure "GET" benchmark 
 * @return return the file name to be used for GET operation
 *///from  www . j av a  2 s .c  o m
public String initForGet() {

    if (client == null || !client.isLoggedin()) {
        client = this.swiftLogin();
    }

    String randfilename = null;
    if (dataObject.getFileSize() < 1024) {
        randfilename = generateRandomFile(String.valueOf(dataObject.getFileSize()), "1");
    } else {
        randfilename = generateRandomFile("1024",
                String.valueOf((int) Math.ceil(dataObject.getFileSize() / 1024)));
    }

    String randfileaddr = getBenchITTemp() + "/" + randfilename;
    String orig_md5 = null;
    try {
        orig_md5 = FilesClient.md5Sum(new File(randfileaddr));
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("Processing file: " + randfileaddr);
    String uploaded_md5 = putFile("benchit_container", randfileaddr, FilesConstants.getMimetype(""));

    //TODO: use assert
    if (!orig_md5.equals(uploaded_md5)) {
        System.out.println("I should terminate the process, and upload the file again...");
    }

    return randfilename;

}

From source file:org.alejandria.web.ajax.querys.AjaxQueryController.java

@RequestMapping(value = "/getAllUsers", method = RequestMethod.GET)
public @ResponseBody JQueryGridPage<Usuario> getAllUsers(@RequestParam int page, @RequestParam int rows) {
    System.out.println(page + " - " + rows);
    int countRows = usuarioDao.getUsersCount();
    final int startIdx = (page - 1) * rows;
    final int endIdx = Math.min(startIdx + rows, countRows);
    int totalPages = (int) (rows < countRows ? Math.ceil(1.0 * countRows / rows) : page);

    List<Usuario> usuarios = usuarioDao.getSetOfUsers(startIdx, endIdx);
    return new JQueryGridPage<Usuario>(page, countRows, totalPages, usuarios);
}