Example usage for java.lang Double doubleValue

List of usage examples for java.lang Double doubleValue

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public double doubleValue() 

Source Link

Document

Returns the double value of this Double object.

Usage

From source file:org.pentaho.reporting.libraries.css.dom.AbstractOutputMetaData.java

public double getNumericFeatureValue(final OutputProcessorFeature.NumericOutputProcessorFeature feature) {
    if (feature == null) {
        throw new NullPointerException();
    }//from  w  ww . j  a  v  a 2  s  .c o m
    final Double d = (Double) numericFeatures.get(feature);
    if (d == null) {
        return 0;
    }
    return d.doubleValue();
}

From source file:de.codesourcery.luaparser.LuaToJSON.java

private Object evaluate(ExpContext value) {
    final ParseTree child0 = value.getChildCount() > 0 ? value.getChild(0) : null;
    final ParseTree child1 = value.getChildCount() >= 1 ? value.getChild(1) : null;
    final ParseTree child2 = value.getChildCount() >= 2 ? value.getChild(2) : null;

    if (child0 instanceof OperatorUnaryContext) {
        return "-" + evaluate(child1);
    }/*from   w  w  w.j a va  2  s.  c o  m*/

    if (child1 == null && child2 == null) {
        return evaluate(child0);
    }

    System.err.println("Child_0: "
            + (child0 == null ? "<not set>" : child0.getText() + " (" + child0.getClass().getName()));
    System.err.println("Child_1: "
            + (child1 == null ? "<not set>" : child1.getText() + " (" + child1.getClass().getName()));
    System.err.println("Child_2: "
            + (child2 == null ? "<not set>" : child2.getText() + " (" + child2.getClass().getName()));

    if (child1 instanceof OperatorMulDivModContext) {
        final String op = child1.getChild(0).getText();

        final Double value0 = (Double) evaluate(child0);
        final Double value1 = (Double) evaluate(child2);
        switch (op) {
        case "/":
            return value0.doubleValue() / value1.doubleValue();
        case "*":
            return value0.doubleValue() * value1.doubleValue();
        }
        System.out.println("Unhandled operator: " + op);
    }

    System.err.println("Unhandled expression: " + value.getText());
    throw new RuntimeException("Unhandled expression");
}

From source file:eu.ascetic.zabbixdatalogger.datasource.ZabbixDirectDbDataSourceAdaptor.java

/**
 * This function sums a list of numbers for historic data.
 *
 * @param list The ArrayList to calculate the values of.
 * @return The sum of the values.//from  ww w . j  a  v a  2  s  .com
 */
private double sumArray(List<Double> list) {
    double answer = 0.0;
    for (Double current : list) {
        answer = answer + current.doubleValue();
    }
    return answer;
}

From source file:org.kalypso.dwd.DWDTaskDelegate.java

public void execute(final ILogger logger, final URL obsRasterURL, final URL dwd2zmlConfUrl,
        final File targetContext, final Date startSim, final Date startForecast, final Date stopSim,
        String filter, final Properties metadata) throws Exception {
    m_metadata = metadata;/*from   www.j  a va2s.  co  m*/

    logger.log(Level.FINE, LoggerUtilities.CODE_NONE, " inputRaster: " + obsRasterURL);
    logger.log(Level.FINE, LoggerUtilities.CODE_NONE, " raster to zml mapping: " + dwd2zmlConfUrl);
    logger.log(Level.FINE, LoggerUtilities.CODE_NONE, " context for targets (zml-files): " + targetContext);
    logger.log(Level.FINE, LoggerUtilities.CODE_NONE, " unmarshall dwd2zml configuration ...");

    final Unmarshaller unmarshaller = JC.createUnmarshaller();
    final DwdzmlConf conf = (DwdzmlConf) unmarshaller.unmarshal(dwd2zmlConfUrl);
    final String axisType = DWDRasterHelper.getAxisTypeForDWDKey(conf.getDwdKey());
    logger.log(Level.FINE, LoggerUtilities.CODE_NONE, " type of ZML to generate" + axisType);

    logger.log(Level.FINE, LoggerUtilities.CODE_NONE, " read inputraster...");
    DWDObservationRaster obsRaster = null;
    try {
        // conf.getNumberOfCells()
        obsRaster = DWDRasterHelper.loadObservationRaster(obsRasterURL, conf.getDwdKey());
    } catch (final Exception e) {
        logger.log(Level.SEVERE, LoggerUtilities.CODE_SHOW_MSGBOX,
                "Konnte Raster nicht laden, DWD-Vorhersage kann nicht verwendet werden: "
                        + e.getLocalizedMessage());
    }

    if (obsRaster != null) {
        final Calendar baseDateCal = Calendar.getInstance();
        baseDateCal.setTime(obsRaster.getBaseDate());

        // REMARK: as the DWD Date wa previously read with UTC-1 (probably wrongly), because of the Saale-Model (HWVOR00),
        // we now delete that hour from the date in order to have a nice message with even dates 0/12 hours.
        // This has to be corrected as sson as we know what timeszone the DWD-LM-Data is truly in.
        baseDateCal.add(Calendar.HOUR, -1);

        final Date firstRasterDate = baseDateCal.getTime();

        /* Produce warning, if rasterDate is much before startForecast */
        if (firstRasterDate == null || startForecast == null)
            logger.log(Level.SEVERE, LoggerUtilities.CODE_SHOW_MSGBOX,
                    "Startdatum der DWD-Rasterdaten konnte nicht ermittelt werden oder Vorhersagezeitpunkt ist nicht gesetzt. Prfen Sie den Dateneingang.");
        else {
            final long distance = startForecast.getTime() - firstRasterDate.getTime();
            final Double distanceInHours = new Double((double) distance / (1000 * 60 * 60));

            final String msg = String.format("DWD-Lokalmodell vom %s",
                    new Object[] { DWD_DATEFORMAT.format(firstRasterDate) });

            if (distanceInHours.doubleValue() > 12) {
                logger.log(Level.WARNING, LoggerUtilities.CODE_SHOW_MSGBOX,
                        "DWD Daten veraltet, bitte prfen Sie den Dateneingang.");
                logger.log(Level.INFO, LoggerUtilities.CODE_SHOW_DETAILS, msg);
            } else if (distanceInHours.doubleValue() < -12) {
                logger.log(Level.WARNING, LoggerUtilities.CODE_SHOW_MSGBOX,
                        "Vorhersagezeitraum liegt deutlich (>12h) vor dem Datum der DWD Daten. Bitte prfen Sie den Dateneingang.");
                logger.log(Level.INFO, LoggerUtilities.CODE_SHOW_DETAILS, msg);
            } else
                // in order to always have a message, if nothing else happens make this mesage a main message
                logger.log(Level.INFO, LoggerUtilities.CODE_SHOW_MSGBOX, msg);
        }
    }
    final List<Target> targetList = conf.getTarget();
    if (filter == null)
        filter = "";
    else
        logger.log(Level.FINE, LoggerUtilities.CODE_NONE, "benutze Filter: " + filter);

    logger.log(Level.FINE, LoggerUtilities.CODE_NONE, "Zeitraum ");
    logger.log(Level.FINE, LoggerUtilities.CODE_NONE, " von " + startSim + " (Messung");
    logger.log(Level.FINE, LoggerUtilities.CODE_NONE, " von " + startForecast + " (Vorhersage)");
    logger.log(Level.FINE, LoggerUtilities.CODE_NONE, " bis " + stopSim);
    logger.log(Level.FINE, LoggerUtilities.CODE_NONE, " generate zml...");
    // iterate zml to generate

    for (final Target targetZML : targetList) {
        final String targetZMLref = targetZML.getTargetZR();
        final File resultFile = new File(targetContext, targetZMLref);

        // iterate hours

        final Date[] dates;
        if (obsRaster != null)
            dates = obsRaster.getDates(startForecast, stopSim);
        else
            dates = new Date[0];
        final Object[][] tupleData = new Object[dates.length][3];
        for (int i = 0; i < dates.length; i++) {
            final Date date = dates[i];
            // iterate rastercells
            final List<Map> map = targetZML.getMap();
            double value = 0;

            for (final Map mapping : map) {
                final int cellPos = mapping.getCellPos();
                final double factor = mapping.getFactor();
                value += factor * obsRaster.getValueFor(date, cellPos);
            }
            tupleData[i][0] = date;
            tupleData[i][1] = new Double(value);
            tupleData[i][2] = new Integer(KalypsoStati.BIT_OK);
        }
        resultFile.getParentFile().mkdirs();

        try {
            final IAxis dateAxis = new DefaultAxis("Datum", ITimeseriesConstants.TYPE_DATE, "", Date.class,
                    true, true);
            final String title = TimeserieUtils.getName(axisType);
            final IAxis valueAxis = new DefaultAxis(title, axisType, TimeserieUtils.getUnit(axisType),
                    TimeserieUtils.getDataClass(axisType), false, true);
            final IAxis statusAxis = KalypsoStatusUtils.createStatusAxisFor(valueAxis, true);
            final IAxis[] axis = new IAxis[] { dateAxis, valueAxis, statusAxis };

            final ITupleModel tupleModel = new SimpleTupleModel(axis, tupleData);

            final MetadataList metadataList = new MetadataList();

            final IObservation dwdObservation = new SimpleObservation("href", title, metadataList, tupleModel);

            final IObservation forecastObservation;
            // generate href from filter and intervall
            final String href = ZmlURL.insertRequest(filter, new ObservationRequest(startForecast, stopSim));
            forecastObservation = ZmlFactory.decorateObservation(dwdObservation, href, targetContext.toURL());

            // ----------------
            // merge with target:
            // load target
            final ObservationRequest observationRequest = new ObservationRequest(startSim, startForecast);
            final String sourceref = ZmlURL.insertRequest(targetZMLref, observationRequest);

            final URL sourceURL = new UrlResolver().resolveURL(targetContext.toURL(), sourceref);
            IObservation targetObservation = null;
            try {
                targetObservation = ZmlFactory.parseXML(sourceURL);
            } catch (final Exception e) {
                // nothing, if target is not existing it will be ignored
            }
            final ForecastFilter fc = new ForecastFilter();
            final IObservation[] srcObs;
            if (targetObservation != null)
                srcObs = new IObservation[] { targetObservation, forecastObservation };
            else
                srcObs = new IObservation[] { forecastObservation };

            // important: the forecast-filter is based on the target-obs (if existing)
            // in order to keep its metadata & co
            final IObservation baseObservation;
            if (targetObservation != null)
                baseObservation = targetObservation;
            else
                baseObservation = new SimpleObservation(axis);

            fc.initFilter(srcObs, baseObservation, targetContext.toURL());
            MetadataHelper.setTargetForecast(fc.getMetadataList(), startForecast, stopSim);

            // ----------------
            // add all the metadata from task-parameters
            fc.getMetadataList().putAll(m_metadata);
            //
            final Observation observationType = ZmlFactory.createXML(fc, null);
            final Marshaller marshaller = ZmlFactory.getMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            final FileOutputStream fileWriter = new FileOutputStream(resultFile);
            final OutputStreamWriter streamWriter = new OutputStreamWriter(fileWriter, "UTF-8");
            try {
                marshaller.marshal(observationType, streamWriter);
            } finally {
                IOUtils.closeQuietly(streamWriter);
                IOUtils.closeQuietly(fileWriter);
            }
        } catch (final Exception e) {
            throw e;
        }
    }
}

From source file:com.pureinfo.srm.reports.table.data.institute.Index3Statitistic.java

/**
 * @see com.pureinfo.srm.reports.table.data.institute.InstituteReportBase#buildDatas(boolean,
 *      boolean)/*from  w w w  .ja  v a  2 s .co m*/
 */
public Object[][] buildDatas(boolean _bAscOrder, boolean _bOrderByValue) throws PureException {
    IObjects results = doMyQuery();
    initOrgDatas();
    Object[][] datas = new Object[m_nTableHight][TABEL_WIDTH];

    for (int i = 0; i < TITLE_HEIGHT; i++) {
        for (int j = 0; j < datas[i].length; j++) {
            datas[i][j] = "";
        }
    }
    datas[0][0] = "";
    datas[0][IDX_SCI] = "SCI";
    datas[0][IDX_EI] = "EI";
    datas[0][IDX_ISTP] = "ISTP";
    datas[1] = new String[] { "", "", "", "", "TOP", "", "", "",
            "", "", "" };
    for (int i = 0; i < datas[2].length; i++) {
        datas[2][i] = null;
    }
    datas[2][IDX_SCI_3KIND_TOTAL] = "";
    datas[2][IDX_SCI_3KIND_IF] = "IF";

    datas[m_nTableHight - 1][0] = "";
    datas[m_nTableHight - 2][0] = "";
    DolphinObject result = null;
    for (Iterator iter = m_collges.entrySet().iterator(); iter.hasNext();) {
        Map.Entry en = (Map.Entry) iter.next();
        Integer iId = (Integer) en.getKey();
        Organization org = (Organization) en.getValue();
        Integer idxCol = (Integer) m_orgIdxes.get(iId);
        Integer idxColOther = (Integer) m_orgIdxes.get(new Integer(-iId.intValue()));
        datas[idxCol.intValue()][0] = org.getCode() + "";
        datas[idxColOther.intValue()][0] = org.getCode() + "";
    }
    for (Iterator iter = m_institutes.entrySet().iterator(); iter.hasNext();) {
        Map.Entry en = (Map.Entry) iter.next();
        Integer iId = (Integer) en.getKey();
        Organization org = (Organization) en.getValue();
        Integer idxIns = (Integer) m_orgIdxes.get(iId);
        datas[idxIns.intValue()][0] = org.getCode();
        datas[idxIns.intValue()][1] = org.getName();
    }
    while ((result = results.next()) != null) {
        Integer iDept = result.getIntegerProperty(DEPARTMENT);
        if (m_institutes.containsKey(iDept)) {
            Integer iIdxIns = (Integer) m_orgIdxes.get(iDept);
            Integer iCol = (Integer) m_InsColMap.get(iDept);
            Integer iIdxCol = (Integer) m_orgIdxes.get(iCol);
            add(datas[iIdxIns.intValue()], result);
            add(datas[iIdxCol.intValue()], result);

        } else if (m_collges.containsKey(iDept)) {
            Integer iIdxIns = (Integer) m_orgIdxes.get(new Integer(-iDept.intValue()));
            Integer iIdxCol = (Integer) m_orgIdxes.get(iDept);
            add(datas[iIdxIns.intValue()], result);
            add(datas[iIdxCol.intValue()], result);
        } else {
            Integer iIdxCol = (Integer) m_orgIdxes.get(IDX_OTHER);
            add(datas[iIdxCol.intValue()], result);
        }
        Integer iIdxCol = (Integer) m_orgIdxes.get(IDX_TOTAL);
        add(datas[iIdxCol.intValue()], result);
    }

    for (int i = TITLE_HEIGHT; i < datas.length; i++) {
        if (datas[i][IDX_SCI_3KIND_IF] == null)
            continue;
        if (datas[i][IDX_SCI_3KIND_TOTAL] == null) {
            datas[i][IDX_SCI_3KIND_IF] = null;
            continue;
        }
        Number iTotal = (Number) datas[i][IDX_SCI_3KIND_TOTAL];
        Double oSum = (Double) datas[i][IDX_SCI_3KIND_IF];
        if (iTotal.intValue() == 0) {
            datas[i][IDX_SCI_3KIND_IF] = null;
        } else {
            datas[i][IDX_SCI_3KIND_IF] = NUM_FORMAT.format(oSum.doubleValue() / iTotal.intValue());
        }
    }
    return datas;
}

From source file:org.hyperic.hq.ui.taglib.display.MetricDecorator.java

public String decorate(Object obj) throws Exception {
    try {//from w w w .jav  a2  s .  c o  m
        // if the metric value is empty, converting to a Double
        // will give a value of 0.0. this makes it impossible for
        // us to distinguish further down the line whether the
        // metric was actually collected with a value of 0.0 or
        // whether it was not collected at all. therefore, we'll
        // let m be null if the metric was not collected, and
        // we'll check for null later when handling the not-avail
        // case.
        // PR: 7588
        Double m = null;

        if (obj != null) {
            String mval = obj.toString();

            if (mval != null && !mval.equals("")) {
                m = new Double(mval);
            }
        }

        String u = getUnit();
        String dk = getDefaultKey();
        Locale l = TagUtils.getInstance().getUserLocale(context, locale);
        StringBuffer buf = new StringBuffer();

        if ((m == null || Double.isNaN(m.doubleValue()) || Double.isInfinite(m.doubleValue())) && dk != null) {
            buf.append(TagUtils.getInstance().message(context, bundle, l.toString(), dk));
        } else if (u.equals("ms")) {
            // we don't care about scaling and such. we just want
            // to show every metric in seconds with millisecond
            // resolution
            String formatted = UnitsFormat.format(
                    new UnitNumber(m.doubleValue(), UnitsConstants.UNIT_DURATION, UnitsConstants.SCALE_MILLI))
                    .toString();

            buf.append(formatted);
        } else {
            FormattedNumber f = UnitsConvert.convert(m.doubleValue(), u, l);

            buf.append(f.getValue());

            if (f.getTag() != null && f.getTag().length() > 0) {
                buf.append(" ").append(f.getTag());
            }
        }

        return buf.toString();
    } catch (NumberFormatException npe) {
        log.error(npe);

        throw new JspTagException(npe);
    } catch (Exception e) {
        log.error(e);

        throw new JspException(e);
    }
}

From source file:org.n52.ifgicopter.spf.input.FakeInputPlugin.java

/**
 * /*from w w  w  .ja  v  a 2s  . com*/
 * @return
 */
private JPanel makeControlPanel() {
    if (this.controlPanel == null) {
        this.controlPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));

        JButton startButton = new JButton("Start");
        startButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        start();
                    }
                });
            }
        });
        this.controlPanel.add(startButton);
        JButton stopButton = new JButton("Stop");
        stopButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        stop();
                    }
                });
            }
        });
        this.controlPanel.add(stopButton);

        JLabel sleepTimeLabel = new JLabel("Time between points in seconds:");
        this.controlPanel.add(sleepTimeLabel);
        double spinnerMin = 0.1d;
        double spinnerMax = 10000.0d;
        SpinnerModel model = new SpinnerNumberModel(DEFAULT_INTERVAL_MILLIS / SECONDS_TO_MILLISECONDS,
                spinnerMin, spinnerMax, 0.1d);
        JSpinner sleepTimeSpinner = new JSpinner(model);
        sleepTimeSpinner.setToolTipText("Select time using controls or manual input within the range of "
                + spinnerMin + " to " + spinnerMax + ".");

        sleepTimeSpinner.addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                Object source = e.getSource();
                if (source instanceof JSpinner) {
                    final JSpinner spinner = (JSpinner) source;

                    EventQueue.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            Double value = (Double) spinner.getValue();
                            value = Double.valueOf(value.doubleValue() * SECONDS_TO_MILLISECONDS);
                            FakeInputPlugin.this.sleepTimeMillis = value.longValue();
                        }
                    });
                } else
                    log.warn("Unsupported ChangeEvent, need JSpinner as source: " + e);
            }
        });
        // catch text change events without loosing the focus
        // JSpinner.DefaultEditor editor = (DefaultEditor) sleepTimeSpinner.getEditor();
        // not implemented, can be done using KeyEvent, but then it hast to be checked where in the text
        // field the keystroke was etc. --> too complicated.

        this.controlPanel.add(sleepTimeSpinner);
    }

    return this.controlPanel;
}

From source file:net.sourceforge.msscodefactory.cflib.v1_11.CFLib.CFLibXmlUtil.java

public static String formatOptionalDouble(String separator, String attrName, Double val) {
    final String S_ProcName = "formatOptionalDouble";
    if ((attrName == null) || (attrName.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(CFLibXmlUtil.class, S_ProcName, 1,
                "attrName");
    }//from ww w.  j av  a  2 s  .c  o m
    String retval;
    if (val != null) {
        retval = formatRequiredDouble(separator, attrName, val.doubleValue());
    } else {
        retval = S_emptyString;
    }
    return (retval);
}

From source file:cerrla.Performance.java

/**
 * Records performance scores using sliding windows of results.
 * /* ww  w . ja v  a  2s  . c  o  m*/
 * @param currentEpisode
 *            The current episode.
 */
public void recordPerformanceScore(int currentEpisode) {
    if (recentScores_.isEmpty())
        return;
    // Transform the queues into arrays
    double[] vals = new double[recentScores_.size()];
    int i = 0;
    for (Double val : recentScores_)
        vals[i++] = val.doubleValue();
    double[] envSDs = new double[internalSDs_.size()];
    i = 0;
    for (Double envSD : internalSDs_)
        envSDs[i++] = envSD.doubleValue();

    Mean m = new Mean();
    StandardDeviation sd = new StandardDeviation();
    double mean = m.evaluate(vals);
    double meanDeviation = sd.evaluate(envSDs) * CONVERGENCE_PERCENT_BUFFER;

    Double[] details = new Double[PerformanceDetails.values().length];
    details[PerformanceDetails.EPISODE.ordinal()] = Double.valueOf(currentEpisode);
    details[PerformanceDetails.MEAN.ordinal()] = mean;
    details[PerformanceDetails.SD.ordinal()] = sd.evaluate(vals);
    performanceDetails_.put(currentEpisode, details);

    // Output current means
    if (ProgramArgument.SYSTEM_OUTPUT.booleanValue() && !frozen_) {
        DecimalFormat formatter = new DecimalFormat("#0.00");
        String meanString = formatter.format(mean);
        String sdString = formatter.format(meanDeviation);
        System.out.println("Average performance: " + meanString + " " + SD_SYMBOL + " " + sdString);
    }
    if (frozen_) {
        System.out.println(currentEpisode + ": " + details[PerformanceDetails.MEAN.ordinal()]);
    }
}

From source file:org.hyperic.hq.plugin.mysql_stats.MySqlStatsMeasurementPlugin.java

private double getSlaveStatusMetric(Metric metric) throws NumberFormatException, MetricUnreachableException,
        SQLException, JDBCQueryCacheException, MetricNotFoundException {
    String valColumn = metric.getObjectProperty("value");
    String alias = metric.getAttributeName();
    JDBCQueryCache replStatus = getQueryCache(metric, SHOW_SLAVE_STATUS);
    if (alias.equalsIgnoreCase(BYTES_BEHIND_MASTER)) {
        final double tmp = getBytesBehindMaster(metric);
        return (tmp >= 0) ? tmp : 0d;
    } else if (alias.equalsIgnoreCase(LOG_FILES_BEHIND_MASTER)) {
        return getLogFilesBehindMaster(metric);
    } else if (alias.equalsIgnoreCase(SECONDS_BEHIND_MASTER)) {
        // HHQ-3207 need to special case this since the metric may be null
        // http://feedblog.org/2007/09/29/where-does-mysql-lie-about-seconds_behind_master/
        Connection conn = getCachedConnection(metric);
        Double val = Double.valueOf(replStatus.getOnlyRow(conn, valColumn).toString());
        if (val == null) {
            throw new MetricNotFoundException("query for " + SECONDS_BEHIND_MASTER + " returned null");
        }//from w ww  .j  av  a 2  s  . c o  m
        return val.doubleValue();
    } else if (metric.isAvail()) {
        Connection conn = getCachedConnection(metric);
        String s = replStatus.getOnlyRow(conn, SLAVE_SQL_RUNNING).toString();
        return (s.equalsIgnoreCase("yes")) ? Metric.AVAIL_UP : Metric.AVAIL_DOWN;
    } else {
        Connection conn = getCachedConnection(metric);
        String s = replStatus.getOnlyRow(conn, valColumn).toString();
        Double val = null;
        if (s.equalsIgnoreCase("yes")) {
            val = new Double(1);
        } else if (s.equalsIgnoreCase("no")) {
            val = new Double(0);
        } else {
            val = Double.valueOf(s);
        }
        return val.doubleValue();
    }
}