List of usage examples for java.lang Float toString
public static String toString(float f)
From source file:eu.itesla_project.eurostag.EurostagImpactAnalysis.java
private void fillMetrics(List<Contingency> contingencies, ExecutionReport report, Map<String, String> metrics) { float successPercent = 100f * (1 - ((float) report.getErrors().size()) / contingencies.size()); metrics.put("successPercent", Float.toString(successPercent)); EurostagUtil.putBadExitCode(report, metrics); }
From source file:org.apache.tez.dag.app.web.AMWebController.java
/** * Renders the response JSON for tasksInfo API * The JSON will have an array of task objects under the key tasks. *///from www .j a v a 2 s .c o m public void getTasksInfo() { if (!setupResponse()) { return; } DAG dag = checkAndGetDAGFromRequest(); if (dag == null) { return; } int limit = MAX_QUERIED; try { limit = getQueryParamInt(WebUIService.LIMIT); } catch (NumberFormatException e) { //Ignore } List<Task> tasks = getRequestedTasks(dag, limit); if (tasks == null) { return; } Map<String, Set<String>> counterNames = getCounterListFromRequest(); ArrayList<Map<String, Object>> tasksInfo = new ArrayList<Map<String, Object>>(); for (Task t : tasks) { Map<String, Object> taskInfo = new HashMap<String, Object>(); taskInfo.put("id", t.getTaskId().toString()); taskInfo.put("progress", Float.toString(t.getProgress())); taskInfo.put("status", t.getState().toString()); try { TezCounters counters = t.getCounters(); Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames); if (counterMap != null && !counterMap.isEmpty()) { taskInfo.put("counters", counterMap); } } catch (LimitExceededException e) { // Ignore // TODO: add an error message instead for counter key } tasksInfo.add(taskInfo); } renderJSON(ImmutableMap.of("tasks", tasksInfo)); }
From source file:com.limewoodmedia.nsdroid.activities.Nation.java
private void doGovernmentSetup() { governmentTitle.setText(getString(R.string.nation_government_title, Utils.capitalize(data.demonym))); // Government size and percent double gov = 0; if (data.sectors.containsKey(IndustrySector.GOVERNMENT)) { gov = data.sectors.get(IndustrySector.GOVERNMENT); }//from w ww . j av a 2 s . co m governmentSize.setText(getString(R.string.nation_government_size, Utils.formatCurrencyAmount(this, Math.round(data.gdp * (gov / 100d))), data.currency)); governmentPercent.setText(getString(R.string.nation_government_percent, String.format("%.1f", gov))); governmentSeries.clear(); governmentRenderer.removeAllRenderers(); Set<Map.Entry<Department, Float>> depts = data.governmentBudget.entrySet(); TreeSet<Map.Entry<IDescriptable, Float>> departments = new TreeSet<>(); for (Map.Entry<Department, Float> d : depts) { departments.add(new DescriptionMapEntry(d)); } NumberFormat format = NumberFormat.getPercentInstance(); format.setMaximumFractionDigits(1); Map<IDescriptable, String> legends = new HashMap<>(); StringBuilder legend; String desc; int colour; for (Map.Entry<IDescriptable, Float> d : departments) { if (d.getValue() == 0) continue; desc = d.getKey().getDescription(); governmentSeries.add(desc, d.getValue() / 100f); SimpleSeriesRenderer renderer = new SimpleSeriesRenderer(); colour = CHART_COLOURS[(governmentSeries.getItemCount() - 1) % CHART_COLOURS.length]; renderer.setColor(colour); renderer.setChartValuesFormat(format); governmentRenderer.addSeriesRenderer(renderer); legend = new StringBuilder(); legend.append("<b><font color='").append(Integer.toString(colour)).append("'>").append(desc); legends.put(d.getKey(), legend.toString()); } governmentChart.repaint(); // Legend legend = new StringBuilder(); for (Department dep : Department.values()) { if (legend.length() > 0) { legend.append("<br/>"); } if (legends.containsKey(dep)) { legend.append(legends.get(dep)).append(": ").append(Float.toString(data.governmentBudget.get(dep))) .append("%</font></b>"); } else { legend.append("<font color='grey'>").append(dep.getDescription()).append(": ").append("0%</font>"); } } governmentLegend.setText(Html.fromHtml(legend.toString()), TextView.BufferType.SPANNABLE); }
From source file:com.example.michel.facetrack.FaceTrackerActivity.java
private void updateState(String response) { String toSpeak;/*w w w. ja va 2 s . co m*/ if (response.isEmpty()) { toSpeak = "Please say your intention."; mTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); waitStartSTT(4000); } switch (state) { case START: try { PostNLU.Intention intention = PostNLU.post(response); if (intention.intent == PostNLU.Intent.TAKE && intention.photoType == PostNLU.PhotoType.SELFIE) { state = State.S_CONFIRMATION; toSpeak = "Hold the camera at eye level and arms length away."; mTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); Thread thread = new Thread() { @Override public void run() { try { sleep(5000); sixSecondFlag = true; } catch (Exception e) { e.printStackTrace(); } } }; thread.start(); while (sixSecondFlag != true) { } sixSecondFlag = false; } else { toSpeak = "Hold the camera at eye level."; mTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); state = State.P_CONFIRMATION; Thread thread = new Thread() { @Override public void run() { try { sleep(4000); sixSecondFlag = true; } catch (Exception e) { e.printStackTrace(); } } }; thread.start(); while (sixSecondFlag != true) { } sixSecondFlag = false; } } catch (IOException e) { e.printStackTrace(); toSpeak = "Error interpreting what you said. Please say it again."; mTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); waitStartSTT(4000); } break; case S_CONFIRMATION: if (response.equals("tiltr")) { toSpeak = "Tilt camera slightly to the left."; mTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); } else if (response.equals("tiltl")) { toSpeak = "Tilt camera slightly to the right."; mTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); } else if (response.equals("close")) { toSpeak = "Move camera slightly farther away from yourself."; mTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); } else if (response.equals("far")) { toSpeak = "Move camera slightly closer towards yourself."; mTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); } else if (response.equals("good")) { state = State.REQUEST_COMMENT; mCameraSource.takePicture(new CameraSource.ShutterCallback() { @Override public void onShutter() { } }, new CameraSource.PictureCallback() { @Override public void onPictureTaken(byte[] bytes) { String file_timestamp = Long.toString(System.currentTimeMillis()); Log.e("File: ", Environment.getExternalStorageDirectory() + "/" + file_timestamp + ".jpg"); final File file = new File( Environment.getExternalStorageDirectory() + "/" + file_timestamp + ".jpg"); try { save(bytes, file); Toast.makeText(FaceTrackerActivity.this, "Saved to " + Environment.getExternalStorageDirectory() + "/" + file_timestamp + ".jpg", Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } } private void save(byte[] bytes, final File file) throws IOException { OutputStream output = null; try { output = new FileOutputStream(file); output.write(bytes); } finally { if (null != output) { output.close(); } } sendPhotoToAzure(file); // Sending a blob (photo) to the Azure Storage String photo_url = "https://blindspot.blob.core.windows.net/image/" + file.getName(); Log.e("Photo_url : ", photo_url); Float happiness = getHappiness(photo_url); // Call the Microsoft's Emotion API using the photo url Log.e("Happiness: ", Float.toString(happiness)); } }); toSpeak = "Picture taken. Do you want to add a comment?"; mTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); waitStartSTT(4000); } break; case P_CONFIRMATION: if (response.equals("tiltr")) { toSpeak = "Tilt camera slightly to the right."; mTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); } else if (response.equals("tiltl")) { toSpeak = "Tilt camera slightly to the left."; mTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); } else if (response.equals("close")) { toSpeak = "Move camera slightly closer towards yourself."; mTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); } else if (response.equals("far")) { toSpeak = "Move camera slightly farther away from yourself."; mTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); } else if (response.equals("good")) { state = State.REQUEST_COMMENT; toSpeak = "Picture taken. Do you want to add a comment?"; mCameraSource.takePicture(new CameraSource.ShutterCallback() { @Override public void onShutter() { } }, new CameraSource.PictureCallback() { @Override public void onPictureTaken(byte[] bytes) { String file_timestamp = Long.toString(System.currentTimeMillis()); Log.e("File: ", Environment.getExternalStorageDirectory() + "/" + file_timestamp + ".jpg"); final File file = new File( Environment.getExternalStorageDirectory() + "/" + file_timestamp + ".jpg"); try { save(bytes, file); Toast.makeText(FaceTrackerActivity.this, "Saved to " + Environment.getExternalStorageDirectory() + "/" + file_timestamp + ".jpg", Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } } private void save(byte[] bytes, final File file) throws IOException { OutputStream output = null; try { output = new FileOutputStream(file); output.write(bytes); } finally { if (null != output) { output.close(); } } sendPhotoToAzure(file); // Sending a blob (photo) to the Azure Storage String photo_url = "https://blindspot.blob.core.windows.net/image/" + file.getName(); Log.e("Photo_url : ", photo_url); Float happiness = getHappiness(photo_url); // Call the Microsoft's Emotion API using the photo url Log.e("Happiness: ", Float.toString(happiness)); } }); mTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); waitStartSTT(4000); } break; case REQUEST_COMMENT: if (response.equalsIgnoreCase("yes")) { state = State.ADD_COMMENT; toSpeak = "Record comment now."; mTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); waitStartSTT(2000); } else if (response.equalsIgnoreCase("no")) { toSpeak = "Storage complete. Goodbye."; mTTS.setOnUtteranceProgressListener(exitListener); mTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); } else { toSpeak = "Error interpreting what you said. Please say it again."; mTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); waitStartSTT(4000); } break; case ADD_COMMENT: toSpeak = "Storage complete. Goodbye"; mTTS.setOnUtteranceProgressListener(exitListener); mTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); Thread thread = new Thread() { @Override public void run() { try { sleep(2000); sixSecondFlag = true; } catch (Exception e) { e.printStackTrace(); } } }; thread.start(); while (sixSecondFlag != true) { } System.exit(0); break; case DONE: break; default: //should not be here } }
From source file:com.stratio.cassandra.lucene.IndexService.java
private Row decorate(Row row, Float score, int nowInSec) { if (column == null || score == null) { return row; }//from w w w . j av a2 s . c o m long timestamp = row.primaryKeyLivenessInfo().timestamp(); Row.Builder builder = BTreeRow.unsortedBuilder(nowInSec); builder.newRow(row.clustering()); builder.addRowDeletion(row.deletion()); builder.addPrimaryKeyLivenessInfo(row.primaryKeyLivenessInfo()); row.cells().forEach(builder::addCell); ByteBuffer value = UTF8Type.instance.decompose(Float.toString(score)); builder.addCell(BufferCell.live(metadata, columnDefinition, timestamp, value)); return builder.build(); }
From source file:net.sf.taverna.t2.activities.apiconsumer.ApiConsumerActivity.java
/** * Converts an object into its string representation. * * @param resultObject//w w w . ja v a2s . c om * @return */ private String convertObjectToString(Object resultObject) { if (resultObject instanceof String) { return (String) resultObject; } else if (resultObject instanceof BigInteger) { return new String(((BigInteger) resultObject).toString()); } else if (resultObject instanceof BigDecimal) { return new String(((BigDecimal) resultObject).toString()); } else if (resultObject instanceof Double) { return new String(Double.toString((Double) resultObject)); } else if (resultObject instanceof Float) { return new String(Float.toString((Float) resultObject)); } else if (resultObject instanceof Integer) { return new String(Integer.toString((Integer) resultObject)); } else if (resultObject instanceof Long) { return new String(Long.toString((Long) resultObject)); } else if (resultObject instanceof Short) { return new String(Short.toString((Short) resultObject)); } else if (resultObject instanceof Boolean) { return new String(Boolean.toString((Boolean) resultObject)); } if (resultObject instanceof char[]) { return new String((char[]) resultObject); } else {// Should not happen return "Error"; } }
From source file:com.farmerbb.notepad.activity.MainActivity.java
@SuppressLint("SetJavaScriptEnabled") @TargetApi(Build.VERSION_CODES.KITKAT)//from ww w.ja v a 2 s.c o m public void printNote(String contentToPrint) { SharedPreferences pref = getSharedPreferences(getPackageName() + "_preferences", MODE_PRIVATE); // Create a WebView object specifically for printing boolean generateHtml = !(pref.getBoolean("markdown", false) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP); WebView webView = generateHtml ? new WebView(this) : new MarkdownView(this); // Apply theme String theme = pref.getString("theme", "light-sans"); int textSize = -1; String fontFamily = null; if (theme.contains("sans")) { fontFamily = "sans-serif"; } if (theme.contains("serif")) { fontFamily = "serif"; } if (theme.contains("monospace")) { fontFamily = "monospace"; } switch (pref.getString("font_size", "normal")) { case "smallest": textSize = 12; break; case "small": textSize = 14; break; case "normal": textSize = 16; break; case "large": textSize = 18; break; case "largest": textSize = 20; break; } String topBottom = " " + Float.toString(getResources().getDimension(R.dimen.padding_top_bottom_print) / getResources().getDisplayMetrics().density) + "px"; String leftRight = " " + Float.toString(getResources().getDimension(R.dimen.padding_left_right_print) / getResources().getDisplayMetrics().density) + "px"; String fontSize = " " + Integer.toString(textSize) + "px"; String css = "body { " + "margin:" + topBottom + topBottom + leftRight + leftRight + "; " + "font-family:" + fontFamily + "; " + "font-size:" + fontSize + "; " + "}"; webView.getSettings().setJavaScriptEnabled(false); webView.getSettings().setLoadsImagesAutomatically(false); webView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(final WebView view, String url) { createWebPrintJob(view); } }); // Load content into WebView if (generateHtml) { webView.loadDataWithBaseURL(null, "<link rel='stylesheet' type='text/css' href='data:text/css;base64," + Base64.encodeToString(css.getBytes(), Base64.DEFAULT) + "' /><html><body><p>" + StringUtils.replace(contentToPrint, "\n", "<br>") + "</p></body></html>", "text/HTML", "UTF-8", null); } else ((MarkdownView) webView).loadMarkdown(contentToPrint, "data:text/css;base64," + Base64.encodeToString(css.getBytes(), Base64.DEFAULT)); }
From source file:org.opendatakit.api.odktables.TableService.java
/** * Replace the properties.csv with the supplied propertiesList. * This does not preserve the existing properties in the properties.csv, * but does a wholesale, atomic, replacement of those properties. * // w w w . j ava 2s . com * This is the JSON variant of this API. See putXmlTableProperties, above. * * @param odkClientVersion * @param propertiesList * @return * @throws ODKDatastoreException * @throws PermissionDeniedException * @throws ODKTaskLockException * @throws TableNotFoundException */ @PUT @Path("properties/{odkClientVersion}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON, ApiConstants.MEDIA_TEXT_XML_UTF8, ApiConstants.MEDIA_APPLICATION_XML_UTF8 }) public Response putJsonTableProperties(@PathParam("odkClientVersion") String odkClientVersion, ArrayList<Map<String, Object>> propertiesList) throws ODKDatastoreException, PermissionDeniedException, ODKTaskLockException, TableNotFoundException { ArrayList<PropertyEntryXml> properties = new ArrayList<PropertyEntryXml>(); for (Map<String, Object> tpe : propertiesList) { // bogus type and value... String partition = (String) tpe.get("partition"); String aspect = (String) tpe.get("aspect"); String key = (String) tpe.get("key"); String type = (String) tpe.get("type"); PropertyEntryXml e = new PropertyEntryXml(partition, aspect, key, type, null); // and figure out the correct type and value... Object value = tpe.get("value"); if (value == null) { e.setValue(null); } else if (value instanceof Boolean) { e.setValue(Boolean.toString((Boolean) value)); } else if (value instanceof Integer) { e.setValue(Integer.toString((Integer) value)); } else if (value instanceof Float) { e.setValue(Float.toString((Float) value)); } else if (value instanceof Double) { e.setValue(Double.toString((Double) value)); } else if (value instanceof List) { try { e.setValue(mapper.writeValueAsString(value)); } catch (JsonProcessingException ex) { ex.printStackTrace(); e.setValue("[]"); } } else { try { e.setValue(mapper.writeValueAsString(value)); } catch (JsonProcessingException ex) { ex.printStackTrace(); e.setValue("{}"); } } properties.add(e); } PropertyEntryXmlList pl = new PropertyEntryXmlList(properties); return putInternalTableProperties(odkClientVersion, pl); }
From source file:org.owasp.webscarab.plugin.sessionid.swing.SessionIDPanel.java
private void updateStats() { if (_key == null) { maxTextField.setText(""); minTextField.setText(""); rangeTextField.setText(""); return;/*from w ww . ja v a 2 s. co m*/ } BigInteger min = _model.getMinimumValue(_key); BigInteger max = _model.getMaximumValue(_key); if (min != null) { minTextField.setText(min.toString()); } else { minTextField.setText(""); } if (max != null) { maxTextField.setText(max.toString()); } else { maxTextField.setText(""); } if (min != null && max != null) { BigInteger range = max.subtract(min); rangeTextField.setText(Float.toString(range.floatValue())); } else { rangeTextField.setText(""); } }
From source file:org.apache.tez.dag.app.web.AMWebController.java
/** * Renders the response JSON for attemptsInfo API * The JSON will have an array of attempt objects under the key attempts. *//*ww w.j av a 2 s . c o m*/ public void getAttemptsInfo() { if (!setupResponse()) { return; } DAG dag = checkAndGetDAGFromRequest(); if (dag == null) { return; } int limit = MAX_QUERIED; try { limit = getQueryParamInt(WebUIService.LIMIT); } catch (NumberFormatException e) { //Ignore } List<TaskAttempt> attempts = getRequestedAttempts(dag, limit); if (attempts == null) { return; } Map<String, Set<String>> counterNames = getCounterListFromRequest(); ArrayList<Map<String, Object>> attemptsInfo = new ArrayList<Map<String, Object>>(); for (TaskAttempt a : attempts) { Map<String, Object> attemptInfo = new HashMap<String, Object>(); attemptInfo.put("id", a.getID().toString()); attemptInfo.put("progress", Float.toString(a.getProgress())); attemptInfo.put("status", a.getState().toString()); try { TezCounters counters = a.getCounters(); Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames); if (counterMap != null && !counterMap.isEmpty()) { attemptInfo.put("counters", counterMap); } } catch (LimitExceededException e) { // Ignore // TODO: add an error message instead for counter key } attemptsInfo.add(attemptInfo); } renderJSON(ImmutableMap.of("attempts", attemptsInfo)); }