Example usage for java.lang Double MIN_VALUE

List of usage examples for java.lang Double MIN_VALUE

Introduction

In this page you can find the example usage for java.lang Double MIN_VALUE.

Prototype

double MIN_VALUE

To view the source code for java.lang Double MIN_VALUE.

Click Source Link

Document

A constant holding the smallest positive nonzero value of type double , 2-1074.

Usage

From source file:eu.qualimaster.monitoring.profiling.predictors.Kalman.java

/**
 * This method updates the Kalman-Filter with the last known state/measurement of the observed value.
 * /*from   w w  w.jav  a  2s  . c om*/
 * @param xMeasured time step of measurement.  
 * It is measured in full, i.e. as {@link Long}, seconds since midnight, January 1, 1970 UTC.
 * @param yMeasured Current measurement.
 * @return True if the update was successful.
 */
public boolean update(long xMeasured, double yMeasured) {
    boolean success = false;
    try {
        // Call predict(0), if no prediction was made since the last update
        // Reason: The Kalman-Filter needs a predict-update(correct)-cycle.
        if (!predictedSinceUpdate && lastUpdate != Double.MIN_VALUE) {
            predict(0);
        }

        filter.correct(new double[] { xMeasured, 0, yMeasured, 0 });
        // When an older value is updated/corrected the attributes 'lastUpdated' and 'lastUpdate' do not change.
        if (lastUpdated < xMeasured) {
            lastUpdated = xMeasured;
            lastUpdate = yMeasured;
        }
        success = true;
        predictedSinceUpdate = false;
    } catch (NullArgumentException | DimensionMismatchException | SingularMatrixException e) {
        LogManager.getLogger(Kalman.class).error(e.getMessage(), e);
    }
    return success;
}

From source file:ome.services.projection.ProjectionBean.java

@RolesAllowed("user")
@Transactional(readOnly = false)/*w  w w  . j a  v  a  2  s  .  com*/
public long projectPixels(long pixelsId, PixelsType pixelsType, int algorithm, int tStart, int tEnd,
        List<Integer> channels, int stepping, int zStart, int zEnd, String name) {
    // First, copy and resize our image with sizeZ = 1.
    ProjectionContext ctx = new ProjectionContext();
    ctx.pixels = iQuery.get(Pixels.class, pixelsId);
    Image image = ctx.pixels.getImage();
    name = name == null ? image.getName() + " Projection" : name;
    //size of the new buffer.
    Integer sizeT = tEnd - tStart + 1;
    if (tStart > tEnd)
        sizeT = tStart - tEnd + 1;
    if (sizeT <= 0)
        sizeT = null;
    long newImageId = iPixels.copyAndResizeImage(image.getId(), null, null, 1, sizeT, channels, name, false);
    Image newImage = iQuery.get(Image.class, newImageId);
    Pixels newPixels = newImage.getPixels(0);
    if (pixelsType == null) {
        pixelsType = ctx.pixels.getPixelsType();
    } else {
        pixelsType = iQuery.get(PixelsType.class, pixelsType.getId());
    }
    newPixels.setPixelsType(pixelsType);

    // Project each stack for each channel and each timepoint in the
    // entire image, copying into the pixel buffer the projected pixels.
    PixelBuffer sourceBuffer = pixelsService.getPixelBuffer(ctx.pixels, false);
    try {
        PixelBuffer destinationBuffer = pixelsService.getPixelBuffer(newPixels, true);
        try {
            ctx.planeSizeInPixels = ctx.pixels.getSizeX() * ctx.pixels.getSizeY();
            int planeSize = ctx.planeSizeInPixels * (iPixels.getBitDepth(pixelsType) / 8);
            byte[] buf = new byte[planeSize];
            ctx.to = new PixelData(pixelsType.getValue(), ByteBuffer.wrap(buf));
            int newC = 0;
            for (Integer c : channels) {
                ctx.minimum = Double.MAX_VALUE;
                ctx.maximum = Double.MIN_VALUE;
                for (int t = tStart; t <= tEnd; t++) {
                    try {
                        ctx.from = sourceBuffer.getStack(c, t);
                        switch (algorithm) {
                        case IProjection.MAXIMUM_INTENSITY: {
                            projectStackMax(ctx, stepping, zStart, zEnd, true);
                            break;
                        }
                        case IProjection.MEAN_INTENSITY: {
                            projectStackMean(ctx, stepping, zStart, zEnd, true);
                            break;
                        }
                        case IProjection.SUM_INTENSITY: {
                            projectStackSum(ctx, stepping, zStart, zEnd, true);
                            break;
                        }
                        default: {
                            throw new IllegalArgumentException("Unknown algorithm: " + algorithm);
                        }
                        }
                        destinationBuffer.setPlane(buf, 0, newC, t);
                    } catch (IOException e) {
                        String error = String.format("I/O error retrieving stack C=%d T=%d: %s", c, t,
                                e.getMessage());
                        log.error(error, e);
                        throw new ResourceError(error);
                    } catch (DimensionsOutOfBoundsException e) {
                        String error = String.format("C=%d or T=%d out of range for Pixels Id %d: %s", c, t,
                                ctx.pixels.getId(), e.getMessage());
                        log.error(error, e);
                        throw new ValidationException(error);
                    }
                }
                // Handle the change of minimum and maximum for this channel.
                Channel channel = newPixels.getChannel(newC);
                StatsInfo si = new StatsInfo();
                si.setGlobalMin(ctx.minimum);
                si.setGlobalMax(ctx.maximum);
                channel.setStatsInfo(si);
                // Set our methodology
                newPixels.setMethodology(IProjection.METHODOLOGY_STRINGS[algorithm]);
                newC++;
            }
        } finally {
            try {
                destinationBuffer.close();
            } catch (IOException e) {
                log.error("Buffer did not close successfully: " + destinationBuffer, e);
                throw new ResourceError(e.getMessage() + " Please check server log.");
            }
        }
    } finally {
        try {
            sourceBuffer.close();
        } catch (IOException e) {
            log.error("Buffer did not close successfully: " + sourceBuffer, e);
            throw new ResourceError(e.getMessage() + " Please check server log.");
        }
    }
    newImage = iUpdate.saveAndReturnObject(newImage);
    return newImage.getId();
}

From source file:org.amanzi.neo.models.impl.network.NetworkModelTest.java

@Test
public void testCheckCreateSiteSuccess() throws ModelException {
    parentElement = new DataElement(getNodeMock());

    Map<String, Object> properties = getProperties();
    properties.put(GENERAL_NODE_PROPERTIES.getNodeNameProperty(), DEFAULT_ELEMENT_NAME);

    DataElement mockedSite = new DataElement(getNodeMock(properties));

    doReturn(mockedSite).when(networkModel).createDefaultElement(NetworkElementType.SITE, parentElement,
            DEFAULT_ELEMENT_NAME, properties);

    networkModel.createSite(parentElement, DEFAULT_ELEMENT_NAME, Double.MAX_VALUE, Double.MIN_VALUE,
            properties);/* ww  w  . j a v a  2s .c  o  m*/
    verify(indexModel).indexInMultiProperty(NetworkElementType.SITE, mockedSite.getNode(), Double.class,
            GEO_NODE_PROPERTIES.getLatitudeProperty(), GEO_NODE_PROPERTIES.getLongitudeProperty());
    verify(networkModel).createDefaultElement(NetworkElementType.SITE, parentElement, DEFAULT_ELEMENT_NAME,
            properties);
}

From source file:de.biomedical_imaging.traj.math.TrajectorySplineFit.java

/**
 * Calculates a spline to a trajectory. Attention: The spline is fitted through a rotated version of the trajectory.
 * To fit the spline the trajectory is rotated into its main direction. You can access this rotated trajectory by 
 * {@link #getRotatedTrajectory() getRotatedTrajectory}.
 * @return The fitted spline/* w  w  w  .  j  av a 2  s .  co m*/
 */
public PolynomialSplineFunction calculateSpline() {

    successfull = false;
    /*
     * 1.Calculate the minimum bounding rectangle
     */
    ArrayList<Point2D.Double> points = new ArrayList<Point2D.Double>();
    for (int i = 0; i < t.size(); i++) {
        Point2D.Double p = new Point2D.Double();
        p.setLocation(t.get(i).x, t.get(i).y);
        points.add(p);
    }

    /*
     * 1.1 Rotate that the major axis is parallel with the xaxis
     */

    Array2DRowRealMatrix gyr = RadiusGyrationTensor2D.getRadiusOfGyrationTensor(t);
    EigenDecomposition eigdec = new EigenDecomposition(gyr);

    double inRad = -1 * Math.atan2(eigdec.getEigenvector(0).getEntry(1), eigdec.getEigenvector(0).getEntry(0));
    boolean doTransform = (Math.abs(Math.abs(inRad) - Math.PI) > 0.001);

    if (doTransform) {
        angleRotated = inRad;
        for (int i = 0; i < t.size(); i++) {
            double x = t.get(i).x;
            double y = t.get(i).y;
            double newX = x * Math.cos(inRad) - y * Math.sin(inRad);
            double newY = x * Math.sin(inRad) + y * Math.cos(inRad);
            rotatedTrajectory.add(newX, newY, 0);
            points.get(i).setLocation(newX, newY);
        }
        //for(int i = 0; i < rect.length; i++){
        //   rect[i].setLocation(rect[i].x*Math.cos(inRad)-rect[i].y*Math.sin(inRad), rect[i].x*Math.sin(inRad)+rect[i].y*Math.cos(inRad));
        //}
    } else {
        angleRotated = 0;
        rotatedTrajectory = t;
    }

    /*
     * 2. Divide the rectangle in n equal segments
     * 2.1 Calculate line in main direction
     * 2.2 Project the points in onto this line
     * 2.3 Calculate the distance between the start of the line and the projected point
     * 2.4 Assign point to segment according to distance of (2.3)
     */
    List<List<Point2D.Double>> pointsInSegments = null;
    boolean allSegmentsContainingAtLeastTwoPoints = true;
    int indexSmallestX = 0;

    double segmentWidth = 0;
    do {
        double smallestX = Double.MAX_VALUE;
        double largestX = Double.MIN_VALUE;

        for (int i = 0; i < points.size(); i++) {
            if (points.get(i).x < smallestX) {
                smallestX = points.get(i).x;
                indexSmallestX = i;
            }
            if (points.get(i).x > largestX) {
                largestX = points.get(i).x;
            }
        }

        allSegmentsContainingAtLeastTwoPoints = true;
        segmentWidth = (largestX - smallestX) / nSegments;
        pointsInSegments = new ArrayList<List<Point2D.Double>>(nSegments);
        for (int i = 0; i < nSegments; i++) {
            pointsInSegments.add(new ArrayList<Point2D.Double>());
        }
        for (int i = 0; i < points.size(); i++) {

            int index = (int) Math.abs((points.get(i).x / segmentWidth));

            if (index > (nSegments - 1)) {
                index = (nSegments - 1);
            }
            pointsInSegments.get(index).add(points.get(i));
        }

        for (int i = 0; i < pointsInSegments.size(); i++) {
            if (pointsInSegments.get(i).size() < 2) {
                if (nSegments > 2) {
                    nSegments--;
                    i = pointsInSegments.size();
                    allSegmentsContainingAtLeastTwoPoints = false;

                }
            }
        }

    } while (allSegmentsContainingAtLeastTwoPoints == false);

    /*
     * 3. Calculate the mean standard deviation over each segment: <s>
     */
    //Point2D.Double eMajorP1 = new Point2D.Double(p1.x - (p3.x-p1.x)/2.0,p1.y - (p3.y-p1.y)/2.0); 
    //   Point2D.Double eMajorP2 = new Point2D.Double(p2.x - (p3.x-p1.x)/2.0,p2.y - (p3.y-p1.y)/2.0); 
    double sumSDOrthogonal = 0;
    int Nsum = 0;
    CenterOfGravityFeature cogf = new CenterOfGravityFeature(rotatedTrajectory);
    Point2D.Double cog = new Point2D.Double(cogf.evaluate()[0], cogf.evaluate()[1]);
    Point2D.Double eMajorP1 = cog;
    Point2D.Double eMajorP2 = new Point2D.Double(cog.getX() + 1, cog.getY());
    for (int i = 0; i < nSegments; i++) {
        StandardDeviation sd = new StandardDeviation();
        double[] distances = new double[pointsInSegments.get(i).size()];
        for (int j = 0; j < pointsInSegments.get(i).size(); j++) {
            int factor = 1;
            if (isLeft(eMajorP1, eMajorP2, pointsInSegments.get(i).get(j))) {
                factor = -1;
            }
            distances[j] = factor * distancePointLine(eMajorP1, eMajorP2, pointsInSegments.get(i).get(j));
        }
        if (distances.length > 0) {
            sd.setData(distances);

            sumSDOrthogonal += sd.evaluate();
            Nsum++;
        }
    }
    double s = sumSDOrthogonal / Nsum;
    if (segmentWidth < Math.pow(10, -15)) {
        return null;
    }
    if (s < Math.pow(10, -15)) {
        //If standard deviation is zero, replace it with the half of the segment width

        s = segmentWidth / 2;
    }
    //rotatedTrajectory.showTrajectory("rot");
    /*
     * 4. Build a kd-tree
     */
    KDTree<Point2D.Double> kdtree = new KDTree<Point2D.Double>(2);

    for (int i = 0; i < points.size(); i++) {
        try {
            //To ensure that all points have a different key, add small random number

            kdtree.insert(new double[] { points.get(i).x, points.get(i).y }, points.get(i));
        } catch (KeySizeException e) {
            e.printStackTrace();
        } catch (KeyDuplicateException e) {
            //Do nothing! It is not important
        }

    }

    /*
     * 5. Using the first point f in trajectory and calculate the center of mass
     * of all points around f (radius: 3*<s>))
     */
    List<Point2D.Double> near = null;

    Point2D.Double first = points.get(indexSmallestX);//minDistancePointToLine(p1, p3, points);
    double r1 = 3 * s;
    try {

        near = kdtree.nearestEuclidean(new double[] { first.x, first.y }, r1);

    } catch (KeySizeException e) {
        e.printStackTrace();
    }

    double cx = 0;
    double cy = 0;
    for (int i = 0; i < near.size(); i++) {
        cx += near.get(i).x;
        cy += near.get(i).y;
    }
    cx /= near.size();
    cy /= near.size();

    splineSupportPoints = new ArrayList<Point2D.Double>();
    splineSupportPoints.add(new Point2D.Double(cx, cy));

    /* 
     * 6. The second point is determined by finding the center-of-mass of particles in the p/2 radian 
     * section of an annulus, r1 < r < 2r1, that is directed toward the angle with the highest number 
     * of particles within p/2 radians.
     * 7. This second point is then used as the center of the annulus for choosing the third point, and the process is repeated (6. & 7.).
     */

    /*
     * 6.1 Find all points in the annolous
     */

    /*
     * 6.2 Write each point in a coordinate system centered at the center of the sphere, calculate direction and
     * check if it in the allowed bounds
     */
    int nCircleSegments = 100;
    double deltaRad = 2 * Math.PI / nCircleSegments;
    boolean stop = false;
    int minN = 7;
    double tempr1 = r1;
    double allowedDeltaDirection = 0.5 * Math.PI;

    while (stop == false) {
        List<Point2D.Double> nearestr1 = null;
        List<Point2D.Double> nearest2xr1 = null;
        try {
            nearestr1 = kdtree
                    .nearestEuclidean(new double[] { splineSupportPoints.get(splineSupportPoints.size() - 1).x,
                            splineSupportPoints.get(splineSupportPoints.size() - 1).y }, tempr1);
            nearest2xr1 = kdtree
                    .nearestEuclidean(new double[] { splineSupportPoints.get(splineSupportPoints.size() - 1).x,
                            splineSupportPoints.get(splineSupportPoints.size() - 1).y }, 2 * tempr1);
        } catch (KeySizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        nearest2xr1.removeAll(nearestr1);

        double lThreshRad = 0;
        double hThreshRad = Math.PI / 2;
        double stopThresh = 2 * Math.PI;
        if (splineSupportPoints.size() > 1) {
            double directionInRad = Math.atan2(
                    splineSupportPoints.get(splineSupportPoints.size() - 1).y
                            - splineSupportPoints.get(splineSupportPoints.size() - 2).y,
                    splineSupportPoints.get(splineSupportPoints.size() - 1).x
                            - splineSupportPoints.get(splineSupportPoints.size() - 2).x)
                    + Math.PI;
            lThreshRad = directionInRad - allowedDeltaDirection / 2 - Math.PI / 4;
            if (lThreshRad < 0) {
                lThreshRad = 2 * Math.PI + lThreshRad;
            }
            if (lThreshRad > 2 * Math.PI) {
                lThreshRad = lThreshRad - 2 * Math.PI;
            }
            hThreshRad = directionInRad + allowedDeltaDirection / 2 + Math.PI / 4;
            if (hThreshRad < 0) {
                hThreshRad = 2 * Math.PI + hThreshRad;
            }
            if (hThreshRad > 2 * Math.PI) {
                hThreshRad = hThreshRad - 2 * Math.PI;
            }
            stopThresh = directionInRad + allowedDeltaDirection / 2 - Math.PI / 4;
            if (stopThresh > 2 * Math.PI) {
                stopThresh = stopThresh - 2 * Math.PI;
            }

        }

        double newCx = 0;
        double newCy = 0;
        int newCN = 0;
        int candN = 0;

        //Find center with highest density of points
        double lastDist = 0;
        double newDist = 0;
        do {
            lastDist = Math.min(Math.abs(lThreshRad - stopThresh),
                    2 * Math.PI - Math.abs(lThreshRad - stopThresh));

            candN = 0;
            double candCx = 0;
            double candCy = 0;

            for (int i = 0; i < nearest2xr1.size(); i++) {
                Point2D.Double centerOfCircle = splineSupportPoints.get(splineSupportPoints.size() - 1);
                Vector2d relativeToCircle = new Vector2d(nearest2xr1.get(i).x - centerOfCircle.x,
                        nearest2xr1.get(i).y - centerOfCircle.y);
                relativeToCircle.normalize();
                double angleInRadians = Math.atan2(relativeToCircle.y, relativeToCircle.x) + Math.PI;

                if (lThreshRad < hThreshRad) {
                    if (angleInRadians > lThreshRad && angleInRadians < hThreshRad) {
                        candCx += nearest2xr1.get(i).x;
                        candCy += nearest2xr1.get(i).y;
                        candN++;
                    }
                } else {
                    if (angleInRadians > lThreshRad || angleInRadians < hThreshRad) {
                        candCx += nearest2xr1.get(i).x;
                        candCy += nearest2xr1.get(i).y;
                        candN++;
                    }
                }

            }

            if (candN > 0 && candN > newCN) {
                candCx /= candN;
                candCy /= candN;
                newCx = candCx;
                newCy = candCy;
                newCN = candN;
            }
            lThreshRad += deltaRad;
            hThreshRad += deltaRad;
            if (lThreshRad > 2 * Math.PI) {
                lThreshRad = lThreshRad - 2 * Math.PI;
            }
            if (hThreshRad > 2 * Math.PI) {
                hThreshRad = hThreshRad - 2 * Math.PI;
            }
            newDist = Math.min(Math.abs(lThreshRad - stopThresh),
                    2 * Math.PI - Math.abs(lThreshRad - stopThresh));

        } while ((newDist - lastDist) > 0);

        //Check if the new center is valid
        if (splineSupportPoints.size() > 1) {
            double currentDirectionInRad = Math.atan2(
                    splineSupportPoints.get(splineSupportPoints.size() - 1).y
                            - splineSupportPoints.get(splineSupportPoints.size() - 2).y,
                    splineSupportPoints.get(splineSupportPoints.size() - 1).x
                            - splineSupportPoints.get(splineSupportPoints.size() - 2).x)
                    + Math.PI;
            double candDirectionInRad = Math.atan2(
                    newCy - splineSupportPoints.get(splineSupportPoints.size() - 1).y,
                    newCx - splineSupportPoints.get(splineSupportPoints.size() - 1).x) + Math.PI;
            double dDir = Math.max(currentDirectionInRad, candDirectionInRad)
                    - Math.min(currentDirectionInRad, candDirectionInRad);
            if (dDir > 2 * Math.PI) {
                dDir = 2 * Math.PI - dDir;
            }
            if (dDir > allowedDeltaDirection) {

                stop = true;
            }
        }
        boolean enoughPoints = (newCN < minN);
        boolean isNormalRadius = Math.abs(tempr1 - r1) < Math.pow(10, -18);
        boolean isExtendedRadius = Math.abs(tempr1 - 3 * r1) < Math.pow(10, -18);

        if (enoughPoints && isNormalRadius) {
            //Not enough points, extend search radius
            tempr1 = 3 * r1;
        } else if (enoughPoints && isExtendedRadius) {
            //Despite radius extension: Not enough points!
            stop = true;
        } else if (stop == false) {
            splineSupportPoints.add(new Point2D.Double(newCx, newCy));
            tempr1 = r1;
        }

    }

    //Sort
    Collections.sort(splineSupportPoints, new Comparator<Point2D.Double>() {

        public int compare(Point2D.Double o1, Point2D.Double o2) {
            if (o1.x < o2.x) {
                return -1;
            }
            if (o1.x > o2.x) {
                return 1;
            }
            return 0;
        }
    });

    //Add endpoints
    if (splineSupportPoints.size() > 1) {
        Vector2d start = new Vector2d(splineSupportPoints.get(0).x - splineSupportPoints.get(1).x,
                splineSupportPoints.get(0).y - splineSupportPoints.get(1).y);
        start.normalize();
        start.scale(r1 * 8);
        splineSupportPoints.add(0, new Point2D.Double(splineSupportPoints.get(0).x + start.x,
                splineSupportPoints.get(0).y + start.y));

        Vector2d end = new Vector2d(
                splineSupportPoints.get(splineSupportPoints.size() - 1).x
                        - splineSupportPoints.get(splineSupportPoints.size() - 2).x,
                splineSupportPoints.get(splineSupportPoints.size() - 1).y
                        - splineSupportPoints.get(splineSupportPoints.size() - 2).y);
        end.normalize();
        end.scale(r1 * 6);
        splineSupportPoints
                .add(new Point2D.Double(splineSupportPoints.get(splineSupportPoints.size() - 1).x + end.x,
                        splineSupportPoints.get(splineSupportPoints.size() - 1).y + end.y));
    } else {
        Vector2d majordir = new Vector2d(-1, 0);
        majordir.normalize();
        majordir.scale(r1 * 8);
        splineSupportPoints.add(0, new Point2D.Double(splineSupportPoints.get(0).x + majordir.x,
                splineSupportPoints.get(0).y + majordir.y));
        majordir.scale(-1);
        splineSupportPoints
                .add(new Point2D.Double(splineSupportPoints.get(splineSupportPoints.size() - 1).x + majordir.x,
                        splineSupportPoints.get(splineSupportPoints.size() - 1).y + majordir.y));

    }

    //Interpolate spline
    double[] supX = new double[splineSupportPoints.size()];
    double[] supY = new double[splineSupportPoints.size()];
    for (int i = 0; i < splineSupportPoints.size(); i++) {
        supX[i] = splineSupportPoints.get(i).x;
        supY[i] = splineSupportPoints.get(i).y;
    }

    SplineInterpolator sIinter = new SplineInterpolator();
    spline = sIinter.interpolate(supX, supY);
    successfull = true;
    return spline;
}

From source file:com.nridge.core.base.field.data.DataFieldAnalyzer.java

/**
 * Returns a data bag of fields describing the scanned value data.
 * The bag will contain the field name, derived type, populated
 * count, null count and a sample count of values (with overall
 * percentages) that repeated most often.
 *
 * @param aSampleCount Identifies the top count of values.
 *
 * @return Data bag of analysis details.
 *///  w  w w  .  j a  v  a 2 s  . c o m
public DataBag getDetails(int aSampleCount) {
    Date dateValue;
    Integer valueCount;
    String fieldName, fieldTitle, dataValue;
    Double valuePercentage, minValue, maxValue;

    Field.Type fieldType = getType();
    int uniqueValues = mValueCount.size();
    DataBag detailsBag = new DataBag(mName);
    detailsBag.add(new DataTextField("name", "Name", mName));
    detailsBag.add(new DataTextField("type", "Type", Field.typeToString(fieldType)));
    detailsBag.add(new DataIntegerField("total_count", "Total Count", mTotalValues));
    detailsBag.add(new DataIntegerField("null_count", "Null Count", mNullCount));
    detailsBag.add(new DataIntegerField("unique_count", "Unique Count", uniqueValues));

    // Create a table from the values map and use sorting to get our top sample size.

    DataTable valuesTable = new DataTable(mName);
    valuesTable.add(new DataTextField("value", "Value"));
    valuesTable.add(new DataIntegerField("count", "Count"));
    valuesTable.add(new DataDoubleField("percentage", "Percentage"));

    minValue = Double.MAX_VALUE;
    maxValue = Double.MIN_VALUE;
    for (Map.Entry<String, Integer> entry : mValueCount.entrySet()) {
        valuesTable.newRow();
        dataValue = entry.getKey();
        valueCount = entry.getValue();
        if (mTotalValues == 0)
            valuePercentage = 0.0;
        else
            valuePercentage = valueCount.doubleValue() / mTotalValues * 100.0;

        valuesTable.newRow();
        valuesTable.setValueByName("value", dataValue);
        valuesTable.setValueByName("count", valueCount);
        valuesTable.setValueByName("percentage", String.format("%.2f", valuePercentage));
        if (Field.isText(fieldType)) {
            minValue = Math.min(minValue, dataValue.length());
            maxValue = Math.max(maxValue, dataValue.length());
        } else if (Field.isNumber(fieldType)) {
            minValue = Math.min(minValue, Double.parseDouble(dataValue));
            maxValue = Math.max(maxValue, Double.parseDouble(dataValue));
        } else if (Field.isDateOrTime(fieldType)) {

            // While we are decomposing the date to milliseconds of time, you can do a Date(milliseconds)
            // reconstruction.

            dateValue = DatUtl.detectCreateDate(dataValue);
            if (dataValue != null) {
                minValue = Math.min(minValue, dateValue.getTime());
                maxValue = Math.max(maxValue, dateValue.getTime());
            }
        }
        valuesTable.addRow();
    }
    valuesTable.sortByColumn("count", Field.Order.DESCENDING);

    if (Field.isBoolean(fieldType)) {
        detailsBag.add(new DataTextField("minimum", "Minimum", StrUtl.STRING_FALSE));
        detailsBag.add(new DataTextField("maximum", "Maximum", StrUtl.STRING_TRUE));
    } else if (Field.isDateOrTime(fieldType)) {
        detailsBag.add(new DataTextField("minimum", "Minimum",
                Field.dateValueFormatted(new Date(minValue.longValue()), Field.FORMAT_DATETIME_DEFAULT)));
        detailsBag.add(new DataTextField("maximum", "Maximum",
                Field.dateValueFormatted(new Date(maxValue.longValue()), Field.FORMAT_DATETIME_DEFAULT)));
    } else {
        detailsBag.add(new DataTextField("minimum", "Minimum", String.format("%.2f", minValue)));
        detailsBag.add(new DataTextField("maximum", "Maximum", String.format("%.2f", maxValue)));
    }

    // Create columns for the top sample sizes (value, matching count, matching percentage)

    int adjCount = Math.min(aSampleCount, valuesTable.rowCount());
    for (int row = 0; row < adjCount; row++) {
        fieldName = String.format("value_%02d", row + 1);
        fieldTitle = String.format("Value %02d", row + 1);
        dataValue = valuesTable.getValueByName(row, "value");
        detailsBag.add(new DataTextField(fieldName, fieldTitle, dataValue));
        fieldName = String.format("count_%02d", row + 1);
        fieldTitle = String.format("Count %02d", row + 1);
        detailsBag.add(new DataIntegerField(fieldName, fieldTitle, valuesTable.getValueByName(row, "count")));
        fieldName = String.format("percent_%02d", row + 1);
        fieldTitle = String.format("Percent %02d", row + 1);
        detailsBag
                .add(new DataDoubleField(fieldName, fieldTitle, valuesTable.getValueByName(row, "percentage")));
    }

    return detailsBag;
}

From source file:com.mobiperf.measurements.PingTask.java

private MeasurementResult constructResult(ArrayList<Double> rrtVals, double packetLoss, int packetsSent,
        String pingMethod) {//from   w ww.  ja  v a  2  s .co  m
    double min = Double.MAX_VALUE;
    double max = Double.MIN_VALUE;
    double mdev, avg, filteredAvg;
    double total = 0;
    boolean success = true;

    if (rrtVals.size() == 0) {
        return null;
    }

    for (double rrt : rrtVals) {
        if (rrt < min) {
            min = rrt;
        }
        if (rrt > max) {
            max = rrt;
        }
        total += rrt;
    }

    avg = total / rrtVals.size();
    mdev = Util.getStandardDeviation(rrtVals, avg);
    filteredAvg = filterPingResults(rrtVals, avg);

    PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils();

    MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId,
            phoneUtils.getDeviceProperty(), PingTask.TYPE, System.currentTimeMillis() * 1000, success,
            this.measurementDesc);

    result.addResult("target_ip", targetIp);
    result.addResult("mean_rtt_ms", avg);
    result.addResult("min_rtt_ms", min);
    result.addResult("max_rtt_ms", max);
    result.addResult("stddev_rtt_ms", mdev);
    if (filteredAvg != avg) {
        result.addResult("filtered_mean_rtt_ms", filteredAvg);
    }
    result.addResult("packet_loss", packetLoss);
    result.addResult("packets_sent", packetsSent);
    result.addResult("ping_method", pingMethod);
    Logger.i(MeasurementJsonConvertor.toJsonString(result));
    return result;
}

From source file:net.tradelib.misc.StrategyText.java

public static List<InstrumentText> buildList(Connection con, String strategy, LocalDate date, String csvPath,
        char csvSep) throws Exception {
    // public static List<InstrumentText> buildList(Connection con, String strategy, LocalDate date) throws Exception {
    ArrayList<InstrumentText> result = new ArrayList<InstrumentText>();

    CSVPrinter printer = null;/* w w w  . j  a  v a  2 s .  c  o  m*/
    if (csvPath != null) {
        // Add withHeader for headers
        printer = CSVFormat.DEFAULT.withDelimiter(csvSep).print(new BufferedWriter(new FileWriter(csvPath)));
    }

    int numCsvColumns = 12;

    int rollMethod = 2;

    DatabaseMetaData dmd = con.getMetaData();
    String driverName = dmd.getDriverName();
    String query = "";
    if (driverName.startsWith("MySQL")) {
        query = STRATEGY_QUERY_MYSQL;
    } else {
        query = STRATEGY_QUERY;
    }

    String prevCategory = "";
    PreparedStatement pstmt = con.prepareStatement(query);
    pstmt.setString(1, strategy);
    pstmt.setTimestamp(2, Timestamp.valueOf(date.atStartOfDay()));
    ResultSet rs = pstmt.executeQuery();
    while (rs.next()) {
        String category = rs.getString(2);
        if (!category.equals(prevCategory)) {
            result.add(InstrumentText.makeSection(category));
            prevCategory = category;

            if (printer != null) {
                printer.print(category);
                for (int ii = 1; ii < numCsvColumns; ++ii) {
                    printer.print("");
                }
                printer.println();
            }
        }
        String name = rs.getString(3);
        String symbol = rs.getString(4);
        String contract = "";
        if (rollMethod == 1) {
            // Uses current_contract and trading_days
            int ndays = rs.getInt(12);
            if (ndays > 1) {
                contract = rs.getString(10);
            } else {
                contract = "Roll to " + rs.getString(11);
            }
        } else if (rollMethod == 2) {
            // Uses current_contract2 and roll_today
            int rollToday = rs.getInt(14);
            if (rollToday == 0) {
                contract = rs.getString(13);
            } else {
                contract = "Roll to " + rs.getString(13);
            }
        }

        if (printer != null) {
            printer.print(name);
            printer.print(symbol);
            printer.print(contract);
        }

        String signal;
        long position = (long) rs.getDouble(5);
        JsonObject jo = new Gson().fromJson(rs.getString(9), JsonObject.class);
        if (position > 0.0) {
            BigDecimal entryPrice;
            double pnl;
            try {
                entryPrice = jo.get("entry_price").getAsBigDecimal();
                pnl = jo.get("pnl").getAsDouble();
            } catch (Exception e) {
                entryPrice = BigDecimal.valueOf(Double.MIN_VALUE);
                pnl = Double.MIN_VALUE;
            }
            signal = String.format("Long [%d] since %s [at %s].", position, rs.getString(6),
                    formatBigDecimal(entryPrice));
            if (printer != null)
                printer.print(signal);
            String openProfit = String.format("Open equity profit %,d.", (int) Math.floor(pnl));
            signal += " " + openProfit;
            if (printer != null)
                printer.print(openProfit);
        } else if (position < 0.0) {
            BigDecimal entryPrice;
            double pnl;
            try {
                entryPrice = jo.get("entry_price").getAsBigDecimal();
                pnl = jo.get("pnl").getAsDouble();
            } catch (Exception e) {
                entryPrice = BigDecimal.valueOf(-1);
                pnl = -1;
            }
            signal = String.format("Short [%d] since %s [at %s].", Math.abs(position), rs.getString(6),
                    formatBigDecimal(entryPrice));
            if (printer != null)
                printer.print(signal);
            String openProfit = String.format("Open equity profit %,d.", (int) Math.floor(pnl));
            signal += " " + openProfit;
            if (printer != null)
                printer.print(openProfit);
        } else {
            signal = "Out.";
            if (printer != null) {
                printer.print(signal);
                // An empty column follows the status if there is no position - there is no profit.
                printer.print("");
            }
        }

        boolean hasOrder = false;
        JsonArray ja = jo.get("orders").getAsJsonArray();
        double entryRisk;
        try {
            entryRisk = jo.get("entry_risk").getAsDouble();
        } catch (Exception ee) {
            entryRisk = Double.NaN;
        }
        String profitTarget;
        Double profitTargetDbl;
        try {
            profitTarget = formatBigDecimal(jo.get("profit_target").getAsBigDecimal());
            profitTargetDbl = jo.get("profit_target").getAsDouble();
        } catch (Exception ee) {
            profitTarget = null;
            profitTargetDbl = null;
        }
        String stopLoss;
        Double stopLossDbl;
        try {
            stopLoss = formatBigDecimal(jo.get("stop_loss").getAsBigDecimal());
            stopLossDbl = jo.get("stop_loss").getAsDouble();
        } catch (Exception ee) {
            stopLoss = null;
            stopLossDbl = null;
        }

        Double lastClose;
        try {
            lastClose = jo.get("last_close").getAsDouble();
        } catch (Exception ee) {
            lastClose = null;
        }

        // Currently maximum one entry and maximum one exit are supported.
        String entryStr = "";
        String exitStr = "";
        String contractRiskStr = "";

        for (int ii = 0; ii < ja.size(); ++ii) {
            JsonObject jorder = ja.get(ii).getAsJsonObject();

            switch (jorder.get("type").getAsString()) {
            case "EXIT_LONG_STOP":
                exitStr = "Exit long at stop " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal())
                        + ".";
                signal += " " + exitStr;
                break;

            case "EXIT_SHORT_STOP":
                exitStr = "Exit short at stop " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal())
                        + ".";
                signal += " " + exitStr;
                break;

            case "ENTER_LONG":
                if (!Double.isNaN(entryRisk)) {
                    entryStr = String.format("Enter long at open. Contract risk is %s.",
                            formatDouble(entryRisk, 0, 0));
                    signal += " " + entryStr;
                } else {
                    entryStr = "Enter long at open.";
                    signal += " " + entryStr;
                }
                break;

            case "ENTER_SHORT":
                if (!Double.isNaN(entryRisk)) {
                    entryStr = String.format("Enter short at open. Contract risk is %s.",
                            formatDouble(entryRisk, 0, 0));
                    signal += " " + entryStr;
                } else {
                    entryStr = "Enter short at open.";
                    signal += " " + entryStr;
                }
                break;

            case "ENTER_LONG_STOP":
                position = jorder.get("quantity").getAsLong();
                entryStr = String.format("Enter long [%d] at stop %s [%s%%].", position,
                        formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()),
                        formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100));
                signal += " " + entryStr;
                if (!Double.isNaN(entryRisk)) {
                    contractRiskStr = String.format(" Contract risk is %s.", formatDouble(entryRisk, 0, 0));
                    signal += " " + contractRiskStr;
                }
                break;

            case "ENTER_LONG_STOP_LIMIT":
                position = jorder.get("quantity").getAsLong();
                entryStr = String.format("Enter long [%d] at limit %s, stop at %s [%s%%].", position,
                        formatBigDecimal(jorder.get("limit_price").getAsBigDecimal()),
                        formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()),
                        formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100));
                signal += " " + entryStr;
                if (!Double.isNaN(entryRisk)) {
                    contractRiskStr = String.format(" Contract risk is %s.", formatDouble(entryRisk, 0, 0));
                    signal += contractRiskStr;
                }
                break;

            case "ENTER_SHORT_STOP":
                // signal += " Enter short at stop " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()) + ".";
                position = jorder.get("quantity").getAsLong();
                entryStr = String.format("Enter short [%d] at stop %s [%s%%].", Math.abs(position),
                        formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()),
                        formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100));
                signal += " " + entryStr;
                if (!Double.isNaN(entryRisk)) {
                    contractRiskStr = String.format(" Contract risk is %s.", formatDouble(entryRisk, 0, 0));
                    signal += " " + contractRiskStr;
                }
                break;

            case "ENTER_SHORT_STOP_LIMIT":
                position = jorder.get("quantity").getAsLong();
                entryStr = String.format("Enter short [%d] at limit %s, stop at %s [%s%%].", Math.abs(position),
                        formatBigDecimal(jorder.get("limit_price").getAsBigDecimal()),
                        formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()),
                        formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100));
                signal += " " + entryStr;
                if (!Double.isNaN(entryRisk)) {
                    contractRiskStr = String.format(" Contract risk is %s.", formatDouble(entryRisk, 0, 0));
                    signal += " " + contractRiskStr;
                }
                break;

            case "EXIT_LONG":
                exitStr = "Exit long at open.";
                signal += " " + exitStr;
                break;

            case "EXIT_SHORT":
                exitStr = "Exit short at open.";
                signal += " " + exitStr;
                break;

            case "EXIT_SHORT_STOP_LIMIT":
                exitStr = "Exit short at limit " + formatBigDecimal(jorder.get("limit_price").getAsBigDecimal())
                        + ", stop at " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()) + " ["
                        + formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100)
                        + "%]" + ".";
                signal += " " + exitStr;
                break;

            case "EXIT_LONG_STOP_LIMIT":
                exitStr = "Exit long at limit " + formatBigDecimal(jorder.get("limit_price").getAsBigDecimal())
                        + ", stop at " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()) + " ["
                        + formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100)
                        + "%]" + ".";
                signal += " " + exitStr;
                break;
            }
            hasOrder = true;
        }

        String lastCloseStr = "Last close at " + formatBigDecimal(jo.get("last_close").getAsBigDecimal()) + ".";
        String stopLossStr = "";
        String profitTargetStr = "";

        if (hasOrder) {
            signal += " " + lastCloseStr;
        }

        if (stopLoss != null) {
            stopLossStr = "Stop loss at " + stopLoss;
            if (lastClose != null && stopLossDbl != null) {
                stopLossStr += " [" + formatPercentage(stopLossDbl / lastClose * 100 - 100) + "%]";
            }
            stopLossStr += ".";
            signal += " " + stopLossStr;
        }

        if (profitTarget != null) {
            profitTargetStr = "Profit target at about " + profitTarget;
            if (profitTargetDbl != null && lastClose != null) {
                profitTargetStr += " [" + formatPercentage(profitTargetDbl / lastClose * 100 - 100) + "%]";
            }
            profitTargetStr += ".";
            signal += " " + profitTargetStr;
        }

        if (printer != null) {
            printer.print(exitStr);
            printer.print(entryStr);
            printer.print(contractRiskStr);
            printer.print(lastCloseStr);
            printer.print(stopLossStr);
            printer.print(profitTargetStr);
            printer.println();
        }

        result.add(InstrumentText.make(name, symbol, contract, signal));
    }

    rs.close();
    pstmt.close();

    if (printer != null)
        printer.flush();

    return result;
}

From source file:au.org.ala.delta.intkey.ui.FindInTaxaDialog.java

public FindInTaxaDialog(Intkey intkeyApp) {
    super(intkeyApp.getMainFrame(), false);
    setResizable(false);/*from  w ww  .  j  av  a  2  s .  co m*/

    ResourceMap resourceMap = Application.getInstance().getContext().getResourceMap(FindInTaxaDialog.class);
    resourceMap.injectFields(this);
    ActionMap actionMap = Application.getInstance().getContext().getActionMap(this);

    _intkeyApp = intkeyApp;

    _numMatchedTaxa = 0;
    _currentMatchedTaxon = -1;

    _findAction = actionMap.get("findTaxa");
    _nextAction = actionMap.get("nextFoundTaxon");

    this.setTitle(windowTitle);

    getContentPane().setLayout(new BorderLayout(0, 0));

    _pnlMain = new JPanel();
    _pnlMain.setBorder(new EmptyBorder(20, 20, 20, 20));
    getContentPane().add(_pnlMain, BorderLayout.CENTER);
    _pnlMain.setLayout(new BorderLayout(0, 0));

    _pnlMainTop = new JPanel();
    _pnlMain.add(_pnlMainTop, BorderLayout.NORTH);
    _pnlMainTop.setLayout(new BoxLayout(_pnlMainTop, BoxLayout.Y_AXIS));

    _lblEnterSearchString = new JLabel(enterSearchStringCaption);
    _lblEnterSearchString.setBorder(new EmptyBorder(0, 0, 5, 0));
    _lblEnterSearchString.setHorizontalAlignment(SwingConstants.LEFT);
    _lblEnterSearchString.setVerticalAlignment(SwingConstants.TOP);
    _lblEnterSearchString.setAlignmentY(Component.TOP_ALIGNMENT);
    _pnlMainTop.add(_lblEnterSearchString);

    _textField = new JTextField();
    _textField.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void removeUpdate(DocumentEvent e) {
            reset();
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            reset();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            reset();
        }
    });

    _pnlMainTop.add(_textField);
    _textField.setColumns(10);

    _pnlMainMiddle = new JPanel();
    _pnlMainMiddle.setBorder(new EmptyBorder(10, 0, 0, 0));
    _pnlMain.add(_pnlMainMiddle, BorderLayout.CENTER);
    _pnlMainMiddle.setLayout(new BoxLayout(_pnlMainMiddle, BoxLayout.Y_AXIS));

    _rdbtnSelectOne = new JRadioButton(selectOneCaption);
    _rdbtnSelectOne.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            reset();
        }
    });
    _pnlMainMiddle.add(_rdbtnSelectOne);

    _rdbtnSelectAll = new JRadioButton(selectAllCaption);
    _rdbtnSelectAll.setSelected(true);
    _rdbtnSelectAll.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            reset();
        }
    });
    _pnlMainMiddle.add(_rdbtnSelectAll);

    ButtonGroup radioButtonGroup = new ButtonGroup();
    radioButtonGroup.add(_rdbtnSelectOne);
    radioButtonGroup.add(_rdbtnSelectAll);

    _pnlMainBottom = new JPanel();
    _pnlMain.add(_pnlMainBottom, BorderLayout.SOUTH);
    _pnlMainBottom.setLayout(new BoxLayout(_pnlMainBottom, BoxLayout.Y_AXIS));

    _chckbxSearchSynonyms = new JCheckBox(searchSynonymsCaption);
    _chckbxSearchSynonyms.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            reset();
        }
    });

    _pnlMainBottom.add(_chckbxSearchSynonyms);

    _chckbxSearchEliminatedTaxa = new JCheckBox(searchEliminatedTaxaCaption);
    _chckbxSearchEliminatedTaxa.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            reset();
        }
    });

    _pnlMainBottom.add(_chckbxSearchEliminatedTaxa);

    _pnlButtons = new JPanel();
    _pnlButtons.setBorder(new EmptyBorder(20, 0, 0, 10));
    getContentPane().add(_pnlButtons, BorderLayout.EAST);
    _pnlButtons.setLayout(new BorderLayout(0, 0));

    _pnlInnerButtons = new JPanel();
    _pnlButtons.add(_pnlInnerButtons, BorderLayout.NORTH);
    GridBagLayout gbl_pnlInnerButtons = new GridBagLayout();
    gbl_pnlInnerButtons.columnWidths = new int[] { 0, 0 };
    gbl_pnlInnerButtons.rowHeights = new int[] { 0, 0, 0, 0 };
    gbl_pnlInnerButtons.columnWeights = new double[] { 0.0, Double.MIN_VALUE };
    gbl_pnlInnerButtons.rowWeights = new double[] { 0.0, 0.0, 0.0, Double.MIN_VALUE };
    _pnlInnerButtons.setLayout(gbl_pnlInnerButtons);

    _btnFindNext = new JButton();
    _btnFindNext.setAction(_findAction);
    GridBagConstraints gbc_btnFind = new GridBagConstraints();
    gbc_btnFind.fill = GridBagConstraints.HORIZONTAL;
    gbc_btnFind.insets = new Insets(0, 0, 5, 0);
    gbc_btnFind.gridx = 0;
    gbc_btnFind.gridy = 0;
    _pnlInnerButtons.add(_btnFindNext, gbc_btnFind);

    _btnPrevious = new JButton();
    _btnPrevious.setAction(actionMap.get("previousFoundTaxon"));
    _btnPrevious.setEnabled(false);
    GridBagConstraints gbc_btnPrevious = new GridBagConstraints();
    gbc_btnPrevious.insets = new Insets(0, 0, 5, 0);
    gbc_btnPrevious.gridx = 0;
    gbc_btnPrevious.gridy = 1;
    _pnlInnerButtons.add(_btnPrevious, gbc_btnPrevious);

    _btnDone = new JButton();
    _btnDone.setAction(actionMap.get("findTaxaDone"));
    GridBagConstraints gbc_btnDone = new GridBagConstraints();
    gbc_btnDone.fill = GridBagConstraints.HORIZONTAL;
    gbc_btnDone.gridx = 0;
    gbc_btnDone.gridy = 2;
    _pnlInnerButtons.add(_btnDone, gbc_btnDone);

    this.pack();
    this.setLocationRelativeTo(_intkeyApp.getMainFrame());
}

From source file:org.openmicroscopy.shoola.agents.measurement.view.GraphPane.java

/**
 * Finds the maximum value from the channelMin map.
 * //from  ww  w . jav a2 s . c  o m
 * @return See above.
 */
private double channelMaxValue() {
    Map channels = model.getActiveChannels();
    Entry entry;
    Iterator i = channels.entrySet().iterator();
    double value = Double.MIN_VALUE;
    int channel;
    while (i.hasNext()) {
        entry = (Entry) i.next();
        channel = (Integer) entry.getKey();
        value = Math.max(value, model.getMetadata(channel).getGlobalMax());
    }
    return value;
}

From source file:it.geosolutions.jaiext.range.RangeTest.java

@BeforeClass
public static void initialSetup() {
    arrayB = new byte[] { 0, 1, 5, 50, 100 };
    arrayUS = new short[] { 0, 1, 5, 50, 100 };
    arrayS = new short[] { -10, 0, 5, 50, 100 };
    arrayI = new int[] { -10, 0, 5, 50, 100 };
    arrayF = new float[] { -10, 0, 5, 50, 100 };
    arrayD = new double[] { -10, 0, 5, 50, 100 };
    arrayL = new long[] { -10, 0, 5, 50, 100 };

    rangeB2bounds = RangeFactory.create((byte) 2, true, (byte) 60, true);
    rangeBpoint = RangeFactory.create(arrayB[2], true, arrayB[2], true);
    rangeU2bounds = RangeFactory.createU((short) 2, true, (short) 60, true);
    rangeUpoint = RangeFactory.createU(arrayUS[2], true, arrayUS[2], true);
    rangeS2bounds = RangeFactory.create((short) 1, true, (short) 60, true);
    rangeSpoint = RangeFactory.create(arrayS[2], true, arrayS[2], true);
    rangeI2bounds = RangeFactory.create(1, true, 60, true);
    rangeIpoint = RangeFactory.create(arrayI[2], true, arrayI[2], true);
    rangeF2bounds = RangeFactory.create(0.5f, true, 60.5f, true, false);
    rangeFpoint = RangeFactory.create(arrayF[2], true, arrayF[2], true, false);
    rangeD2bounds = RangeFactory.create(1.5d, true, 60.5d, true, false);
    rangeDpoint = RangeFactory.create(arrayD[2], true, arrayD[2], true, false);
    rangeL2bounds = RangeFactory.create(1L, true, 60L, true);
    rangeLpoint = RangeFactory.create(arrayL[2], true, arrayL[2], true);

    arrayBtest = new Byte[100];
    arrayStest = new Short[100];
    arrayItest = new Integer[100];
    arrayFtest = new Float[100];
    arrayDtest = new Double[100];

    // Random value creation for the various Ranges
    for (int j = 0; j < 100; j++) {
        double randomValue = Math.random();

        arrayBtest[j] = (byte) (randomValue * (Byte.MAX_VALUE - Byte.MIN_VALUE) + Byte.MIN_VALUE);
        arrayStest[j] = (short) (randomValue * (Short.MAX_VALUE - Short.MIN_VALUE) + Short.MIN_VALUE);
        arrayItest[j] = (int) (randomValue * (Integer.MAX_VALUE - Integer.MIN_VALUE) + Integer.MIN_VALUE);
        arrayFtest[j] = (float) (randomValue * (Float.MAX_VALUE - Float.MIN_VALUE) + Float.MIN_VALUE);
        arrayDtest[j] = (randomValue * (Double.MAX_VALUE - Double.MIN_VALUE) + Double.MIN_VALUE);
    }//from www  .  j  a  v a 2s. c om

    // JAI tools Ranges
    rangeJTB = org.jaitools.numeric.Range.create((byte) 1, true, (byte) 60, true);
    rangeJTS = org.jaitools.numeric.Range.create((short) 1, true, (short) 60, true);
    rangeJTI = org.jaitools.numeric.Range.create(1, true, 60, true);
    rangeJTF = org.jaitools.numeric.Range.create(0.5f, true, 60.5f, true);
    rangeJTD = org.jaitools.numeric.Range.create(1.5d, true, 60.5d, true);
    // 1 point Ranges
    rangeJTBpoint = org.jaitools.numeric.Range.create((byte) 5, true, (byte) 5, true);
    rangeJTSpoint = org.jaitools.numeric.Range.create((short) 5, true, (short) 5, true);
    rangeJTIpoint = org.jaitools.numeric.Range.create(5, true, 5, true);
    rangeJTFpoint = org.jaitools.numeric.Range.create(5f, true, 5f, true);
    rangeJTDpoint = org.jaitools.numeric.Range.create(5d, true, 5d, true);

    // JAI Ranges
    rangeJAIB = new javax.media.jai.util.Range(Byte.class, (byte) 1, true, (byte) 60, true);
    rangeJAIS = new javax.media.jai.util.Range(Short.class, (short) 1, true, (short) 60, true);
    rangeJAII = new javax.media.jai.util.Range(Integer.class, 1, true, 60, true);
    rangeJAIF = new javax.media.jai.util.Range(Float.class, 0.5f, true, 60.5f, true);
    rangeJAID = new javax.media.jai.util.Range(Double.class, 1.5d, true, 60.5d, true);
    // 1 point Ranges
    rangeJAIBpoint = new javax.media.jai.util.Range(Byte.class, (byte) 5, true, (byte) 5, true);
    rangeJAISpoint = new javax.media.jai.util.Range(Short.class, (short) 5, true, (short) 5, true);
    rangeJAIIpoint = new javax.media.jai.util.Range(Integer.class, 5, true, 5, true);
    rangeJAIFpoint = new javax.media.jai.util.Range(Float.class, 5f, true, 5f, true);
    rangeJAIDpoint = new javax.media.jai.util.Range(Double.class, 5d, true, 5d, true);

    // Apache Common Ranges
    rangeCommonsB = new org.apache.commons.lang.math.IntRange((byte) 1, (byte) 60);
    rangeCommonsS = new org.apache.commons.lang.math.IntRange((short) 1, (short) 60);
    rangeCommonsI = new org.apache.commons.lang.math.IntRange(1, 60);
    rangeCommonsF = new org.apache.commons.lang.math.FloatRange(0.5f, 60.5f);
    rangeCommonsD = new org.apache.commons.lang.math.DoubleRange(1.5d, 60.5d);
    // 1 point Ranges
    rangeCommonsBpoint = new org.apache.commons.lang.math.IntRange(5);
    rangeCommonsSpoint = new org.apache.commons.lang.math.IntRange(5);
    rangeCommonsIpoint = new org.apache.commons.lang.math.IntRange(5);
    rangeCommonsFpoint = new org.apache.commons.lang.math.FloatRange(5f);
    rangeCommonsDpoint = new org.apache.commons.lang.math.DoubleRange(5d);

    //        // GeoTools Ranges
    //        rangeGeoToolsB = new org.geotools.util.NumberRange<Byte>(Byte.class, (byte) 1, (byte) 60);
    //        rangeGeoToolsS = new org.geotools.util.NumberRange<Short>(Short.class, (short) 1,
    //                (short) 60);
    //        rangeGeoToolsI = new org.geotools.util.NumberRange<Integer>(Integer.class, 1, 60);
    //        rangeGeoToolsF = new org.geotools.util.NumberRange<Float>(Float.class, 0.5f, 60.5f);
    //        rangeGeoToolsD = new org.geotools.util.NumberRange<Double>(Double.class, 1.5d, 60.5d);
    //        // 1 point Ranges
    //        rangeGeoToolsBpoint = new org.geotools.util.NumberRange<Byte>(Byte.class, (byte) 5,
    //                (byte) 5);
    //        rangeGeoToolsSpoint = new org.geotools.util.NumberRange<Short>(Short.class, (short) 5,
    //                (short) 5);
    //        rangeGeoToolsIpoint = new org.geotools.util.NumberRange<Integer>(Integer.class, 5, 5);
    //        rangeGeoToolsFpoint = new org.geotools.util.NumberRange<Float>(Float.class, 5f, 5f);
    //        rangeGeoToolsDpoint = new org.geotools.util.NumberRange<Double>(Double.class, 5d, 5d);

    //        // Guava Ranges
    //        rangeGuavaB = com.google.common.collect.Range.closed((byte) 1, (byte) 60);
    //        rangeGuavaS = com.google.common.collect.Range.closed((short) 1, (short) 60);
    //        rangeGuavaI = com.google.common.collect.Range.closed(1, 60);
    //        rangeGuavaF = com.google.common.collect.Range.closed(0.5f, 60.5f);
    //        rangeGuavaD = com.google.common.collect.Range.closed(1.5d, 60.5d);
    //        // 1 point Ranges
    //        rangeGuavaBpoint = com.google.common.collect.Range.singleton((byte) 5);
    //        rangeGuavaSpoint = com.google.common.collect.Range.singleton((short) 5);
    //        rangeGuavaIpoint = com.google.common.collect.Range.singleton(5);
    //        rangeGuavaFpoint = com.google.common.collect.Range.singleton(5f);
    //        rangeGuavaDpoint = com.google.common.collect.Range.singleton(5d);
}