internal NumberFormatInfo(Locale locale) { _locale = locale; _numbers = NumberFormat.GetNumberInstance(locale); _symbols = new DecimalFormatSymbols(locale) { Infinity = "Infinity" }; _decimals = _numbers as DecimalFormat ?? new DecimalFormat(); _decimals.DecimalFormatSymbols = _symbols; _currency = NumberFormat.GetCurrencyInstance(locale) as DecimalFormat ?? _decimals; _percent = NumberFormat.GetPercentInstance(locale) as DecimalFormat ?? _decimals; }
public int SentiAnalysis(string text) { // Annotation var annotation = new edu.stanford.nlp.pipeline.Annotation(text); pipeline.annotate(annotation); using (var stream = new ByteArrayOutputStream()) { pipeline.prettyPrint(annotation, new PrintWriter(stream)); int mainSentiment = 0; int longest = 0; String[] sentimentText = { "Very Negative", "Negative", "Neutral", "Positive", "Very Positive" }; NumberFormat NF = new DecimalFormat("0.0000"); var sentences = annotation.get(new CoreAnnotations.SentencesAnnotation().getClass()) as ArrayList; foreach (CoreMap sentence in sentences) { Tree tree = (Tree)sentence.get(typeof(SentimentCoreAnnotations.SentimentAnnotatedTree)); int sentiment = edu.stanford.nlp.neural.rnn.RNNCoreAnnotations.getPredictedClass(tree); String partText = sentence.ToString(); try { } catch (IndexOutOfRangeException e) { } if (partText.Length > longest) { mainSentiment = sentiment; longest = partText.Length; } return(sentiment); } } return(-1); }
/// <summary>A helper function for dumping the accuracy of the trained classifier.</summary> /// <param name="classifier">The classifier to evaluate.</param> /// <param name="dataset">The dataset to evaluate the classifier on.</param> public static void DumpAccuracy(IClassifier <ClauseSplitter.ClauseClassifierLabel, string> classifier, GeneralDataset <ClauseSplitter.ClauseClassifierLabel, string> dataset) { DecimalFormat df = new DecimalFormat("0.00%"); Redwood.Log("size: " + dataset.Size()); Redwood.Log("split count: " + StreamSupport.Stream(dataset.Spliterator(), false).Filter(null).Collect(Collectors.ToList()).Count); Redwood.Log("interm count: " + StreamSupport.Stream(dataset.Spliterator(), false).Filter(null).Collect(Collectors.ToList()).Count); Pair <double, double> pr = classifier.EvaluatePrecisionAndRecall(dataset, ClauseSplitter.ClauseClassifierLabel.ClauseSplit); Redwood.Log("p (split): " + df.Format(pr.first)); Redwood.Log("r (split): " + df.Format(pr.second)); Redwood.Log("f1 (split): " + df.Format(2 * pr.first * pr.second / (pr.first + pr.second))); pr = classifier.EvaluatePrecisionAndRecall(dataset, ClauseSplitter.ClauseClassifierLabel.ClauseInterm); Redwood.Log("p (interm): " + df.Format(pr.first)); Redwood.Log("r (interm): " + df.Format(pr.second)); Redwood.Log("f1 (interm): " + df.Format(2 * pr.first * pr.second / (pr.first + pr.second))); }
public ValueEval Evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) { if (args.Length != 1 && args.Length != 2) { return(ErrorEval.VALUE_INVALID); } try { double val = singleOperandEvaluate(args[0], srcRowIndex, srcColumnIndex); double d1 = args.Length == 1 ? 2.0 : singleOperandEvaluate(args[1], srcRowIndex, srcColumnIndex); // second arg converts to int by truncating toward zero int nPlaces = (int)d1; if (nPlaces > 127) { return(ErrorEval.VALUE_INVALID); } if (nPlaces < 0) { d1 = Math.Abs(d1); double temp = val / Math.Pow(10, d1); temp = Math.Round(temp, 0); val = temp * Math.Pow(10, d1); } StringBuilder decimalPlacesFormat = new StringBuilder(); if (nPlaces > 0) { decimalPlacesFormat.Append('.'); } for (int i = 0; i < nPlaces; i++) { decimalPlacesFormat.Append('0'); } StringBuilder decimalFormatString = new StringBuilder(); decimalFormatString.Append("$#,##0").Append(decimalPlacesFormat) .Append(";($#,##0").Append(decimalPlacesFormat).Append(')'); DecimalFormat df = new DecimalFormat(decimalFormatString.ToString()); return(new StringEval(df.Format(val))); } catch (EvaluationException e) { return(e.GetErrorEval()); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private util.Bits getBinaryDocsWithField(index.FieldInfo fieldInfo) throws java.io.IOException private Bits getBinaryDocsWithField(FieldInfo fieldInfo) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final OneField field = fields.get(fieldInfo.name); OneField field = fields[fieldInfo.name]; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final store.IndexInput in = data.clone(); IndexInput @in = data.clone(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final util.BytesRef scratch = new util.BytesRef(); BytesRef scratch = new BytesRef(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.text.DecimalFormat decoder = new java.text.DecimalFormat(field.pattern, new java.text.DecimalFormatSymbols(java.util.Locale.ROOT)); DecimalFormat decoder = new DecimalFormat(field.pattern, new DecimalFormatSymbols(Locale.ROOT)); return(new BitsAnonymousInnerClassHelper2(this, field, @in, scratch, decoder)); }
private BigDecimal nDigitFormat(BigDecimal value, int scale) { /* * I needed 123,45, locale independent.I tried * NumberFormat.getCurrencyInstance().format( 12345.6789 ); but that is * locale specific.I also tried DecimalFormat df = new DecimalFormat( * "0,00" ); df.setDecimalSeparatorAlwaysShown(true); * df.setGroupingUsed(false); DecimalFormatSymbols symbols = new * DecimalFormatSymbols(); symbols.setDecimalSeparator(','); * symbols.setGroupingSeparator(' '); * df.setDecimalFormatSymbols(symbols); * * but that would not switch off grouping. Although I liked very much * the (incomplete) "BNF diagram" in * http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html * in the end I decided to calculate myself and take eur+sparator+cents * * This function will cut off, i.e. floor() subcent values Tests: * System.err.println(utils.currencyFormat(new BigDecimal(0), * ".")+"\n"+utils.currencyFormat(new BigDecimal("-1.10"), * ",")+"\n"+utils.currencyFormat(new BigDecimal("-1.1"), * ",")+"\n"+utils.currencyFormat(new BigDecimal("-1.01"), * ",")+"\n"+utils.currencyFormat(new BigDecimal("20000123.3489"), * ",")+"\n"+utils.currencyFormat(new BigDecimal("20000123.3419"), * ",")+"\n"+utils.currencyFormat(new BigDecimal("12"), ",")); * * results 0.00 -1,10 -1,10 -1,01 20000123,34 20000123,34 12,00 */ value = value.setScale(scale, BigDecimal.ROUND_HALF_UP); // first, round // so that // e.g. // 1.189999999999999946709294817992486059665679931640625 // becomes // 1.19 char[] repeat = new char[scale]; Arrays.fill(repeat, '0'); DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(); otherSymbols.setDecimalSeparator('.'); DecimalFormat dec = new DecimalFormat("0." + new String(repeat), otherSymbols); return(new BigDecimal(dec.format(value))); }
/*** * MUST represent all integer numbers (those with a zero-valued fractional part) * without a leading minus sign when the value is zero, and * without a decimal point, and * without an exponent * * MUST represent all non-integer numbers in exponential notation * including a nonzero single-digit significant integer part, and * including a nonempty significant fractional part, and * including no trailing zeroes in the significant fractional part (other than as part of a ".0" required to satisfy the preceding point), and * including a capital "E", and * including no plus sign in the exponent, and * including no insignificant leading zeroes in the exponent * @param bd * @throws IOException */ private void SerializeNumber(string value) { BigDecimal bd = new BigDecimal(value); try { //attempt converting to fixed number buffer.append(bd.toBigIntegerExact().toString()); } catch (java.lang.ArithmeticException) { NumberFormat formatter = new DecimalFormat("0.0E0"); formatter.setMinimumFractionDigits(1); formatter.setMaximumFractionDigits(bd.precision()); string val = formatter.format(bd).Replace("+", ""); buffer.append(val); } }
/// <summary> /// Display result in TextView /// </summary> private void DisplaySuccess(MLFace mFace) { DecimalFormat decimalFormat = new DecimalFormat("0.000"); string result = "Left eye open Probability: " + decimalFormat.Format(mFace.Features.LeftEyeOpenProbability); result += "\nRight eye open Probability: " + decimalFormat.Format(mFace.Features.RightEyeOpenProbability); result += "\nMoustache Probability: " + decimalFormat.Format(mFace.Features.MoustacheProbability); result += "\nGlass Probability: " + decimalFormat.Format(mFace.Features.SunGlassProbability); result += "\nHat Probability: " + decimalFormat.Format(mFace.Features.HatProbability); result += "\nAge: " + mFace.Features.Age; result += "\nGender: " + ((mFace.Features.SexProbability > 0.5f) ? "Female" : "Male"); result += "\nRotationAngleY: " + decimalFormat.Format(mFace.RotationAngleY); result += "\nRotationAngleZ: " + decimalFormat.Format(mFace.RotationAngleZ); result += "\nRotationAngleX: " + decimalFormat.Format(mFace.RotationAngleX); this.mTextView.Text = (result); }
public void TestSetDefaultNumberFormat() { IRow row = wb.GetSheetAt(0).GetRow(3); List <ICell> cells = row.Cells; FormatBase defaultFormat = new DecimalFormat("Balance $#,#00.00 USD;Balance -$#,#00.00 USD"); formatter.SetDefaultNumberFormat(defaultFormat); Random rand = new Random((int)DateTime.Now.ToFileTime()); log("\n==== DEFAULT NUMBER FORMAT ===="); foreach (ICell cell in cells) { cell.SetCellValue(cell.NumericCellValue * rand.Next() / 1000000 - 1000); log(formatter.FormatCellValue(cell)); Assert.IsTrue(formatter.FormatCellValue(cell).StartsWith("Balance ")); Assert.IsTrue(formatter.FormatCellValue(cell).EndsWith(" USD")); } }
public static String FormatBytes(long bytes) { long inputBytes = bytes; BigDecimal bigBytes = new BigDecimal(bytes); NumberFormat numberFormat = new DecimalFormat(); numberFormat.MaximumFractionDigits = 1; int index; for (index = 0; index < BYTES_UNIT_LIST.Length; index++) { if (inputBytes < CONVERSION_BASE) { break; } inputBytes /= CONVERSION_BASE; } return(numberFormat.Format(bigBytes.Divide(new BigDecimal(BASE_LIST[index]))) + " " + BYTES_UNIT_LIST[index]); }
/// <summary> /// Formats a decimal object into a 0.0 object or an empty string /// </summary> /// <param name="o">The object</param> /// <param name="fIncludeZero">True to return an "0" for zero values.</param> /// <param name="fUseHHMM">True for hh:mm format</param> /// <returns></returns> public static string FormatDecimal(this object o, bool fUseHHMM, bool fIncludeZero = false) { if (o == null || o == System.DBNull.Value) { return(string.Empty); } Decimal d = Convert.ToDecimal(o, CultureInfo.CurrentCulture); // See if this user has a decimal preference // This is stored in the current session. It's a bit of a hack because hhmm vs. decimal is deeply embedded throughout the system, and in many cases there's no way to pass down the context if it's an explicit property. DecimalFormat df = DecimalFormat.Adaptive; // default if (HttpContext.Current?.Session?[MFBConstants.keyDecimalSettings] != null) { df = (DecimalFormat)HttpContext.Current.Session[MFBConstants.keyDecimalSettings]; } return((d == 0.0M && !fIncludeZero) ? string.Empty : (fUseHHMM ? d.ToHHMM() : d.ToString(df == DecimalFormat.Adaptive ? "#,##0.0#" : (df == DecimalFormat.OneDecimal ? "#,##0.0" : "#,##0.00"), CultureInfo.CurrentCulture))); }
/// <summary> /// Return a string matching all the outcome names with all the /// probabilities produced by the <code>eval(String[] context)</code> /// method. /// </summary> /// <param name="ocs"> A <code>double[]</code> as returned by the /// <code>eval(String[] context)</code> /// method. </param> /// <returns> String containing outcome names paired with the normalized /// probability (contained in the <code>double[] ocs</code>) /// for each one. </returns> public string getAllOutcomes(double[] ocs) { if (ocs.Length != outcomeNames.Length) { return ("The double array sent as a parameter to GISModel.getAllOutcomes() must not have been produced by this model."); } else { DecimalFormat df = new DecimalFormat("0.0000"); StringBuilder sb = new StringBuilder(ocs.Length * 2); sb.Append(outcomeNames[0]).Append("[").Append(df.format(ocs[0])).Append("]"); for (int i = 1; i < ocs.Length; i++) { sb.Append(" ").Append(outcomeNames[i]).Append("[").Append(df.format(ocs[i])).Append("]"); } return(sb.ToString()); } }
public static string doubleToScientificString(double number, int fractionDigits) { DecimalFormat decimalFormat = new DecimalFormat(); StringBuilder stringBuilder = new StringBuilder(5 + fractionDigits).append("0."); for (int i = 0; i < fractionDigits; i++) { stringBuilder.append('0'); } stringBuilder.append("E00"); decimalFormat.applyPattern(stringBuilder.toString()); string text = decimalFormat.format(number); int num = String.instancehelper_indexOf(text, 69); if (String.instancehelper_charAt(text, num + 1) != '-') { return(new StringBuilder().append(String.instancehelper_substring(text, 0, num + 1)).append('+').append(String.instancehelper_substring(text, num + 1)).toString()); } return(text); }
public virtual void ArrayToFile(double[] thisArray, string fileName) { PrintWriter file = null; NumberFormat nf = new DecimalFormat("0.000E0"); try { file = new PrintWriter(new FileOutputStream(fileName), true); } catch (IOException e) { log.Info("Caught IOException outputing List to file: " + e.Message); System.Environment.Exit(1); } foreach (double element in thisArray) { file.Print(nf.Format(element) + " "); } file.Close(); }
private void loadUI() { JPanel jPanel = new JPanel(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.text.DecimalFormat decimalFormat = (java.text.DecimalFormat)java.text.DecimalFormat.getInstance(java.util.Locale.ENGLISH).clone(); DecimalFormat decimalFormat = (DecimalFormat)DecimalFormat.getInstance(Locale.ENGLISH).clone(); decimalFormat.applyPattern("0"); this.o_progressBar = new JProgressBar(0, this.o_totalTimes); this.o_progressBar.StringPainted = true; this.o_descriptionLabel = new JLabel(); this.o_progressBar.addChangeListener(new ChangeListenerAnonymousInnerClass(this, decimalFormat)); jPanel.Border = BorderFactory.createEmptyBorder(10, 0, 0, 0); jPanel.Layout = new BoxLayout(jPanel, 1); jPanel.add(this.o_descriptionLabel); jPanel.add(Box.createVerticalStrut(5)); jPanel.add(this.o_progressBar); jPanel.add(Box.createVerticalStrut(5)); this.o_mainPanel.Border = BorderFactory.createEmptyBorder(8, 8, 8, 8); this.o_mainPanel.add(jPanel, "Center"); }
//------------------------------------------------------------------------- //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test(enabled = false) public void test_javaBroken() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: public virtual void test_javaBroken() { // uncomment system out to see how broken it is // very specific format instance needed DecimalFormat format = new DecimalFormat("#,##0.###", new DecimalFormatSymbols(Locale.ENGLISH)); Random random = new Random(1); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); AtomicInteger broken = new AtomicInteger(); int threadCount = 15; for (int i = 0; i < threadCount; i++) { ThreadStart runner = () => { try { latch.await(); int val = random.Next(999); string a = format.format((double)val); string b = Convert.ToInt32(val).ToString(); Console.WriteLine(a + " " + b); if (!a.Equals(b)) { broken.incrementAndGet(); } } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); } }; (new Thread(runner, "TestThread" + i)).Start(); } // start all threads together latch.Signal(); Thread.Sleep(1000); Console.WriteLine("Broken: " + broken.get()); assertTrue(broken.get() > 0); }
/// <summary> /// Formats a number or date cell, be that a real number, or the /// answer to a formula /// </summary> /// <param name="cell">The cell.</param> /// <param name="value">The value.</param> /// <returns></returns> private String FormatNumberDateCell(CellValueRecordInterface cell, double value) { // Get the built in format, if there is one int formatIndex = ft.GetFormatIndex(cell); String formatString = ft.GetFormatString(cell); if (formatString == null) { return(value.ToString(CultureInfo.InvariantCulture)); } else { // Is it a date? if (Npoi.Core.SS.UserModel.DateUtil.IsADateFormat(formatIndex, formatString) && Npoi.Core.SS.UserModel.DateUtil.IsValidExcelDate(value)) { // Java wants M not m for month formatString = formatString.Replace('m', 'M'); // Change \- into -, if it's there formatString = formatString.Replace("\\\\-", "-"); // Format as a date DateTime d = Npoi.Core.SS.UserModel.DateUtil.GetJavaDate(value, false); SimpleDateFormat df = new SimpleDateFormat(formatString); return(df.Format(d, CultureInfo.CurrentCulture)); } else { if (formatString == "General") { // Some sort of wierd default return(value.ToString(CultureInfo.InvariantCulture)); } // Format as a number DecimalFormat df = new DecimalFormat(formatString); return(df.Format(value, CultureInfo.CurrentCulture)); } } }
public void TestSetDefaultNumberFormat() { Row row = wb.GetSheetAt(0).GetRow(2); IEnumerator it = row.GetCellEnumerator(); FormatBase defaultFormat = new DecimalFormat("Balance $#,#00.00 USD;Balance -$#,#00.00 USD"); formatter.SetDefaultNumberFormat(defaultFormat); log("\n==== DEFAULT NUMBER FORMAT ===="); Random rand = new Random((int)DateTime.Now.ToFileTime()); while (it.MoveNext()) { Cell cell = (Cell)it.Current; cell.SetCellValue(cell.NumericCellValue * rand.Next() / 1000000 - 1000); string result = formatter.FormatCellValue(cell); log(result); Assert.IsTrue(result.StartsWith("Balance ")); Assert.IsTrue(result.EndsWith(" USD")); } }
public double PorcentajeVuelos(DtoRPorcentaje dto) { double porcentaje = 0; using (AlasPUMEntities context = new AlasPUMEntities()) { int vuelos = context.Vuelo.Select(s => s).Count(); List <Vuelo> colVuelo = context.Vuelo.Where(w => w.dtLlegada == dto.fechaInicio && w.dtSalida == dto.fechaFin).ToList(); int eso = colVuelo.Count(); porcentaje = (vuelos * eso) / 100; } DecimalFormat df = new DecimalFormat("#.00"); string total = df.Format(porcentaje); porcentaje = double.Parse(total); return(porcentaje); }
// no public constructor; use static methods instead public override string ToString() { NumberFormat nf = new DecimalFormat("0.0##E0"); IList <E> keyList = new List <E>(KeySet()); keyList.Sort(null); StringBuilder sb = new StringBuilder(); sb.Append("["); for (int i = 0; i < NumEntriesInString; i++) { if (keyList.Count <= i) { break; } E o = keyList[i]; double prob = ProbabilityOf(o); sb.Append(o).Append(":").Append(nf.Format(prob)).Append(" "); } sb.Append("]"); return(sb.ToString()); }
private DecimalFormat ResolveFormatName(string formatName) { string ns = string.Empty, local = string.Empty; if (formatName != null) { string prefix; PrefixQName.ParseQualifiedName(formatName, out prefix, out local); ns = LookupNamespace(prefix); } DecimalFormat formatInfo = this.processor.RootAction.GetDecimalFormat(new XmlQualifiedName(local, ns)); if (formatInfo == null) { if (formatName != null) { throw XsltException.Create(Res.Xslt_NoDecimalFormat, formatName); } formatInfo = new DecimalFormat(new NumberFormatInfo(), '#', '0', ';'); } return(formatInfo); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public index.SortedSetDocValues getSortedSet(index.FieldInfo fieldInfo) throws java.io.IOException public override SortedSetDocValues getSortedSet(FieldInfo fieldInfo) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final OneField field = fields.get(fieldInfo.name); OneField field = fields[fieldInfo.name]; // SegmentCoreReaders already verifies this field is // valid: Debug.Assert(field != null); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final store.IndexInput in = data.clone(); IndexInput @in = data.clone(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final util.BytesRef scratch = new util.BytesRef(); BytesRef scratch = new BytesRef(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.text.DecimalFormat decoder = new java.text.DecimalFormat(field.pattern, new java.text.DecimalFormatSymbols(java.util.Locale.ROOT)); DecimalFormat decoder = new DecimalFormat(field.pattern, new DecimalFormatSymbols(Locale.ROOT)); return(new SortedSetDocValuesAnonymousInnerClassHelper(this, field, @in, scratch, decoder)); }
/// <summary> /// Lists the applications matching the given application Types And application /// States present in the Resource Manager /// </summary> /// <param name="appTypes"/> /// <param name="appStates"/> /// <exception cref="Org.Apache.Hadoop.Yarn.Exceptions.YarnException"/> /// <exception cref="System.IO.IOException"/> private void ListApplications(ICollection <string> appTypes, EnumSet <YarnApplicationState > appStates) { PrintWriter writer = new PrintWriter(new OutputStreamWriter(sysout, Sharpen.Extensions.GetEncoding ("UTF-8"))); if (allAppStates) { foreach (YarnApplicationState appState in YarnApplicationState.Values()) { appStates.AddItem(appState); } } else { if (appStates.IsEmpty()) { appStates.AddItem(YarnApplicationState.Running); appStates.AddItem(YarnApplicationState.Accepted); appStates.AddItem(YarnApplicationState.Submitted); } } IList <ApplicationReport> appsReport = client.GetApplications(appTypes, appStates); writer.WriteLine("Total number of applications (application-types: " + appTypes + " and states: " + appStates + ")" + ":" + appsReport.Count); writer.Printf(ApplicationsPattern, "Application-Id", "Application-Name", "Application-Type" , "User", "Queue", "State", "Final-State", "Progress", "Tracking-URL"); foreach (ApplicationReport appReport in appsReport) { DecimalFormat formatter = new DecimalFormat("###.##%"); string progress = formatter.Format(appReport.GetProgress()); writer.Printf(ApplicationsPattern, appReport.GetApplicationId(), appReport.GetName (), appReport.GetApplicationType(), appReport.GetUser(), appReport.GetQueue(), appReport .GetYarnApplicationState(), appReport.GetFinalApplicationStatus(), progress, appReport .GetOriginalTrackingUrl()); } writer.Flush(); }
public override View GetView(int position, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater layoutInflater = (LayoutInflater)Application.Context.GetSystemService(Context.LayoutInflaterService); convertView = layoutInflater.Inflate(Resource.Layout.item_face_with_description, parent, false); } convertView.Id = position; // Show the face thumbnail. ((ImageView)convertView.FindViewById(Resource.Id.face_thumbnail)).SetImageBitmap( faceThumbnails[position]); if (mIdentifyResults.Count == faces.Count) { // Show the face details. DecimalFormat formatter = new DecimalFormat("#0.00"); if (mIdentifyResults[position].Candidates.Count > 0) { String personId = ((Candidate)mIdentifyResults[position].Candidates[0]).PersonId.ToString(); String personName = StorageHelper.GetPersonName( personId, activity.mPersonGroupId, activity); String identity = "Person: " + personName + "\n" + "Confidence: " + formatter.Format( ((Candidate)mIdentifyResults[position].Candidates[0]).Confidence); ((TextView)convertView.FindViewById(Resource.Id.text_detected_face)).Text = identity; } else { ((TextView)convertView.FindViewById(Resource.Id.text_detected_face)).Text = Application.Context.GetString(Resource.String.face_cannot_be_identified); } } return(convertView); }
/// <summary> /// 获取Cell字符串 /// </summary> /// <param name="cell"></param> /// <returns></returns> public static string GetCellString(ICell cell) { string cellValue = ""; if (null != cell) { // 以下是判断数据的类型 switch (cell.CellType) { case CellType.Numeric: // 数字 if (HSSFDateUtil.IsCellDateFormatted(cell)) { // 判断是否为日期类型 cellValue = cell.DateCellValue.ToString("yyyyMMdd HH:mm:ss"); } else { // 有些数字过大,直接输出使用的是科学计数法: 2.67458622E8 要进行处理 DecimalFormat df = new DecimalFormat("####.####"); cellValue = df.Format(cell.NumericCellValue); // cellValue = cell.getNumericCellValue() + ""; } break; case CellType.String: // 字符串 cellValue = cell.StringCellValue; break; case CellType.Boolean: // Boolean cellValue = cell.BooleanCellValue ? "1" : "0"; break; default: cellValue = "wuwuyaoyao"; break; } } return(cellValue); }
public virtual void PrintF1(Logger logger, bool printF1First) { NumberFormat nf = new DecimalFormat("0.0000"); double r = GetRecall(); double p = GetPrecision(); double f1 = GetF1(); string R = nf.Format(r); string P = nf.Format(p); string F1 = nf.Format(f1); NumberFormat nf2 = new DecimalFormat("00.0"); string Rr = nf2.Format(r * 100); string Pp = nf2.Format(p * 100); string F1f1 = nf2.Format(f1 * 100); if (printF1First) { string str = "F1 = " + F1 + ", P = " + P + " (" + (int)precisionNumSum + "/" + (int)precisionDenSum + "), R = " + R + " (" + (int)recallNumSum + "/" + (int)recallDenSum + ")"; if (scoreType == CorefScorer.ScoreType.Pairwise) { logger.Fine("Pairwise " + str); } else { if (scoreType == CorefScorer.ScoreType.BCubed) { logger.Fine("B cubed " + str); } else { logger.Fine("MUC " + str); } } } else { logger.Fine("& " + Pp + " & " + Rr + " & " + F1f1); } }
public string Localize(decimal input, DecimalFormat format) { var roundRule = MidpointRounding.AwayFromZero; switch (format) { case DecimalFormat.AsWeightInGrams: return(Math.Round(input, 3, roundRule).ToString("n3", _currentCulture)); case DecimalFormat.AsWeightInHectograms: return(Math.Round(input, 1, roundRule).ToString("n1", _currentCulture)); case DecimalFormat.AsMoney: return(Math.Round(input, 2, roundRule).ToString("n2", _currentCulture)); case DecimalFormat.AsNumber: return(Math.Round(input, 2, roundRule).ToString("n2", _currentCulture)); case DecimalFormat.WithFiveDecPlaces: return(Math.Round(input, 5, roundRule).ToString("n5", _currentCulture)); case DecimalFormat.WithZeroDecPlaces: return(Math.Round(input, 0, roundRule).ToString("n0", _currentCulture)); case DecimalFormat.WithFourDecPlaces: return(Math.Round(input, 4, roundRule).ToString("n4", _currentCulture)); default: throw new ArgumentException("Localize decimal unknown mode"); } }
public static void Main(string[] args) { if (args.Length == 0) { Console.Error.WriteLine("Usage: GISModel modelname < contexts"); Environment.Exit(1); } AbstractModel m = (new SuffixSensitiveGISModelReader(new Jfile(args[0]))).Model; BufferedReader @in = new BufferedReader(new InputStreamReader(new InputStream(Console.OpenStandardInput()))); // TODO get from System.in DecimalFormat df = new DecimalFormat(".###"); for (string line = @in.readLine(); line != null; line = @in.readLine()) { string[] context = line.Split(" ", true); double[] dist = m.eval(context); for (int oi = 0; oi < dist.Length; oi++) { Console.Write("[" + m.getOutcome(oi) + " " + df.format(dist[oi]) + "] "); } Console.WriteLine(); } }
/** * 转换文件大小 * * @param fileLen 单位B * @return */ public static string formatFileSizeToString(long fileLen) { DecimalFormat df = new DecimalFormat("0.00"); string fileSizestring = ""; if (fileLen < 1024) { fileSizestring = df.Format((double)fileLen) + "B"; } else if (fileLen < 1048576) { fileSizestring = df.Format((double)fileLen / 1024) + "K"; } else if (fileLen < 1073741824) { fileSizestring = df.Format((double)fileLen / 1048576) + "M"; } else { fileSizestring = df.Format((double)fileLen / 1073741824) + "G"; } return(fileSizestring); }
private void PrintQueueInfo(PrintWriter writer, QueueInfo queueInfo) { writer.Write("Queue Name : "); writer.WriteLine(queueInfo.GetQueueName()); writer.Write("\tState : "); writer.WriteLine(queueInfo.GetQueueState()); DecimalFormat df = new DecimalFormat("#.0"); writer.Write("\tCapacity : "); writer.WriteLine(df.Format(queueInfo.GetCapacity() * 100) + "%"); writer.Write("\tCurrent Capacity : "); writer.WriteLine(df.Format(queueInfo.GetCurrentCapacity() * 100) + "%"); writer.Write("\tMaximum Capacity : "); writer.WriteLine(df.Format(queueInfo.GetMaximumCapacity() * 100) + "%"); writer.Write("\tDefault Node Label expression : "); if (null != queueInfo.GetDefaultNodeLabelExpression()) { writer.WriteLine(queueInfo.GetDefaultNodeLabelExpression()); } else { writer.WriteLine(); } ICollection <string> nodeLabels = queueInfo.GetAccessibleNodeLabels(); StringBuilder labelList = new StringBuilder(); writer.Write("\tAccessible Node Labels : "); foreach (string nodeLabel in nodeLabels) { if (labelList.Length > 0) { labelList.Append(','); } labelList.Append(nodeLabel); } writer.WriteLine(labelList.ToString()); }
private void OutputStatistics() { DecimalFormat formatPercentage = new DecimalFormat("##.##"); DecimalFormat formatCount = new DecimalFormat("###,###"); long totalCount = _readCount + _writeCount + _syncCount + _seekCount; string totalCountString = formatCount.Format(totalCount); double readCountPercentage = CountPercentage(_readCount, totalCount); string readCountPercentageString = formatPercentage.Format(readCountPercentage); double writeCountPercentage = CountPercentage(_writeCount, totalCount); string writeCountPercentageString = formatPercentage.Format(writeCountPercentage); double syncCountPercentage = CountPercentage(_syncCount, totalCount); string syncCountPercentageString = formatPercentage.Format(syncCountPercentage); double seekCountPercentage = CountPercentage(_seekCount, totalCount); string seekCountPercentageString = formatPercentage.Format(seekCountPercentage); long totalBytes = _readBytes + _writeBytes; string totalBytesString = formatCount.Format(totalBytes); double readBytesPercentage = CountPercentage(_readBytes, totalBytes); string readBytesPercentageString = formatPercentage.Format(readBytesPercentage); double writeBytesPercentage = CountPercentage(_writeBytes, totalBytes); string writeBytesPercentageString = formatPercentage.Format(writeBytesPercentage); string readCountString = formatCount.Format(_readCount); string writeCountString = formatCount.Format(_writeCount); string syncCountString = formatCount.Format(_syncCount); string seekCountString = formatCount.Format(_seekCount); string readBytesString = formatCount.Format(_readBytes); string writeBytesString = formatCount.Format(_writeBytes); PrintHeader(); _out.WriteLine("<tr><td>Reads</td><td></td><td align=\"right\">" + readCountString + "</td><td></td><td align=\"right\">" + readCountPercentageString + "</td><td></td><td align=\"right\">" + readBytesString + "</td><td></td><td align=\"right\">" + readBytesPercentageString + "</td></tr>"); _out.WriteLine("<tr><td>Writes</td><td></td><td align=\"right\">" + writeCountString + "</td><td></td><td align=\"right\">" + writeCountPercentageString + "</td><td></td><td align=\"right\">" + writeBytesString + "</td><td></td><td align=\"right\">" + writeBytesPercentageString + "</td></tr>"); _out.WriteLine("<tr><td>Seeks</td><td></td><td align=\"right\">" + seekCountString + "</td><td></td><td align=\"right\">" + seekCountPercentageString + "</td><td></td><td></td></tr>" ); _out.WriteLine("<tr><td>Syncs</td><td></td><td align=\"right\">" + syncCountString + "</td><td></td><td align=\"right\">" + syncCountPercentageString + "</td><td></td><td></td></tr>" ); _out.WriteLine("<tr><td colspan=\"9\"></td></tr>"); _out.WriteLine("<tr><td>Total</td><td></td><td align=\"right\">" + totalCountString + "</td><td></td><td></td><td></td><td>" + totalBytesString + "</td><td></td></tr>" ); _out.WriteLine("</table>"); double avgBytesPerRead = _readBytes / _readCount; string avgBytesPerReadString = formatCount.Format(avgBytesPerRead); double avgBytesPerWrite = _writeBytes / _writeCount; string avgBytesPerWriteString = formatCount.Format(avgBytesPerWrite); _out.WriteLine("<p>"); _out.WriteLine("Average byte count per read: " + avgBytesPerReadString); _out.WriteLine("<br>"); _out.WriteLine("Average byte count per write: " + avgBytesPerWriteString); _out.WriteLine("</p>"); PrintFooter(); }
public override ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) { double s0; String s1; try { s0 = TextFunction.EvaluateDoubleArg(arg0, srcRowIndex, srcColumnIndex); s1 = TextFunction.EvaluateStringArg(arg1, srcRowIndex, srcColumnIndex); } catch (EvaluationException e) { return e.GetErrorEval(); } if (Regex.Match(s1, "[y|m|M|d|s|h]+").Success) { //may be datetime string ValueEval result = TryParseDateTime(s0, s1); if (result != ErrorEval.VALUE_INVALID) return result; } //The regular expression needs ^ and $. if (Regex.Match(s1, @"^[\d,\#,\.,\$,\,]+$").Success) { //TODO: simulate DecimalFormat class in java. FormatBase formatter = new DecimalFormat(s1); return new StringEval(formatter.Format(s0)); } else if (s1.IndexOf("/", StringComparison.Ordinal) == s1.LastIndexOf("/", StringComparison.Ordinal) && s1.IndexOf("/", StringComparison.Ordinal) >= 0 && !s1.Contains("-")) { double wholePart = Math.Floor(s0); double decPart = s0 - wholePart; if (wholePart * decPart == 0) { return new StringEval("0"); } String[] parts = s1.Split(' '); String[] fractParts; if (parts.Length == 2) { fractParts = parts[1].Split('/'); } else { fractParts = s1.Split('/'); } if (fractParts.Length == 2) { double minVal = 1.0; double currDenom = Math.Pow(10, fractParts[1].Length) - 1d; double currNeum = 0; for (int i = (int)(Math.Pow(10, fractParts[1].Length) - 1d); i > 0; i--) { for (int i2 = (int)(Math.Pow(10, fractParts[1].Length) - 1d); i2 > 0; i2--) { if (minVal >= Math.Abs((double)i2 / (double)i - decPart)) { currDenom = i; currNeum = i2; minVal = Math.Abs((double)i2 / (double)i - decPart); } } } FormatBase neumFormatter = new DecimalFormat(fractParts[0]); FormatBase denomFormatter = new DecimalFormat(fractParts[1]); if (parts.Length == 2) { FormatBase wholeFormatter = new DecimalFormat(parts[0]); String result = wholeFormatter.Format(wholePart) + " " + neumFormatter.Format(currNeum) + "/" + denomFormatter.Format(currDenom); return new StringEval(result); } else { String result = neumFormatter.Format(currNeum + (currDenom * wholePart)) + "/" + denomFormatter.Format(currDenom); return new StringEval(result); } } else { return ErrorEval.VALUE_INVALID; } } else { return TryParseDateTime(s0, s1); } }
public static UIData<decimal> Validate(this UIData<decimal> item, DecimalFormat format = DecimalFormat.Plain, string requiredMessage = "") { if (item == null) { item = new UIData<decimal>(0, Types.Decimal); } bool isGood = Constants.YES; string message = string.Empty; bool required = (requiredMessage.Length != 0); if (required && item.Value == 0) { isGood = Constants.NO; message = (requiredMessage.Length == 0 ? "Value required" : requiredMessage); } item.IsValid = isGood; item.Message = message; return item; }
/// <summary> /// Converts a JSON-LD value object to an RDF literal or a JSON-LD string or /// node object to an RDF resource. /// </summary> /// <remarks> /// Converts a JSON-LD value object to an RDF literal or a JSON-LD string or /// node object to an RDF resource. /// </remarks> /// <param name="item">the JSON-LD value or node object.</param> /// <param name="namer">the UniqueNamer to use to assign blank node names.</param> /// <returns>the RDF literal or RDF resource.</returns> private static JObject ObjectToRDF(JToken item, UniqueNamer namer) { JObject @object = new JObject(); // convert value object to RDF if (JsonLdUtils.IsValue(item)) { @object["type"] = "literal"; JToken value = ((JObject)item)["@value"]; JToken datatype = ((JObject)item)["@type"]; // convert to XSD datatypes as appropriate if (value.Type == JTokenType.Boolean || value.Type == JTokenType.Float || value.Type == JTokenType.Integer ) { // convert to XSD datatype if (value.Type == JTokenType.Boolean) { @object["value"] = value.ToString(); @object["datatype"] = datatype.IsNull() ? JSONLDConsts.XsdBoolean : datatype; } else { if (value.Type == JTokenType.Float) { // canonical double representation @object["value"] = string.Format("{0:0.0###############E0}", (double)value); @object["datatype"] = datatype.IsNull() ? JSONLDConsts.XsdDouble : datatype; } else { DecimalFormat df = new DecimalFormat("0"); @object["value"] = df.Format((int)value); @object["datatype"] = datatype.IsNull() ? JSONLDConsts.XsdInteger : datatype; } } } else { if (((IDictionary<string, JToken>)item).ContainsKey("@language")) { @object["value"] = value; @object["datatype"] = datatype.IsNull() ? JSONLDConsts.RdfLangstring : datatype; @object["language"] = ((IDictionary<string, JToken>)item)["@language"]; } else { @object["value"] = value; @object["datatype"] = datatype.IsNull() ? JSONLDConsts.XsdString : datatype; } } } else { // convert string/node object to RDF string id = JsonLdUtils.IsObject(item) ? (string)((JObject)item )["@id"] : (string)item; if (id.IndexOf("_:") == 0) { @object["type"] = "blank node"; @object["value"] = namer.GetName(id); } else { @object["type"] = "IRI"; @object["value"] = id; } } return @object; }
/// <summary> /// Formats a number or date cell, be that a real number, or the /// answer to a formula /// </summary> /// <param name="cell">The cell.</param> /// <param name="value">The value.</param> /// <returns></returns> private String FormatNumberDateCell(CellValueRecordInterface cell, double value) { // Get the built in format, if there is one int formatIndex = ft.GetFormatIndex(cell); String formatString = ft.GetFormatString(cell); if (formatString == null) { return value.ToString(CultureInfo.InvariantCulture); } else { // Is it a date? if (LF.Utils.NPOI.SS.UserModel.DateUtil.IsADateFormat(formatIndex, formatString) && LF.Utils.NPOI.SS.UserModel.DateUtil.IsValidExcelDate(value)) { // Java wants M not m for month formatString = formatString.Replace('m', 'M'); // Change \- into -, if it's there formatString = formatString.Replace("\\\\-", "-"); // Format as a date DateTime d = LF.Utils.NPOI.SS.UserModel.DateUtil.GetJavaDate(value, false); SimpleDateFormat df = new SimpleDateFormat(formatString); return df.Format(d); } else { if (formatString == "General") { // Some sort of wierd default return value.ToString(CultureInfo.InvariantCulture); } // Format as a number DecimalFormat df = new DecimalFormat(formatString); return df.Format(value); } } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public void listSegments() throws java.io.IOException public virtual void listSegments() { DecimalFormat formatter = new DecimalFormat("###,###.###", DecimalFormatSymbols.getInstance(Locale.ROOT)); for (int x = 0; x < infos.size(); x++) { SegmentCommitInfo info = infos.info(x); string sizeStr = formatter.format(info.sizeInBytes()); Console.WriteLine(info.info.name + " " + sizeStr); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public void test10kPulsed() throws Exception public virtual void test10kPulsed() { // we always run this test with pulsing codec. Codec cp = TestUtil.alwaysPostingsFormat(new Pulsing41PostingsFormat(1)); File f = createTempDir("10kpulsed"); BaseDirectoryWrapper dir = newFSDirectory(f); dir.CheckIndexOnClose = false; // we do this ourselves explicitly RandomIndexWriter iw = new RandomIndexWriter(random(), dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setCodec(cp)); Document document = new Document(); FieldType ft = new FieldType(TextField.TYPE_STORED); switch (TestUtil.Next(random(), 0, 2)) { case 0: ft.IndexOptions = IndexOptions.DOCS_ONLY; break; case 1: ft.IndexOptions = IndexOptions.DOCS_AND_FREQS; break; default: ft.IndexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS; break; } Field field = newField("field", "", ft); document.add(field); NumberFormat df = new DecimalFormat("00000", new DecimalFormatSymbols(Locale.ROOT)); for (int i = 0; i < 10050; i++) { field.StringValue = df.format(i); iw.addDocument(document); } IndexReader ir = iw.Reader; iw.close(); TermsEnum te = MultiFields.getTerms(ir, "field").iterator(null); DocsEnum de = null; for (int i = 0; i < 10050; i++) { string expected = df.format(i); assertEquals(expected, te.next().utf8ToString()); de = TestUtil.docs(random(), te, null, de, DocsEnum.FLAG_NONE); assertTrue(de.nextDoc() != DocIdSetIterator.NO_MORE_DOCS); assertEquals(DocIdSetIterator.NO_MORE_DOCS, de.nextDoc()); } ir.close(); TestUtil.checkIndex(dir); dir.close(); }
private void ShowNotification() { Log.Debug(logTag, "GpsService.ShowNotification called"); Intent intent = new Intent(this, typeof(MainActivity)); PendingIntent pendingintent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.UpdateCurrent); DecimalFormat decimalformat = new DecimalFormat("###.######"); ; string s = "Waiting for next location. Please wait..."; if (Session.hasValidLocation()) { s = String.Format("Lat {0} Lon {1}", decimalformat.Format(Session.getCurrentLatitude()), decimalformat.Format(Session.getCurrentLongitude())); } // Build the notification NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .SetAutoCancel(true) // dismiss the notification from the notification area when the user clicks on it //.SetContentIntent(pendingintent) // start up this activity when the user clicks the intent. .SetContentTitle("in1go Tracker running...") // Set the title .SetSmallIcon(Resource.Drawable.icon) // This is the icon to display .SetContentText(s); // the message to display. gpsNotifyManager.Notify(NOTIFICATION_ID, builder.Build()); StartForeground(NOTIFICATION_ID, builder.Build()); }
/// <summary> /// a variant, that uses pulsing, but uses a high TF to force pass thru to the underlying codec /// </summary> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public void test10kNotPulsed() throws Exception public virtual void test10kNotPulsed() { // we always run this test with pulsing codec. int freqCutoff = TestUtil.Next(random(), 1, 10); Codec cp = TestUtil.alwaysPostingsFormat(new Pulsing41PostingsFormat(freqCutoff)); File f = createTempDir("10knotpulsed"); BaseDirectoryWrapper dir = newFSDirectory(f); dir.CheckIndexOnClose = false; // we do this ourselves explicitly RandomIndexWriter iw = new RandomIndexWriter(random(), dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setCodec(cp)); Document document = new Document(); FieldType ft = new FieldType(TextField.TYPE_STORED); switch (TestUtil.Next(random(), 0, 2)) { case 0: ft.IndexOptions = IndexOptions.DOCS_ONLY; break; case 1: ft.IndexOptions = IndexOptions.DOCS_AND_FREQS; break; default: ft.IndexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS; break; } Field field = newField("field", "", ft); document.add(field); NumberFormat df = new DecimalFormat("00000", new DecimalFormatSymbols(Locale.ROOT)); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final int freq = freqCutoff + 1; int freq = freqCutoff + 1; for (int i = 0; i < 10050; i++) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < freq; j++) { sb.Append(df.format(i)); sb.Append(' '); // whitespace } field.StringValue = sb.ToString(); iw.addDocument(document); } IndexReader ir = iw.Reader; iw.close(); TermsEnum te = MultiFields.getTerms(ir, "field").iterator(null); DocsEnum de = null; for (int i = 0; i < 10050; i++) { string expected = df.format(i); assertEquals(expected, te.next().utf8ToString()); de = TestUtil.docs(random(), te, null, de, DocsEnum.FLAG_NONE); assertTrue(de.nextDoc() != DocIdSetIterator.NO_MORE_DOCS); assertEquals(DocIdSetIterator.NO_MORE_DOCS, de.nextDoc()); } ir.close(); TestUtil.checkIndex(dir); dir.close(); }