Example usage for java.lang Math floor

List of usage examples for java.lang Math floor

Introduction

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

Prototype

public static double floor(double a) 

Source Link

Document

Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.

Usage

From source file:io.hops.experiments.results.compiler.InterleavedBMResultsAggregator.java

public static InterleavedBMResults processInterleavedResults(Collection<Object> responses, Configuration args)
        throws FileNotFoundException, IOException, InterruptedException {
    Map<BenchmarkOperations, double[][]> allOpsPercentiles = new HashMap<BenchmarkOperations, double[][]>();
    System.out.println("Processing the results ");
    DescriptiveStatistics successfulOps = new DescriptiveStatistics();
    DescriptiveStatistics failedOps = new DescriptiveStatistics();
    DescriptiveStatistics speed = new DescriptiveStatistics();
    DescriptiveStatistics duration = new DescriptiveStatistics();
    DescriptiveStatistics opsLatency = new DescriptiveStatistics();
    DescriptiveStatistics noOfNNs = new DescriptiveStatistics();
    for (Object obj : responses) {
        if (!(obj instanceof InterleavedBenchmarkCommand.Response)) {
            throw new IllegalStateException("Wrong response received from the client");
        } else {/*from   w w w.j  av a 2  s  .co m*/
            InterleavedBenchmarkCommand.Response response = (InterleavedBenchmarkCommand.Response) obj;
            successfulOps.addValue(response.getTotalSuccessfulOps());
            failedOps.addValue(response.getTotalFailedOps());
            speed.addValue(response.getOpsPerSec());
            duration.addValue(response.getRunTime());
            opsLatency.addValue(response.getAvgOpLatency());
            noOfNNs.addValue(response.getNnCount());
        }
    }

    //write the response objects to files. 
    //these files are processed by CalculatePercentiles.java
    int responseCount = 0;
    for (Object obj : responses) {
        if (!(obj instanceof InterleavedBenchmarkCommand.Response)) {
            throw new IllegalStateException("Wrong response received from the client");
        } else {
            String filePath = args.getResultsDir();
            if (!filePath.endsWith("/")) {
                filePath += "/";
            }
            InterleavedBenchmarkCommand.Response response = (InterleavedBenchmarkCommand.Response) obj;
            filePath += "ResponseRawData" + responseCount++ + ConfigKeys.RAW_RESPONSE_FILE_EXT;
            System.out.println("Writing Rwaw results to " + filePath);
            FileOutputStream fout = new FileOutputStream(filePath);
            ObjectOutputStream oos = new ObjectOutputStream(fout);
            oos.writeObject(response);
            oos.close();
        }
    }

    InterleavedBMResults result = new InterleavedBMResults(args.getNamenodeCount(),
            (int) Math.floor(noOfNNs.getMean()), args.getNdbNodesCount(), args.getInterleavedBmWorkloadName(),
            (successfulOps.getSum() / ((duration.getMean() / 1000))), (duration.getMean() / 1000),
            (successfulOps.getSum()), (failedOps.getSum()), allOpsPercentiles, opsLatency.getMean());

    //    // failover testing
    //    if(args.testFailover()){
    //      if(responses.size() != 1){
    //        throw new UnsupportedOperationException("Currently we only support failover testing for one slave machine");
    //      }
    //
    //      String prefix = args.getBenchMarkFileSystemName().toString();
    //      if(args.getBenchMarkFileSystemName() == BenchMarkFileSystemName.HopsFS){
    //        prefix+="-"+args.getNameNodeSelectorPolicy();
    //      }
    //
    //      final String outputFolder = args.getResultsDir();
    //      InterleavedBenchmarkCommand.Response response = (InterleavedBenchmarkCommand.Response)responses.iterator().next();
    //
    //
    //      StringBuilder sb = new StringBuilder();
    //      for(String data : response.getFailOverLog()){
    //        sb.append(data).append("\n");
    //      }
    //
    //      String datFile = prefix+"-failover.dat";
    //      CompileResults.writeToFile(outputFolder+"/"+datFile, sb.toString(), false);
    //
    //
    //      StringBuilder plot = new StringBuilder("set terminal postscript eps enhanced color font \"Helvetica,18\"  #monochrome\n");
    //      plot.append( "set output '| ps2pdf - failover.pdf'\n");
    //      plot.append( "#set size 1,0.75 \n ");
    //      plot.append( "set ylabel \"ops/sec\" \n");
    //      plot.append( "set xlabel \"Time (sec)\" \n");
    //      plot.append( "set format y \"%.0s%c\"\n");
    //
    //
    //      StringBuilder sbx = new StringBuilder();
    //      String oldPt = "";
    //      for(String data : response.getFailOverLog()){
    //
    //        if(data.startsWith("#")) {
    //          StringTokenizer st = new StringTokenizer(oldPt);
    //          long time = Long.parseLong(st.nextToken());
    //          long spd = Long.parseLong(st.nextToken());
    //          sbx.append("set label 'NN-Restart' at "+time+","+spd+" rotate by 270").append("\n");
    //        }
    //        oldPt = data;
    //      }
    //      plot.append(sbx.toString());
    //
    //
    //      plot.append( "plot '"+datFile+"' with linespoints ls 1");
    //      CompileResults.writeToFile(outputFolder+"/"+prefix+"-failover.gnu", plot.toString(), false);
    //
    //    }

    return result;
}

From source file:no.uio.medicine.virsurveillance.charts.StackedChart_AWT.java

private Color getColor(int index) {
    int index2 = index + this.colorOffset;
    switch (index2) {
    case 0://  ww w .j a  v a  2 s .com
        return Color.RED;
    case 1:
        return Color.BLUE;
    case 2:
        return Color.GREEN;
    case 3:
        return Color.YELLOW;
    case 4:
        return Color.DARK_GRAY;
    case 5:
        return Color.ORANGE;
    case 6:
        return Color.BLACK;
    case 7:
        return Color.CYAN;
    case 8:
        return Color.GRAY;
    case 9:
        return Color.LIGHT_GRAY;
    case 10:
        return Color.MAGENTA;
    case 11:
        return Color.PINK;
    case 12:
        return Color.WHITE;
    default:
        return getColor((int) Math.floor(Math.random() * 14));
    }

}

From source file:com.fdwills.external.http.JsonStreamerEntity.java

@Override
public void writeTo(final OutputStream out) throws IOException {
    if (out == null) {
        throw new IllegalStateException("Output stream cannot be null.");
    }/*  w  w w. jav  a2s .c  o  m*/

    // Record the time when uploading started.
    long now = System.currentTimeMillis();

    // Use GZIP compression when sending streams, otherwise just use
    // a buffered output stream to speed things up a bit.
    OutputStream os = null != contentEncoding ? new GZIPOutputStream(out, BUFFER_SIZE) : out;

    // Always send a JSON object.
    os.write('{');

    // Keys used by the HashMaps.
    Set<String> keys = jsonParams.keySet();

    boolean isFileWrapper;

    // Go over all keys and handle each's value.
    for (String key : keys) {
        // Evaluate the value (which cannot be null).
        Object value = jsonParams.get(key);

        // Bail out prematurely if value's null.
        if (value == null) {
            continue;
        }

        // Write the JSON object's key.
        os.write(escape(key));
        os.write(':');

        // Check if this is a FileWrapper.
        isFileWrapper = value instanceof RequestParams.FileWrapper;

        // If a file should be uploaded.
        if (isFileWrapper || value instanceof RequestParams.StreamWrapper) {
            // All uploads are sent as an object containing the file's details.
            os.write('{');

            // Determine how to handle this entry.
            if (isFileWrapper) {
                writeToFromFile(os, (RequestParams.FileWrapper) value);
            } else {
                writeToFromStream(os, (RequestParams.StreamWrapper) value);
            }

            // End the file's object and prepare for next one.
            os.write('}');
        } else if (value instanceof JsonValueInterface) {
            os.write(((JsonValueInterface) value).getEscapedJsonValue());
        } else if (value instanceof org.json.JSONObject) {
            os.write(((org.json.JSONObject) value).toString().getBytes());
        } else if (value instanceof org.json.JSONArray) {
            os.write(((org.json.JSONArray) value).toString().getBytes());
        } else if (value instanceof Boolean) {
            os.write((Boolean) value ? JSON_TRUE : JSON_FALSE);
        } else if (value instanceof Long) {
            os.write((((Number) value).longValue() + "").getBytes());
        } else if (value instanceof Double) {
            os.write((((Number) value).doubleValue() + "").getBytes());
        } else if (value instanceof Float) {
            os.write((((Number) value).floatValue() + "").getBytes());
        } else if (value instanceof Integer) {
            os.write((((Number) value).intValue() + "").getBytes());
        } else {
            os.write(escape(value.toString()));
        }

        os.write(',');
    }

    // Include the elapsed time taken to upload everything.
    // This might be useful for somebody, but it serves us well since
    // there will almost always be a ',' as the last sent character.
    os.write(STREAM_ELAPSED);
    os.write(':');
    long elapsedTime = System.currentTimeMillis() - now;
    os.write((elapsedTime + "}").getBytes());

    Log.i(LOG_TAG, "Uploaded JSON in " + Math.floor(elapsedTime / 1000) + " seconds");

    // Flush the contents up the stream.
    os.flush();
    AsyncHttpClient.silentCloseOutputStream(os);
}

From source file:com.lfrj.diancan.http.JsonStreamerEntity.java

@Override
public void writeTo(final OutputStream out) throws IOException {
    if (out == null) {
        throw new IllegalStateException("Output stream cannot be null.");
    }/*from  w w  w  .  ja  v a 2 s .  c o  m*/

    // Record the time when uploading started.
    long now = System.currentTimeMillis();

    // Use GZIP compression when sending streams, otherwise just use
    // a buffered output stream to speed things up a bit.
    OutputStream os = null != contentEncoding ? new GZIPOutputStream(out, BUFFER_SIZE) : out;

    // Always send a JSON object.
    os.write('{');

    // Keys used by the HashMaps.
    Set<String> keys = jsonParams.keySet();

    boolean isFileWrapper;

    // Go over all keys and handle each's value.
    for (String key : keys) {
        // Evaluate the value (which cannot be null).
        Object value = jsonParams.get(key);

        // Bail out prematurely if value's null.
        if (value == null) {
            continue;
        }

        // Write the JSON object's key.
        os.write(escape(key));
        os.write(':');

        // Check if this is a FileWrapper.
        isFileWrapper = value instanceof RequestParams.FileWrapper;

        // If a file should be uploaded.
        if (isFileWrapper || value instanceof RequestParams.StreamWrapper) {
            // All uploads are sent as an object containing the file's
            // details.
            os.write('{');

            // Determine how to handle this entry.
            if (isFileWrapper) {
                writeToFromFile(os, (RequestParams.FileWrapper) value);
            } else {
                writeToFromStream(os, (RequestParams.StreamWrapper) value);
            }

            // End the file's object and prepare for next one.
            os.write('}');
        } else if (value instanceof JsonValueInterface) {
            os.write(((JsonValueInterface) value).getEscapedJsonValue());
        } else if (value instanceof org.json.JSONObject) {
            os.write(((org.json.JSONObject) value).toString().getBytes());
        } else if (value instanceof org.json.JSONArray) {
            os.write(((org.json.JSONArray) value).toString().getBytes());
        } else if (value instanceof Boolean) {
            os.write((Boolean) value ? JSON_TRUE : JSON_FALSE);
        } else if (value instanceof Long) {
            os.write((((Number) value).longValue() + "").getBytes());
        } else if (value instanceof Double) {
            os.write((((Number) value).doubleValue() + "").getBytes());
        } else if (value instanceof Float) {
            os.write((((Number) value).floatValue() + "").getBytes());
        } else if (value instanceof Integer) {
            os.write((((Number) value).intValue() + "").getBytes());
        } else {
            os.write(escape(value.toString()));
        }

        os.write(',');
    }

    // Include the elapsed time taken to upload everything.
    // This might be useful for somebody, but it serves us well since
    // there will almost always be a ',' as the last sent character.
    os.write(STREAM_ELAPSED);
    os.write(':');
    long elapsedTime = System.currentTimeMillis() - now;
    os.write((elapsedTime + "}").getBytes());

    Log.i(LOG_TAG, "Uploaded JSON in " + Math.floor(elapsedTime / 1000) + " seconds");

    // Flush the contents up the stream.
    os.flush();
    AsyncHttpClient.silentCloseOutputStream(os);
}

From source file:ark.data.annotation.DataSet.java

public <C> List<DataSet<D, L>> makePartition(double[] distribution, Datum.Tools.Clusterer<D, L, C> clusterer,
        Random random) {// ww  w. ja  v  a2  s.  c o  m
    Map<C, List<D>> clusters = cluster(clusterer);
    List<C> clusterList = MathUtil.randomPermutation(random, new ArrayList<C>(clusters.keySet()));
    List<DataSet<D, L>> partition = new ArrayList<DataSet<D, L>>(distribution.length);

    int offset = 0;
    for (int i = 0; i < distribution.length; i++) {
        int partSize = (int) Math.floor(clusterList.size() * distribution[i]);
        if (i == distribution.length - 1 && offset + partSize < clusterList.size())
            partSize = clusterList.size() - offset;

        DataSet<D, L> part = new DataSet<D, L>(this.datumTools, this.labelMapping);
        for (int j = offset; j < offset + partSize; j++) {
            part.addAll(clusters.get(clusterList.get(j)));
        }

        offset += partSize;
        partition.add(part);
    }

    return partition;
}

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox.PDFAsVisualSignatureBuilder.java

private void readTableResources(PDFBoxTable table, PDDocument template) throws PdfAsException, IOException {

    float[] colsSizes = table.getColsRelativeWith();
    int max_cols = table.getColCount();
    float padding = table.getPadding();
    if (colsSizes == null) {
        colsSizes = new float[max_cols];
        // set the column ratio for all columns to 1
        for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) {
            colsSizes[cols_idx] = 1;//from   ww w  .j ava  2  s  .  c o m
        }
    }

    logger.debug("TOTAL Width: " + table.getWidth());

    float total = 0;

    for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) {
        total += colsSizes[cols_idx];
    }

    for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) {
        colsSizes[cols_idx] = (colsSizes[cols_idx] / total) * table.getWidth();
    }

    for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) {
        logger.debug("Col: " + cols_idx + " : " + colsSizes[cols_idx]);
    }

    /*
     * if(!addedFonts.contains(table.getFont().getFont(null))) { PDFont font
     * = table.getFont().getFont(template); addedFonts.add(font);
     * innerFormResources.addFont(font); }
     *
     * if(!addedFonts.contains(table.getValueFont().getFont(null))) { PDFont
     * font = table.getValueFont().getFont(template); addedFonts.add(font);
     * innerFormResources.addFont(font); }
     */

    for (int i = 0; i < table.getRowCount(); i++) {
        ArrayList<Entry> row = table.getRow(i);
        for (int j = 0; j < row.size(); j++) {
            Entry cell = (Entry) row.get(j);
            if (cell.getType() == Entry.TYPE_IMAGE) {
                String img_value = (String) cell.getValue();
                String img_ref = createHashedId(img_value);
                if (!images.containsKey(img_ref)) {
                    BufferedImage img = ImageUtils.getImage(img_value, settings);

                    float width = colsSizes[j];
                    float height = table.getRowHeights()[i] + padding * 2;

                    float iwidth = (int) Math.floor((double) width);
                    iwidth -= 2 * padding;

                    float iheight = (int) Math.floor((double) height);
                    iheight -= 2 * padding;

                    float origWidth = (float) img.getWidth();
                    float origHeight = (float) img.getHeight();

                    if (table.style != null) {
                        if (table.style.getImageScaleToFit() != null) {
                            iwidth = table.style.getImageScaleToFit().getWidth();
                            iheight = table.style.getImageScaleToFit().getHeight();
                        }
                    }

                    float wfactor = iwidth / origWidth;
                    float hfactor = iheight / origHeight;
                    float scaleFactor = wfactor;
                    if (hfactor < wfactor) {
                        scaleFactor = hfactor;
                    }

                    iwidth = (float) Math.floor((double) (scaleFactor * origWidth));
                    iheight = (float) Math.floor((double) (scaleFactor * origHeight));

                    logger.debug("Scaling image to: " + iwidth + " x " + iheight);

                    if (this.designer.properties.getSignatureProfileSettings().isPDFA()) {
                        img = ImageUtils.removeAlphaChannel(img);
                    } else {
                        if (img.getAlphaRaster() == null && img.getColorModel().hasAlpha()) {
                            img = ImageUtils.removeAlphaChannel(img);
                        }
                    }
                    // img = ImageUtils.convertRGBAToIndexed(img);

                    PDXObjectImage pdImage = new PDPixelMap(template, img);

                    ImageObject image = new ImageObject(pdImage, iwidth, iheight);
                    images.put(img_ref, image);
                    innerFormResources.addXObject(pdImage, "Im");
                }
            } else if (cell.getType() == Entry.TYPE_TABLE) {
                PDFBoxTable tbl_value = (PDFBoxTable) cell.getValue();
                readTableResources(tbl_value, template);
            }
        }
    }
}

From source file:com.eyekabob.EventInfo.java

private void handleImageResponse(Bitmap img) {
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    float metWidth = metrics.widthPixels;
    float imgWidth = img.getWidth();
    float ratio = metWidth / imgWidth;
    // Add a little buffer room
    int newWidth = (int) Math.floor(img.getWidth() * ratio) - 50;
    int newHeight = (int) Math.floor(img.getHeight() * ratio) - 50;

    ImageView iv = (ImageView) findViewById(R.id.infoImageView);
    Bitmap rescaledImg = Bitmap.createScaledBitmap(img, newWidth, newHeight, false);
    iv.setImageBitmap(rescaledImg);//from   ww w.j  a v  a 2  s. c om
}

From source file:fr.amap.lidar.amapvox.jeeb.archimed.raytracing.voxel.DirectionalTransmittance.java

public double directionalTransmittance(Point3d origin, Vector3d direction) {

    List<Double> distances = distToVoxelWallsV2(origin, direction);

    //we can optimize this by storing the angle value to avoid repeating this for each position
    double directionAngle = FastMath.toDegrees(FastMath.acos(direction.z));

    double dMoy;//from w  w w.ja va 2s  .c o m
    Point3d pMoy;

    double d1 = 0;
    double transmitted = 1;
    for (Double d2 : distances) {
        double pathLength = d2 - d1;
        dMoy = (d1 + d2) / 2.0;
        pMoy = new Point3d(direction);
        pMoy.scale(dMoy);
        pMoy.add(origin);
        pMoy.sub(min);

        int i = (int) Math.floor(pMoy.x / voxSize.x);
        int j = (int) Math.floor(pMoy.y / voxSize.y);
        int k = (int) Math.floor(pMoy.z / voxSize.z);

        if (i < 0 || j < 0 || k < 0 || i >= splitting.x || j >= splitting.y || k >= splitting.z) {

            if (toricity) {

                while (i < 0) {
                    i += splitting.x;
                }
                while (j < 0) {
                    j += splitting.y;
                }
                while (i >= splitting.x) {
                    i -= splitting.x;
                }
                while (j >= splitting.y) {
                    j -= splitting.y;
                }

                if (k < 0 || k >= splitting.z) {
                    break;
                }

            } else {
                break;
            }
        }

        // Test if current voxel is below the ground level
        if (pMoy.z < mnt[i][j]) {
            transmitted = 0;
        } else {
            if (Float.isNaN(voxels[i][j][k].padBV)) {
                //test
                //voxels[i][j][k].padBV = 3.536958f;
                return Double.NaN;
            }

            float coefficientGTheta = (float) direcTrans.getGThetaFromAngle(directionAngle, true);

            //input transmittance
            //double transmittedBefore = transmitted;

            transmitted *= Math.exp(-coefficientGTheta * voxels[i][j][k].padBV * pathLength);

            //output transmittance
            //double transmittedAfter = transmitted;

            //intercepted transmittance
            //double interceptedTrans = transmittedAfter - transmittedBefore;

            //transmitted *= Math.exp(-0.5 * voxels[i][j][k].padBV * pathLength)/*(default coeff)*/;
        }

        if (transmitted <= EPSILON && toricity) {
            break;
        }

        d1 = d2;
    }

    return transmitted;
}

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox2.PDFAsVisualSignatureBuilder.java

private void readTableResources(PDFBoxTable table, PDDocument template) throws PdfAsException, IOException {

    float[] colsSizes = table.getColsRelativeWith();
    int max_cols = table.getColCount();
    float padding = table.getPadding();
    if (colsSizes == null) {
        colsSizes = new float[max_cols];
        // set the column ratio for all columns to 1
        for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) {
            colsSizes[cols_idx] = 1;/*  w w  w  . j a va 2s. co  m*/
        }
    }

    logger.debug("TOTAL Width: " + table.getWidth());

    float total = 0;

    for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) {
        total += colsSizes[cols_idx];
    }

    for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) {
        colsSizes[cols_idx] = (colsSizes[cols_idx] / total) * table.getWidth();
    }

    for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) {
        logger.debug("Col: " + cols_idx + " : " + colsSizes[cols_idx]);
    }

    /*
     * if(!addedFonts.contains(table.getFont().getFont(null))) { PDFont font
     * = table.getFont().getFont(template); addedFonts.add(font);
     * innerFormResources.addFont(font); }
     * 
     * if(!addedFonts.contains(table.getValueFont().getFont(null))) { PDFont
     * font = table.getValueFont().getFont(template); addedFonts.add(font);
     * innerFormResources.addFont(font); }
     */

    for (int i = 0; i < table.getRowCount(); i++) {
        ArrayList<Entry> row = table.getRow(i);
        for (int j = 0; j < row.size(); j++) {
            Entry cell = (Entry) row.get(j);
            if (cell.getType() == Entry.TYPE_IMAGE) {
                String img_value = (String) cell.getValue();
                String img_ref = createHashedId(img_value);
                if (!images.containsKey(img_ref)) {
                    BufferedImage img = ImageUtils.getImage(img_value, settings);

                    float width = colsSizes[j];
                    float height = table.getRowHeights()[i] + padding * 2;

                    float iwidth = (int) Math.floor((double) width);
                    iwidth -= 2 * padding;

                    float iheight = (int) Math.floor((double) height);
                    iheight -= 2 * padding;

                    float origWidth = (float) img.getWidth();
                    float origHeight = (float) img.getHeight();

                    if (table.style != null) {
                        if (table.style.getImageScaleToFit() != null) {
                            iwidth = table.style.getImageScaleToFit().getWidth();
                            iheight = table.style.getImageScaleToFit().getHeight();
                        }
                    }

                    float wfactor = iwidth / origWidth;
                    float hfactor = iheight / origHeight;
                    float scaleFactor = wfactor;
                    if (hfactor < wfactor) {
                        scaleFactor = hfactor;
                    }

                    iwidth = (float) Math.floor((double) (scaleFactor * origWidth));
                    iheight = (float) Math.floor((double) (scaleFactor * origHeight));

                    logger.debug("Scaling image to: " + iwidth + " x " + iheight);

                    if (this.designer.properties.getSignatureProfileSettings().isPDFA()) {
                        img = ImageUtils.removeAlphaChannel(img);
                    } else {
                        if (img.getAlphaRaster() == null && img.getColorModel().hasAlpha()) {
                            img = ImageUtils.removeAlphaChannel(img);
                        }
                    }
                    // img = ImageUtils.convertRGBAToIndexed(img);

                    PDImageXObject pdImage = LosslessFactory.createFromImage(template, img);

                    ImageObject image = new ImageObject(pdImage, iwidth, iheight);
                    images.put(img_ref, image);
                    innerFormResources.add(pdImage, "Im");
                }
            } else if (cell.getType() == Entry.TYPE_TABLE) {
                PDFBoxTable tbl_value = (PDFBoxTable) cell.getValue();
                readTableResources(tbl_value, template);
            }
        }
    }
}