List of usage examples for java.text NumberFormat getPercentInstance
public static final NumberFormat getPercentInstance()
From source file:com.twocents.report.charts.StandardPieItemLabelGenerator.java
/** * Creates an item label generator.// w w w . ja v a 2s. co m * * @param labelFormat the label format. */ public StandardPieItemLabelGenerator(String labelFormat) { this(labelFormat, NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()); }
From source file:org.grouplens.lenskit.eval.traintest.TrainTestJob.java
@SuppressWarnings("PMD.AvoidCatchingThrowable") private void runEvaluation() throws IOException, RecommenderBuildException { EventBus bus = task.getProject().getEventBus(); bus.post(JobEvents.started(this)); Closer closer = Closer.create();//from w w w.j a v a 2 s .c o m try { outputs = task.getOutputs().getPrefixed(algorithmInfo, dataSet); TableWriter userResults = outputs.getUserWriter(); List<Object> outputRow = Lists.newArrayList(); logger.info("Building {} on {}", algorithmInfo, dataSet); StopWatch buildTimer = new StopWatch(); buildTimer.start(); buildRecommender(); buildTimer.stop(); logger.info("Built {} in {}", algorithmInfo.getName(), buildTimer); logger.info("Measuring {} on {}", algorithmInfo.getName(), dataSet.getName()); StopWatch testTimer = new StopWatch(); testTimer.start(); List<Object> userRow = Lists.newArrayList(); List<MetricWithAccumulator<?>> accumulators = Lists.newArrayList(); for (Metric<?> eval : outputs.getMetrics()) { accumulators.add(makeMetricAccumulator(eval)); } LongSet testUsers = dataSet.getTestData().getUserDAO().getUserIds(); final NumberFormat pctFormat = NumberFormat.getPercentInstance(); pctFormat.setMaximumFractionDigits(2); pctFormat.setMinimumFractionDigits(2); final int nusers = testUsers.size(); logger.info("Testing {} on {} ({} users)", algorithmInfo, dataSet, nusers); int ndone = 0; for (LongIterator iter = testUsers.iterator(); iter.hasNext();) { if (Thread.interrupted()) { throw new InterruptedException("eval job interrupted"); } long uid = iter.nextLong(); userRow.add(uid); userRow.add(null); // placeholder for the per-user time assert userRow.size() == 2; Stopwatch userTimer = Stopwatch.createStarted(); TestUser test = getUserResults(uid); userRow.add(test.getTrainHistory().size()); userRow.add(test.getTestHistory().size()); for (MetricWithAccumulator<?> accum : accumulators) { List<Object> ures = accum.measureUser(test); if (ures != null) { userRow.addAll(ures); } } userTimer.stop(); userRow.set(1, userTimer.elapsed(TimeUnit.MILLISECONDS) * 0.001); if (userResults != null) { try { userResults.writeRow(userRow); } catch (IOException e) { throw new RuntimeException("error writing user row", e); } } userRow.clear(); ndone += 1; if (ndone % 100 == 0) { testTimer.split(); double time = testTimer.getSplitTime(); double tpu = time / ndone; double tleft = (nusers - ndone) * tpu; logger.info("tested {} of {} users ({}), ETA {}", ndone, nusers, pctFormat.format(((double) ndone) / nusers), DurationFormatUtils.formatDurationHMS((long) tleft)); } } testTimer.stop(); logger.info("Tested {} in {}", algorithmInfo.getName(), testTimer); writeMetricValues(buildTimer, testTimer, outputRow, accumulators); bus.post(JobEvents.finished(this)); } catch (Throwable th) { bus.post(JobEvents.failed(this, th)); throw closer.rethrow(th, RecommenderBuildException.class); } finally { try { cleanup(); } finally { outputs = null; closer.close(); } } }
From source file:org.apache.maven.graph.common.version.SingleVersionComparisonsTest.java
@After public void checkErrors() { if (!failed.isEmpty()) { final NumberFormat fmt = NumberFormat.getPercentInstance(); fmt.setMaximumFractionDigits(2); final String message = name.getMethodName() + ": " + (fmt.format(failed.size() / ((double) failed.size() + (double) okay.size()))) + " (" + failed.size() + "/" + (failed.size() + okay.size()) + ") of version comparisons FAILED."; System.out.println(message); if (!okay.isEmpty()) { System.out.println("OKAY " + join(okay, "\nOKAY ")); }// w ww .j a v a2 s. com System.out.println("FAIL " + join(failed, "\nFAIL ")); fail(message); } else { System.out.println(name.getMethodName() + ": All tests OKAY"); } }
From source file:org.talend.dq.indicators.preview.table.ChartDataEntity.java
/** * check the inString is a validate value. * //from www . ja v a 2 s .c o m * @param inString * @return */ public boolean isOutOfValue(String inString) { if (inString.equals(PluginConstant.NA_STRING)) { // $NON-NLS-1$ return true; } boolean isOutOfValue = false; // the default value check isPercent = inString.indexOf('%') > 0; // $NON-NLS-1$ if (isPercent) { NumberFormat nFromat = NumberFormat.getPercentInstance(); try { Number number = nFromat.parse(inString); if (number instanceof Double) { Double doubleString = (Double) number; if (doubleString < 0 || doubleString > 1) { isOutOfValue = true; } } else if (number instanceof Long) { Long longString = (Long) number; if (longString < 0 || longString > 1) { isOutOfValue = true; } } } catch (ParseException e) { isOutOfValue = false; } } else { Double douString = Double.valueOf(inString); if (douString < 0) { isOutOfValue = true; } } return isOutOfValue; }
From source file:org.jfree.chart.demo.ParetoChartDemo.java
/** * Creates a new demo instance./*from w w w . ja v a 2s . c o m*/ * * @param title the frame title. */ public ParetoChartDemo(final String title) { super(title); final DefaultKeyedValues data = new DefaultKeyedValues(); data.addValue("C", new Integer(4843)); data.addValue("C++", new Integer(2098)); data.addValue("C#", new Integer(26)); data.addValue("Java", new Integer(1901)); data.addValue("Perl", new Integer(2507)); data.addValue("PHP", new Integer(1689)); data.addValue("Python", new Integer(948)); data.addValue("Ruby", new Integer(100)); data.addValue("SQL", new Integer(263)); data.addValue("Unix Shell", new Integer(485)); data.sortByValues(SortOrder.DESCENDING); final KeyedValues cumulative = DataUtilities.getCumulativePercentages(data); final CategoryDataset dataset = DatasetUtilities.createCategoryDataset("Languages", data); // create the chart... final JFreeChart chart = ChartFactory.createBarChart("Freshmeat Software Projects", // chart title "Language", // domain axis label "Projects", // range axis label dataset, // data PlotOrientation.VERTICAL, true, // include legend true, false); // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART... chart.addSubtitle(new TextTitle("By Programming Language")); chart.addSubtitle(new TextTitle("As at 5 March 2003")); // set the background color for the chart... chart.setBackgroundPaint(new Color(0xBBBBDD)); // get a reference to the plot for further customisation... final CategoryPlot plot = chart.getCategoryPlot(); final CategoryAxis domainAxis = plot.getDomainAxis(); domainAxis.setLowerMargin(0.02); domainAxis.setUpperMargin(0.02); // set the range axis to display integers only... final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); final LineAndShapeRenderer renderer2 = new LineAndShapeRenderer(); final CategoryDataset dataset2 = DatasetUtilities.createCategoryDataset("Cumulative", cumulative); final NumberAxis axis2 = new NumberAxis("Percent"); axis2.setNumberFormatOverride(NumberFormat.getPercentInstance()); plot.setRangeAxis(1, axis2); plot.setDataset(1, dataset2); plot.setRenderer(1, renderer2); plot.mapDatasetToRangeAxis(1, 1); plot.setDatasetRenderingOrder(DatasetRenderingOrder.REVERSE); // OPTIONAL CUSTOMISATION COMPLETED. // add the chart to a panel... final ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(550, 270)); setContentPane(chartPanel); }
From source file:org.jfree.chart.demo.MultiplePieChartDemo2.java
/** * Creates a sample chart with the given dataset. * // ww w . j av a 2 s . c o m * @param dataset the dataset. * * @return A sample chart. */ private JFreeChart createChart(final CategoryDataset dataset) { final JFreeChart chart = ChartFactory.createMultiplePieChart("Multiple Pie Chart", // chart title dataset, // dataset TableOrder.BY_COLUMN, true, // include legend true, false); final MultiplePiePlot plot = (MultiplePiePlot) chart.getPlot(); plot.setBackgroundPaint(Color.white); plot.setOutlineStroke(new BasicStroke(1.0f)); final JFreeChart subchart = plot.getPieChart(); final PiePlot p = (PiePlot) subchart.getPlot(); p.setBackgroundPaint(null); p.setOutlineStroke(null); p.setLabelGenerator(new StandardPieItemLabelGenerator("{0} ({2})", NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance())); p.setMaximumLabelWidth(0.35); p.setLabelFont(new Font("SansSerif", Font.PLAIN, 9)); p.setInteriorGap(0.30); return chart; }
From source file:com.newatlanta.bluedragon.CategoryItemLabelGenerator.java
protected Object[] createItemArray(CategoryDataset dataset, int row, int column) { Object[] result = new Object[5]; result[0] = dataset.getRowKey(row).toString(); result[1] = dataset.getColumnKey(column).toString(); Number value = dataset.getValue(row, column); if (value != null) { if (yAxisSymbols != null) { int intValue = value.intValue(); if (intValue < yAxisSymbols.length) result[2] = yAxisSymbols[intValue]; else/* w w w.j a v a2 s . c o m*/ result[2] = "???"; } else if (this.getNumberFormat() != null) { result[2] = this.getNumberFormat().format(value); } else if (this.getDateFormat() != null) { result[2] = this.getDateFormat().format(value); } } else { result[2] = "-"; // this.nullValueString; } if (value != null) { double total = DataUtilities.calculateRowTotal(dataset, row); double percent = value.doubleValue() / total; result[3] = NumberFormat.getPercentInstance().format(percent); if (this.getNumberFormat() != null) { result[4] = this.getNumberFormat().format(total); } else if (this.getDateFormat() != null) { // result[4] = this.getDateFormat().format(total); } } return result; }
From source file:com.jd.survey.web.pdf.StatisticsPdf.java
@Override protected void buildPdfDocument(Map model, Document document, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, String> messages = (Map<String, String>) model.get("messages"); SurveyDefinition surveyDefinition = (SurveyDefinition) model.get("surveyDefinition"); SurveyStatistic surveyStatistic = (SurveyStatistic) model.get("surveyStatistic"); Map<String, List<QuestionStatistic>> allQuestionStatistics = (Map<String, List<QuestionStatistic>>) model .get("allquestionStatistics"); List<QuestionStatistic> questionStatistics; String surveyLabel = messages.get("surveyLabel"); String totalLabel = messages.get("totalLabel"); String completedLabel = messages.get("completedLabel"); String noStatstisticsMessage = messages.get("noStatstisticsMessage"); String pageLabel = messages.get("pageLabel"); String optionLabel = messages.get("optionLabel"); String optionFrequencyLabel = messages.get("optionFrequencyLabel"); String minimumLabel = messages.get("minimumLabel"); String maximumLabel = messages.get("maximumLabel"); String averageLabel = messages.get("averageLabel"); String standardDeviationLabel = messages.get("standardDeviationLabel"); String date_format = messages.get("date_format"); String falseLabel = messages.get("falseLabel"); String trueLabel = messages.get("trueLabel"); NumberFormat percentFormat = NumberFormat.getPercentInstance(); percentFormat.setMaximumFractionDigits(1); Paragraph titleParagraph;// w ww. j a va2 s . co m //Render Survey statistics writeTitle(document, surveyLabel + ": " + surveyDefinition.getName()); writeEntry(document, totalLabel, surveyStatistic.getTotalCount().toString()); writeEntry(document, completedLabel, surveyStatistic.getSubmittedCount().toString() + " (" + percentFormat.format(surveyStatistic.getSubmittedPercentage()) + ")"); //Render Question statistics for (SurveyDefinitionPage page : surveyDefinition.getPages()) { //loop on the pages writeTitle(document, pageLabel + " " + page.getTwoDigitPageOrder() + ": " + page.getTitle()); for (Question question : page.getQuestions()) { Policy policy = Policy.getInstance(this.getClass().getResource(POLICY_FILE_LOCATION)); AntiSamy as = new AntiSamy(); CleanResults cr = as.scan(question.getQuestionText(), policy); question.setQuestionText(cr.getCleanHTML()); writeSubTitle(document, question.getTwoDigitPageOrder() + "- " + question.getQuestionText()); questionStatistics = (List<QuestionStatistic>) allQuestionStatistics .get("q" + question.getId().toString()); switch (question.getType()) { case YES_NO_DROPDOWN: writeBooleanQuestionStatistics(document, question, questionStatistics, optionLabel, optionFrequencyLabel, trueLabel, falseLabel); writeOptionsQuestionStatistics(document, question, questionStatistics, optionLabel, optionFrequencyLabel); break; case SHORT_TEXT_INPUT: writeEntry(document, noStatstisticsMessage); break; case LONG_TEXT_INPUT: writeEntry(document, noStatstisticsMessage); break; case HUGE_TEXT_INPUT: writeEntry(document, noStatstisticsMessage); break; case INTEGER_INPUT: writeEntry(document, minimumLabel, questionStatistics.get(0).getMin()); writeEntry(document, maximumLabel, questionStatistics.get(0).getMax()); writeEntry(document, averageLabel, questionStatistics.get(0).getAverage()); writeEntry(document, standardDeviationLabel, questionStatistics.get(0).getSampleStandardDeviation()); break; case CURRENCY_INPUT: writeCurrencyEntry(document, minimumLabel, questionStatistics.get(0).getMin()); writeCurrencyEntry(document, maximumLabel, questionStatistics.get(0).getMax()); writeCurrencyEntry(document, averageLabel, questionStatistics.get(0).getAverage()); writeCurrencyEntry(document, standardDeviationLabel, questionStatistics.get(0).getSampleStandardDeviation()); break; case DECIMAL_INPUT: writeEntry(document, minimumLabel, questionStatistics.get(0).getMin()); writeEntry(document, maximumLabel, questionStatistics.get(0).getMax()); writeEntry(document, averageLabel, questionStatistics.get(0).getAverage()); writeEntry(document, standardDeviationLabel, questionStatistics.get(0).getSampleStandardDeviation()); break; case DATE_INPUT: writeEntry(document, minimumLabel, questionStatistics.get(0).getMinDate(), date_format); writeEntry(document, maximumLabel, questionStatistics.get(0).getMaxDate(), date_format); break; case SINGLE_CHOICE_DROP_DOWN: writeOptionsQuestionStatistics(document, question, questionStatistics, optionLabel, optionFrequencyLabel); break; case MULTIPLE_CHOICE_CHECKBOXES: writeOptionsQuestionStatistics(document, question, questionStatistics, optionLabel, optionFrequencyLabel); break; case DATASET_DROP_DOWN: writeOptionsQuestionStatistics(document, question, questionStatistics, optionLabel, optionFrequencyLabel); break; case SINGLE_CHOICE_RADIO_BUTTONS: writeOptionsQuestionStatistics(document, question, questionStatistics, optionLabel, optionFrequencyLabel); break; case YES_NO_DROPDOWN_MATRIX: writeBooleanMatrixQuestionStatistics(document, question, questionStatistics, trueLabel, falseLabel); break; case SHORT_TEXT_INPUT_MATRIX: writeEntry(document, noStatstisticsMessage); break; case INTEGER_INPUT_MATRIX: writeNumericMatrixQuestionStatistics(document, question, questionStatistics, minimumLabel, maximumLabel, averageLabel, standardDeviationLabel); break; case CURRENCY_INPUT_MATRIX: writeCurrencyMatrixQuestionStatistics(document, question, questionStatistics, minimumLabel, maximumLabel, averageLabel, standardDeviationLabel); break; case DECIMAL_INPUT_MATRIX: writeNumericMatrixQuestionStatistics(document, question, questionStatistics, minimumLabel, maximumLabel, averageLabel, standardDeviationLabel); break; case DATE_INPUT_MATRIX: writeDateMatrixQuestionStatistics(document, question, questionStatistics, minimumLabel, maximumLabel, date_format); break; case IMAGE_DISPLAY: writeEntry(document, noStatstisticsMessage); break; case VIDEO_DISPLAY: writeEntry(document, noStatstisticsMessage); break; case FILE_UPLOAD: writeEntry(document, noStatstisticsMessage); break; case STAR_RATING: writeOptionsQuestionStatistics(document, question, questionStatistics, optionLabel, optionFrequencyLabel); break; case SMILEY_FACES_RATING: writeOptionsQuestionStatistics(document, question, questionStatistics, optionLabel, optionFrequencyLabel); break; } } } }
From source file:org.punksearch.web.statistics.FileTypeStatistics.java
public static PieDataset makePieDataset(Map<String, Long> values, long total) { long sum = 0; for (Long value : values.values()) { sum += value;/*from w ww.j a v a 2s . c o m*/ } long other = total - sum; NumberFormat nfPercent = NumberFormat.getPercentInstance(); NumberFormat nfNumber = NumberFormat.getNumberInstance(); nfPercent.setMaximumFractionDigits(2); DefaultPieDataset dataset = new DefaultPieDataset(); for (Map.Entry<String, Long> entry : values.entrySet()) { long value = entry.getValue(); dataset.setValue(entry.getKey() + " " + nfPercent.format(value / (total + 0.0)) + " (" + nfNumber.format(value) + ")", value); } if (other > 0) { dataset.setValue( "other " + nfPercent.format(other / (total + 0.0)) + " (" + nfNumber.format(other) + ")", other); } return dataset; }
From source file:info.magnolia.ui.form.field.upload.basic.BasicUploadProgressIndicator.java
/** * Creates a percentage representation of the upload currently in progress. *///from ww w . j a v a 2 s.c o m private String createPercentage(long readBytes, long contentLength) { double read = Double.valueOf(readBytes); double from = Double.valueOf(contentLength); NumberFormat defaultFormat = NumberFormat.getPercentInstance(); return defaultFormat.format((read / from)); }