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 static String toString(double d) 

Source Link

Document

Returns a string representation of the double argument.

Usage

From source file:cn.ctyun.amazonaws.util.StringUtils.java

/**
 * Returns the string representation of the specified double.
 *
 * @param d/*ww  w .ja  va 2 s  . c  om*/
 *            The double to represent as a string.
 *
 * @return The string representation of the specified double.
 */
public static String fromDouble(Double d) {
    return Double.toString(d);
}

From source file:com.fortydegree.ra.data.POIDownloader.java

public void download(Location l, int radius, int maxResults, final CallBack<List<Marker>> places)
        throws WebServiceException {

    List<String> parameters = Arrays.asList("latitude", Double.toString(l.getLatitude()), "longitude",
            Double.toString(l.getLongitude()), "radius", Integer.toString(radius), "max",
            Integer.toString(maxResults));

    this.downloader.download(parameters, new CallBack<String>() {
        public void execute(String input) {
            try {
                if (input != null && input.length() > 0) {
                    List<Marker> list = JsonUnmarshaller.load(new JSONObject(input));
                    places.execute(list);
                }/* ww  w . j  a v a  2  s. co  m*/
            } catch (JSONException e) {
                Log.e(TAG, e.getMessage(), e);
                throw new Error(e);// should not happen
            }
        }
    }, new CallBack<Throwable>() {
        public void execute(Throwable input) {
            Log.e(TAG, input.getMessage(), input);

        }
    });

}

From source file:com.mobiaware.auction.provider.impl.CSVExportService.java

@Override
public void exportBids(final int auctionUid, final Writer writer) throws IOException {
    List<Item> items = _dataService.getItemsUpdatesOnly(auctionUid);

    if (items == null) {
        throw new NotFoundException();
    }/*from ww w.  j  a  va2  s  .  c o m*/

    CSVWriter csvwriter = null;
    try {
        csvwriter = new CSVWriter(writer, ',');

        String[] array = { "item_number", "bidder_number", "value" };
        csvwriter.writeNext(array);

        for (Item item : items) {
            array[0] = item.getItemNumber();
            array[1] = item.getWinner();
            array[2] = Double.toString(item.getCurPrice());
            csvwriter.writeNext(array);
        }
    } finally {
        IOUtils.closeQuietly(csvwriter);
    }
}

From source file:com.sciaps.utils.ImportExportSpectrumCSV.java

public void exportSpectrumFile(File saveFile, PiecewiseSpectrum spectrum) throws IOException {
    if (spectrum == null || saveFile == null) {
        logger_.warn("", "will not save spectrum csv file");
        return;//from   w ww . j a  v a2 s .c  o  m
    }

    final UnivariateFunction intensity = spectrum.getIntensityFunction();

    BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(saveFile)));
    try {
        bout.append("wavelength, intensity");
        bout.newLine();
        final DoubleRange range = spectrum.getValidRange();

        for (double x = range.getMinimumDouble(); x <= range.getMaximumDouble(); x += 1.0
                / EXPORT_SAMPLE_RATE) {
            double y = intensity.value(x);
            if (Double.isNaN(y)) {
                y = 0;
            }
            bout.append(Double.toString(x));
            bout.append(", ");
            bout.append(Double.toString(y));
            bout.newLine();
        }
    } finally {
        bout.close();
    }

    logger_.info("saved spectrum csv file to " + saveFile.getAbsolutePath());
}

From source file:com.mac.hazewinkel.plist.util.PListXmlWriter.java

public void write(PList plist, StringBuilder buffer) {
    if (plist instanceof PListBoolean) {
        if (((PListBoolean) plist).getValue())
            buffer.append("<true/>\n");
        else// w  ww. ja va 2 s .co m
            buffer.append("<false/>\n");
    } else if (plist instanceof PListData) {
        byte[] data = ((PListData) plist).getValue();
        buffer.append("<data>\n");
        try {
            buffer.append(new String(Base64.encodeBase64Chunked(data), "ISO8859-1"));
        } catch (UnsupportedEncodingException e) {
            // should never happen. Latin1 is a required part of the JRE
        }
        buffer.append("</data>\n");
    } else if (plist instanceof PListDate) {
        Date date = ((PListDate) plist).getValue();
        buffer.append("<date>").append(getDateFormatter().format(date)).append("</date>\n");
    } else if (plist instanceof PListFloat) {
        double real = ((PListFloat) plist).getValue();
        buffer.append("<real>").append(Double.toString(real)).append("</real>\n");
    } else if (plist instanceof PListInteger) {
        int integer = ((PListInteger) plist).getValue();
        buffer.append("<integer>").append(String.valueOf(integer)).append("</integer>\n");
    } else if (plist instanceof PListString) {
        String string = ((PListString) plist).getValue();
        buffer.append("<string>").append(string).append("</string>\n");
    } else if (plist instanceof PListArray) {
        buffer.append("<array>\n");
        for (PListEntry entry : ((PListArray) plist).elements()) {
            write(entry.getValue(), buffer);
        }
        buffer.append("</array>\n");
    } else if (plist instanceof PListDictionary) {
        buffer.append("<dict>\n");
        for (PListEntry entry : ((PListDictionary) plist).elements()) {
            buffer.append("<key>").append(entry.getKey()).append("</key>\n");
            write(entry.getValue(), buffer);
        }
        buffer.append("</dict>\n");
    }
}

From source file:ai.susi.mind.SusiCognition.java

public SusiCognition(final SusiMind mind, final String query, int timezoneOffset, double latitude,
        double longitude, int maxcount, ClientIdentity identity) {
    this.json = new JSONObject(true);

    // get a response from susis mind
    String client = identity.getClient();
    this.setQuery(query);
    this.json.put("count", maxcount);
    SusiThought observation = new SusiThought();
    observation.addObservation("timezoneOffset", Integer.toString(timezoneOffset));

    if (!Double.isNaN(latitude) && !Double.isNaN(longitude)) {
        observation.addObservation("latitude", Double.toString(latitude));
        observation.addObservation("longitude", Double.toString(longitude));
    }/*  w w w  . java  2s .co m*/
    this.json.put("client_id", Base64.getEncoder().encodeToString(UTF8.getBytes(client)));
    long query_date = System.currentTimeMillis();
    this.json.put("query_date", DateParser.utcFormatter.print(query_date));

    // compute the mind reaction
    List<SusiArgument> dispute = mind.react(query, maxcount, client, observation);
    long answer_date = System.currentTimeMillis();

    // store answer and actions into json
    this.json.put("answers", new JSONArray(
            dispute.stream().map(argument -> argument.finding(client, mind)).collect(Collectors.toList())));
    this.json.put("answer_date", DateParser.utcFormatter.print(answer_date));
    this.json.put("answer_time", answer_date - query_date);
    this.json.put("language", "en");
}

From source file:com.google.pubsub.flic.common.LatencyDistribution.java

public static String getNthPercentileMidpoint(long[] bucketValues, double percentile) {
    int index = getNthPercentileIndex(bucketValues, percentile);
    if (index < 1) {
        return "N/A";
    }//  ww  w.j a v a  2s .c o m
    return Double.toString((LATENCY_BUCKETS[index - 1] + LATENCY_BUCKETS[index]) / 2);
}

From source file:es.yrbcn.graph.weighted.WeightedPageRankPowerMethod.java

public static void main(final String[] arg)
        throws IOException, JSAPException, ConfigurationException, ClassNotFoundException {

    SimpleJSAP jsap = new SimpleJSAP(WeightedPageRankPowerMethod.class.getName(),
            "Computes PageRank of a graph with given graphBasename using the power method."
                    + "The resulting doubles are stored in binary form in rankFile."
                    + "\n[STOPPING CRITERION] The computation is stopped as soon as two successive iterates have"
                    + "an L2-distance smaller than a given threshold (-t option); in any case no more than a fixed"
                    + "number of iterations (-i option) is performed.",
            new Parameter[] {
                    new FlaggedOption("alpha", JSAP.DOUBLE_PARSER,
                            Double.toString(WeightedPageRank.DEFAULT_ALPHA), JSAP.NOT_REQUIRED, 'a', "alpha",
                            "Damping factor."),
                    new FlaggedOption("maxIter", JSAP.INTEGER_PARSER,
                            Integer.toString(WeightedPageRank.DEFAULT_MAX_ITER), JSAP.NOT_REQUIRED, 'i',
                            "max-iter", "Maximum number of iterations."),
                    new FlaggedOption("threshold", JSAP.DOUBLE_PARSER,
                            Double.toString(WeightedPageRank.DEFAULT_THRESHOLD), JSAP.NOT_REQUIRED, 't',
                            "threshold", "Threshold to determine whether to stop."),
                    new FlaggedOption("coeff", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'c',
                            "coeff", "Save the k-th coefficient of the Taylor polynomial using this basename."),
                    new FlaggedOption("derivative", JSAP.INTEGER_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED,
                            'd', "derivative", "The order(s) of the the derivative(s) to be computed (>0).")
                                    .setAllowMultipleDeclarations(true),
                    new FlaggedOption("preferenceVector", JSAP.STRING_PARSER, JSAP.NO_DEFAULT,
                            JSAP.NOT_REQUIRED, 'p', "preference-vector",
                            "A preference vector stored as a vector of binary doubles."),
                    new FlaggedOption("preferenceObject", JSAP.STRING_PARSER, JSAP.NO_DEFAULT,
                            JSAP.NOT_REQUIRED, 'P', "preference-object",
                            "A preference vector stored as a serialised DoubleList."),
                    new FlaggedOption("startFilename", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED,
                            '1', "start", "Start vector filename."),
                    new FlaggedOption("buckets", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'b',
                            "buckets",
                            "The buckets of the graph; if supplied, buckets will be treated as dangling nodes."),
                    new Switch("offline", 'o', "offline", "use loadOffline() to load the graph"),
                    new Switch("strongly", 'S', "strongly",
                            "use the preference vector to redistribute the dangling rank."),
                    new Switch("sortedRank", 's', "sorted-ranks",
                            "Store the ranks (from highest to lowest) into <rankBasename>-sorted.ranks."),
                    new FlaggedOption("norm", JSAP.STRING_PARSER, WeightedPageRank.Norm.INFTY.toString(),
                            JSAP.NOT_REQUIRED, 'n', "norm",
                            "Norm type. Possible values: " + Arrays.toString(WeightedPageRank.Norm.values())),
                    new UnflaggedOption("graphBasename", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED,
                            JSAP.NOT_GREEDY, "The basename of the graph."),
                    new UnflaggedOption("rankBasename", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED,
                            JSAP.NOT_GREEDY,
                            "The filename where the resulting rank (doubles in binary form) are stored.") });

    JSAPResult jsapResult = jsap.parse(arg);
    if (jsap.messagePrinted())
        return;//from   w  w w.ja  v a  2 s  . c  om

    final boolean offline = jsapResult.getBoolean("offline", false);
    final boolean strongly = jsapResult.getBoolean("strongly", false);
    final boolean sorted = jsapResult.getBoolean("sortedRank", false);
    final int[] order = jsapResult.getIntArray("derivative");
    final String graphBasename = jsapResult.getString("graphBasename");
    final String rankBasename = jsapResult.getString("rankBasename");
    final String buckets = jsapResult.getString("buckets");
    final String startFilename = jsapResult.getString("startFilename", null);
    final String coeffBasename = jsapResult.getString("coeff");
    final String norm = jsapResult.getString("norm");
    final ProgressLogger progressLogger = new ProgressLogger(LOGGER, "nodes");

    ArcLabelledImmutableGraph graph = offline
            ? ArcLabelledImmutableGraph.loadOffline(graphBasename, progressLogger)
            : ArcLabelledImmutableGraph.loadSequential(graphBasename, progressLogger);

    DoubleList preference = null;
    String preferenceFilename = null;
    if (jsapResult.userSpecified("preferenceVector"))
        preference = DoubleArrayList
                .wrap(BinIO.loadDoubles(preferenceFilename = jsapResult.getString("preferenceVector")));

    if (jsapResult.userSpecified("preferenceObject")) {
        if (jsapResult.userSpecified("preferenceVector"))
            throw new IllegalArgumentException("You cannot specify twice the preference vector");
        preference = (DoubleList) BinIO
                .loadObject(preferenceFilename = jsapResult.getString("preferenceObject"));
    }

    if (strongly && preference == null)
        throw new IllegalArgumentException("The 'strongly' option requires a preference vector");

    DoubleList start = null;
    if (startFilename != null) {
        LOGGER.debug("Loading start vector \"" + startFilename + "\"...");
        start = DoubleArrayList.wrap(BinIO.loadDoubles(startFilename));
        LOGGER.debug("done.");
    }

    WeightedPageRankPowerMethod pr = new WeightedPageRankPowerMethod(graph);
    pr.alpha = jsapResult.getDouble("alpha");
    pr.preference = preference;
    pr.buckets = (BitSet) (buckets == null ? null : BinIO.loadObject(buckets));
    pr.stronglyPreferential = strongly;
    pr.start = start;
    pr.norm = WeightedPageRank.Norm.valueOf(norm);
    pr.order = order != null ? order : null;
    pr.coeffBasename = coeffBasename;

    // cycle until we reach maxIter interations or the norm is less than the given threshold (whichever comes first)
    pr.stepUntil(or(new WeightedPageRank.NormDeltaStoppingCriterion(jsapResult.getDouble("threshold")),
            new WeightedPageRank.IterationNumberStoppingCriterion(jsapResult.getInt("maxIter"))));

    System.err.print("Saving ranks...");
    BinIO.storeDoubles(pr.rank, rankBasename + ".ranks");
    if (pr.numNodes < 100) {
        for (int i = 0; i < pr.rank.length; i++) {
            System.err.println("PageRank[" + i + "]=" + pr.rank[i]);
        }
    }
    Properties prop = pr.buildProperties(graphBasename, preferenceFilename, startFilename);
    prop.save(rankBasename + ".properties");

    if (order != null) {
        System.err.print("Saving derivatives...");
        for (int i = 0; i < order.length; i++)
            BinIO.storeDoubles(pr.derivative[i], rankBasename + ".der-" + order[i]);
    }

    final double[] rank = pr.rank;
    pr = null; // Let us free some memory...
    graph = null;

    if (sorted) {
        System.err.print("Sorting ranks...");
        Arrays.sort(rank);
        final int n = rank.length;
        int i = n / 2;
        double t;
        // Since we need the ranks from highest to lowest, we invert their order.
        while (i-- != 0) {
            t = rank[i];
            rank[i] = rank[n - i - 1];
            rank[n - i - 1] = t;
        }
        System.err.print(" saving sorted ranks...");
        BinIO.storeDoubles(rank, rankBasename + "-sorted.ranks");
        System.err.println(" done.");
    }
}

From source file:blue.soundObject.jmask.Random.java

public Element saveAsXML() {
    Element retVal = new Element("generator");
    retVal.setAttribute("type", getClass().getName());

    retVal.addElement("min").setText(Double.toString(min));
    retVal.addElement("max").setText(Double.toString(max));

    return retVal;
}

From source file:io.fabric8.example.stddev.http.StdDevProcessorTest.java

@Test
public void testProcess() throws Exception {
    RandomGenerator rg = new JDKRandomGenerator();
    double[] array = new double[10];
    ObjectMapper objectMapper = new ObjectMapper();
    for (int i = 0; i < array.length; i++) {
        array[i] = rg.nextDouble();//  w ww .  j  av  a  2s .  com
    }
    String body = objectMapper.writeValueAsString(array);
    SummaryStatistics summaryStatistics = new SummaryStatistics();
    List<Double> list = new ObjectMapper().readValue(body, List.class);
    for (Double value : list) {
        summaryStatistics.addValue(value);
    }
    String stdDev = Double.toString(summaryStatistics.getStandardDeviation());

    resultEndpoint.expectedBodiesReceived(stdDev);

    template.sendBody(body);

    resultEndpoint.assertIsSatisfied();
}