Example usage for java.lang Double isInfinite

List of usage examples for java.lang Double isInfinite

Introduction

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

Prototype

public static boolean isInfinite(double v) 

Source Link

Document

Returns true if the specified number is infinitely large in magnitude, false otherwise.

Usage

From source file:org.gwaspi.reports.GenericReportGenerator.java

private static List<Double> assembleQQPlotData(OperationKey testOpKey) throws IOException {

    CommonTestOperationDataSet testOpDS = (CommonTestOperationDataSet) OperationManager
            .generateOperationDataSet(testOpKey);
    Collection<Double> chiSqrVals = testOpDS.getTs(-1, -1);
    List<Double> obsChiSqrVals = new ArrayList<Double>(chiSqrVals.size());
    for (Double chiSqr : chiSqrVals) {
        if (!Double.isNaN(chiSqr) && !Double.isInfinite(chiSqr)) {
            obsChiSqrVals.add(chiSqr);/*  w  w w. j a  v a  2  s . c  om*/
        }
    }
    Collections.sort(obsChiSqrVals);

    return obsChiSqrVals;
}

From source file:com.github.lindenb.jvarkit.tools.redon.CopyNumber01.java

private void normalizeCoverage() {
    final Median medianOp = new Median();
    final Mean meanOp = new Mean();

    if (medianOp.evaluate(new double[] { 20, 1000, 19 }) != 20) {
        throw new RuntimeException("boum");
    }/*from  w w  w  .j a  va 2  s .c  o  m*/

    int autosome_count = 0;
    Collections.sort(this.interval2row, CopyNumber01.sortOnXY);

    for (int j = 0; j < this.interval2row.size(); ++j) {
        GCAndDepth r = this.interval2row.get(j);
        if (isSexualChrom(r.getChrom()))
            continue;
        autosome_count++;
    }

    double x[] = new double[autosome_count];
    double y[] = new double[autosome_count];

    int i = 0;
    for (int j = 0; j < this.interval2row.size(); ++j) {
        GCAndDepth r = this.interval2row.get(j);
        if (isSexualChrom(r.getChrom()))
            continue;
        x[i] = r.getX();
        y[i] = r.getY();
        ++i;
    }

    final double min_x = x[0];
    final double max_x = x[x.length - 1];

    /* merge adjacent x having same values */
    i = 0;
    int k = 0;
    while (i < x.length) {
        int j = i + 1;

        while (j < x.length && Double.compare(x[i], x[j]) == 0) {
            ++j;
        }
        x[k] = x[i];
        y[k] = meanOp.evaluate(y, i, j - i);
        ++k;
        i = j;
    }

    /* reduce size of x et y */
    if (k != x.length) {
        info("Compacting X from " + x.length + " to " + k);
        x = Arrays.copyOf(x, k);
        y = Arrays.copyOf(y, k);
    }

    //min depth cal
    double min_depth = Double.MAX_VALUE;

    UnivariateInterpolator interpolator = createInterpolator();
    UnivariateFunction spline = interpolator.interpolate(x, y);
    int points_removed = 0;
    i = 0;
    while (i < this.interval2row.size()) {
        GCAndDepth r = this.interval2row.get(i);
        if (r.getX() < min_x || r.getX() > max_x) {
            this.interval2row.remove(i);
            ++points_removed;
        } else {
            double norm = spline.value(r.getX());
            if (Double.isNaN(norm) || Double.isInfinite(norm)) {
                info("NAN " + r);
                this.interval2row.remove(i);
                ++points_removed;
                continue;
            }
            r.depth -= norm;
            min_depth = Math.min(min_depth, r.depth);
            ++i;
        }
    }
    info("Removed " + points_removed + " because GC% is too small (Sexual chrom)");
    spline = null;

    //fit to min, fill new y for median calculation
    info("min:" + min_depth);

    y = new double[this.interval2row.size()];
    for (i = 0; i < this.interval2row.size(); ++i) {
        GCAndDepth gc = this.interval2row.get(i);
        gc.depth -= min_depth;
        y[i] = gc.depth;
    }

    //normalize on median
    double median_depth = medianOp.evaluate(y, 0, y.length);
    info("median:" + median_depth);
    for (i = 0; i < this.interval2row.size(); ++i) {
        GCAndDepth gc = this.interval2row.get(i);
        gc.depth /= median_depth;
    }

    //restore genomic order
    Collections.sort(this.interval2row, CopyNumber01.sortOnPosition);

    /**  smoothing values with neighbours */
    final int SMOOTH_WINDOW = 5;
    y = new double[this.interval2row.size()];
    for (i = 0; i < this.interval2row.size(); ++i) {
        y[i] = this.interval2row.get(i).getY();
    }
    for (i = 0; i < this.interval2row.size(); ++i) {
        GCAndDepth gc = this.interval2row.get(i);
        int left = i;
        int right = i;
        while (left > 0 && i - left < SMOOTH_WINDOW && this.interval2row.get(left - 1).tid == gc.tid) {
            left--;
        }
        while (right + 1 < this.interval2row.size() && right - i < SMOOTH_WINDOW
                && this.interval2row.get(right + 1).tid == gc.tid) {
            right++;
        }
        gc.depth = medianOp.evaluate(y, left, (right - left) + 1);
    }

}

From source file:afest.datastructures.tree.decision.erts.grower.AERTGrower.java

/**
 * Create a split on the given attribute by choosing a uniformly random threshold in [min, max).
 * @param <T> Type of ITrainingPoints used by the Extra Trees.
 * @param set set containing the points in which we choose the threshold.
 * @param attribute attribute to pick the threshold for.
 * @return a split on the given attribute by choosing a uniformly random threshold in [min, max).
 *///from ww w. j a v a2s .  c om
private <T extends ITrainingPoint<R, O>> ERTSplit<R> createSplit(Collection<T> set, R attribute) {
    double min = Double.POSITIVE_INFINITY;
    double max = Double.NEGATIVE_INFINITY;
    for (T aT : set) {
        double value = aT.getValue(attribute);
        if (value > max) {
            max = value;
        }
        if (value < min) {
            min = value;
        }
    }

    if (Double.isInfinite(max)) {
        max = Double.MAX_VALUE;
    }
    if (Double.isInfinite(min)) {
        min = -Double.MAX_VALUE;
    }

    max = max - Double.MIN_VALUE;
    min = min + Double.MIN_VALUE;
    double threshold = fRandom.nextDouble() * (max - min) + min;
    ERTSplit<R> split = new ERTSplit<R>(attribute, threshold);
    return split;
}

From source file:net.librec.recommender.AbstractRecommender.java

/**
 * Post each iteration, we do things://from   ww w.ja v a2 s .co  m
 * <ol>
 * <li>print debug information</li>
 * <li>check if converged</li>
 * <li>if not, adjust learning rate</li>
 * </ol>
 * @param iter current iteration
 * @return boolean: true if it is converged; false otherwise
 * @throws LibrecException if error occurs
 */
protected boolean isConverged(int iter) throws LibrecException {
    float delta_loss = (float) (lastLoss - loss);

    // print out debug info
    if (verbose) {
        String recName = getClass().getSimpleName().toString();
        String info = recName + " iter " + iter + ": loss = " + loss + ", delta_loss = " + delta_loss;
        LOG.info(info);
    }

    if (Double.isNaN(loss) || Double.isInfinite(loss)) {
        //            LOG.error("Loss = NaN or Infinity: current settings does not fit the recommender! Change the settings and try again!");
        throw new LibrecException(
                "Loss = NaN or Infinity: current settings does not fit the recommender! Change the settings and try again!");
    }

    // check if converged
    boolean converged = Math.abs(loss) < 1e-5;
    lastLoss = loss;

    return converged;
}

From source file:org.easyrec.plugin.pearson.impl.PearsonServiceImpl.java

private void predict(final Integer tenantId, final Integer actionTypeId, final Integer itemTypeId,
        final Integer sourceTypeId, final Date changeDate, final List<User> users,
        final Map<Integer, Double> averageRatings, final Integer minRatingValue, final Integer maxRatingValue) {
    // final List<ItemVO<Integer, Integer>> items = latestActionDao.getAvailableItemsForTenant(tenantId,
    // itemTypeId);

    final double caseAmplification = settings.getCaseAmplification();
    final boolean useCaseAmplification = settings.getCaseAmplification() != null;

    int cur = 0;//from   w w  w  .j  a  v a 2  s . c  o m
    final int perc25 = (int) (users.size() * 0.25);
    final int perc50 = (int) (users.size() * 0.5);
    final int perc75 = (int) (users.size() * 0.75);

    for (final User activeUser : users) {
        if (logger.isInfoEnabled()) {
            if (cur == perc25)
                logger.info("Predictions at 25%");
            if (cur == perc50)
                logger.info("Predictions at 50%");
            if (cur == perc75)
                logger.info("Predictions at 75%");

            logger.info(String.format("Predictions at user %d of %d", cur, users.size()));
        }

        cur++;

        // final List<Weight> weights = weightDao.getWeightsForUser1(tenantId, activeUser.getUser());

        // if (weights.size() == 0) {
        // if (logger.isInfoEnabled())
        // logger.info(String.format(
        // "Couldn't calculate prediction for user %d because no weights were present",
        // activeUser.getUser()));
        //
        // continue;
        // }

        final List<ItemVO<Integer, Integer>> items;

        if (settings.getTestDataSourceType() == null)
            items = latestActionDao.getItemsNotRatedByUser(tenantId, activeUser.getUser(), itemTypeId);
        else
            // we are only predicting for the test-set
            items = userAssocDao.getItemsAssociatedToUser(tenantId, activeUser.getUser(), itemTypeId,
                    settings.getTestDataSourceType());

        for (final ItemVO<Integer, Integer> item : items) {
            if (latestActionDao.didUserRateItem(activeUser.getUser(), item, actionTypeId))
                continue;

            double kappa = 0.0;
            double weightedRatings = 0.0;

            final List<Weight> weights = weightDao.getWeightsForUser1AndItem(tenantId, activeUser.getUser(),
                    item.getItem(), item.getType());

            if (weights.size() == 0) {
                if (logger.isInfoEnabled())
                    logger.info(String.format(
                            "Couldn't calculate prediction for user %d and item %d because no weights were present",
                            activeUser.getUser(), item.getItem()));

                continue;
            }

            // TODO get users that rated item
            // TODO get weights for users that rated item
            for (final Weight weight : weights) {
                double currentWeight = weight.getWeight();
                final User otherUser = weight.getUser2();

                final List<RatingVO<Integer, Integer>> ratingsOther = latestActionDao.getLatestRatingsForTenant(
                        tenantId, itemTypeId, item.getItem(), otherUser.getUser(), null);

                if (ratingsOther.size() > 1 && logger.isWarnEnabled())
                    logger.warn("    There shouldn't be more than 1 rating");

                double ratingOther = 0.0;

                if (ratingsOther.size() == 1)
                    ratingOther = ratingsOther.get(0).getRatingValue();
                else
                    // the other user didn't rate the current item
                    continue;

                if (useCaseAmplification)
                    if (currentWeight >= 0)
                        currentWeight = Math.pow(currentWeight, caseAmplification);
                    else
                        currentWeight = -Math.pow(-currentWeight, caseAmplification);

                final double averageRatingOther = averageRatings.get(otherUser.getUser());
                kappa += Math.abs(currentWeight);
                weightedRatings += currentWeight * (ratingOther - averageRatingOther);
            }

            if (kappa == 0.0 || Double.isNaN(kappa) || Double.isInfinite(kappa)) {
                if (logger.isInfoEnabled())
                    logger.info(String.format("    Prediction for user %d item %d failed (kappa=%f)",
                            activeUser.getUser(), item.getItem(), kappa));

                continue;
            }

            double prediction = weightedRatings / kappa;

            if (Double.isNaN(weightedRatings) || Double.isInfinite(weightedRatings)) {
                if (logger.isInfoEnabled())
                    logger.info(String.format(
                            "    Prediction for user %d item %d failed (prediction=%f, weightedRatings=%f, kappa=%f)",
                            activeUser.getUser(), item.getItem(), prediction, weightedRatings, kappa));

                continue;
            }

            final double averageRatingActive = averageRatings.get(activeUser.getUser());
            prediction += averageRatingActive;

            if (settings.isNormalizePredictions()) {
                prediction = Math.max(prediction, minRatingValue);
                prediction = Math.min(prediction, maxRatingValue);
            }

            final UserAssoc userAssoc = new UserAssoc(prediction, changeDate, item, sourceTypeId, tenantId,
                    activeUser.getUser());
            userAssocDao.insertOrUpdateUserAssoc(userAssoc);
        }
    }
}

From source file:com.rapidminer.gui.plotter.charts.Abstract2DChartPlotter.java

private void prepareNominalData() {
    this.nominal = true;
    dataSet = new DefaultXYDataset();

    if (axis[X_AXIS] >= 0 && axis[Y_AXIS] >= 0) {
        Map<String, List<double[]>> dataCollection = new LinkedHashMap<String, List<double[]>>();
        Map<String, List<String>> idCollection = new LinkedHashMap<String, List<String>>();

        synchronized (dataTable) {
            if (colorColumn >= 0) {
                for (int v = 0; v < dataTable.getNumberOfValues(colorColumn); v++) {
                    dataCollection.put(dataTable.mapIndex(colorColumn, v), new LinkedList<double[]>());
                    idCollection.put(dataTable.mapIndex(colorColumn, v), new LinkedList<String>());
                }//ww w . j  av  a 2  s  .c  o m
            }

            Iterator<DataTableRow> i = this.dataTable.iterator();
            int index = 0;
            while (i.hasNext()) {
                DataTableRow row = i.next();

                double xValue = row.getValue(axis[X_AXIS]);
                double yValue = row.getValue(axis[Y_AXIS]);

                double colorValue = Double.NaN;
                if (colorColumn >= 0) {
                    colorValue = row.getValue(colorColumn);
                }

                // TM: removed check
                // if (!Double.isNaN(xValue) && !Double.isNaN(yValue)) {
                addPoint(dataCollection, idCollection, row.getId(), xValue, yValue, colorValue);
                // }
                index++;
            }
        }

        double minX = Double.POSITIVE_INFINITY;
        double maxX = Double.NEGATIVE_INFINITY;
        double minY = Double.POSITIVE_INFINITY;
        double maxY = Double.NEGATIVE_INFINITY;

        Iterator<Map.Entry<String, List<double[]>>> i = dataCollection.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry<String, List<double[]>> entry = i.next();
            List<double[]> dataList = entry.getValue();
            Iterator<double[]> j = dataList.iterator();
            while (j.hasNext()) {
                double[] current = j.next();
                minX = MathFunctions.robustMin(minX, current[X_AXIS]);
                maxX = MathFunctions.robustMax(maxX, current[X_AXIS]);
                minY = MathFunctions.robustMin(minY, current[Y_AXIS]);
                maxY = MathFunctions.robustMax(maxY, current[Y_AXIS]);
            }
        }

        Random jitterRandom = new Random(2001);
        double oldXRange = maxX - minX;
        double oldYRange = maxY - minY;

        if (Double.isInfinite(oldXRange) || Double.isNaN(oldXRange)) {
            oldXRange = 0;
        }
        if (Double.isInfinite(oldYRange) || Double.isNaN(oldYRange)) {
            oldYRange = 0;
        }

        i = dataCollection.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry<String, List<double[]>> entry = i.next();
            String seriesName = entry.getKey();
            List<double[]> dataList = entry.getValue();

            double[][] data = new double[2][dataList.size()];
            int listCounter = 0;
            Iterator<double[]> j = dataList.iterator();
            while (j.hasNext()) {
                double[] current = j.next();
                data[X_AXIS][listCounter] = current[X_AXIS];
                data[Y_AXIS][listCounter] = current[Y_AXIS];

                if (this.jitterAmount > 0) {
                    double pertX = oldXRange * (jitterAmount / 200.0d) * jitterRandom.nextGaussian();
                    double pertY = oldYRange * (jitterAmount / 200.0d) * jitterRandom.nextGaussian();
                    data[X_AXIS][listCounter] += pertX;
                    data[Y_AXIS][listCounter] += pertY;
                }

                listCounter++;
            }

            ((DefaultXYDataset) dataSet).addSeries(seriesName, data);
        }

        int seriesCounter = 0;
        Iterator<List<String>> v = idCollection.values().iterator();
        while (v.hasNext()) {
            List<String> idList = v.next();
            int itemCounter = 0;
            Iterator<String> j = idList.iterator();
            while (j.hasNext()) {
                idMap.put(new SeriesAndItem(seriesCounter, itemCounter++), j.next());
            }
            seriesCounter++;
        }
    }
}

From source file:ml.shifu.shifu.util.NormalUtils.java

/**
 * Normalize variable by (modelType, normMethod). One variable val could be normalized into multi double value
 *
 * @param modelConfig - to check modelType. TreeModel or NN/LR model?
 * @param cutoff      - cutoff for ZScale
 * @param config      - variable configuration
 * @param val         - raw variable value
 * @return - most normalization method return 1 element double list,
 * but OneHot will will return multi-elements double list
 *//*from   ww w . java2 s . c  o  m*/
private static List<Double> computeNumericNormResult(ModelConfig modelConfig, double cutoff,
        ColumnConfig config, String val) {
    List<Double> normalizeValue = null;
    if (CommonUtils.isTreeModel(modelConfig.getAlgorithm())) {
        try {
            normalizeValue = Arrays.asList(new Double[] { Double.parseDouble(val) });
        } catch (Exception e) {
            normalizeValue = Arrays.asList(new Double[] { Normalizer.defaultMissingValue(config) });
        }
    } else {
        normalizeValue = Normalizer.normalize(config, val, cutoff, modelConfig.getNormalizeType());
    }

    if (CollectionUtils.isNotEmpty(normalizeValue)) {
        for (int i = 0; i < normalizeValue.size(); i++) {
            Double nval = normalizeValue.get(i);
            if (Double.isInfinite(nval) || Double.isNaN(nval)) {
                // if the value is Infinite or NaN, treat it as missing value
                // should treat Infinite as missing value also?
                normalizeValue.set(i, defaultMissingValue(config));
            }
        }
    }
    return normalizeValue;
}

From source file:com.machinepublishers.jbrowserdriver.diagnostics.Test.java

private void doTests() {
    JBrowserDriver driver = null;//from   w  w w  .j a  v  a2 s.  c o m
    Thread shutdownHook = null;
    try {
        HttpServer.launch(TEST_PORT_HTTP);
        final File cacheDir = Files.createTempDirectory("jbd_test_cache").toFile();
        final File userDataDir = Files.createTempDirectory("jbd_test_userdata").toFile();
        shutdownHook = new Thread(new Runnable() {
            @Override
            public void run() {
                FileUtils.deleteQuietly(cacheDir);
                FileUtils.deleteQuietly(userDataDir);
            }
        });
        Runtime.getRuntime().addShutdownHook(shutdownHook);
        final String mainPage = "http://" + InetAddress.getLoopbackAddress().getHostAddress() + ":"
                + TEST_PORT_HTTP;
        final int ajaxWait = 150;
        final Settings.Builder builder = Settings.builder().processes(TEST_PORTS_RMI)
                .screen(new Dimension(1024, 768)).logger(null).logJavascript(true).ajaxWait(ajaxWait)
                .cacheDir(cacheDir).cache(true).ignoreDialogs(false);
        driver = new JBrowserDriver(builder.build());

        /*
         * Load a page
         */
        driver.get(mainPage);
        test(driver.getStatusCode() == 200);
        long initialRequestId = HttpServer.previousRequestId();

        /*
         * Load page from cache
         */
        driver.get(mainPage);
        test(driver.getStatusCode() == 200);
        test(HttpServer.previousRequestId() == initialRequestId);
        boolean viaHeader = false;
        for (String line : HttpServer.previousRequest()) {
            if (line.toLowerCase().startsWith("via:")) {
                viaHeader = true;
                break;
            }
        }
        test(!viaHeader);

        /*
         * Driver reset
         */
        driver.reset();
        driver.get(mainPage);
        test(driver.getStatusCode() == 200);
        test(HttpServer.previousRequestId() == initialRequestId);
        driver.reset(builder.cacheDir(null).build());
        driver.get(mainPage);
        test(driver.getStatusCode() == 200);
        test(HttpServer.previousRequestId() != initialRequestId);

        /*
         * Javascript logs
         */
        int messages = 0;
        for (LogEntry entry : driver.manage().logs().get("javascript").filter(Level.ALL)) {
            ++messages;
            test(!StringUtils.isEmpty(entry.getMessage()));
        }
        test(messages == 3);

        /*
         * User-data directory
         */
        driver.findElement(By.id("populate-local-storage")).click();
        driver.findElement(By.id("load-from-local-storage")).click();
        test("test-value".equals(driver.findElement(By.id("local-storage-value-holder")).getText()));
        driver.get(mainPage);
        driver.findElement(By.id("load-from-local-storage")).click();
        test("test-value".equals(driver.findElement(By.id("local-storage-value-holder")).getText()));
        driver.reset();
        driver.get(mainPage);
        driver.findElement(By.id("load-from-local-storage")).click();
        test("".equals(driver.findElement(By.id("local-storage-value-holder")).getText()));
        driver.reset(builder.userDataDirectory(userDataDir).build());
        driver.get(mainPage);
        driver.findElement(By.id("populate-local-storage")).click();
        driver.findElement(By.id("load-from-local-storage")).click();
        test("test-value".equals(driver.findElement(By.id("local-storage-value-holder")).getText()));
        driver.reset();
        driver.get(mainPage);
        driver.findElement(By.id("load-from-local-storage")).click();
        test("test-value".equals(driver.findElement(By.id("local-storage-value-holder")).getText()));

        /*
         * Select DOM elements
         */
        test("test-data-attr".equals(driver.findElement(By.id("divtext1")).getAttribute("data-selected")));
        test(driver.findElement(By.id("divtext1")).getAttribute("undefinedattr") == null);
        test(driver.findElement(By.id("divtext1")).getAttribute("innerText").equals("test1"));
        test(driver.findElements(By.name("divs")).size() == 2);
        test(driver.findElements(By.name("divs")).get(1).getAttribute("innerText").equals("test2"));
        test(driver.findElementByClassName("divclass").getAttribute("id").equals("divtext1"));
        test(driver.findElementsByClassName("divclass").get(1).getAttribute("id").equals("divtext2"));
        test(driver.findElementByCssSelector("#divtext1").getAttribute("id").equals("divtext1"));
        test(driver.findElementsByCssSelector("html > *").get(1).getAttribute("id").equals("testbody"));
        test(driver.findElementById("divtext1").getTagName().equals("div"));
        test(driver.findElementsById("divtext1").get(0).getTagName().equals("div"));
        test(driver.findElementByLinkText("anchor").getAttribute("id").equals("anchor1"));
        test(driver.findElementsByLinkText("anchor").get(1).getAttribute("id").equals("anchor2"));
        test(driver.findElementByName("divs").getAttribute("id").equals("divtext1"));
        test(driver.findElementsByName("divs").get(1).getAttribute("id").equals("divtext2"));
        test(driver.findElementByPartialLinkText("anch").getAttribute("id").equals("anchor1"));
        test(driver.findElementsByPartialLinkText("anch").get(1).getAttribute("id").equals("anchor2"));
        test(driver.findElementByTagName("div").getAttribute("id").equals("divtext1"));
        test(driver.findElementsByTagName("div").get(1).getAttribute("id").equals("divtext2"));
        test(driver.findElementByXPath("//*[@id='divtext1']").getAttribute("id").equals("divtext1"));
        test(driver.findElementByTagName("body").findElement(By.xpath("//*[@id='divtext1']")).getAttribute("id")
                .equals("divtext1"));
        test(driver.findElementsByXPath("//html/*").get(1).getAttribute("id").equals("testbody"));
        test(driver.findElement(By.xpath("//a[contains(@href,'1')]")).getAttribute("id").equals("anchor1"));
        test(driver.findElementsByXPath("//a[contains(@href,'!!!')]").isEmpty());
        test(driver.findElementsByClassName("xx").isEmpty());
        test(driver.findElementsByTagName("xx").isEmpty());
        test(driver.findElementsByCssSelector("#xx").isEmpty());
        Throwable error = null;
        try {
            driver.findElementByTagName("xx");
        } catch (NoSuchElementException e) {
            error = e;
        }
        test(error != null);
        error = null;
        try {
            driver.findElementByCssSelector("#xx");
        } catch (NoSuchElementException e) {
            error = e;
        }
        test(error != null);
        error = null;
        try {
            driver.findElementsByXPath("!!!");
        } catch (WebDriverException e) {
            error = e;
        }
        test(error != null);
        error = null;
        try {
            driver.findElement(By.id("divtext1")).findElements(By.cssSelector("???"));
        } catch (WebDriverException e) {
            error = e;
        }
        test(error != null);

        /*
         * WebElement Equals/HashCode
         */
        test(driver.findElements(By.name("divs")).get(0).equals(driver.findElements(By.name("divs")).get(0)));
        test(driver.findElements(By.name("divs")).get(0).hashCode() == driver.findElements(By.name("divs"))
                .get(0).hashCode());

        /*
         * Typing text
         */
        driver.findElement(By.id("text-input")).sendKeys("testing");
        driver.findElement(By.id("text-input")).sendKeys("");
        test(driver.findElement(By.id("text-input")).getAttribute("value").equals("testing"));
        driver.findElement(By.id("text-input")).sendKeys(JBrowserDriver.KEYBOARD_DELETE);
        test(driver.findElement(By.id("text-input")).getAttribute("value") == null);
        driver.findElement(By.id("text-input")).sendKeys("testing");
        test(driver.findElement(By.id("text-input")).getAttribute("value").equals("testing"));
        driver.findElement(By.id("text-input")).clear();
        test(driver.findElement(By.id("text-input")).getAttribute("value") == null);

        /*
         * Clicking on elements
         */
        test(!driver.findElement(By.id("testoption2")).isSelected());
        driver.findElement(By.id("testoption2")).click();
        test(driver.findElement(By.id("testoption2")).isSelected());
        driver.findElement(By.id("testoption1")).click();
        test(driver.findElement(By.id("testoption1")).isSelected());
        driver.findElement(By.id("anchor5")).click();
        test("anchor clicked".equals(driver.findElement(By.id("testspan")).getText()));

        /*
         * Execute javascript
         */
        test(((WebElement) driver.executeScript("return arguments[0];", driver.findElement(By.id("divtext1"))))
                .getAttribute("innerText").equals("test1"));
        test(((WebElement) driver.executeScript("return arguments[0].parentNode;",
                driver.findElement(By.id("divtext1")))).getTagName().equals("body"));
        test(((WebElement) ((JavascriptExecutor) driver.findElement(By.id("divtext1")))
                .executeAsyncScript("arguments[0](this);")).getAttribute("innerText").equals("test1"));
        test((driver.executeAsyncScript("arguments[1](arguments[0].innerText);",
                driver.findElement(By.id("divtext1")))).equals("test1"));
        Map<String, Object> map = (Map<String, Object>) driver.executeScript("return {"
                + "key1:['value1','value2','value3'], " + "key2:5," + "key3:function(){return 'testing';}, "
                + "key4:undefined, key5:null, key6:1/0, key7:0/0, key8:'', key9:[], key10:{}, key11:[{},{}],"
                + "key12:document.getElementById('divtext1'), " + "key13:document.getElementsByName('divs'), "
                + "key14:[document.getElementById('divtext1'),document.getElementsByName('divs'),{subkey1:'subval1'}]};");
        test(map.size() == 14);
        test(((List) map.get("key1")).size() == 3);
        test(((List) map.get("key1")).get(2).equals("value3"));
        test(((List) map.get("key1")).get(2) instanceof String);
        test(map.get("key2").equals(new Long(5)));
        test("function () {return 'testing';}".equals(map.get("key3"))
                || "function (){return 'testing';}".equals(map.get("key3")));
        test(map.get("key4") == null);
        test(map.get("key5") == null);
        test(Double.isInfinite(((Double) map.get("key6")).doubleValue()));
        test(Double.isNaN(((Double) map.get("key7")).doubleValue()));
        test("".equals(map.get("key8")));
        test(map.get("key9") instanceof List);
        test(map.get("key10") instanceof Map);
        test(((List) map.get("key11")).size() == 2);
        test(((Map) ((List) map.get("key11")).get(1)).isEmpty());
        test("test1".equals(((WebElement) map.get("key12")).getAttribute("innerText")));
        test(((List<WebElement>) map.get("key13")).size() == 2);
        test(((List<WebElement>) map.get("key13")).get(1).getAttribute("innerText").equals("test2"));
        test(((List) map.get("key14")).size() == 3);
        test(((List) ((List) map.get("key14")).get(1)).size() == 2);
        test(((WebElement) ((List) ((List) map.get("key14")).get(1)).get(1)).getAttribute("innerText")
                .equals("test2"));
        test(((Map) ((List) map.get("key14")).get(2)).size() == 1);
        test("subval1".equals(((Map) ((List) map.get("key14")).get(2)).get("subkey1")));
        test(((List) driver.executeScript("return [];")).isEmpty());
        test(((Map) driver.executeScript("return {};")).isEmpty());
        error = null;
        try {
            driver.executeScript("invalid.execute()");
        } catch (WebDriverException e) {
            error = e;
        }
        test(error != null);

        /*
         * DOM element properties
         */
        WebElement element = driver.findElement(By.id("divtext1"));
        Point point = element.getLocation();
        test(point.getX() > 0);
        test(point.getY() > 0);
        Dimension dimension = element.getSize();
        test(dimension.width > 0);
        test(dimension.height > 0);
        Rectangle rect = element.getRect();
        test(rect.x == point.getX());
        test(rect.y == point.getY());
        test(rect.width == dimension.getWidth());
        test(rect.height == dimension.getHeight());
        test("Testing\ntext.".equals(driver.findElement(By.id("text-node1")).getText()));
        test("".equals(driver.findElement(By.id("text-node2")).getText()));
        test("".equals(driver.findElement(By.id("text-node3")).getText()));
        List<WebElement> options = driver.findElementsByCssSelector("#testselect option");
        test(options.size() == 2);
        test(options.get(0).isSelected());
        test(!options.get(1).isSelected());
        test(driver.findElementById("checkbox1").isSelected());
        test(!driver.findElementById("checkbox2").isSelected());

        /*
         * Cookie manager
         */
        driver.manage().addCookie(new Cookie("testname", "testvalue"));
        Cookie cookie = driver.manage().getCookieNamed("testname");
        test(cookie.getValue().equals("testvalue"));
        test(InetAddress.getLoopbackAddress().getHostAddress().equals(cookie.getDomain()));

        /*
         * Screenshots
         */
        test(driver.getScreenshotAs(OutputType.BYTES).length > 0);

        /*
         * File Input Type
         */
        driver.findElement(By.id("upload")).sendKeys("some-file");
        test("event-test".equals(driver.findElement(By.id("file-input-onchange")).getText()));
        test(driver.findElement(By.id("upload")).getAttribute("value").endsWith("some-file"));

        /*
         * Javascript alerts
         */
        driver.findElement(By.tagName("button")).click();
        test(driver.switchTo().alert().getText().equals("test-alert"));
        driver.switchTo().alert().dismiss();
        test(driver.switchTo().alert().getText().equals("test-confirm"));
        driver.switchTo().alert().dismiss();
        test(driver.switchTo().alert().getText().equals("test-prompt"));
        driver.switchTo().alert().sendKeys("test-input");
        driver.switchTo().alert().accept();
        test(driver.findElement(By.id("testspan")).getAttribute("innerHTML").equals("test-input"));

        /*
         * Request headers
         */
        List<String> request = HttpServer.previousRequest();
        if (TEST_PORT_HTTP != 443 && TEST_PORT_HTTP != 80) {
            test(request.get(1).endsWith(":" + TEST_PORT_HTTP));
        }
        test(request.size() > 1);
        Set<String> headers = new HashSet<String>();
        for (String line : request) {
            if (line.contains(":")) {
                headers.add(line.split(":")[0].toLowerCase());
            }
        }
        test(request.size() - 2 == headers.size());

        /*
         * HTTP Post
         */
        driver.findElement(By.id("form-submit")).click();
        test(driver.getStatusCode() == 201);
        test("form-field=test-form-value"
                .equals(HttpServer.previousRequest().get(HttpServer.previousRequest().size() - 1)));

        /*
         * Frames
         */
        driver.switchTo().frame(driver.findElementByTagName("iframe"));
        test(driver.findElementById("iframebody") != null);
        driver.switchTo().parentFrame();
        test(driver.findElementById("testbody") != null);
        driver.switchTo().frame(0);
        test(driver.findElementById("iframebody") != null);
        driver.switchTo().defaultContent();
        driver.switchTo().frame("testiframe");
        test(driver.findElementById("iframebody") != null);
        driver.get(mainPage);
        test(driver.getPageSource() != null);
        driver.switchTo().frame(driver.findElementByTagName("iframe"));
        test(driver.findElementById("iframebody") != null);
        driver.switchTo().parentFrame();
        driver.findElement(By.id("anchor3")).click();
        test(driver.getPageSource() != null);
        driver.switchTo().frame(driver.findElementByTagName("iframe"));
        driver.findElement(By.id("iframe-anchor")).click(); //TODO iframe coord offset needed on any other methods?
        driver.pageWait();
        test(HttpServer.previousRequest().get(0).startsWith("GET /iframe.htm?param=fromiframe"));
        driver.get(mainPage);
        driver.switchTo().frame(driver.findElementByTagName("iframe"));
        Actions actions = new Actions(driver);
        actions.moveToElement(driver.findElement(By.id("iframe-anchor")));
        actions.click();
        actions.build().perform();
        driver.pageWait();
        test(HttpServer.previousRequest().get(0).startsWith("GET /iframe.htm?param=fromiframe"));
        driver.get(mainPage);
        driver.switchTo().frame(driver.findElementByTagName("iframe"));
        driver.getMouse().click(((Locatable) driver.findElement(By.id("iframe-anchor"))).getCoordinates());
        driver.getMouse().mouseMove(((Locatable) driver.findElement(By.id("iframe-anchor"))).getCoordinates(),
                5, 5);
        driver.pageWait();
        test(HttpServer.previousRequest().get(0).startsWith("GET /iframe.htm?param=fromiframe"));
        //TODO fingerprinting
        //System.out.println(driver.findElement(By.id("iframe-useragent")).getAttribute("innerHTML"));
        //System.out.println(driver.findElement(By.id("iframe-nested-useragent")).getAttribute("innerHTML"));

        /*
         * Redirects and cookies
         */
        driver.get(mainPage + "/redirect/site1#testfragment");
        test(HttpServer.previousRequestId() != initialRequestId);
        test(driver.getStatusCode() == 200);
        test(driver.getCurrentUrl().endsWith("/redirect/site2#testfragment"));
        cookie = driver.manage().getCookieNamed("JSESSIONID");
        test(cookie.getValue().equals("ABC123"));
        test(InetAddress.getLoopbackAddress().getHostAddress().equals(cookie.getDomain()));

        /*
         * Cookies set by Javascript
         */
        test("jsCookieValue1".equals(driver.manage().getCookieNamed("jsCookieName1").getValue()));
        test("jsCookieValue2".equals(driver.manage().getCookieNamed("jsCookieName2").getValue()));
        test("jsCookieValue3".equals(driver.manage().getCookieNamed("jsCookieName3").getValue()));
        test("jsCookieValue4".equals(driver.manage().getCookieNamed("jsCookieName4").getValue()));

        /*
         * Window size and position
         */
        driver.manage().window().setSize(new Dimension(5000, 5000));
        test(driver.manage().window().getSize().getWidth() == 1024);
        test(driver.manage().window().getSize().getHeight() == 768);
        driver.manage().window().setSize(new Dimension(800, 600));
        test(driver.manage().window().getSize().getWidth() == 800);
        test(driver.manage().window().getSize().getHeight() == 600);
        driver.manage().window().setPosition(new Point(5000, 5000));
        test(driver.manage().window().getPosition().getX() == 224);
        test(driver.manage().window().getPosition().getY() == 168);
        driver.manage().window().setPosition(new Point(20, 50));
        test(driver.manage().window().getPosition().getX() == 20);
        test(driver.manage().window().getPosition().getY() == 50);
        driver.manage().window().maximize();
        test(driver.manage().window().getPosition().getX() == 0);
        test(driver.manage().window().getPosition().getY() == 0);
        test(driver.manage().window().getSize().getWidth() == 1024);
        test(driver.manage().window().getSize().getHeight() == 768);
        driver.manage().window().setSize(new Dimension(800, 600));
        driver.manage().window().setPosition(new Point(20, 50));
        driver.manage().window().fullscreen();
        test(driver.manage().window().getPosition().getX() == 0);
        test(driver.manage().window().getPosition().getY() == 0);
        test(driver.manage().window().getSize().getWidth() == 1024);
        test(driver.manage().window().getSize().getHeight() == 768);
        driver.manage().window().fullscreen();
        test(driver.manage().window().getPosition().getX() == 20);
        test(driver.manage().window().getPosition().getY() == 50);
        test(driver.manage().window().getSize().getWidth() == 800);
        test(driver.manage().window().getSize().getHeight() == 600);
        driver.manage().window().setSize(new Dimension(400, 200));
        driver.manage().window().setPosition(new Point(10, 30));
        test(driver.manage().window().getPosition().getX() == 10);
        test(driver.manage().window().getPosition().getY() == 30);
        test(driver.manage().window().getSize().getWidth() == 400);
        test(driver.manage().window().getSize().getHeight() == 200);
        driver.manage().window().setSize(new Dimension(1024, 768));
        test(driver.manage().window().getPosition().getX() == 0);
        test(driver.manage().window().getPosition().getY() == 0);
        test(driver.manage().window().getSize().getWidth() == 1024);
        test(driver.manage().window().getSize().getHeight() == 768);

        /*
         * Element visibility
         */
        test(driver.findElement(By.id("iframe-anchor")).isDisplayed());
        test(!driver.findElement(By.id("anchor-visibility-hidden")).isDisplayed());
        test(!driver.findElement(By.id("anchor-display-none")).isDisplayed());
        error = null;
        try {
            driver.findElement(By.id("anchor-visibility-hidden")).click();
        } catch (ElementNotVisibleException e) {
            error = e;
        }
        test(error != null);
        error = null;
        try {
            driver.findElement(By.id("anchor-display-none")).click();
        } catch (ElementNotVisibleException e) {
            error = e;
        }
        test(error != null);

        /*
         * Operations on elements that no longer exist
         */
        WebElement body = driver.findElement(By.tagName("body"));
        test(!StringUtils.isEmpty(body.getAttribute("outerHTML")));
        driver.get("about:blank");
        error = null;
        try {
            body.getAttribute("outerHTML");
        } catch (StaleElementReferenceException e) {
            error = e;
        }
        test(error != null);

        /*
         * Timeouts
         */
        driver.manage().timeouts().pageLoadTimeout(1, TimeUnit.MILLISECONDS);
        error = null;
        try {
            driver.get(mainPage + "/wait-forever");
        } catch (TimeoutException e) {
            error = e;
        }
        test(error != null);

    } catch (Throwable t) {
        outputError(testLabel("failed", curTest + 1, t));
    } finally {
        try {
            driver.quit();
        } catch (Throwable t) {
            outputError(toString(t));
        }
        try {
            HttpServer.stop();
        } catch (Throwable t) {
            outputError(toString(t));
        }
        try {
            Runtime.getRuntime().removeShutdownHook(shutdownHook);
            shutdownHook.run();
        } catch (Throwable t) {
        }
    }
}

From source file:org.apache.carbondata.core.scan.executor.util.RestructureUtil.java

/**
 * Gets the default value based on the column data type.
 *
 * @param columnSchema//from   w w  w  .  j av a 2 s.co m
 * @param defaultValue
 * @return
 */
public static Object getMeasureDefaultValueByType(ColumnSchema columnSchema, byte[] defaultValue) {
    Object measureDefaultValue = null;
    if (!isDefaultValueNull(defaultValue)) {
        String value = null;
        switch (columnSchema.getDataType()) {
        case SHORT:
            value = new String(defaultValue, Charset.forName(CarbonCommonConstants.DEFAULT_CHARSET));
            measureDefaultValue = Short.parseShort(value);
            break;
        case INT:
            value = new String(defaultValue, Charset.forName(CarbonCommonConstants.DEFAULT_CHARSET));
            measureDefaultValue = Integer.parseInt(value);
            break;
        case LONG:
            value = new String(defaultValue, Charset.forName(CarbonCommonConstants.DEFAULT_CHARSET));
            measureDefaultValue = Long.parseLong(value);
            break;
        case DECIMAL:
            BigDecimal decimal = DataTypeUtil.byteToBigDecimal(defaultValue);
            if (columnSchema.getScale() > decimal.scale()) {
                decimal = decimal.setScale(columnSchema.getScale(), RoundingMode.HALF_UP);
            }
            measureDefaultValue = Decimal.apply(decimal);
            break;
        default:
            value = new String(defaultValue, Charset.forName(CarbonCommonConstants.DEFAULT_CHARSET));
            Double parsedValue = Double.valueOf(value);
            if (!Double.isInfinite(parsedValue) && !Double.isNaN(parsedValue)) {
                measureDefaultValue = parsedValue;
            }
        }
    }
    return measureDefaultValue;
}

From source file:Math.java

/**
 * Returns the relative absolute difference between the specified
 * values, defined to be:/* w ww .  jav  a 2 s.  c om*/
 *
 * <blockquote><pre>
 * relAbsDiff(x,y) = abs(x-y) / (abs(x) + abs(y))</pre></blockquote>
 *
 * @param x First value.
 * @param y Second value.
 * @return The absolute relative difference between the values.
 */
public static double relativeAbsoluteDifference(double x, double y) {
    return (Double.isInfinite(x) || Double.isInfinite(y)) ? Double.POSITIVE_INFINITY
            : (java.lang.Math.abs(x - y) / (java.lang.Math.abs(x) + java.lang.Math.abs(y)));
}