Example usage for java.text DecimalFormatSymbols DecimalFormatSymbols

List of usage examples for java.text DecimalFormatSymbols DecimalFormatSymbols

Introduction

In this page you can find the example usage for java.text DecimalFormatSymbols DecimalFormatSymbols.

Prototype

public DecimalFormatSymbols(Locale locale) 

Source Link

Document

Create a DecimalFormatSymbols object for the given locale.

Usage

From source file:jsdp.app.lotsizing.sS_jsdp.java

public static void solveSampleInstanceBackwardRecursion(Distribution[] distributions, double minDemand,
        double maxDemand, double fixedOrderingCost, double proportionalOrderingCost, double holdingCost,
        double penaltyCost, double initialInventory, double confidence, double errorTolerance,
        sS_StateSpaceSampleIterator.SamplingScheme samplingScheme, int maxSampleSize) {

    sS_BackwardRecursion recursion = new sS_BackwardRecursion(distributions, minDemand, maxDemand,
            fixedOrderingCost, proportionalOrderingCost, holdingCost, penaltyCost, samplingScheme,
            maxSampleSize);//from w  w w  . j  a  va  2  s . co m
    /*sS_SequentialBackwardRecursion recursion = new sS_SequentialBackwardRecursion(distributions,
                                                                            fixedOrderingCost,
                                                                            proportionalOrderingCost,
                                                                            holdingCost,
                                                                            penaltyCost);*/

    StopWatch timer = new StopWatch();
    timer.start();
    recursion.runBackwardRecursion();
    timer.stop();
    System.out.println();
    double ETC = recursion.getExpectedCost(initialInventory);
    System.out.println(
            "Expected total cost (assuming an initial inventory level " + initialInventory + "): " + ETC);
    System.out.println("Time elapsed: " + timer);
    System.out.println();

    double[][] optimalPolicy = recursion.getOptimalPolicy(initialInventory);
    double[] s = optimalPolicy[0];
    double[] S = optimalPolicy[1];
    for (int i = 0; i < distributions.length; i++) {
        System.out.println("S[" + (i + 1) + "]:" + S[i] + "\ts[" + (i + 1) + "]:" + s[i]);
    }

    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
    DecimalFormat df = new DecimalFormat("#.00", otherSymbols);

    double[] results = SimulatePolicies.simulate_sS(distributions, fixedOrderingCost, holdingCost, penaltyCost,
            proportionalOrderingCost, initialInventory, S, s, confidence, errorTolerance);
    System.out.println();
    System.out.println("Simulated cost: " + df.format(results[0]) + " Confidence interval=("
            + df.format(results[0] - results[1]) + "," + df.format(results[0] + results[1]) + ")@"
            + df.format(confidence * 100) + "% confidence");
    System.out.println();
}

From source file:velocitekProStartAnalyzer.MainWindow.java

private DefaultTableModel buildTableModel(List<PointDto> pointDto) {
    // ResultSetMetaData metaData = rs.getMetaData();

    // names of columns
    Vector<String> columnNames = new Vector<>();
    columnNames.add("ID");//TODO:delete at release
    columnNames.add("Time");
    columnNames.add("Heading");
    columnNames.add("Speed");
    columnNames.add("Latitude");
    columnNames.add("Longtitude");
    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
    otherSymbols.setDecimalSeparator('.');
    DecimalFormat dfHeading = new DecimalFormat("#", otherSymbols);
    DecimalFormat dfSpeed = new DecimalFormat("#.#", otherSymbols);
    DecimalFormat dfGeo = new DecimalFormat("#.######", otherSymbols);
    // data of the table
    Vector<Vector<Object>> data = new Vector<Vector<Object>>();
    for (PointDto point : pointDto) {
        Vector<Object> vector = new Vector<Object>();
        for (int columnIndex = 0; columnIndex < columnNames.size(); columnIndex++) {

            vector.add(point.getPointID());
            vector.add(point.getPointDateHHmmss());
            vector.add(Math.round(Double.valueOf(dfHeading.format(point.getPointHeading()))));
            vector.add(Double.valueOf(dfSpeed.format(point.getPointSpeed())));
            vector.add(Double.valueOf(dfGeo.format(point.getPointLatidude())));
            vector.add(Double.valueOf(dfGeo.format(point.getPointLongtidude())));
        }/*  w  w  w. j  a v a  2  s  . com*/
        data.add(vector);
    }
    return new DefaultTableModel(data, columnNames) {

        private static final long serialVersionUID = -6622905133391297170L;

        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };
}

From source file:at.alladin.rmbt.controlServer.TestResultDetailResource.java

@Post("json")
public String request(final String entity) {
    long startTime = System.currentTimeMillis();
    addAllowOrigin();//  www . j a v a  2 s . c o m

    JSONObject request = null;

    final ErrorList errorList = new ErrorList();
    final JSONObject answer = new JSONObject();
    String answerString;

    final String clientIpRaw = getIP();
    System.out.println(MessageFormat.format(labels.getString("NEW_TESTRESULT_DETAIL"), clientIpRaw));

    if (entity != null && !entity.isEmpty())
        // try parse the string to a JSON object
        try {
            request = new JSONObject(entity);

            String lang = request.optString("language");
            JSONArray options = request.optJSONArray("options");
            if (options != null) {
                for (int i = 0; i < options.length(); i++) {
                    final String op = options.optString(i, null);
                    if (op != null) {
                        if (OPTION_WITH_KEYS.equals(op.toUpperCase(Locale.US))) {
                            optionWithKeys = true;
                        }
                    }
                }
            }

            // Load Language Files for Client

            final List<String> langs = Arrays
                    .asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*"));

            if (langs.contains(lang)) {
                errorList.setLanguage(lang);
                labels = ResourceManager.getSysMsgBundle(new Locale(lang));
            } else
                lang = settings.getString("RMBT_DEFAULT_LANGUAGE");

            //                System.out.println(request.toString(4));

            if (conn != null) {

                final Client client = new Client(conn);
                final Test test = new Test(conn);
                TestNdt ndt = new TestNdt(conn);

                final String testUuid = request.optString("test_uuid");
                if (testUuid != null && test.getTestByUuid(UUID.fromString(testUuid)) > 0
                        && client.getClientByUid(test.getField("client_id").intValue())) {

                    if (!ndt.loadByTestId(test.getUid()))
                        ndt = null;

                    final Locale locale = new Locale(lang);
                    final Format format = new SignificantFormat(2, locale);

                    final JSONArray resultList = new JSONArray();

                    final JSONObject singleItem = addObject(resultList, "time");
                    final Field timeField = test.getField("time");
                    if (!timeField.isNull()) {
                        final Date date = ((TimestampField) timeField).getDate();
                        final long time = date.getTime();
                        singleItem.put("time", time); //csv 3

                        final Field timezoneField = test.getField("timezone");
                        if (!timezoneField.isNull()) {
                            final String tzString = timezoneField.toString();
                            final TimeZone tz = TimeZone.getTimeZone(timezoneField.toString());
                            singleItem.put("timezone", tzString);

                            final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
                                    DateFormat.MEDIUM, locale);
                            dateFormat.setTimeZone(tz);
                            singleItem.put("value", dateFormat.format(date));

                            final Format tzFormat = new DecimalFormat("+0.##;-0.##",
                                    new DecimalFormatSymbols(locale));

                            final float offset = tz.getOffset(time) / 1000f / 60f / 60f;
                            addString(resultList, "timezone", String.format("UTC%sh", tzFormat.format(offset)));
                        }
                    }

                    // speed download in Mbit/s (converted from kbit/s) - csv 10 (in kbit/s)
                    final Field downloadField = test.getField("speed_download");
                    if (!downloadField.isNull()) {
                        final String download = format.format(downloadField.doubleValue() / 1000d);
                        addString(resultList, "speed_download",
                                String.format("%s %s", download, labels.getString("RESULT_DOWNLOAD_UNIT")));
                    }

                    // speed upload im MBit/s (converted from kbit/s) - csv 11 (in kbit/s)
                    final Field uploadField = test.getField("speed_upload");
                    if (!uploadField.isNull()) {
                        final String upload = format.format(uploadField.doubleValue() / 1000d);
                        addString(resultList, "speed_upload",
                                String.format("%s %s", upload, labels.getString("RESULT_UPLOAD_UNIT")));
                    }

                    // median ping in ms
                    final Field pingMedianField = test.getField("ping_median");
                    if (!pingMedianField.isNull()) {
                        final String pingMedian = format.format(pingMedianField.doubleValue() / 1000000d);
                        addString(resultList, "ping_median",
                                String.format("%s %s", pingMedian, labels.getString("RESULT_PING_UNIT")));
                    }

                    // signal strength RSSI in dBm - csv 13
                    final Field signalStrengthField = test.getField("signal_strength");
                    if (!signalStrengthField.isNull())
                        addString(resultList, "signal_strength", String.format("%d %s",
                                signalStrengthField.intValue(), labels.getString("RESULT_SIGNAL_UNIT")));

                    //signal strength RSRP in dBm (LTE) - csv 29
                    final Field lteRsrpField = test.getField("lte_rsrp");
                    if (!lteRsrpField.isNull())
                        addString(resultList, "signal_rsrp", String.format("%d %s", lteRsrpField.intValue(),
                                labels.getString("RESULT_SIGNAL_UNIT")));

                    //signal quality in LTE, RSRQ in dB
                    final Field lteRsrqField = test.getField("lte_rsrq");
                    if (!lteRsrqField.isNull())
                        addString(resultList, "signal_rsrq", String.format("%d %s", lteRsrqField.intValue(),
                                labels.getString("RESULT_DB_UNIT")));

                    // network, eg. "3G (HSPA+)
                    //TODO fix helper-function
                    final Field networkTypeField = test.getField("network_type");
                    if (!networkTypeField.isNull())
                        addString(resultList, "network_type",
                                Helperfunctions.getNetworkTypeName(networkTypeField.intValue()));

                    // geo-location
                    JSONObject locationJson = getGeoLocation(this, test, settings, conn, labels);

                    if (locationJson != null) {
                        if (locationJson.has("location")) {
                            addString(resultList, "location", locationJson.getString("location"));
                        }
                        if (locationJson.has("country_location")) {
                            addString(resultList, "country_location",
                                    locationJson.getString("country_location"));
                        }
                        if (locationJson.has("motion")) {
                            addString(resultList, "motion", locationJson.getString("motion"));
                        }
                    }

                    // country derived from AS registry
                    final Field countryAsnField = test.getField("country_asn");
                    if (!countryAsnField.isNull())
                        addString(resultList, "country_asn", countryAsnField.toString());

                    // country derived from geo-IP database
                    final Field countryGeoipField = test.getField("country_geoip");
                    if (!countryGeoipField.isNull())
                        addString(resultList, "country_geoip", countryGeoipField.toString());

                    final Field zipCodeField = test.getField("zip_code");
                    if (!zipCodeField.isNull()) {
                        final String zipCode = zipCodeField.toString();
                        final int zipCodeInt = zipCodeField.intValue();
                        if (zipCodeInt > 999 || zipCodeInt <= 9999) // plausibility of zip code (must be 4 digits in Austria)
                            addString(resultList, "zip_code", zipCode);
                    }

                    final Field dataField = test.getField("data");
                    if (!Strings.isNullOrEmpty(dataField.toString())) {
                        final JSONObject data = new JSONObject(dataField.toString());

                        if (data.has("region"))
                            addString(resultList, "region", data.getString("region"));
                        if (data.has("municipality"))
                            addString(resultList, "municipality", data.getString("municipality"));
                        if (data.has("settlement"))
                            addString(resultList, "settlement", data.getString("settlement"));
                        if (data.has("whitespace"))
                            addString(resultList, "whitespace", data.getString("whitespace"));

                        if (data.has("cell_id"))
                            addString(resultList, "cell_id", data.getString("cell_id"));
                        if (data.has("cell_name"))
                            addString(resultList, "cell_name", data.getString("cell_name"));
                        if (data.has("cell_id_multiple") && data.getBoolean("cell_id_multiple"))
                            addString(resultList, "cell_id_multiple",
                                    getTranslation("value", "cell_id_multiple"));
                    }

                    final Field speedTestDurationField = test.getField("speed_test_duration");
                    if (!speedTestDurationField.isNull()) {
                        final String speedTestDuration = format
                                .format(speedTestDurationField.doubleValue() / 1000d);
                        addString(resultList, "speed_test_duration", String.format("%s %s", speedTestDuration,
                                labels.getString("RESULT_DURATION_UNIT")));
                    }

                    // public client ip (private)
                    addString(resultList, "client_public_ip", test.getField("client_public_ip"));

                    // AS number - csv 24
                    addString(resultList, "client_public_ip_as", test.getField("public_ip_asn"));

                    // name of AS
                    addString(resultList, "client_public_ip_as_name", test.getField("public_ip_as_name"));

                    // reverse hostname (from ip) - (private)
                    addString(resultList, "client_public_ip_rdns", test.getField("public_ip_rdns"));

                    // operator - derived from provider_id (only for pre-defined operators)
                    //TODO replace provider-information by more generic information
                    addString(resultList, "provider", test.getField("provider_id_name"));

                    // type of client local ip (private)
                    addString(resultList, "client_local_ip", test.getField("client_ip_local_type"));

                    // nat-translation of client - csv 23
                    addString(resultList, "nat_type", test.getField("nat_type"));

                    // wifi base station id SSID (numberic) eg 01:2c:3d..
                    addString(resultList, "wifi_ssid", test.getField("wifi_ssid"));
                    // wifi base station id - BSSID (text) eg 'my hotspot'
                    addString(resultList, "wifi_bssid", test.getField("wifi_bssid"));

                    // nominal link speed of wifi connection in MBit/s
                    final Field linkSpeedField = test.getField("wifi_link_speed");
                    if (!linkSpeedField.isNull())
                        addString(resultList, "wifi_link_speed", String.format("%s %s",
                                linkSpeedField.toString(), labels.getString("RESULT_WIFI_LINK_SPEED_UNIT")));
                    // name of mobile network operator (eg. 'T-Mobile AT')
                    addString(resultList, "network_operator_name", test.getField("network_operator_name"));

                    // mobile network name derived from MCC/MNC of network, eg. '232-01'
                    final Field networkOperatorField = test.getField("network_operator");

                    // mobile provider name, eg. 'Hutchison Drei' (derived from mobile_provider_id)
                    final Field mobileProviderNameField = test.getField("mobile_provider_name");
                    if (mobileProviderNameField.isNull()) // eg. '248-02'
                        addString(resultList, "network_operator", networkOperatorField);
                    else {
                        if (networkOperatorField.isNull())
                            addString(resultList, "network_operator", mobileProviderNameField);
                        else // eg. 'Hutchison Drei (232-10)'
                            addString(resultList, "network_operator",
                                    String.format("%s (%s)", mobileProviderNameField, networkOperatorField));
                    }

                    addString(resultList, "network_sim_operator_name",
                            test.getField("network_sim_operator_name"));

                    final Field networkSimOperatorField = test.getField("network_sim_operator");
                    final Field networkSimOperatorTextField = test
                            .getField("network_sim_operator_mcc_mnc_text");
                    if (networkSimOperatorTextField.isNull())
                        addString(resultList, "network_sim_operator", networkSimOperatorField);
                    else
                        addString(resultList, "network_sim_operator",
                                String.format("%s (%s)", networkSimOperatorTextField, networkSimOperatorField));

                    final Field roamingTypeField = test.getField("roaming_type");
                    if (!roamingTypeField.isNull())
                        addString(resultList, "roaming",
                                Helperfunctions.getRoamingType(labels, roamingTypeField.intValue()));

                    final long totalDownload = test.getField("total_bytes_download").longValue();
                    final long totalUpload = test.getField("total_bytes_upload").longValue();
                    final long totalBytes = totalDownload + totalUpload;
                    if (totalBytes > 0) {
                        final String totalBytesString = format.format(totalBytes / (1000d * 1000d));
                        addString(resultList, "total_bytes", String.format("%s %s", totalBytesString,
                                labels.getString("RESULT_TOTAL_BYTES_UNIT")));
                    }

                    // interface volumes - total including control-server and pre-tests (and other tests)
                    final long totalIfDownload = test.getField("test_if_bytes_download").longValue();
                    final long totalIfUpload = test.getField("test_if_bytes_upload").longValue();
                    // output only total of down- and upload
                    final long totalIfBytes = totalIfDownload + totalIfUpload;
                    if (totalIfBytes > 0) {
                        final String totalIfBytesString = format.format(totalIfBytes / (1000d * 1000d));
                        addString(resultList, "total_if_bytes", String.format("%s %s", totalIfBytesString,
                                labels.getString("RESULT_TOTAL_BYTES_UNIT")));
                    }
                    // interface volumes during test
                    // download test - volume in download direction
                    final long testDlIfBytesDownload = test.getField("testdl_if_bytes_download").longValue();
                    if (testDlIfBytesDownload > 0l) {
                        final String testDlIfBytesDownloadString = format
                                .format(testDlIfBytesDownload / (1000d * 1000d));
                        addString(resultList, "testdl_if_bytes_download", String.format("%s %s",
                                testDlIfBytesDownloadString, labels.getString("RESULT_TOTAL_BYTES_UNIT")));
                    }
                    // download test - volume in upload direction
                    final long testDlIfBytesUpload = test.getField("testdl_if_bytes_upload").longValue();
                    if (testDlIfBytesUpload > 0l) {
                        final String testDlIfBytesUploadString = format
                                .format(testDlIfBytesUpload / (1000d * 1000d));
                        addString(resultList, "testdl_if_bytes_upload", String.format("%s %s",
                                testDlIfBytesUploadString, labels.getString("RESULT_TOTAL_BYTES_UNIT")));
                    }
                    // upload test - volume in upload direction
                    final long testUlIfBytesUpload = test.getField("testul_if_bytes_upload").longValue();
                    if (testUlIfBytesUpload > 0l) {
                        final String testUlIfBytesUploadString = format
                                .format(testUlIfBytesUpload / (1000d * 1000d));
                        addString(resultList, "testul_if_bytes_upload", String.format("%s %s",
                                testUlIfBytesUploadString, labels.getString("RESULT_TOTAL_BYTES_UNIT")));
                    }
                    // upload test - volume in download direction
                    final long testUlIfBytesDownload = test.getField("testul_if_bytes_download").longValue();
                    if (testDlIfBytesDownload > 0l) {
                        final String testUlIfBytesDownloadString = format
                                .format(testUlIfBytesDownload / (1000d * 1000d));
                        addString(resultList, "testul_if_bytes_download", String.format("%s %s",
                                testUlIfBytesDownloadString, labels.getString("RESULT_TOTAL_BYTES_UNIT")));
                    }

                    //start time download-test 
                    final Field time_dl_ns = test.getField("time_dl_ns");
                    if (!time_dl_ns.isNull()) {
                        addString(resultList, "time_dl",
                                String.format("%s %s", format.format(time_dl_ns.doubleValue() / 1000000000d), //convert ns to s
                                        labels.getString("RESULT_DURATION_UNIT")));
                    }

                    //duration download-test 
                    final Field duration_download_ns = test.getField("nsec_download");
                    if (!duration_download_ns.isNull()) {
                        addString(resultList, "duration_dl",
                                String.format("%s %s",
                                        format.format(duration_download_ns.doubleValue() / 1000000000d), //convert ns to s
                                        labels.getString("RESULT_DURATION_UNIT")));
                    }

                    //start time upload-test 
                    final Field time_ul_ns = test.getField("time_ul_ns");
                    if (!time_ul_ns.isNull()) {
                        addString(resultList, "time_ul",
                                String.format("%s %s", format.format(time_ul_ns.doubleValue() / 1000000000d), //convert ns to s
                                        labels.getString("RESULT_DURATION_UNIT")));
                    }

                    //duration upload-test 
                    final Field duration_upload_ns = test.getField("nsec_upload");
                    if (!duration_upload_ns.isNull()) {
                        addString(resultList, "duration_ul",
                                String.format("%s %s",
                                        format.format(duration_upload_ns.doubleValue() / 1000000000d), //convert ns to s
                                        labels.getString("RESULT_DURATION_UNIT")));
                    }

                    if (ndt != null) {
                        final String downloadNdt = format.format(ndt.getField("s2cspd").doubleValue());
                        addString(resultList, "speed_download_ndt",
                                String.format("%s %s", downloadNdt, labels.getString("RESULT_DOWNLOAD_UNIT")));

                        final String uploaddNdt = format.format(ndt.getField("c2sspd").doubleValue());
                        addString(resultList, "speed_upload_ndt",
                                String.format("%s %s", uploaddNdt, labels.getString("RESULT_UPLOAD_UNIT")));

                        // final String pingNdt =
                        // format.format(ndt.getField("avgrtt").doubleValue());
                        // addString(resultList, "ping_ndt",
                        // String.format("%s %s", pingNdt,
                        // labels.getString("RESULT_PING_UNIT")));
                    }

                    addString(resultList, "server_name", test.getField("server_name"));
                    addString(resultList, "plattform", test.getField("plattform"));
                    addString(resultList, "os_version", test.getField("os_version"));
                    addString(resultList, "model", test.getField("model_fullname"));
                    addString(resultList, "client_name", test.getField("client_name"));
                    addString(resultList, "client_software_version", test.getField("client_software_version"));
                    final String encryption = test.getField("encryption").toString();

                    if (encryption != null) {
                        addString(resultList, "encryption",
                                "NONE".equals(encryption) ? labels.getString("key_encryption_false")
                                        : labels.getString("key_encryption_true"));
                    }

                    addString(resultList, "client_version", test.getField("client_version"));

                    addString(resultList, "duration", String.format("%d %s",
                            test.getField("duration").intValue(), labels.getString("RESULT_DURATION_UNIT")));

                    // number of threads for download-test
                    final Field num_threads = test.getField("num_threads");
                    if (!num_threads.isNull()) {
                        addInt(resultList, "num_threads", num_threads);
                    }

                    //number of threads for upload-test
                    final Field num_threads_ul = test.getField("num_threads_ul");
                    if (!num_threads_ul.isNull()) {
                        addInt(resultList, "num_threads_ul", num_threads_ul);
                    }

                    //dz 2013-11-09 removed UUID from details as users might get confused by two
                    //              ids;
                    //addString(resultList, "uuid", String.format("T%s", test.getField("uuid")));

                    final Field openTestUUIDField = test.getField("open_test_uuid");
                    if (!openTestUUIDField.isNull())
                        addString(resultList, "open_test_uuid", String.format("O%s", openTestUUIDField));

                    //number of threads for upload-test
                    final Field tag = test.getField("tag");
                    if (!tag.isNull()) {
                        addString(resultList, "tag", tag);
                    }

                    if (ndt != null) {
                        addString(resultList, "ndt_details_main", ndt.getField("main"));
                        addString(resultList, "ndt_details_stat", ndt.getField("stat"));
                        addString(resultList, "ndt_details_diag", ndt.getField("diag"));
                    }

                    if (resultList.length() == 0)
                        errorList.addError("ERROR_DB_GET_TESTRESULT_DETAIL");

                    answer.put("testresultdetail", resultList);
                } else
                    errorList.addError("ERROR_REQUEST_TEST_RESULT_DETAIL_NO_UUID");

            } else
                errorList.addError("ERROR_DB_CONNECTION");

        } catch (final JSONException e) {
            errorList.addError("ERROR_REQUEST_JSON");
            System.out.println("Error parsing JSDON Data " + e.toString());
        }
    else
        errorList.addErrorString("Expected request is missing.");

    try {
        answer.putOpt("error", errorList.getList());
    } catch (final JSONException e) {
        System.out.println("Error saving ErrorList: " + e.toString());
    }

    answerString = answer.toString();

    long elapsedTime = System.currentTimeMillis() - startTime;
    System.out.println(MessageFormat.format(labels.getString("NEW_TESTRESULT_DETAIL_SUCCESS"), clientIpRaw,
            Long.toString(elapsedTime)));

    return answerString;
}

From source file:com.netease.qa.emmagee.utils.CpuInfo.java

/**
 * reserve used ratio of process CPU and total CPU, meanwhile collect
 * network traffic.// w w  w .j av  a  2 s  .  co  m
 * 
 * @return network traffic ,used ratio of process CPU and total CPU in
 *         certain interval
 */
public ArrayList<String> getCpuRatioInfo(String totalBatt, String currentBatt, String temperature,
        String voltage, String fps, boolean isRoot) {

    String heapData = "";
    DecimalFormat fomart = new DecimalFormat();
    fomart.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    fomart.setGroupingUsed(false);
    fomart.setMaximumFractionDigits(2);
    fomart.setMinimumFractionDigits(2);

    cpuUsedRatio.clear();
    idleCpu.clear();
    totalCpu.clear();
    totalCpuRatio.clear();
    readCpuStat();

    try {
        String mDateTime2;
        Calendar cal = Calendar.getInstance();
        if ((Build.MODEL.equals("sdk")) || (Build.MODEL.equals("google_sdk"))) {
            mDateTime2 = formatterFile.format(cal.getTime().getTime() + 8 * 60 * 60 * 1000);
            totalBatt = Constants.NA;
            currentBatt = Constants.NA;
            temperature = Constants.NA;
            voltage = Constants.NA;
        } else
            mDateTime2 = formatterFile.format(cal.getTime().getTime());
        if (isInitialStatics) {
            preTraffic = trafficInfo.getTrafficInfo();
            isInitialStatics = false;
        } else {
            lastestTraffic = trafficInfo.getTrafficInfo();
            if (preTraffic == -1)
                traffic = -1;
            else {
                if (lastestTraffic > preTraffic) {
                    traffic += (lastestTraffic - preTraffic + 1023) / 1024;
                }
            }
            preTraffic = lastestTraffic;
            Log.d(LOG_TAG, "lastestTraffic===" + lastestTraffic);
            Log.d(LOG_TAG, "preTraffic===" + preTraffic);
            StringBuffer totalCpuBuffer = new StringBuffer();
            if (null != totalCpu2 && totalCpu2.size() > 0) {
                processCpuRatio = fomart.format(100 * ((double) (processCpu - processCpu2)
                        / ((double) (totalCpu.get(0) - totalCpu2.get(0)))));
                for (int i = 0; i < (totalCpu.size() > totalCpu2.size() ? totalCpu2.size()
                        : totalCpu.size()); i++) {
                    String cpuRatio = "0.00";
                    if (totalCpu.get(i) - totalCpu2.get(i) > 0) {
                        cpuRatio = fomart.format(100 * ((double) ((totalCpu.get(i) - idleCpu.get(i))
                                - (totalCpu2.get(i) - idleCpu2.get(i)))
                                / (double) (totalCpu.get(i) - totalCpu2.get(i))));
                    }
                    totalCpuRatio.add(cpuRatio);
                    totalCpuBuffer.append(cpuRatio + Constants.COMMA);
                }
            } else {
                processCpuRatio = "0";
                totalCpuRatio.add("0");
                totalCpuBuffer.append("0,");
                totalCpu2 = (ArrayList<Long>) totalCpu.clone();
                processCpu2 = processCpu;
                idleCpu2 = (ArrayList<Long>) idleCpu.clone();
            }
            // cpucsv
            for (int i = 0; i < getCpuNum() - totalCpuRatio.size() + 1; i++) {
                totalCpuBuffer.append("0.00,");
            }
            long pidMemory = mi.getPidMemorySize(pid, context);
            String pMemory = fomart.format((double) pidMemory / 1024);
            long freeMemory = mi.getFreeMemorySize(context);
            String fMemory = fomart.format((double) freeMemory / 1024);
            String percent = context.getString(R.string.stat_error);
            if (totalMemorySize != 0) {
                percent = fomart.format(((double) pidMemory / (double) totalMemorySize) * 100);
            }

            if (isPositive(processCpuRatio) && isPositive(totalCpuRatio.get(0))) {
                String trafValue;
                // whether certain device supports traffic statics or not
                if (traffic == -1) {
                    trafValue = Constants.NA;
                } else {
                    trafValue = String.valueOf(traffic);
                }
                if (isRoot) {
                    String[][] heapArray = MemoryInfo.getHeapSize(pid, context);
                    heapData = heapArray[0][1] + "/" + heapArray[0][0] + Constants.COMMA + heapArray[1][1] + "/"
                            + heapArray[1][0] + Constants.COMMA;
                }
                EmmageeService.bw.write(mDateTime2 + Constants.COMMA + ProcessInfo.getTopActivity(context)
                        + Constants.COMMA + heapData + pMemory + Constants.COMMA + percent + Constants.COMMA
                        + fMemory + Constants.COMMA + processCpuRatio + Constants.COMMA
                        + totalCpuBuffer.toString() + trafValue + Constants.COMMA + totalBatt + Constants.COMMA
                        + currentBatt + Constants.COMMA + temperature + Constants.COMMA + voltage
                        + Constants.COMMA + fps + Constants.LINE_END);

                JSONObject jsonobj = new JSONObject();
                JSONArray jsonarr = new JSONArray();
                jsonarr.put(System.currentTimeMillis());
                jsonarr.put(pMemory);
                jsonarr.put(percent);
                jsonarr.put(fMemory);
                jsonarr.put(processCpuRatio);
                jsonarr.put(totalCpuBuffer.toString().split(",")[0]);
                jsonarr.put(trafValue);
                jsonarr.put(totalBatt);
                jsonarr.put(currentBatt);
                jsonarr.put(temperature);
                jsonarr.put(voltage);
                jsonarr.put(fps);
                jsonobj.put("testSuitId", HttpUtils.testSuitId);
                jsonobj.put("data", jsonarr);

                HttpUtils.postAppPerfData(jsonobj.toString());

                totalCpu2 = (ArrayList<Long>) totalCpu.clone();
                processCpu2 = processCpu;
                idleCpu2 = (ArrayList<Long>) idleCpu.clone();
                cpuUsedRatio.add(processCpuRatio);
                cpuUsedRatio.add(totalCpuRatio.get(0));
                cpuUsedRatio.add(String.valueOf(traffic));
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return cpuUsedRatio;
}

From source file:org.pentaho.plugin.jfreereport.reportcharts.MultiPieChartExpression.java

protected void configureChart(final JFreeChart chart) {
    super.configureChart(chart);

    final Plot plot = chart.getPlot();
    final MultiplePiePlot mpp = (MultiplePiePlot) plot;
    final JFreeChart pc = mpp.getPieChart();
    configureSubChart(pc);//from   w  w  w.  j a  v a 2  s.  c o  m

    final PiePlot pp = (PiePlot) pc.getPlot();
    if (StringUtils.isEmpty(getTooltipFormula()) == false) {
        pp.setToolTipGenerator(new FormulaPieTooltipGenerator(getRuntime(), getTooltipFormula()));
    }
    if (StringUtils.isEmpty(getUrlFormula()) == false) {
        pp.setURLGenerator(new FormulaPieURLGenerator(getRuntime(), getUrlFormula()));
    }

    if (shadowPaint != null) {
        pp.setShadowPaint(shadowPaint);
    }
    if (shadowXOffset != null) {
        pp.setShadowXOffset(shadowXOffset.doubleValue());
    }
    if (shadowYOffset != null) {
        pp.setShadowYOffset(shadowYOffset.doubleValue());
    }

    final CategoryDataset c = mpp.getDataset();
    if (c != null) {
        final String[] colors = getSeriesColor();
        final int keysSize = c.getColumnKeys().size();
        for (int i = 0; i < colors.length; i++) {
            if (keysSize > i) {
                pp.setSectionPaint(c.getColumnKey(i), parseColorFromString(colors[i]));
            }
        }
    }

    if (StringUtils.isEmpty(getLabelFont()) == false) {
        pp.setLabelFont(Font.decode(getLabelFont()));
    }

    if (Boolean.FALSE.equals(getItemsLabelVisible())) {
        pp.setLabelGenerator(null);
    } else {
        final ExpressionRuntime runtime = getRuntime();
        final Locale locale = runtime.getResourceBundleFactory().getLocale();

        final FastDecimalFormat fastPercent = new FastDecimalFormat(FastDecimalFormat.TYPE_PERCENT, locale);
        final FastDecimalFormat fastInteger = new FastDecimalFormat(FastDecimalFormat.TYPE_INTEGER, locale);

        final DecimalFormat numFormat = new DecimalFormat(fastInteger.getPattern(),
                new DecimalFormatSymbols(locale));
        numFormat.setRoundingMode(RoundingMode.HALF_UP);

        final DecimalFormat percentFormat = new DecimalFormat(fastPercent.getPattern(),
                new DecimalFormatSymbols(locale));
        percentFormat.setRoundingMode(RoundingMode.HALF_UP);

        final StandardPieSectionLabelGenerator labelGen = new StandardPieSectionLabelGenerator(
                multipieLabelFormat, numFormat, percentFormat);
        pp.setLabelGenerator(labelGen);
    }
}

From source file:org.pentaho.plugin.jfreereport.reportcharts.PieChartExpression.java

protected void configureChart(final JFreeChart chart) {
    super.configureChart(chart);

    final Plot plot = chart.getPlot();
    final PiePlot pp = (PiePlot) plot;
    final PieDataset pieDS = pp.getDataset();
    pp.setDirection(rotationClockwise ? Rotation.CLOCKWISE : Rotation.ANTICLOCKWISE);
    if ((explodeSegment != null) && (explodePct != null)) {
        configureExplode(pp);/*from www  .  j  a  v a2s .  c  om*/
    }
    if (StringUtils.isEmpty(getTooltipFormula()) == false) {
        pp.setToolTipGenerator(new FormulaPieTooltipGenerator(getRuntime(), getTooltipFormula()));
    }
    if (StringUtils.isEmpty(getUrlFormula()) == false) {
        pp.setURLGenerator(new FormulaPieURLGenerator(getRuntime(), getUrlFormula()));
    }

    pp.setIgnoreNullValues(ignoreNulls);
    pp.setIgnoreZeroValues(ignoreZeros);
    if (Boolean.FALSE.equals(getItemsLabelVisible())) {
        pp.setLabelGenerator(null);
    } else {
        final ExpressionRuntime runtime = getRuntime();
        final Locale locale = runtime.getResourceBundleFactory().getLocale();

        final FastDecimalFormat fastPercent = new FastDecimalFormat(FastDecimalFormat.TYPE_PERCENT, locale);
        final FastDecimalFormat fastInteger = new FastDecimalFormat(FastDecimalFormat.TYPE_INTEGER, locale);

        final DecimalFormat numFormat = new DecimalFormat(fastInteger.getPattern(),
                new DecimalFormatSymbols(locale));
        numFormat.setRoundingMode(RoundingMode.HALF_UP);

        final DecimalFormat percentFormat = new DecimalFormat(fastPercent.getPattern(),
                new DecimalFormatSymbols(locale));
        percentFormat.setRoundingMode(RoundingMode.HALF_UP);

        final StandardPieSectionLabelGenerator labelGen = new StandardPieSectionLabelGenerator(pieLabelFormat,
                numFormat, percentFormat);
        pp.setLabelGenerator(labelGen);

        final StandardPieSectionLabelGenerator legendGen = new StandardPieSectionLabelGenerator(
                pieLegendLabelFormat, numFormat, percentFormat);
        pp.setLegendLabelGenerator(legendGen);
    }

    if (StringUtils.isEmpty(getLabelFont()) == false) {
        pp.setLabelFont(Font.decode(getLabelFont()));
    }

    if (pieDS != null) {
        final String[] colors = getSeriesColor();
        for (int i = 0; i < colors.length; i++) {
            if (i < pieDS.getItemCount()) {
                pp.setSectionPaint(pieDS.getKey(i), parseColorFromString(colors[i]));
            } else {
                break;
            }
        }
    }

    if (shadowPaint != null) {
        pp.setShadowPaint(shadowPaint);
    }
    if (shadowXOffset != null) {
        pp.setShadowXOffset(shadowXOffset.doubleValue());
    }
    if (shadowYOffset != null) {
        pp.setShadowYOffset(shadowYOffset.doubleValue());
    }
    pp.setCircular(circular);

    if (isShowBorder() == false || isChartSectionOutline() == false) {
        chart.setBorderVisible(false);
        chart.getPlot().setOutlineVisible(false);
    }

}

From source file:org.matsim.contrib.drt.analysis.DynModeTripsAnalyser.java

public static void analyseWaitTimes(String fileName, List<DynModeTrip> trips, int binsize_s) {
    Collections.sort(trips);//from   w  ww .ja  v a2  s .co m
    if (trips.size() == 0)
        return;
    int startTime = ((int) (trips.get(0).getDepartureTime() / binsize_s)) * binsize_s;
    int endTime = ((int) (trips.get(trips.size() - 1).getDepartureTime() / binsize_s) + binsize_s) * binsize_s;
    Map<Double, List<DynModeTrip>> splitTrips = splitTripsIntoBins(trips, startTime, endTime, binsize_s);

    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);
    format.setMaximumFractionDigits(2);
    format.setGroupingUsed(false);

    SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");

    BufferedWriter bw = IOUtils.getBufferedWriter(fileName + ".csv");
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    TimeSeriesCollection datasetrequ = new TimeSeriesCollection();
    TimeSeries averageWaitC = new TimeSeries("average");
    TimeSeries medianWait = new TimeSeries("median");
    TimeSeries p_5Wait = new TimeSeries("5th percentile");
    TimeSeries p_95Wait = new TimeSeries("95th percentile");
    TimeSeries requests = new TimeSeries("Ride requests");

    try {
        bw.write("timebin;trips;average_wait;min;p_5;p_25;median;p_75;p_95;max");
        for (Entry<Double, List<DynModeTrip>> e : splitTrips.entrySet()) {
            long rides = 0;
            double averageWait = 0;
            double min = 0;
            double p_5 = 0;
            double p_25 = 0;
            double median = 0;
            double p_75 = 0;
            double p_95 = 0;
            double max = 0;
            if (!e.getValue().isEmpty()) {
                DescriptiveStatistics stats = new DescriptiveStatistics();
                for (DynModeTrip t : e.getValue()) {
                    stats.addValue(t.getWaitTime());
                }
                rides = stats.getN();
                averageWait = stats.getMean();
                min = stats.getMin();
                p_5 = stats.getPercentile(5);
                p_25 = stats.getPercentile(25);
                median = stats.getPercentile(50);
                p_75 = stats.getPercentile(75);
                p_95 = stats.getPercentile(95);
                max = stats.getMax();

            }
            Minute h = new Minute(sdf2.parse(Time.writeTime(e.getKey())));

            medianWait.addOrUpdate(h, Double.valueOf(median));
            averageWaitC.addOrUpdate(h, Double.valueOf(averageWait));
            p_5Wait.addOrUpdate(h, Double.valueOf(p_5));
            p_95Wait.addOrUpdate(h, Double.valueOf(p_95));
            requests.addOrUpdate(h, rides * 3600. / binsize_s);// normalised [req/h]
            bw.newLine();
            bw.write(Time.writeTime(e.getKey()) + ";" + rides + ";" + format.format(averageWait) + ";"
                    + format.format(min) + ";" + format.format(p_5) + ";" + format.format(p_25) + ";"
                    + format.format(median) + ";" + format.format(p_75) + ";" + format.format(p_95) + ";"
                    + format.format(max));

        }
        bw.flush();
        bw.close();
        dataset.addSeries(averageWaitC);
        dataset.addSeries(medianWait);
        dataset.addSeries(p_5Wait);
        dataset.addSeries(p_95Wait);
        datasetrequ.addSeries(requests);
        JFreeChart chart = chartProfile(splitTrips.size(), dataset, "Waiting times", "Wait time (s)");
        JFreeChart chart2 = chartProfile(splitTrips.size(), datasetrequ, "Ride requests per hour",
                "Requests per hour (req/h)");
        ChartSaveUtils.saveAsPNG(chart, fileName, 1500, 1000);
        ChartSaveUtils.saveAsPNG(chart2, fileName + "_requests", 1500, 1000);

    } catch (IOException | ParseException e) {

        e.printStackTrace();
    }

}

From source file:com.magestore.app.pos.service.config.POSConfigService.java

private DecimalFormat floatFormat(ConfigPriceFormat priceFormat) {
    // khi to float format
    String pattern = "###,###.#";
    DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.getDefault());
    symbols.setDecimalSeparator(priceFormat.getDecimalSymbol().charAt(0));
    symbols.setGroupingSeparator(priceFormat.getGroupSymbol().charAt(0));
    DecimalFormat format = new DecimalFormat(pattern, symbols);
    format.setGroupingSize(priceFormat.getGroupLength());
    format.setMaximumFractionDigits(priceFormat.getPrecision());
    format.setMinimumFractionDigits(priceFormat.getRequirePrecision());
    return format;
}

From source file:org.eclipse.wb.internal.core.parser.JavaInfoParser.java

/**
 * Checks that Java version used to run Eclipse is compatible with Java version of
 * {@link IJavaProject}.//from   w ww  . jav a2  s .co m
 */
private static void checkJavaVersion(ICompilationUnit unit) {
    IJavaProject javaProject = unit.getJavaProject();
    float projectVersion = ProjectUtils.getJavaVersion(javaProject);
    float eclipseVersion = EnvironmentUtils.getJavaVersion();
    if (eclipseVersion < projectVersion) {
        NumberFormat format = new DecimalFormat("#.###", new DecimalFormatSymbols(Locale.ENGLISH));
        String projectVersionString = format.format(projectVersion);
        String eclipseVersionString = format.format(eclipseVersion);
        throw new DesignerException(ICoreExceptionConstants.PARSER_JAVA_VERSION, projectVersionString,
                eclipseVersionString);
    }
}

From source file:org.apache.maven.report.projectinfo.dependencies.renderer.DependenciesRenderer.java

/**
 * Default constructor.// w w  w.  j  a v a  2s . c  o  m
 *
 * @param sink
 * @param locale
 * @param i18n
 * @param log
 * @param settings
 * @param dependencies
 * @param dependencyTreeNode
 * @param config
 * @param repoUtils
 * @param artifactFactory
 * @param mavenProjectBuilder
 * @param remoteRepositories
 * @param localRepository
 */
public DependenciesRenderer(Sink sink, Locale locale, I18N i18n, Log log, Settings settings,
        Dependencies dependencies, DependencyNode dependencyTreeNode, DependenciesReportConfiguration config,
        RepositoryUtils repoUtils, ArtifactFactory artifactFactory, MavenProjectBuilder mavenProjectBuilder,
        List<ArtifactRepository> remoteRepositories, ArtifactRepository localRepository) {
    super(sink, i18n, locale);

    this.log = log;
    this.settings = settings;
    this.dependencies = dependencies;
    this.dependencyNode = dependencyTreeNode;
    this.repoUtils = repoUtils;
    this.configuration = config;
    this.artifactFactory = artifactFactory;
    this.mavenProjectBuilder = mavenProjectBuilder;
    this.remoteRepositories = remoteRepositories;
    this.localRepository = localRepository;

    // Using the right set of symbols depending of the locale
    DEFAULT_DECIMAL_FORMAT.setDecimalFormatSymbols(new DecimalFormatSymbols(locale));

    this.fileLengthDecimalFormat = new FileDecimalFormat(i18n, locale);
    this.fileLengthDecimalFormat.setDecimalFormatSymbols(new DecimalFormatSymbols(locale));
}