Example usage for java.lang Double toString

List of usage examples for java.lang Double toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of this Double object.

Usage

From source file:com.gallatinsystems.surveyal.app.web.SurveyalRestServlet.java

/**
 * tries several methods to resolve the lat/lon to a GeoPlace. If a geoPlace is found, looks for
 * the country in the database and creates it if not found
 *
 * @param lat//w w  w .ja v  a 2  s.com
 * @param lon
 * @return
 */
private GeoPlace getGeoPlace(Double lat, Double lon) {
    GeoLocationServiceGeonamesImpl gs = new GeoLocationServiceGeonamesImpl();
    GeoPlace geoPlace = gs.manualLookup(lat.toString(), lon.toString(),
            OGRFeature.FeatureType.SUB_COUNTRY_OTHER);
    if (geoPlace == null) {
        geoPlace = gs.findGeoPlace(lat.toString(), lon.toString());
    }
    // check the country code to make sure it is in the database
    if (geoPlace != null && geoPlace.getCountryCode() != null) {
        Country country = countryDao.findByCode(geoPlace.getCountryCode());
        if (country == null) {
            country = new Country();
            country.setIsoAlpha2Code(geoPlace.getCountryCode());
            country.setName(
                    geoPlace.getCountryName() != null ? geoPlace.getCountryName() : geoPlace.getCountryCode());
            country.setDisplayName(country.getName());
            countryDao.save(country);
        }
    }
    return geoPlace;
}

From source file:net.solarnetwork.central.dras.dao.ibatis.test.AbstractIbatisDaoTestSupport.java

/**
 * Insert a test event rule into the solardras.event_rule table.
 * // ww w .j av a 2 s .  c  o m
 * @param id the ID
 * @param name the name
 */
protected void setupTestEventRule(Long id, String name, Set<Double> enums, Set<Duration> sched) {
    simpleJdbcTemplate.update("insert into solardras.event_rule (id,creator,rule_name,min_value,max_value) "
            + "values (?,?,?,?,?)", id, TEST_USER_ID, name, 3, 4);
    if (enums != null) {
        for (Double d : enums) {
            simpleJdbcTemplate
                    .update("insert into solardras.event_rule_enum (evr_id,target_value) values (?,?)", id, d);
        }
    }
    if (sched != null) {
        for (Duration d : sched) {
            simpleJdbcTemplate.update(
                    "insert into solardras.event_rule_schedule (evr_id,event_offset) values (?, CAST(? AS INTERVAL))",
                    id, d.toString());
        }
    }
}

From source file:edu.ucla.stat.SOCR.analyses.gui.AnovaOneWay.java

/** convert a generic double s to a "nice" fixed length string */
public String monoString(double s) {
    final double zero = 0.00001;
    Double sD = new Double(s);
    String sAdd = new String();
    if (s > zero)
        sAdd = new String(sD.toString());
    else// ww  w  . j  a  v  a 2  s . c o  m
        sAdd = "<0.00001";

    sAdd = sAdd.toLowerCase();
    int i = sAdd.indexOf('e');
    if (i > 0)
        sAdd = sAdd.substring(0, 4) + "E" + sAdd.substring(i + 1, sAdd.length());
    else if (sAdd.length() > 10)
        sAdd = sAdd.substring(0, 10);

    sAdd = sAdd + "                                      ";
    return sAdd.substring(0, 14);
}

From source file:gate.termraider.output.PairCsvGenerator.java

private void writeContent(PrintWriter writer, Term t0, Term t1, Double score, Integer documents,
        Integer frequency) {//w ww  . j  ava2 s  .c  o  m
    StringBuilder sb = new StringBuilder();
    sb.append(StringEscapeUtils.escapeCsv(t0.getTermString()));
    sb.append(',');
    sb.append(StringEscapeUtils.escapeCsv(t0.getLanguageCode()));
    sb.append(',');
    sb.append(StringEscapeUtils.escapeCsv(t0.getType()));
    sb.append(',');
    sb.append(StringEscapeUtils.escapeCsv(t1.getTermString()));
    sb.append(',');
    sb.append(StringEscapeUtils.escapeCsv(t1.getLanguageCode()));
    sb.append(',');
    sb.append(StringEscapeUtils.escapeCsv(t1.getType()));
    sb.append(',');
    sb.append(StringEscapeUtils.escapeCsv(score.toString()));
    sb.append(',');
    sb.append(StringEscapeUtils.escapeCsv(documents.toString()));
    sb.append(',');
    sb.append(StringEscapeUtils.escapeCsv(frequency.toString()));
    writer.println(sb.toString());
}

From source file:dbsimulator.dal.mysql.MySqlSimDal.java

@Override
public List<InsertedItem> insertItems(String oppkey, ItemGroup itemgroup, int page, _Ref<String> status,
        _Ref<String> dateCreated, _Ref<String> error) {

    List<InsertedItem> items = new ArrayList<>();
    status.set(null);//from   w ww  . j a v a2  s.  com
    dateCreated.set(null);
    error.set(null);
    try (SQLConnection connection = getSQLConnection()) {
        // Elena: same ugly double-to-float issue
        Double groupBDouble = itemgroup.getGroupB();
        Float groupB = Float.parseFloat(groupBDouble.toString());

        MultiDataResultSet sets = _studentdll.T_InsertItems_SP(connection, UUID.fromString(oppkey),
                UUID.fromString(getSessionKey()), UUID.fromString(getBrowserKey()),
                itemgroup.getSegmentPosition(), itemgroup.getSegmentID(), page, itemgroup.getGroupID(),
                itemgroup.getItemIDString(","), ',', itemgroup.getNumRequired(), groupB, 0, false);

        Iterator<SingleDataResultSet> iter = sets.getResultSets();
        if (iter.hasNext()) {
            // first result set
            SingleDataResultSet rs1 = iter.next();
            DbResultRecord rec1 = (rs1.getCount() > 0 ? rs1.getRecords().next() : null);
            if (rec1 != null) {
                status.set(rec1.<String>get("status"));
                if ("failed".equalsIgnoreCase(status.get())) {
                    error.set(rec1.<String>get("reason"));
                    return items;
                }
                dateCreated.set(rec1.<String>get("dateCreated"));
            }
        }
        // second result set
        if (iter.hasNext()) {
            SingleDataResultSet rs2 = iter.next();
            Iterator<DbResultRecord> it = rs2.getRecords();
            while (it.hasNext()) {
                InsertedItem itm = new InsertedItem();
                DbResultRecord rec2 = it.next();
                itm.setItemID(rec2.<String>get("bankitemkey"));
                itm.setPage(rec2.<Integer>get("page"));
                itm.setPosition(rec2.<Integer>get("position"));
                items.add(itm);
            }
        }
    } catch (SQLException se) {
        _logger.error(se.getMessage());
    } catch (ReturnStatusException re) {
        _logger.error(re.getMessage());
    }
    return items;
}

From source file:it.geosolutions.geobatch.opensdi.ndvi.NDVIStatsAction.java

/**
 * Generate CSV file with the parameters
 * //from  www  .  j  a  v  a  2 s  .  com
 * @param coverage tiff file to use in stats
 * @param fc zones to obtain the NDVI
 * @param classifier
 * @param mask
 * @param ndviFileName
 * @param csvSeparator
 * @param maskFullPath
 * 
 * @throws Exception
 */
private void generateCSV(GridCoverage2D coverage, SimpleFeatureCollection fc, CLASSIFIER_TYPE classifier,
        MASK_TYPE mask, String ndviFileName, String csvSeparator, String maskFullPath) throws Exception {

    // Prepare for CSV generation
    String csvPath = getCSVFullPath(classifier, mask, ndviFileName);

    // obtain header
    List<String> header = getHeader(classifier);

    // values
    String year = "";
    String month = "";
    String dekad = "";
    String factor = "NDVI_avg";
    String distr = "";
    String prov = "";

    // Obtain year, month, decad from the name of the file:
    // dv_20130101_20130110.tif
    year = ndviFileName.substring(3, 7);
    month = ndviFileName.substring(7, 9);
    // Remove "0"
    if (month.startsWith("0")) {
        month = month.replace("0", "");
    }
    month = getMonthName(Integer.decode(month));
    dekad = ndviFileName.substring(9, 11);
    dekad = dekad.equals("01") ? "1" : dekad.equals("11") ? "2" : "3";

    @SuppressWarnings("unchecked")
    Set<Object[]> data = new ListOrderedSet();
    data.add(header.toArray());
    int i = 1;

    List<FeatureAggregation> result = new ArrayList<FeatureAggregation>();

    // only one band
    int[] bands = new int[] { 0 };
    StatsType[] stats = new StatsType[] { StatsType.MEAN };

    // get the world to grid transformation
    final GridGeometry2D gg2D = coverage.getGridGeometry();
    final MathTransform worldToGrid = gg2D.getGridToCRS(PixelInCell.CELL_CORNER).inverse();
    final CoordinateReferenceSystem rasterCRS = gg2D.getCoordinateReferenceSystem();

    // ROI for the MASK in raster space
    final ROIGeometry maskROI = getROIMask(mask, worldToGrid, rasterCRS, maskFullPath);

    // getting the ROI in raster space for the zones
    final List<ROI> zonesROI = new ArrayList<ROI>();
    SimpleFeatureIterator iterator = null;

    // Selection of the FeatureCollection CoordinateReferenceSystem
    final CoordinateReferenceSystem featureCollectionCRS = fc.getSchema().getCoordinateReferenceSystem();
    if (featureCollectionCRS == null) {
        throw new IllegalArgumentException("The input features need a CRS");
    }
    // do we need to reproject?
    if (!CRS.equalsIgnoreMetadata(rasterCRS, featureCollectionCRS)) {
        // create a transformation
        final MathTransform transform = CRS.findMathTransform(featureCollectionCRS, rasterCRS, true);// lenient tranformation
        if (!transform.isIdentity()) {
            // reproject
            fc = new ReprojectProcess().execute(fc, featureCollectionCRS, rasterCRS);

        }
    }
    // Cycle on the features for creating a list of geometries
    try {
        iterator = fc.features();
        listenerForwarder.progressing(1f, "Classifing zones...");

        while (iterator.hasNext()) {
            SimpleFeature feature = iterator.next();

            // zones ROI
            ROI transformedROI = new ROIGeometry(
                    JTS.transform((Geometry) feature.getDefaultGeometry(), worldToGrid));

            zonesROI.add(transformedROI);

            // CSV Data
            if (CLASSIFIER_TYPE.DISTRICT.equals(classifier) || CLASSIFIER_TYPE.PROVINCE.equals(classifier)) {
                prov = feature.getProperty("province").getValue().toString();
            }
            if (CLASSIFIER_TYPE.DISTRICT.equals(classifier)) {
                distr = feature.getProperty("district").getValue().toString();
            }
            Map<String, Object> parameters = new HashMap<String, Object>();
            parameters.put("rowId", i++);
            parameters.put("year", year);
            parameters.put("mon", month);
            parameters.put("dec", dekad);
            parameters.put("factor", factor);
            parameters.put("prov", prov);
            parameters.put("distr", distr);
            // parameters.put("NDVI_avg", avg.toString());
            FeatureAggregation featureAgregation = new FeatureAggregation(parameters, header, ",", true);
            result.add(featureAgregation);
        }
        listenerForwarder.progressing(10f, ("Found " + result.size() + " zones for statistic generation"));
    } finally {
        if (iterator != null)
            iterator.close();
        if (dbStore != null) {
            dbStore.dispose();
        }
    }
    // Definition of the ZonalStats operation
    listenerForwarder.progressing(15f, "Zonal statistics");
    RenderedOp op = ZonalStatsDescriptor.create(coverage.getRenderedImage(), null, null, zonesROI, null,
            maskROI, false, bands, stats, null, null, null, null, false, null);
    // Calculation of the ZonalStats property
    @SuppressWarnings("unchecked")
    List<ZoneGeometry> statsResult = (List<ZoneGeometry>) op.getProperty(ZonalStatsDescriptor.ZS_PROPERTY);
    int index = 0;
    listenerForwarder.progressing(90f, "Result Post Processing");
    for (ZoneGeometry statResult : statsResult) {
        FeatureAggregation featureAgregation = result.get(index++);
        Double mean = (Double) statResult.getStatsPerBandNoClassifierNoRange(0)[0].getResult();
        // If the mean is 0, then no calculations are performed
        if (mean != 0.0) {
            // apply NDVI: Physical value = pixel value*0.004 - 0.1
            Double ndvi = (mean * 0.004) - 0.1;
            featureAgregation.getProperties().put("NDVI_avg", ndvi.toString());
            if (mean > 0.0) {
                // include data
                data.add(featureAgregation.toRow());
            } else {
                // log error: the mean shouldn't be never less than 0
                LOGGER.error("Zonal statistics corrupted not included for: " + featureAgregation.toRow());
            }
        }
    }

    File csv = new File(csvPath);
    listenerForwarder.progressing(95f, "writing output file...");
    CSVWriter.writeCsv(LOGGER, data, csv, csvSeparator, true);
    listenerForwarder.progressing(100f, "output file " + csvPath + " generated successfully!");
}

From source file:com.wizecommerce.hecuba.HecubaClientManager.java

/**
 * Updates the value of the column in the given row (identified by the key).
 * /*from   www  .jav  a2s .co m*/
 * Note that the value will be converted to a String before storing in Cassandra.
 *
 * @param key        - key to identify the row.
 * @param columnName - column to be updated.
 * @param value      - value to be inserted.
 */
public void updateDouble(K key, String columnName, Double value) {
    updateString(key, columnName, value.toString());
}

From source file:ctd.services.getCleanData2.java

private ArrayList<Double> writeFile(PrintStream pr, HashMap<String, String> chip_annotation_ids, String ssa_id,
        String gct_file_generated, String name_raw_file) throws FileNotFoundException, IOException {

    BufferedReader input = new BufferedReader(new FileReader(gct_file_generated));
    String line;/*from  w w w.  j  av  a 2s  .c o  m*/

    Integer expression_column = null;
    Integer name_column = null;
    Integer description_column = null;
    Boolean do_header = false;
    Boolean do_data = false;
    Boolean start = false;
    ArrayList<Double> values = new ArrayList<Double>();

    while ((line = input.readLine()) != null) {

        String[] columns = line.split("\t");
        if (columns[0].equals("Name")) {
            do_header = true;
            name_column = 0;
        }

        if (do_header) {
            for (int i = 0; i < columns.length; i++) {
                String header = columns[i].trim();
                String xx = name_raw_file + ".CEL";
                if (header.equals(xx)) {
                    expression_column = i;
                    do_data = true;
                }

                //                    if (header.equals("Name")) {
                //                        name_column = i;
                //                    }
            }
        }
        do_header = false;

        if (start) {
            String probesetid = columns[name_column];

            Double value = Double.valueOf(columns[expression_column]);

            values.add(value);
            String chip_annotation_id = chip_annotation_ids.get(probesetid);
            String expr_line = ssa_id + "\t" + chip_annotation_id + "\t" + value.toString();
            pr.println(expr_line);
        }

        if (do_data) {
            start = true;
        }

    }
    return values;
}

From source file:gsn.reports.scriptlets.StreamScriptlet.java

@SuppressWarnings("unchecked")
public void setStatistics() throws JRScriptletException {

    String max = "NA";
    String min = "NA";
    String average = "NA";
    String stdDeviation = "NA";
    String median = "NA";
    String nb = "0";
    String startTime = "NA";
    String endTime = "NA";
    String samplingAverage = "NA";
    //      String samplingAverageUnit      = "NA";
    String nbOfNull = "0";
    String samplingStdDeviation = "NA";
    //      String samplingStdDeviationUnit   = "NA";

    Collection<Data> datas = (Collection<Data>) this.getFieldValue("datas");
    if (datas.size() > 0) {
        Double max_value = Double.MIN_VALUE;
        Double min_value = Double.MAX_VALUE;
        Double average_value = 0.0;
        Double sum_value = 0.0;/*from   ww  w .  j  a  v  a  2 s  .c  om*/
        Long start_time_value = 0L;
        Long end_time_value = 0L;
        Long sampling_average_value = 0L;
        Integer nb_value = 0;
        Integer nb_of_null = 0;
        Iterator<Data> iter = datas.iterator();
        Data nextData;
        Double nextDataValue;
        while (iter.hasNext()) {
            nextData = iter.next();
            if (nextData.getValue() != null) {
                nextDataValue = (Double) nextData.getValue();
                //
                sum_value += nextDataValue;
                //
                if (nextDataValue < min_value)
                    min_value = nextDataValue;
                if (nextDataValue > max_value)
                    max_value = nextDataValue;
                //               
                if (datas.size() == 1 || nb_value == datas.size() / 2)
                    median = nextDataValue.toString();
                //
                if (!iter.hasNext()) {
                    startTime = sdf.format(new Date((Long) nextData.getP2())).toString();
                    start_time_value = (Long) nextData.getP2();
                }
                if (nb_value == 0) {
                    endTime = sdf.format(new Date((Long) nextData.getP2())).toString();
                    end_time_value = (Long) nextData.getP2();
                }
            } else {
                nb_of_null++;
            }
            nb_value++;
        }
        //
        max = max_value == Double.MIN_VALUE ? "NA" : max_value.toString();
        min = min_value == Double.MAX_VALUE ? "NA" : min_value.toString();
        nb = nb_value.toString();
        average_value = (Double) (sum_value / nb_value);
        average = average_value.toString();
        nbOfNull = nb_of_null.toString();
        //
        if (datas.size() > 1) {
            sampling_average_value = (end_time_value - start_time_value) / (nb_value - 1);
            samplingAverage = Helpers.formatTimePeriod(sampling_average_value);
        }
        //
        iter = datas.iterator();
        Double variance_value = 0.0;
        Double sampling_variance_value = 0.0;
        Long lastDataTime = end_time_value;
        int i = 0;
        while (iter.hasNext()) {
            nextData = iter.next();
            if (nextData.getValue() != null) {
                nextDataValue = (Double) nextData.getValue();
                variance_value += Math.pow((average_value - nextDataValue), 2);
                if (i > 0) {
                    sampling_variance_value += Math
                            .pow((sampling_average_value - ((lastDataTime - (Long) nextData.getP2()))), 2);
                    lastDataTime = (Long) nextData.getP2();
                }
                i++;
            }
        }
        stdDeviation = ((Double) Math.sqrt(variance_value)).toString();
        if (datas.size() > 1) {
            Double sampling_std_deviation = (Double) Math.sqrt(sampling_variance_value);
            samplingStdDeviation = Helpers.formatTimePeriod(sampling_std_deviation.longValue());
        }
    }

    this.setVariableValue("max", max); // ok
    this.setVariableValue("min", min); // ok
    this.setVariableValue("average", average); // ok
    this.setVariableValue("stdDeviation", stdDeviation); // ok
    this.setVariableValue("median", median); // ok
    this.setVariableValue("nb", nb); // ok
    this.setVariableValue("startTime", startTime); // ok
    this.setVariableValue("endTime", endTime); // ok
    this.setVariableValue("samplingAverage", samplingAverage); // ok
    this.setVariableValue("nbOfNull", nbOfNull); // ok
    this.setVariableValue("samplingStdDeviation", samplingStdDeviation); // ok
}

From source file:edu.ku.brc.af.prefs.AppPreferences.java

/**
 * Sets a Double value into a pref.//from   w  w w  .ja va 2s  .  c  o m
 * @param name the name
 * @param value the new value
 */
public void putDouble(final String name, final Double value) {
    put(name, value.toString());
}