List of usage examples for java.text DecimalFormat DecimalFormat
public DecimalFormat(String pattern)
From source file:com.music.Generator.java
public static void main(String[] args) throws Exception { Score score1 = new Score(); Read.midi(score1, "c:/tmp/gen.midi"); for (Part part : score1.getPartArray()) { System.out.println(part.getInstrument()); }//from w w w. j a v a2 s . c o m new StartupListener().contextInitialized(null); Generator generator = new Generator(); generator.configLocation = "c:/config/music"; generator.maxConcurrentGenerations = 5; generator.init(); UserPreferences prefs = new UserPreferences(); prefs.setElectronic(Ternary.YES); //prefs.setSimpleMotif(Ternary.YES); //prefs.setMood(Mood.MAJOR); //prefs.setDrums(Ternary.YES); //prefs.setClassical(true); prefs.setAccompaniment(Ternary.YES); prefs.setElectronic(Ternary.YES); final ScoreContext ctx = generator.generatePiece(); Score score = ctx.getScore(); for (Part part : score.getPartArray()) { System.out.println(part.getTitle() + ": " + part.getInstrument()); } System.out.println("Metre: " + ctx.getMetre()[0] + "/" + ctx.getMetre()[1]); System.out.println(ctx); Write.midi(score, "c:/tmp/gen.midi"); new Thread(new Runnable() { @Override public void run() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(0, 0, 500, 500); frame.setVisible(true); Part part = ctx.getParts().get(PartType.MAIN); Note[] notes = part.getPhrase(0).getNoteArray(); List<Integer> pitches = new ArrayList<Integer>(); for (Note note : notes) { if (!note.isRest()) { pitches.add(note.getPitch()); } } GraphicsPanel gp = new GraphicsPanel(pitches); frame.setContentPane(gp); } }).start(); DecimalFormat df = new DecimalFormat("#.##"); for (Part part : score.getPartArray()) { StringBuilder sb = new StringBuilder(); printStatistics(ctx, part); System.out.println("------------ " + part.getTitle() + "-----------------"); Phrase[] phrases = part.getPhraseArray(); for (Phrase phr : phrases) { if (phr instanceof ExtendedPhrase) { sb.append("Contour=" + ((ExtendedPhrase) phr).getContour() + " "); } double measureSize = 0; int measures = 0; double totalLength = 0; List<String> pitches = new ArrayList<String>(); List<String> lengths = new ArrayList<String>(); System.out.println("((Phrase notes: " + phr.getNoteArray().length + ")"); for (Note note : phr.getNoteArray()) { if (!note.isRest()) { int degree = 0; if (phr instanceof ExtendedPhrase) { degree = Arrays.binarySearch(((ExtendedPhrase) phr).getScale().getDefinition(), note.getPitch() % 12); } pitches.add(String.valueOf(note.getPitch() + " (" + degree + ") ")); } else { pitches.add(" R "); } lengths.add(df.format(note.getRhythmValue())); measureSize += note.getRhythmValue(); totalLength += note.getRhythmValue(); ; if (measureSize >= ctx.getNormalizedMeasureSize()) { pitches.add(" || "); lengths.add(" || " + (measureSize > ctx.getNormalizedMeasureSize() ? "!" : "")); measureSize = 0; measures++; } } sb.append(pitches.toString() + "\r\n"); sb.append(lengths.toString() + "\r\n"); if (part.getTitle().equals(PartType.MAIN.getTitle())) { sb.append("\r\n"); } System.out.println("Phrase measures: " + measures); System.out.println("Phrase length: " + totalLength); } System.out.println(sb.toString()); } MutingPrintStream.ignore.set(true); Write.midi(score, "c:/tmp/gen.midi"); MutingPrintStream.ignore.set(null); Play.midi(score); generator.toMp3(FileUtils.readFileToByteArray(new File("c:/tmp/gen.midi"))); }
From source file:it.alus.GPSreceiver.instruments.Altimeter.java
public Altimeter(float groundAltitudeFt) { super(null);//w w w. j av a 2s . c o m altitude = 0; if (groundAltitudeFt < 0) groundAltitude = 0; else groundAltitude = groundAltitudeFt; hoursDataset = new DefaultValueDataset(0.0); minutesDataset = new DefaultValueDataset(0.0); DialPlot plot = new DialPlot(); plot.setView(0.0, 0.0, 1.0, 1.0); Image background = Toolkit.getDefaultToolkit().getImage(getClass().getResource("altimeter.png")); plot.setDataset(0, hoursDataset); plot.setDataset(1, minutesDataset); StandardDialFrame dialFrame = new StandardDialFrame(); dialFrame.setBackgroundPaint(Color.lightGray); dialFrame.setForegroundPaint(Color.gray); DialTextAnnotation annotation = new DialTextAnnotation("Feet"); annotation.setFont(new Font("Arial", 1, 14)); annotation.setRadius(0.4D); annotation.setPaint(Color.lightGray); plot.addLayer(annotation); DialValueIndicator valueindicator = new DialValueIndicator(0); NumberFormat formatter = new DecimalFormat("#"); plot.addLayer(valueindicator); plot.setDialFrame(dialFrame); StandardDialScale scale = new StandardDialScale(0, 10, 90, -360, 1, 10); scale.setMajorTickPaint(Color.white); scale.setMinorTickPaint(Color.lightGray); scale.setFirstTickLabelVisible(false); scale.setTickRadius(0.88); scale.setTickLabelOffset(0.15); scale.setTickLabelFormatter(formatter); scale.setTickLabelFont(new Font("Arial", Font.BOLD, 24)); scale.setTickLabelPaint(Color.white); plot.addScale(3, scale); plot.setBackground(new DialBackground(Color.black)); StandardDialScale hourScale = new StandardDialScale(0, 10000, 90, -360, 1000, 10); hourScale.setVisible(false); hourScale.setTickRadius(0.88); hourScale.setTickLabelOffset(0.15); plot.addScale(0, hourScale); StandardDialScale minScale = new StandardDialScale(0, 1000, 90, -360, 0, 0); minScale.setVisible(false); minScale.setMajorTickIncrement(5.0); minScale.setTickRadius(0.68); plot.addScale(1, minScale); Pointer hourNeedle = new Pointer(0); hourNeedle.setRadius(0.55); hourNeedle.setFillPaint(Color.lightGray); plot.addLayer(hourNeedle); plot.mapDatasetToScale(1, 1); Pointer minNeedle = new Pointer(1); minNeedle.setFillPaint(Color.white); plot.addLayer(minNeedle); DialCap cap = new DialCap(); cap.setRadius(0.10); cap.setFillPaint(Color.lightGray); plot.setCap(cap); jChart = new JFreeChart(plot); jChart.setBackgroundImage(background); super.setChart(jChart); super.setPreferredSize(new Dimension(400, 400)); }
From source file:com.jennifer.ui.chart.brush.PieBrush.java
@Override public Object draw() { DecimalFormat format = new DecimalFormat(".##"); double all = 359.99, startAngle = 0, max = 0; JSONObject data = chart.data(0);//w ww. jav a 2s. c o m JSONArray target = options.getJSONArray("target"); int maxCount = 0; for (int i = 0, len = target.length(); i < len; i++) { double value = data.getDouble(target.getString(i)); String formatDoubleValue = formatNumber(value).replaceAll(",", ""); value = Double.parseDouble(formatDoubleValue); max += value; if (value > 0) { maxCount++; } } if (max == 0) { Transform g = drawPie(centerX, centerY, outerRadius, 0, 359.99, new JSONObject().put("fill", color(1)) .put("stroke", chart.theme("pieBorderColor")).put("stroke-width", 0)); Transform text = drawText(centerX, centerY, outerRadius, 0, 180, "0%"); g.append(text); root.append(g); } else { for (int i = 0; i < target.length(); i++) { double value = data.getDouble(target.getString(i)); String formatDoubleValue = formatNumber(value).replaceAll(",", ""); value = Double.parseDouble(formatDoubleValue); double rate = value / max; double endAngle = all * rate; Transform g = drawPie(centerX, centerY, outerRadius, startAngle, endAngle, new JSONObject() .put("fill", color(i)).put("stroke", chart.theme("pieBorderColor")).put("stroke-width", 0)); Transform text = drawText(centerX, centerY, outerRadius, startAngle, endAngle, formatNumber(rate * 100) + "%"); g.append(text); root.append(g); startAngle += endAngle; } } return new JSONObject().put("root", root); }
From source file:it.alus.GPSreceiver.instruments.Accelerometer.java
public Accelerometer() { super(null);/* w w w .j a v a 2 s . com*/ dataset = new DefaultValueDataset(0.0); DialPlot plot = new DialPlot(); plot.setView(0.0, 0.0, 1.0, 1.0); plot.setDataset(0, dataset); StandardDialFrame dialFrame = new StandardDialFrame(); dialFrame.setBackgroundPaint(Color.lightGray); dialFrame.setForegroundPaint(Color.gray); DialTextAnnotation titleLabel = new DialTextAnnotation("Acceleration"); titleLabel.setFont(new Font("Arial", 1, 18)); titleLabel.setRadius(0.45D); titleLabel.setAngle(90); titleLabel.setPaint(Color.lightGray); plot.addLayer(titleLabel); DialValueIndicator valueindicator = new DialValueIndicator(0); plot.addLayer(valueindicator); DialTextAnnotation annotation = new DialTextAnnotation("g"); annotation.setFont(new Font("Arial", 1, 20)); annotation.setRadius(0.4D); annotation.setPaint(Color.lightGray); plot.addLayer(annotation); plot.setDialFrame(dialFrame); StandardDialScale scale = new StandardDialScale(-1, 3, -95, -340, 1, 20); scale.setMajorTickPaint(Color.white); scale.setMinorTickPaint(Color.lightGray); scale.setFirstTickLabelVisible(true); scale.setTickRadius(0.88); scale.setTickLabelOffset(0.15); NumberFormat formatter = new DecimalFormat("#"); scale.setTickLabelFormatter(formatter); scale.setTickLabelFont(new Font("Arial", Font.BOLD, 24)); scale.setTickLabelPaint(Color.white); plot.addScale(0, scale); plot.setBackground(new DialBackground(Color.black)); Pointer needle = new Pointer(0); needle.setFillPaint(Color.white); plot.addLayer(needle); plot.mapDatasetToScale(1, 1); DialCap cap = new DialCap(); cap.setRadius(0.10); cap.setFillPaint(Color.gray); plot.setCap(cap); jChart = new JFreeChart(plot); super.setChart(jChart); super.setPreferredSize(new Dimension(400, 400)); }
From source file:freenet.support.TimeUtil.java
/** * It converts a given time interval into a * week/day/hour/second.milliseconds string. * @param timeInterval interval to convert * @param maxTerms the terms number to display * (e.g. 2 means "h" and "m" if the time could be expressed in hour, * 3 means "h","m","s" in the same example). * The maximum terms number available is 6 * @param withSecondFractions if true it displays seconds.milliseconds * @return the formatted String//from ww w . j a va2 s. c o m */ public static String formatTime(long timeInterval, int maxTerms, boolean withSecondFractions) { if (maxTerms > 6) throw new IllegalArgumentException(); StringBuilder sb = new StringBuilder(64); long l = timeInterval; int termCount = 0; // if (l < 0) { sb.append('-'); l = l * -1; } if (!withSecondFractions && l < 1000) { return "0"; } if (termCount >= maxTerms) { return sb.toString(); } // long weeks = (l / (7L * 24 * 60 * 60 * 1000)); if (weeks > 0) { sb.append(weeks).append('w'); termCount++; l = l - (weeks * (7L * 24 * 60 * 60 * 1000)); } if (termCount >= maxTerms) { return sb.toString(); } // long days = (l / (24L * 60 * 60 * 1000)); if (days > 0) { sb.append(days).append('d'); termCount++; l = l - (days * (24L * 60 * 60 * 1000)); } if (termCount >= maxTerms) { return sb.toString(); } // long hours = (l / (60L * 60 * 1000)); if (hours > 0) { sb.append(hours).append('h'); termCount++; l = l - (hours * (60L * 60 * 1000)); } if (termCount >= maxTerms) { return sb.toString(); } // long minutes = (l / (60L * 1000)); if (minutes > 0) { sb.append(minutes).append('m'); termCount++; l = l - (minutes * (60L * 1000)); } if (termCount >= maxTerms) { return sb.toString(); } if (withSecondFractions && ((maxTerms - termCount) >= 2)) { if (l > 0) { double fractionalSeconds = l / (1000.0D); DecimalFormat fix3 = new DecimalFormat("0.000"); sb.append(fix3.format(fractionalSeconds)).append('s'); termCount++; //l = l - ((long)fractionalSeconds * (long)1000); } } else { long seconds = (l / 1000L); if (seconds > 0) { sb.append(seconds).append('s'); termCount++; //l = l - ((long)seconds * (long)1000); } } // return sb.toString(); }
From source file:com.epam.ta.reportportal.core.project.impl.ProjectInfoWidgetDataConverter.java
/** * <b>Percentage Of Investigation</b> project info widget content * //from w w w. j av a 2s .c o m * @param initial * @param interval * @return */ public Map<String, List<ChartObject>> getInvestigatedProjectInfo(List<Launch> initial, InfoInterval interval) { if (initial.isEmpty()) { return new HashMap<>(); } final DecimalFormat formatter = new DecimalFormat("###.##"); final String INV = "investigated"; final String TI = "toInvestigate"; Map<String, List<ChartObject>> result = new HashMap<>(); Map<String, List<Launch>> grouped = groupBy(initial, grouping.get(interval)); Iterator<Entry<String, List<Launch>>> iterator = grouped.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, List<Launch>> pair = iterator.next(); double investigated = 0; double toInvestigate = 0; List<Launch> group = pair.getValue(); ChartObject currentGroup = new ChartObject(); currentGroup.setName(pair.getKey()); Map<String, String> values = new HashMap<>(); for (Launch one : group) { investigated = investigated + one.getStatistics().getIssueCounter().getProductBugTotal() + one.getStatistics().getIssueCounter().getSystemIssueTotal() + one.getStatistics().getIssueCounter().getAutomationBugTotal(); toInvestigate = toInvestigate + one.getStatistics().getIssueCounter().getToInvestigateTotal(); } if ((investigated + toInvestigate) > 0) { double investigatedPercent = (investigated / (investigated + toInvestigate)) * 100; double toInvestigatePercent = 100 - investigatedPercent; values.put(INV, formatter.format(investigatedPercent)); values.put(TI, formatter.format(toInvestigatePercent)); } else { values.put(INV, "0"); values.put(TI, "0"); } currentGroup.setValues(values); result.put(pair.getKey(), Collections.singletonList(currentGroup)); iterator.remove(); } return result; }
From source file:com.bigtobster.pgnextractalt.chess.ChessEvaluator.java
/** * Evaluates how closely a player correlates to a machine playing at maximum skill. Inserts a number into the player's name tag. The closer the * number inserted tends towards 0, the more the moves played by that player correlated to a highly skilled machine. Note that this is a highly * computationally intense method - treat with caution. * * @param games The list of games the be assessed for machine correlation * @param depth The minimum depth that the engine will look for before returning a best move * @param wait The period of time the application will wait in ms before polling the uci engine for a best move/delay * @param force Whether to overwrite cases which have already got a MC value * @return The number of games correctly evaluated * @throws IOException Thrown on an unknown engine failure - typically a failure to connect to the engine for some reason * @throws OperationNotSupportedException Thrown when connected to the engine but engine does not support the current operating system or * architecture * @throws java.net.URISyntaxException Thrown on a failure to detect a Stockfish binary *///from w w w . ja va2 s . c o m @SuppressWarnings({ "FeatureEnvy", "OverlyLongMethod", "BooleanParameter", "MethodWithMoreThanThreeNegations" }) public static int evaluateMachineCorrelation(final ArrayList<Game> games, final int depth, final int wait, final boolean force) throws IOException, OperationNotSupportedException, URISyntaxException { final NumberFormat formatter = new DecimalFormat("#0.00"); final UCIEngine uciEngine = new UCIEngine(); uciEngine.startEngine(ChessContext.resolveStockfishPath()); int modifiedGames = 0; boolean isGameModified = false; for (final Game game : games) { float whiteMCScore = 0.0F; float blackMCScore = 0.0F; if (force || !ChessPresso.isMachineCorrelationEvaluated(game.getWhite()) || !ChessPresso.isMachineCorrelationEvaluated(game.getBlack())) { game.gotoStart(); Move move = game.getNextMove(); while (move != null) { final Position position = game.getPosition(); if (move.isWhiteMove()) { if (force || !ChessPresso.isMachineCorrelationEvaluated(game.getWhite())) { final float moveScore = ChessEvaluator.evaluateMoveCorrelationScore(uciEngine, depth, wait, move, position); whiteMCScore += moveScore; } } else { if (force || !ChessPresso.isMachineCorrelationEvaluated(game.getBlack())) { final float moveScore = ChessEvaluator.evaluateMoveCorrelationScore(uciEngine, depth, wait, move, position); blackMCScore += moveScore; } } game.goForward(); move = game.getNextMove(); uciEngine.reset(); } } if (force || !ChessPresso.isMachineCorrelationEvaluated(game.getWhite())) { final String newWhiteName = game.getWhite() + ChessEvaluator.SPACE + ChessEvaluator.HYPHEN + ChessEvaluator.SPACE + ChessPresso.MC_TAG_PREFIX + ChessEvaluator.SPACE + formatter.format((double) whiteMCScore); game.setTag(ChessContext.WHITE_KEY, newWhiteName); isGameModified = true; } if (force || !ChessPresso.isMachineCorrelationEvaluated(game.getBlack())) { final String newBlackName = game.getBlack() + ChessEvaluator.SPACE + ChessEvaluator.HYPHEN + ChessEvaluator.SPACE + ChessPresso.MC_TAG_PREFIX + ChessEvaluator.SPACE + formatter.format((double) blackMCScore); game.setTag(ChessContext.BLACK_KEY, newBlackName); isGameModified = true; } if (isGameModified) { modifiedGames++; } } uciEngine.stopEngine(); return modifiedGames; }
From source file:com.mxgraph.examples.swing.chart.PieChartDemo1.java
/** * Creates a chart.//w w w . j ava 2 s. c o m * * @param dataset the dataset. * * @return A chart. */ public static JFreeChart createChart(PieDataset dataset) { JFreeChart chart = ChartFactory.createPieChart("", // chart title dataset, // data true, // include legend true, false); PiePlot plot = (PiePlot) chart.getPlot(); plot.setSectionOutlinesVisible(false); plot.setNoDataMessage("No data available"); plot.setCircular(true); plot.setLabelGap(0.01D);// plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}:\r\n{1}({2})", NumberFormat.getNumberInstance(), new DecimalFormat("0.00%"))); // // plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})")); chart.getTitle().setFont(new Font("", Font.PLAIN, 20));// PiePlot piePlot = (PiePlot) chart.getPlot();// piePlot.setLabelFont(new Font("", Font.PLAIN, 10)); chart.getLegend().setItemFont(new Font("", Font.PLAIN, 10)); return chart; }
From source file:com.webarch.common.lang.StringSeriesTools.java
/** * double,?0,?0.00// w w w.j a v a 2s . c o m * * @param numString * @param pattern ?? * @return double */ public static double string2double(final String numString, final String pattern) { try { double num = Double.parseDouble(numString); String defalutPattern = pattern == null ? "0.00" : pattern; DecimalFormat decimalFormat = new DecimalFormat(defalutPattern); num = Double.parseDouble(decimalFormat.format(num)); return num; } catch (NumberFormatException e) { return 0; } }
From source file:com.epam.ta.reportportal.core.widget.content.LaunchesComparisonContentLoader.java
private Map<String, List<ChartObject>> convertResult(List<ChartObject> objects) { Map<String, List<ChartObject>> result = new HashMap<>(); DecimalFormat formatter = new DecimalFormat("###.##"); for (ChartObject object : objects) { Map<String, String> values = new HashMap<>(); /* Total */ Double totalValue = Double.valueOf(object.getValues().get(getTotalFieldName())); values.put(getTotalFieldName(), formatter.format(totalValue)); /* Failed */ Double failedItems = totalValue.intValue() == 0 ? 0.0 : Double.valueOf(object.getValues().get(getFailedFieldName())) / totalValue * 100; values.put(getFailedFieldName(), formatter.format(failedItems)); /* Skipped */ Double skippedItems = totalValue.intValue() == 0 ? 0.0 : Double.valueOf(object.getValues().get(getSkippedFieldName())) / totalValue * 100; values.put(getSkippedFieldName(), formatter.format(skippedItems)); /* Passed */ values.put(getPassedFieldName(), formatter.format((totalValue.intValue() == 0) ? 0.0 : 100 - failedItems - skippedItems)); /* To Investigate */ int toInvestigateQuantity = Integer.parseInt(object.getValues().get(getToInvestigateFieldName())); /* Product Bugs */ int productBugsQuantity = Integer.parseInt(object.getValues().get(getProductBugFieldName())); /* System Issues */ int systemIssuesQuantity = Integer.parseInt(object.getValues().get(getSystemIssueFieldName())); /* Automation Bugs */ int testBugsQuantity = Integer.parseInt(object.getValues().get(getAutomationBugFieldName())); String noDefectValue = object.getValues().get(getNoDefectFieldName()); int noDefectQuantity = noDefectValue == null ? 0 : Integer.parseInt(noDefectValue); int failedQuantity = toInvestigateQuantity + productBugsQuantity + systemIssuesQuantity + testBugsQuantity + noDefectQuantity; if (failedQuantity != 0) { Double investigatedItems = (double) toInvestigateQuantity / failedQuantity * 100; values.put(getToInvestigateFieldName(), formatter.format(investigatedItems)); Double productBugItems = (double) productBugsQuantity / failedQuantity * 100; values.put(getProductBugFieldName(), formatter.format(productBugItems)); Double systemIssueItems = (double) systemIssuesQuantity / failedQuantity * 100; values.put(getSystemIssueFieldName(), formatter.format(systemIssueItems)); Double noDefectItems = (double) noDefectQuantity / failedQuantity * 100; values.put(getNoDefectFieldName(), formatter.format(noDefectItems)); values.put(getAutomationBugFieldName(), formatter .format(100 - investigatedItems - productBugItems - systemIssueItems - noDefectItems)); } else {/* www. j a va 2 s .c o m*/ String formatted = formatter.format(0.0); values.put(getToInvestigateFieldName(), formatted); values.put(getProductBugFieldName(), formatted); values.put(getSystemIssueFieldName(), formatted); values.put(getAutomationBugFieldName(), formatted); values.put(getNoDefectFieldName(), formatted); } object.setValues(values); } result.put(RESULT, objects); return result; }