Here are the examples of the csharp api double.ToString(System.IFormatProvider) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
840 Examples
19
View Source File : ExprPlainWriter.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public void VisitPlainProperty(string name, double? value, int ctx)
{
this._buffer.Add(this._factory(ctx, ctx, null, false, name, value?.ToString(CultureInfo.InvariantCulture)));
}
19
View Source File : ExpressionResolver.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
private static void ResolveInForGeneric(StringBuilder sqlBuilder, string columnName, Expression exp, Type valueType, bool notContainer = false)
{
var value = ResolveDynamicInvoke(exp);
var isValueType = false;
var list = new List<string>();
if (valueType.IsEnum)
{
isValueType = true;
var valueList = (IEnumerable)value;
if (valueList != null)
{
foreach (var c in valueList)
{
list.Add(Enum.Parse(valueType, c.ToString()!).ToInt().ToString());
}
}
}
else
{
var typeName = valueType.Name;
switch (typeName)
{
case "Guid":
if (value is IEnumerable<Guid> guidValues)
{
foreach (var c in guidValues)
{
list.Add(c.ToString());
}
}
break;
case "DateTime":
if (value is IEnumerable<DateTime> dateTimeValues)
{
foreach (var c in dateTimeValues)
{
list.Add(c.ToString("yyyy-MM-dd HH:mm:ss"));
}
}
break;
case "Byte":
isValueType = true;
if (value is IEnumerable<byte> byteValues)
{
foreach (var c in byteValues)
{
list.Add(c.ToString(CultureInfo.InvariantCulture));
}
}
break;
case "Char":
if (value is IEnumerable<char> charValues)
{
foreach (var c in charValues)
{
list.Add(c.ToString());
}
}
break;
case "Int16":
isValueType = true;
if (value is IEnumerable<short> shortValues)
{
foreach (var c in shortValues)
{
list.Add(c.ToString());
}
}
break;
case "Int32":
isValueType = true;
if (value is IEnumerable<int> intValues)
{
foreach (var c in intValues)
{
list.Add(c.ToString());
}
}
break;
case "Int64":
isValueType = true;
if (value is IEnumerable<long> longValues)
{
foreach (var c in longValues)
{
list.Add(c.ToString());
}
}
break;
case "Double":
isValueType = true;
if (value is IEnumerable<double> doubleValues)
{
foreach (var c in doubleValues)
{
list.Add(c.ToString(CultureInfo.InvariantCulture));
}
}
break;
case "Single":
isValueType = true;
if (value is IEnumerable<float> floatValues)
{
foreach (var c in floatValues)
{
list.Add(c.ToString(CultureInfo.InvariantCulture));
}
}
break;
case "Decimal":
isValueType = true;
if (value is IEnumerable<decimal> decimalValues)
{
foreach (var c in decimalValues)
{
list.Add(c.ToString(CultureInfo.InvariantCulture));
}
}
break;
}
}
if (list!.Count < 1)
return;
sqlBuilder.Append(columnName);
sqlBuilder.Append(notContainer ? " NOT IN (" : " IN (");
//值类型不带引号
if (isValueType)
{
for (var i = 0; i < list.Count; i++)
{
sqlBuilder.AppendFormat("{0}", list[i]);
if (i != list.Count - 1)
{
sqlBuilder.Append(",");
}
}
}
else
{
for (var i = 0; i < list.Count; i++)
{
sqlBuilder.AppendFormat("'{0}'", list[i].Replace("'", "''"));
if (i != list.Count - 1)
{
sqlBuilder.Append(",");
}
}
}
sqlBuilder.Append(")");
}
19
View Source File : TimestampConverter.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (writer == null) throw new ArgumentNullException(nameof(writer));
if (quotes)
writer.WriteValue(Math.Round(((DateTime)value - new DateTime(1970, 1, 1)).TotalMilliseconds));
else
writer.WriteRawValue(Math.Round(((DateTime)value - new DateTime(1970, 1, 1)).TotalMilliseconds).ToString(CultureInfo.InvariantCulture));
}
19
View Source File : HistogramViewModel.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private IRenderableSeriesViewModel GenerateColumn(double startsAt, double[] data, string styleKey)
{
var dataSeries = new UniformXyDataSeries<double>(startsAt, 0.25);
dataSeries.Append(data);
// Annotations for text labels
for (int i = 0; i < data.Length; i++)
{
ChartLabels.Add(new HistogramLabelViewModel(startsAt + (0.25 * i), data[i], data[i].ToString(CultureInfo.InvariantCulture)));
}
return new ColumnRenderableSeriesViewModel
{
DataSeries = dataSeries,
StyleKey = styleKey,
};
}
19
View Source File : Sheet.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
public static string GetScaleBarScale(Element replacedleBlock)
{
if (replacedleBlock == null)
{
return string.Empty;
}
try
{
var p = replacedleBlock.GetParameters(Settings1.Default.ScalebarScaleParameter);
if (p == null || p.Count < 1)
{
return string.Empty;
}
double d = p[0].AsDouble();
return d.ToString(CultureInfo.InvariantCulture);
}
catch (FormatException)
{
return string.Empty;
}
}
19
View Source File : StaduimSeatingTier.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
[SuppressMessage("ReSharper", "BitwiseOperatorOnEnumWithoutFlags", Justification = "Revit API...")]
public void Draw()
{
using (var t = new Transaction(doc, "Create sight line view"))
{
t.Start();
string times = DateTime.Now.Ticks.ToString(CultureInfo.CurrentCulture);
view = CreateLineOfSightDraftingView(
"LOS-X" + distanceToFirstRowX + "-Y" + distanceToFirstRowY + "-T" +
TreadSize + "-MinN" + MinimumRiserHeight + "-Inc" + RiserIncrement +
"-Eye" + EyeHeight + "-MinC" + MinimumCValue + "_" + times);
view.Scale = 50;
int i;
for (i = 0; i < NumberOfRows; i++)
{
if (i == 0)
{
DrawLine(0, 0, distanceToFirstRowX, 0, "Thin Lines");
DrawText(
distanceToFirstRowX / 2,
0,
distanceToFirstRowX.ToString(CultureInfo.InvariantCulture),
TextAlignFlags.TEF_ALIGN_CENTER | TextAlignFlags.TEF_ALIGN_TOP);
DrawText(
distanceToFirstRowX,
distanceToFirstRowY / 2,
distanceToFirstRowY.ToString(CultureInfo.InvariantCulture),
TextAlignFlags.TEF_ALIGN_CENTER | TextAlignFlags.TEF_ALIGN_BOTTOM);
}
// Draw the sight line
DrawLine(0, 0, rows[i].EyeToFocusX, rows[i].HeightToFocus, "Dash - 0.1 pen");
// Draw the head
DrawCircle(rows[i].EyeToFocusX, rows[i].HeightToFocus, "Medium Lines");
// Draw the body
DrawLine(
rows[i].EyeToFocusX,
rows[i].HeightToFocus,
rows[i].EyeToFocusX,
rows[i].HeightToFocus - rows[i].EyeHeight,
"Thin Lines");
// Draw the riser
DrawRiser(i);
// Draw the going
DrawGoing(i);
// Draw the c-value text
DrawText(
rows[i].EyeToFocusX + 125,
rows[i].HeightToFocus,
"c:" + Math.Round(rows[i].CValue, 2).ToString(CultureInfo.InvariantCulture),
TextAlignFlags.TEF_ALIGN_LEFT);
//// Draw the going text (treadSize)
DrawText(
rows[i].EyeToFocusX - (rows[i].Going / 2),
rows[i].HeightToFocus - rows[i].EyeHeight,
"R" + (i + 1).ToString(CultureInfo.InvariantCulture) + " : " + TreadSize.ToString(CultureInfo.InvariantCulture),
TextAlignFlags.TEF_ALIGN_CENTER | TextAlignFlags.TEF_ALIGN_TOP);
//// Draw the riser text)
if (i > 0)
{
DrawText(
rows[i].EyeToFocusX - TreadSize,
rows[i].HeightToFocus - rows[i].EyeHeight - (rows[i].RiserHeight / 2),
rows[i].RiserHeight.ToString(CultureInfo.InvariantCulture),
TextAlignFlags.TEF_ALIGN_CENTER | TextAlignFlags.TEF_ALIGN_BOTTOM);
}
}
t.Commit();
Autodesk.Revit.UI.UIDoreplacedent uidoc = new Autodesk.Revit.UI.UIDoreplacedent(doc);
uidoc.ActiveView = view;
}
}
19
View Source File : CmsEventSource.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
[NonEvent]
public string LatencyInfo(ICrmSubscriptionMessage subscriptionMessage)
{
DateTime enqueueEventHubUtc = subscriptionMessage.EnqueuedEventhubTimeUtc;
DateTime dequeueEventHubUtc = subscriptionMessage.DequeuedEventhubTimeUtc;
TimeSpan eventHubLatency = dequeueEventHubUtc - enqueueEventHubUtc;
DateTime enqueueTopicUtc = subscriptionMessage.EnqueuedTopicTimeUtc;
DateTime dequeueTopicUtc = subscriptionMessage.DequeuedTopicTimeUtc;
TimeSpan topicLatency = dequeueTopicUtc - enqueueTopicUtc;
WriteEventLatencyInfo(
subscriptionMessage.MessageId.ToString("D"),
enqueueEventHubUtc.ToString(CultureInfo.InvariantCulture),
dequeueEventHubUtc.ToString(CultureInfo.InvariantCulture),
enqueueTopicUtc.ToString(CultureInfo.InvariantCulture),
dequeueTopicUtc.ToString(CultureInfo.InvariantCulture),
eventHubLatency.TotalSeconds.ToString(CultureInfo.InvariantCulture),
topicLatency.TotalSeconds.ToString(CultureInfo.InvariantCulture),
(topicLatency.TotalSeconds + eventHubLatency.TotalSeconds).ToString(CultureInfo.InvariantCulture),
this.PortalUrl,
this.PortalVersion,
this.ProductionOrTrial);
return GetActivityId();
}
19
View Source File : EventSourceBase.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
[NonEvent]
protected string ElapsedTime()
{
try
{
if (this.HttpContext == null)
return string.Empty;
if (this.OwinContext == null || this.OwinContext.Get<RequestElapsedTimeContext>() == null)
{
var inspector = ItemDecorator.GetInspectorInstance(this.HttpContextBase);
var startTime = inspector[ItemDecorator.RequestStartTime];
if (startTime != null)
{
var requestStartTime = (DateTime)startTime;
return (DateTime.UtcNow - requestStartTime).TotalMilliseconds.ToString(CultureInfo.InvariantCulture);
}
return string.Empty;
}
else
{
return this.OwinContext.Get<RequestElapsedTimeContext>().ElapsedTime().ToString();
}
}
catch
{
// eat exception expecting it to possibly happen in scenarios without context
// i.g., background worker threads
return string.Empty;
}
}
19
View Source File : EntityFormFunctions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
internal static string TryConvertAttributeValueToString(OrganizationServiceContext context, Dictionary<string, AttributeTypeCode?> attributeTypeCodeDictionary, string enreplacedyName, string attributeName, object value)
{
if (context == null || string.IsNullOrWhiteSpace(enreplacedyName) || string.IsNullOrWhiteSpace(attributeName))
{
return string.Empty;
}
var newValue = string.Empty;
var attributeTypeCode = attributeTypeCodeDictionary.FirstOrDefault(a => a.Key == attributeName).Value;
if (attributeTypeCode == null)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "Unable to recognize the attribute specified.");
return string.Empty;
}
try
{
switch (attributeTypeCode)
{
case AttributeTypeCode.BigInt:
newValue = value == null ? string.Empty : Convert.ToInt64(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Boolean:
newValue = value == null ? string.Empty : Convert.ToBoolean(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Customer:
if (value is EnreplacedyReference)
{
var enreplacedyref = value as EnreplacedyReference;
newValue = enreplacedyref.Id.ToString();
}
break;
case AttributeTypeCode.DateTime:
newValue = value == null ? string.Empty : Convert.ToDateTime(value).ToUniversalTime().ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Decimal:
newValue = value == null ? string.Empty : Convert.ToDecimal(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Double:
newValue = value == null ? string.Empty : Convert.ToDouble(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Integer:
newValue = value == null ? string.Empty : Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Lookup:
if (value is EnreplacedyReference)
{
var enreplacedyref = value as EnreplacedyReference;
newValue = enreplacedyref.Id.ToString();
}
break;
case AttributeTypeCode.Memo:
newValue = value as string;
break;
case AttributeTypeCode.Money:
newValue = value == null ? string.Empty : Convert.ToDecimal(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Picklist:
newValue = value == null ? string.Empty : Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.State:
newValue = value == null ? string.Empty : Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.Status:
newValue = value == null ? string.Empty : Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
break;
case AttributeTypeCode.String:
newValue = value as string;
break;
case AttributeTypeCode.Uniqueidentifier:
if (value is Guid)
{
var id = (Guid)value;
newValue = id.ToString();
}
break;
default:
ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("Attribute type '{0}' is unsupported.", attributeTypeCode));
break;
}
}
catch (Exception ex)
{
WebEventSource.Log.GenericWarningException(ex, string.Format("Attribute specified is expecting a {0}. The value provided is not valid.", attributeTypeCode));
}
return newValue;
}
19
View Source File : ProgressIndicator.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected int RenderTypeProgressBar(IEnumerable dataSource)
{
var count = 0;
var progressIndex = 0;
var clreplacedName = "progress";
var controlContainer = new HtmlGenericControl("div");
var e = dataSource.GetEnumerator();
if (string.IsNullOrWhiteSpace(Position))
{
CssClreplaced = string.Join(" ", CssClreplaced, clreplacedName);
}
else
{
switch (Position.ToLowerInvariant())
{
case "top":
clreplacedName += " top";
break;
case "bottom":
clreplacedName += " bottom";
break;
case "left":
clreplacedName += " left";
CssClreplaced += " col-sm-3 col-md-2";
break;
case "right":
clreplacedName += " right";
CssClreplaced += " col-sm-3 col-sm-push-9 col-md-2 col-md-push-10";
break;
}
CssClreplaced = string.Join(" ", CssClreplaced, clreplacedName);
}
while (e.MoveNext())
{
if (e.Current == null)
{
continue;
}
var indexValue = DataBinder.GetPropertyValue(e.Current, IndexDataPropertyName);
var activeValue = DataBinder.GetPropertyValue(e.Current, ActiveDataPropertyName);
var index = Convert.ToInt32(indexValue);
var active = Convert.ToBoolean(activeValue);
if (active)
{
if (ZeroBasedIndex)
{
index++;
}
progressIndex = index > 0 ? index - 1 : 0;
}
count++;
}
controlContainer.Attributes["clreplaced"] = "bar progress-bar";
double percent = 0;
if (count > 0)
{
if (!CountLastStepInProgress)
{
percent = (double)(progressIndex * 100) / (count - 1);
}
else
{
percent = (double)(progressIndex * 100) / count;
}
}
var progress = Math.Floor(percent);
controlContainer.Attributes["style"] = string.Format("width: {0}%;", progress);
controlContainer.Attributes["role"] = "progressbar";
controlContainer.Attributes["aria-valuemin"] = "0";
controlContainer.Attributes["aria-valuemax"] = "100";
controlContainer.Attributes["aria-valuenow"] = progress.ToString(CultureInfo.InvariantCulture);
if (progress.CompareTo(0) == 0)
{
controlContainer.Attributes["clreplaced"] = controlContainer.Attributes["clreplaced"] + " zero";
}
controlContainer.InnerHtml = string.Format("{0}%", progress);
Controls.Add(controlContainer);
return count;
}
19
View Source File : ScheduleService.aspx.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private void BindTimeDropDowns()
{
for (var t = DateTime.MinValue; t < DateTime.MinValue.AddDays(1); t = t.AddMinutes(30))
{
StartTime.Items.Add(new Lisreplacedem(t.ToString("h:mm tt"), t.Subtract(DateTime.MinValue).TotalMinutes.ToString(CultureInfo.InvariantCulture)));
EndTime.Items.Add(new Lisreplacedem(t.ToString("h:mm tt"), t.Subtract(DateTime.MinValue).TotalMinutes.ToString(CultureInfo.InvariantCulture)));
}
StartTime.Text = "540"; // 9 AM
EndTime.Text = "1020"; // 5 PM
}
19
View Source File : ExcelImporter.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
protected static string GetNumericValue(ICell cell, double vl)
{
if (DateUtil.IsCellDateFormatted(cell))
{
return ExcelHelper.ExcelBaseDate.AddDays(vl).ToString("yyyy-MM-dd");
}
return (decimal)vl == (int)vl ? ((int)vl).ToString() : vl.ToString(CultureInfo.InvariantCulture);
}
19
View Source File : INIFile.cs
License : GNU General Public License v3.0
Project Creator : akaAgar
License : GNU General Public License v3.0
Project Creator : akaAgar
private string ConvertStringFrom<T>(T value)
{
Type type = typeof(T);
object inObject = value;
string outString = value.ToString();
if (type == typeof(bool))
outString = ((bool)inObject).ToString(NumberFormatInfo.InvariantInfo);
else if (type == typeof(double))
outString = ((double)inObject).ToString(NumberFormatInfo.InvariantInfo);
else if (type == typeof(float))
outString = ((float)inObject).ToString(NumberFormatInfo.InvariantInfo);
else if (type == typeof(int))
outString = ((int)inObject).ToString(NumberFormatInfo.InvariantInfo);
return outString;
}
19
View Source File : DCSMission.cs
License : GNU General Public License v3.0
Project Creator : akaAgar
License : GNU General Public License v3.0
Project Creator : akaAgar
internal void SetValue(string key, double value)
{
SetValue(key, value.ToString(NumberFormatInfo.InvariantInfo), false);
}
19
View Source File : Toolbox.cs
License : GNU General Public License v3.0
Project Creator : akaAgar
License : GNU General Public License v3.0
Project Creator : akaAgar
internal static string ToInvariantString(this double value)
{
return value.ToString(NumberFormatInfo.InvariantInfo);
}
19
View Source File : NumericManipulator.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private string ToString(double value, int significantDigits)
{
// this method will round and then append zeros if needed.
// i.e. if you round .002 to two significant figures, the resulting number should be .0020.
var currentInfo = CultureInfo.CurrentCulture.NumberFormat;
if (double.IsNaN(value))
{
return currentInfo.NaNSymbol;
}
if (double.IsPositiveInfinity(value))
{
return currentInfo.PositiveInfinitySymbol;
}
if (double.IsNegativeInfinity(value))
{
return currentInfo.NegativeInfinitySymbol;
}
int roundingPosition;
var roundedValue = RoundSignificantDigits(value, significantDigits, out roundingPosition);
// when rounding causes a cascading round affecting digits of greater significance,
// need to re-round to get a correct rounding position afterwards
// this fixes a bug where rounding 9.96 to 2 figures yeilds 10.0 instead of 10
RoundSignificantDigits(roundedValue, significantDigits, out roundingPosition);
if (Math.Abs(roundingPosition) > 9)
{
// use exponential notation format
// ReSharper disable FormatStringProblem
return string.Format(currentInfo, "{0:E" + (significantDigits - 1) + "}", roundedValue);
// ReSharper restore FormatStringProblem
}
// string.format is only needed with decimal numbers (whole numbers won't need to be padded with zeros to the right.)
// ReSharper disable FormatStringProblem
return roundingPosition > 0 ? string.Format(currentInfo, "{0:F" + roundingPosition + "}", roundedValue) : roundedValue.ToString(currentInfo);
// ReSharper restore FormatStringProblem
}
19
View Source File : HtmlFromXamlConverter.cs
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
private static string ParseXamlThickness(string thickness)
{
string[] values = thickness.Split(',');
for (int i = 0; i < values.Length; i++)
{
double value;
if (double.TryParse(values[i], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out value))
{
values[i] = Math.Ceiling(value).ToString(CultureInfo.InvariantCulture);
}
else
{
values[i] = "1";
}
}
string cssThickness;
switch (values.Length)
{
case 1:
cssThickness = thickness;
break;
case 2:
cssThickness = values[1] + " " + values[0];
break;
case 4:
cssThickness = values[1] + " " + values[2] + " " + values[3] + " " + values[0];
break;
default:
cssThickness = values[0];
break;
}
return cssThickness;
}
19
View Source File : JsonRpcId.cs
License : MIT License
Project Creator : alexanderkozlenko
License : MIT License
Project Creator : alexanderkozlenko
public string ToString(IFormatProvider provider)
{
switch (_type)
{
case JsonRpcIdType.String:
{
return _valueString;
}
case JsonRpcIdType.Number:
{
return _valueNumber.ToString(provider);
}
default:
{
return string.Empty;
}
}
}
19
View Source File : AMD10CPU.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
public override string GetReport() {
StringBuilder r = new StringBuilder();
r.Append(base.GetReport());
r.Append("Miscellaneous Control Address: 0x");
r.AppendLine((miscellaneousControlAddress).ToString("X",
CultureInfo.InvariantCulture));
r.Append("Time Stamp Counter Multiplier: ");
r.AppendLine(timeStampCounterMultiplier.ToString(
CultureInfo.InvariantCulture));
if (family == 0x14) {
uint value = 0;
Ring0.ReadPciConfig(miscellaneousControlAddress,
CLOCK_POWER_TIMING_CONTROL_0_REGISTER, out value);
r.Append("PCI Register D18F3xD4: ");
r.AppendLine(value.ToString("X8", CultureInfo.InvariantCulture));
}
r.AppendLine();
return r.ToString();
}
19
View Source File : IntelCPU.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
public override string GetReport() {
StringBuilder r = new StringBuilder();
r.Append(base.GetReport());
r.Append("Microarchitecture: ");
r.AppendLine(microarchitecture.ToString());
r.Append("Time Stamp Counter Multiplier: ");
r.AppendLine(timeStampCounterMultiplier.ToString(
CultureInfo.InvariantCulture));
r.AppendLine();
return r.ToString();
}
19
View Source File : RangeAxis.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
internal static double RemoveNoiseFromDoubleMath(double value)
{
if (value == 0.0 || Math.Abs((Math.Log10(Math.Abs(value)))) < 27)
{
return (double)((decimal)value);
}
return Double.Parse(value.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
}
19
View Source File : CodeGeneratorStringExtensions.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
public static string ToCode(this double value)
{
if (double.IsNaN(value))
{
return "double.NaN";
}
if (double.IsPositiveInfinity(value))
{
return "double.PositiveInfinity";
}
if (double.IsNegativeInfinity(value))
{
return "double.NegativeInfinity";
}
if (value.Equals(double.MinValue))
{
return "double.MinValue";
}
if (value.Equals(double.MaxValue))
{
return "double.MaxValue";
}
return value.ToString(CultureInfo.InvariantCulture);
}
19
View Source File : DoubleExtensions.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
public static double RemoveNoiseFromDoubleMath(this double value)
{
if (value.IsZero() || Math.Abs(Math.Log10(Math.Abs(value))) < 27)
{
return (double)((decimal)value);
}
return double.Parse(value.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
}
19
View Source File : GPosRecord.cs
License : Apache License 2.0
Project Creator : alexreinert
License : Apache License 2.0
Project Creator : alexreinert
protected internal override void EncodeRecordData(byte[] messageData, int offset, ref int currentPosition, Dictionary<DomainName, ushort> domainNames, bool useCanonical)
{
DnsMessageBase.EncodeTextBlock(messageData, ref currentPosition, Longitude.ToString(CultureInfo.InvariantCulture));
DnsMessageBase.EncodeTextBlock(messageData, ref currentPosition, Lareplacedude.ToString(CultureInfo.InvariantCulture));
DnsMessageBase.EncodeTextBlock(messageData, ref currentPosition, Alreplacedude.ToString(CultureInfo.InvariantCulture));
}
19
View Source File : GPosRecord.cs
License : Apache License 2.0
Project Creator : alexreinert
License : Apache License 2.0
Project Creator : alexreinert
internal override string RecordDataToString()
{
return Longitude.ToString(CultureInfo.InvariantCulture)
+ " " + Lareplacedude.ToString(CultureInfo.InvariantCulture)
+ " " + Alreplacedude.ToString(CultureInfo.InvariantCulture);
}
19
View Source File : LocRecord.cs
License : Apache License 2.0
Project Creator : alexreinert
License : Apache License 2.0
Project Creator : alexreinert
[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
internal override string RecordDataToString()
{
return Lareplacedude.ToLareplacedudeString()
+ " "
+ Longitude.ToLongitudeString()
+ " " + Alreplacedude.ToString(CultureInfo.InvariantCulture) + "m"
+ (((Size != 1) || (HorizontalPrecision != 10000) || (VerticalPrecision != 10)) ? " " + Size + "m" : "")
+ (((HorizontalPrecision != 10000) || (VerticalPrecision != 10)) ? " " + HorizontalPrecision + "m" : "")
+ ((VerticalPrecision != 10) ? " " + VerticalPrecision + "m" : "");
}
19
View Source File : MarketDepthPainter.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
void _glreplacedBox_SelectionChanged(object sender, EventArgs e)
{
try
{
if (_glreplacedBox.InvokeRequired)
{
_glreplacedBox.Invoke(new Action<object, EventArgs>(_glreplacedBox_SelectionChanged), sender, e);
return;
}
decimal price;
try
{
if (_glreplacedBox.CurrentCell == null ||
_glreplacedBox.Rows.Count == 0 ||
_glreplacedBox.Rows[_glreplacedBox.CurrentCell.RowIndex].Cells.Count < 2 ||
_glreplacedBox.Rows[_glreplacedBox.CurrentCell.RowIndex].Cells[2].Value == null)
{
return;
}
price = _glreplacedBox.Rows[_glreplacedBox.CurrentCell.RowIndex].Cells[2].Value.ToString().ToDecimal();
}
catch (Exception)
{
return;
}
if (price == 0)
{
return;
}
if (_hostGlreplaced != null)
{
_lastSelectPrice = price;
_textBoxLimitPrice.Text = Convert.ToDouble(_lastSelectPrice).ToString(new CultureInfo("RU-ru"));
}
}
catch (Exception error)
{
SendNewLogMessage(error.ToString(), LogMessageType.Error);
}
}
19
View Source File : MarketDepthPainter.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public void StartPaint(WindowsFormsHost glreplaced, System.Windows.Controls.TextBox textBoxLimitPrice)
{
try
{
if (_glreplacedBox == null)
{
return;
}
if (_glreplacedBox.InvokeRequired)
{
_glreplacedBox.Invoke(new Action<WindowsFormsHost, System.Windows.Controls.TextBox>(StartPaint), glreplaced, textBoxLimitPrice);
return;
}
_textBoxLimitPrice = textBoxLimitPrice;
_textBoxLimitPrice.TextChanged += _textBoxLimitPrice_TextChanged;
_hostGlreplaced = glreplaced;
ProcessBidAsk(_bid, _ask);
_hostGlreplaced.Child = _glreplacedBox;
_hostGlreplaced.Child.Refresh();
_textBoxLimitPrice.Text = Convert.ToDouble(_lastSelectPrice).ToString(new CultureInfo("RU-ru"));
ProcessMarketDepth(_lastMarketDepth);
}
catch (Exception error)
{
SendNewLogMessage(error.ToString(), LogMessageType.Error);
}
}
19
View Source File : DealStaticticGenerator.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public static List<string> GetStatisticNew(List<Position> positions, bool withPunkt)
{
if (positions == null)
{
return null;
}
List<Position> positionsNew = positions.FindAll((
position => position.State != PositionStateType.OpeningFail
&& position.EntryPrice != 0 && position.ClosePrice != 0));
if (positionsNew.Count == 0)
{
return null;
}
Position[] deals = positionsNew.ToArray();
List<string> report = new List<string>();
/*
Чистый П\У
Чистый П\У %
Количество сделок
Сред. П\У по сделке
Сред. П\У % по сделке
Сред. П\У на капитал
Сред. П\У % на капитал
Прибыльных сделок
Прибыльных %
Сред. П\У по сделке
Сред. П\У % по сделке
Сред. П\У на капитал
Сред. П\У % на капитал
Максимум подряд
Убыточных сделок
Убыточных %
Сред. П\У по сделке
Сред. П\У % по сделке
Сред. П\У на капитал
Сред. П\У % на капитал
Максимум подряд
Макс просадка %
Размер комиссии
*/
/*Net Profit/Loss
Net Profit/Loss
Number of transactions
Average. Profit/Loss on the deal
Average. Profit/Loss % of the transaction
Average. Profit/Loss for capital
Average. Profit/Loss % for capital
Profitable deals
Profitable %
Average. Profit/Loss on the deal
Average. Profit/Loss % of the transaction
Average. Profit/Loss for capital
Average. Profit/Loss % for capital
At most in a row.
Loss transactions
Losses.
Average. Profit/Loss on the deal
Average. Profit/Loss % of the transaction
Average. Profit/Loss for capital
Average. Profit/Loss % for capital
At most in a row.
Max drawdown %
Comission amount
*/
report.Add(Convert.ToDouble(GetAllProfitInPunkt(deals)).ToString(new CultureInfo("ru-RU"))); //Net profit
report.Add(Math.Round(GetAllProfitPersent(deals), 6).ToString(new CultureInfo("ru-RU")));//Net profti %
report.Add(deals.Length.ToString(new CultureInfo("ru-RU")));// Number of transactions
report.Add(Math.Round(GetProfitFactor(deals), 6).ToString(new CultureInfo("ru-RU"))); //Profit Factor
report.Add(Math.Round(GetRecovery(deals), 6).ToString(new CultureInfo("ru-RU"))); // Recovery
report.Add("");
report.Add(Convert.ToDouble(GetMidleProfitInPunkt(deals)).ToString(new CultureInfo("ru-RU"))); //average profit
report.Add(Math.Round(GetMidleProfitInPersent(deals), 6).ToString(new CultureInfo("ru-RU"))); //average profit in %
report.Add(Convert.ToDouble(GetMidleProfitInPunktToDepozit(deals)).ToString(new CultureInfo("ru-RU"))); //average profit
report.Add(Math.Round(GetMidleProfitInPersentToDepozit(deals), 6).ToString(new CultureInfo("ru-RU"))); //average profit in %
report.Add(""); // 11
report.Add(GetProfitDial(deals).ToString(new CultureInfo("ru-RU"))); //wining trades/выигрышных сделок
report.Add(Math.Round(GetProfitDialPersent(deals), 6).ToString(new CultureInfo("ru-RU")));//wining trade in %/выигрышных сделок в %
//report += Convert.ToDouble(GetAllProfitInProfitInPunkt(deals)).ToString(new CultureInfo("ru-RU")) + "\r\n"; //total profit margins/общий профит выигрышных сделок
report.Add(Convert.ToDouble(GetAllMidleProfitInProfitInPunkt(deals)).ToString(new CultureInfo("ru-RU"))); //Average profit in winning trades/средний профит в выигрышных сделках
report.Add(Math.Round(GetAllMidleProfitInProfitInPersent(deals), 6).ToString(new CultureInfo("ru-RU"))); //Average profit as a percentage of winning trades/средний профит в процентах в выигрышных сделках
report.Add(Convert.ToDouble(GetAllMidleProfitInProfitInPunktOnDepozit(deals)).ToString(new CultureInfo("ru-RU"))); //Average profit in winning trades/средний профит в выигрышных сделках
report.Add(Math.Round(GetAllMidleProfitInProfitInPersentOnDepozit(deals), 6).ToString(new CultureInfo("ru-RU")));//Average profit as a percentage of winning trades/средний профит в процентах в выигрышных сделках
report.Add(GetMaxProfitSeries(deals).ToString(new CultureInfo("ru-RU"))); //maximum series of winning trades/максимальная серия выигрышных сделок
report.Add("");
report.Add(GetLossDial(deals).ToString(new CultureInfo("ru-RU"))); //losing trades/проигрышных сделок
report.Add(Math.Round(GetLossDialPersent(deals), 6).ToString(new CultureInfo("ru-RU"))); //losing deals in/проигрышных сделок в %
//report += Convert.ToDouble(GetAllLossInLossInPunkt(deals)).ToString(new CultureInfo("ru-RU")) + "\r\n"; //loss-making total profit/общий профит проигрышных сделок
report.Add(Convert.ToDouble(GetAllMidleLossInLossInPunkt(deals)).ToString(new CultureInfo("ru-RU")));//average profit in losing trades/средний профит в проигрышных сделках
report.Add(Math.Round(GetAllMidleLossInLossInPersent(deals), 6).ToString(new CultureInfo("ru-RU")));//Average profit as a percentage in losing trades/средний профит в процентах в проигрышных сделках
report.Add(Convert.ToDouble(GetAllMidleLossInLossInPunktOnDepozit(deals)).ToString(new CultureInfo("ru-RU"))); //Average profit in winning trades/средний профит в выигрышных сделках
report.Add(Math.Round(GetAllMidleLossInLossInPersentOnDepozit(deals), 6).ToString(new CultureInfo("ru-RU")));//Average profit as a percentage of winning trades/средний профит в процентах в выигрышных сделках
report.Add(GetMaxLossSeries(deals).ToString(new CultureInfo("ru-RU")));//maximum series of winning trades/максимальная серия выигрышных сделок
report.Add("");
report.Add(Math.Round(GetMaxDownPersent(deals), 6).ToString(new CultureInfo("ru-RU"))); //maximum drawdown in percent/максимальная просадка в процентах
report.Add(Math.Round(GetCommissionAmount(deals), 6).ToString(new CultureInfo("ru-RU"))); //maximum drawdown in percent/максимальная просадка в процентах
/*report += Math.Round(GetSharp(), 2).ToString(new CultureInfo("ru-RU"));
*/
return report;
}
19
View Source File : Guideline.cs
License : MIT License
Project Creator : AlFasGD
License : MIT License
Project Creator : AlFasGD
public override string ToString() => $"{TimeStamp.ToString(CultureInfo.InvariantCulture)}~{Color}";
19
View Source File : SongMetadata.cs
License : MIT License
Project Creator : AlFasGD
License : MIT License
Project Creator : AlFasGD
public override string ToString() => $"<k>kCEK</k><i>6</i><k>1</k><i>{ID}</i><k>2</k><s>{replacedle}</s><k>3</k><i>{ArtistID}</i><k>4</k><s>{Artist}</s><k>5</k><r>{SongSizeMB.ToString(CultureInfo.InvariantCulture)}</r><k>6</k><s>{YouTubeSongVideoID}</s><k>7</k><s>{YouTubeArtistChannelID}</s><k>9</k><i>{UnknownKey9}</i><k>10</k><s>{DownloadLink}</s>";
19
View Source File : HSVDifference.cs
License : MIT License
Project Creator : AlFasGD
License : MIT License
Project Creator : AlFasGD
public override string ToString() => $"{Hue.ToString(CultureInfo.InvariantCulture)}a{Saturation.ToString(CultureInfo.InvariantCulture)}a{Brightness.ToString(CultureInfo.InvariantCulture)}a{(int)SaturationMode}a{(int)BrightnessMode}";
19
View Source File : Level.cs
License : MIT License
Project Creator : AlFasGD
License : MIT License
Project Creator : AlFasGD
public string GetRawLevel() => $"<k>kCEK</k><i>4</i><k>k1</k><i>{ID}</i><k>k2</k><s>{Name}</s><k>k4</k><s>{LevelString}</s>{(Description.Length > 0 ? $"<k>k3</k><s>{Convert.ToBase64String(Encoding.ASCII.GetBytes(Description))}</s>" : "")}<k>k46</k><i>{Revision}</i><k>k5</k><s>{CreatorName}</s><k>k13</k><t />{GetBoolPropertyString("k14", VerifiedStatus)}{GetBoolPropertyString("k15", UploadedStatus)}{GetBoolPropertyString("k79", Unlisted)}<k>k21</k><i>2</i><k>k16</k><i>{Version}</i><k>k23</k><s>{(int)Length}</s><k>k8</k><i>{OfficialSongID}</i><k>k45</k><i>{CustomSongID}</i><k>k80</k><i>{BuildTime}</i><k>k50</k><i>{BinaryVersion}</i><k>k47</k><t /><k>k84</k><i>{Folder}</i><k>kI1</k><r>{CameraX.ToString(CultureInfo.InvariantCulture)}</r><k>kI2</k><r>{CameraY.ToString(CultureInfo.InvariantCulture)}</r><k>kI3</k><r>{CameraZoom}</r>";
19
View Source File : BPM.cs
License : MIT License
Project Creator : AlFasGD
License : MIT License
Project Creator : AlFasGD
public override string ToString() => Value.ToString(CultureInfo.InvariantCulture);
19
View Source File : DownloadUpdateDialog.cs
License : MIT License
Project Creator : Analogy-LogViewer
License : MIT License
Project Creator : Analogy-LogViewer
private static string BytesToString(long byteCount)
{
string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" };
if (byteCount == 0)
{
return "0" + suf[0];
}
long bytes = Math.Abs(byteCount);
int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
double num = Math.Round(bytes / Math.Pow(1024, place), 1);
return $"{(Math.Sign(byteCount) * num).ToString(CultureInfo.InvariantCulture)} {suf[place]}";
}
19
View Source File : MicrophoneTransmitter.cs
License : MIT License
Project Creator : anderm
License : MIT License
Project Creator : anderm
private void SendFixedSizedChunk(NetworkConnection connection, byte[] data, int dataSize)
{
DateTime currentTime = DateTime.Now;
float seconds = (float)(currentTime - timeOfLastPacketSend).TotalSeconds;
timeOfLastPacketSend = currentTime;
if (seconds < 10.0)
{
if (worstTimeBetweenPackets < seconds)
{
worstTimeBetweenPackets = seconds;
}
if (ShowInterPacketTime)
{
Debug.LogFormat("Microphone: Millisecs since last sent: {0}, Worst: {1}",
(seconds * 1000.0).ToString(CultureInfo.InvariantCulture),
(worstTimeBetweenPackets * 1000.0).ToString(CultureInfo.InvariantCulture));
}
}
int clientId = SharingStage.Instance.Manager.GetLocalUser().GetID();
// pack the header
NetworkOutMessage msg = connection.CreateMessage((byte)MessageID.AudioSamples);
int dataCountFloats = dataSize / 4;
msg.Write((byte)5); // 8 byte header size
Int32 pack = 0;
versionPacker.SetBits(ref pack, 1); // version
audioStreamCountPacker.SetBits(ref pack, 1); // AudioStreamCount
channelCountPacker.SetBits(ref pack, 1); // ChannelCount
sampleRatePacker.SetBits(ref pack, sampleRateType); // SampleRate: 1 = 16000, 3 = 48000
sampleTypePacker.SetBits(ref pack, 0); // SampleType
sampleCountPacker.SetBits(ref pack, dataCountFloats); // SampleCount (data count is in bytes and the actual data is in floats, so div by 4)
codecTypePacker.SetBits(ref pack, 0); // CodecType
mutePacker.SetBits(ref pack, Mute ? 1 : 0);
sequenceNumberPacker.SetBits(ref pack, sequenceNumber++);
sequenceNumber %= 32;
msg.Write(pack); // the packed bits
// This is where stream data starts. Write all data for one stream
msg.Write(0.0f); // average amplitude. Not needed in direction from client to server.
msg.Write(clientId); // non-zero client ID for this client.
// HRTF position bits
Vector3 cameraPosRelativeToGlobalAnchor = Vector3.zero;
Vector3 cameraDirectionRelativeToGlobalAnchor = Vector3.zero;
if (GlobalAnchorTransform != null)
{
cameraPosRelativeToGlobalAnchor = MathUtils.TransformPointFromTo(
null,
GlobalAnchorTransform,
Camera.main.transform.position);
cameraDirectionRelativeToGlobalAnchor = MathUtils.TransformDirectionFromTo(
null,
GlobalAnchorTransform,
Camera.main.transform.position);
}
cameraPosRelativeToGlobalAnchor.Normalize();
cameraDirectionRelativeToGlobalAnchor.Normalize();
// Camera position
msg.Write(cameraPosRelativeToGlobalAnchor.x);
msg.Write(cameraPosRelativeToGlobalAnchor.y);
msg.Write(cameraPosRelativeToGlobalAnchor.z);
// HRTF direction bits
msg.Write(cameraDirectionRelativeToGlobalAnchor.x);
msg.Write(cameraDirectionRelativeToGlobalAnchor.y);
msg.Write(cameraDirectionRelativeToGlobalAnchor.z);
msg.WriteArray(data, (uint)dataCountFloats * 4);
connection.Send(msg, MessagePriority.Immediate, MessageReliability.ReliableOrdered, MessageChannel.Audio, true);
}
19
View Source File : SyncObject.cs
License : MIT License
Project Creator : anderm
License : MIT License
Project Creator : anderm
protected virtual void OnDoubleElementChanged(long elementID, double newValue)
{
if (primitiveMap.ContainsKey(elementID))
{
SyncPrimitive primitive = primitiveMap[elementID];
primitive.UpdateFromRemote(newValue);
NotifyPrimitiveChanged(primitive);
}
else
{
LogUnknownElement(elementID.ToString(), newValue.ToString(CultureInfo.InvariantCulture), typeof(double));
}
}
19
View Source File : Probability.cs
License : MIT License
Project Creator : AndreyAkinshin
License : MIT License
Project Creator : AndreyAkinshin
public string ToString(IFormatProvider formatProvider)
{
return Value.ToString(formatProvider);
}
19
View Source File : Rqq.cs
License : MIT License
Project Creator : AndreyAkinshin
License : MIT License
Project Creator : AndreyAkinshin
public void DumpTreeAscii([NotNull] StreamWriter writer, bool details = false)
{
var valuesStr = values.Select(v => v.ToString(CultureInfo.InvariantCulture)).ToArray(); // TODO: precision
// Calculate width for each node
var width = new int[nodeCount];
for (int node = 0; node < nodeCount; node++)
{
width[node] += rangeRight[node] - rangeLeft[node] + 2; // result += <widths of spaces>
if (kinds[node] != NodeKind.Fake)
for (int i = rangeLeft[node]; i <= rangeRight[node]; i++)
width[node] += valuesStr[i].Length; // result += <widths of values>
width[node] += 2; // result += <widths of borders>
}
// Calculate padding for each node and connector-with-child positions
var paddingLeft = new int[nodeCount];
var paddingRight = new int[nodeCount];
var connectorDownLeft = new int[nodeCount];
var connectorDownRight = new int[nodeCount];
var connectorUp = new int[nodeCount];
for (int node = nodeCount - 1; node >= 0; node--)
{
if (kinds[node] == NodeKind.Parent)
{
int child1 = node * 2 + 1;
int child2 = node * 2 + 2;
int totalWidth1 = paddingLeft[child1] + width[child1] + paddingRight[child1];
int totalWidth2 = paddingLeft[child2] + width[child2] + paddingRight[child2];
int childrenWidth = totalWidth1 + 1 + totalWidth2;
int padding = Math.Max(0, childrenWidth - width[node]);
paddingLeft[node] = paddingLeft[child1] + width[child1] +
(paddingRight[child1] + 1 + paddingLeft[child2]) / 2 -
width[node] / 2;
paddingRight[node] = padding - paddingLeft[node];
connectorDownLeft[node] = 1;
connectorDownRight[node] = width[node] - 2;
connectorUp[child1] = paddingLeft[node] + connectorDownLeft[node] - paddingLeft[child1];
connectorUp[child2] = paddingLeft[node] + connectorDownRight[node] -
(totalWidth1 + 1) - paddingLeft[child2];
}
}
int layer = -1;
while (true)
{
layer++;
int node2 = (1 << (layer + 1)) - 2;
int node1 = node2 - (1 << layer) + 1;
if (node1 >= nodeCount)
break;
void DumpLine(char leftBorder, char separator, char rightBorder, Func<int, string> element,
char? down = null, char? up = null)
{
for (int node = node1; node <= node2; node++)
{
if (kinds[node] == NodeKind.Fake)
{
if (node % 2 == 1) // It's a left child
{
int parentIndex = (node - 1) / 2;
int parentWidth = 1 + paddingLeft[parentIndex] + width[parentIndex] +
paddingRight[parentIndex];
for (int j = 0; j < parentWidth; j++)
writer.Write(' ');
}
continue;
}
int position = -paddingLeft[node];
void PrintChar(char c)
{
if (kinds[node] == NodeKind.Parent && down.HasValue &&
(position == connectorDownLeft[node] ||
position == connectorDownRight[node]))
writer.Write(down.Value);
else if (position == connectorUp[node] && node > 0 && up.HasValue)
writer.Write(up.Value);
else
writer.Write(c);
position++;
}
void PrintString(string s)
{
foreach (var c in s)
PrintChar(c);
}
for (int j = 0; j < paddingLeft[node]; j++)
PrintChar(' ');
PrintChar(leftBorder);
PrintChar(separator);
for (int i = rangeLeft[node]; i <= rangeRight[node]; i++)
{
string elementStr = element(i);
int elementPadding = Math.Max(0, valuesStr[i].Length - elementStr.Length);
for (int j = 0; j < elementPadding; j++)
PrintChar(separator);
PrintString(elementStr);
if (i != rangeRight[node])
PrintChar(separator);
}
PrintChar(separator);
PrintChar(rightBorder);
for (int j = 0; j < paddingRight[node]; j++)
PrintChar(' ');
if (node != node2)
PrintChar(' ');
}
writer.WriteLine();
}
DumpLine('┌', '─', '┐', i => "─", up: '┴');
DumpLine('│', ' ', '│', i => valuesStr[i]);
DumpLine('│', ' ', '│', i => b[i] == BinaryFlag.NotDefined ? " " : ((int) b[i]).ToString());
DumpLine('└', '─', '┘', i => "─", down: '┬');
DumpLine(' ', ' ', ' ', i => "", down: '│');
}
writer.WriteLine();
if (details)
{
for (int node = 0; node < nodeCount; node++)
{
writer.Write('#');
writer.Write(node.ToString());
writer.Write(": ");
switch (kinds[node])
{
case NodeKind.Parent:
writer.Write("NODE(");
for (int i = rangeLeft[node]; i <= rangeRight[node]; i++)
{
writer.Write(valuesStr[i]);
if (i != rangeRight[node])
writer.Write(',');
}
writer.Write("); Children = { #");
writer.Write(node * 2 + 1);
writer.Write(", #");
writer.Write(node * 2 + 2);
writer.WriteLine(" }");
break;
case NodeKind.Leaf:
writer.Write("LEAF(");
writer.Write(valuesStr[rangeLeft[node]]);
writer.WriteLine(")");
break;
case NodeKind.Fake:
writer.WriteLine("FAKE");
break;
default:
throw new ArgumentOutOfRangeException();
}
}
writer.WriteLine();
writer.WriteLine("Allocated values : " + values.Length);
writer.WriteLine("Used values : " + usedValues);
}
writer.Flush();
}
19
View Source File : AxesArrayDesigner.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
DataPoint dataPoint = value as DataPoint;
if (destinationType == typeof(InstanceDescriptor) && dataPoint != null)
{
if (dataPoint.YValues.Length > 1)
{
ConstructorInfo ci = typeof(DataPoint).GetConstructor(new Type[] { typeof(double), typeof(string) });
string yValues = "";
foreach (double y in dataPoint.YValues)
{
yValues += y.ToString(System.Globalization.CultureInfo.InvariantCulture) + ",";
}
return new InstanceDescriptor(ci, new object[] { dataPoint.XValue, yValues.TrimEnd(',') }, false);
}
else
{
ConstructorInfo ci = typeof(DataPoint).GetConstructor(new Type[] { typeof(double), typeof(double) });
return new InstanceDescriptor(ci, new object[] { dataPoint.XValue, dataPoint.YValues[0] }, false);
}
}
// Always call base, even if you can't convert.
return base.ConvertTo(context, culture, value, destinationType);
}
19
View Source File : RenkoChart.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
private static double GetBoxSize(Series series, Series originalData, int yValueIndex)
{
// Check "BoxSize" custom attribute
double boxSize = 1.0;
double percentOfPriceRange = 4.0;
bool roundBoxSize = true;
if(series.IsCustomPropertySet(CustomPropertyName.BoxSize))
{
string attrValue = series[CustomPropertyName.BoxSize].Trim();
bool usePercentage = attrValue.EndsWith("%", StringComparison.Ordinal);
if(usePercentage)
{
attrValue = attrValue.Substring(0, attrValue.Length - 1);
}
try
{
if(usePercentage)
{
percentOfPriceRange = double.Parse(attrValue, CultureInfo.InvariantCulture);
roundBoxSize = false;
}
else
{
boxSize = double.Parse(attrValue, CultureInfo.InvariantCulture);
percentOfPriceRange = 0.0;
}
}
catch
{
throw (new InvalidOperationException(SR.ExceptionRenkoBoxSizeFormatInvalid));
}
}
// Calculate box size using the percentage of price range
if(percentOfPriceRange > 0.0)
{
// Set default box size
boxSize = 1.0;
// Calculate percent of the highest and lowest price difference.
double highest = double.MinValue;
double lowest = double.MaxValue;
foreach(DataPoint dp in originalData.Points)
{
if(!dp.IsEmpty)
{
if(dp.YValues[yValueIndex] > highest)
{
highest = dp.YValues[yValueIndex];
}
if(dp.YValues[yValueIndex] < lowest)
{
lowest = dp.YValues[yValueIndex];
}
}
}
// Calculate box size as percentage of price difference
if(lowest == highest)
{
boxSize = 1.0;
}
else if( (highest - lowest) < 0.000001)
{
boxSize = 0.000001;
}
else
{
boxSize = (highest - lowest) * (percentOfPriceRange / 100.0);
}
// Round calculated value
if(roundBoxSize)
{
double[] availableBoxSizes = new double[]
{ 0.000001, 0.00001, 0.0001, 0.001, 0.01, 0.1, 0.25, 0.5, 1.0, 2.0, 2.5, 3.0, 4.0, 5.0, 7.5, 10.0, 15.0, 20.0, 25.0, 50.0, 100.0, 200.0, 500.0, 1000.0, 5000.0, 10000.0, 50000.0, 100000.0, 1000000.0, 1000000.0};
for(int index = 1; index < availableBoxSizes.Length; index ++)
{
if(boxSize > availableBoxSizes[index - 1] &&
boxSize < availableBoxSizes[index])
{
boxSize = availableBoxSizes[index];
}
}
}
}
// Save current box size as a custom attribute of the original series
series["CurrentBoxSize"] = boxSize.ToString(CultureInfo.InvariantCulture);
return boxSize;
}
19
View Source File : CustomAttributesConverters.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
public string GetStringFromValue(object value)
{
if(value is Color)
{
ColorConverter colorConverter = new ColorConverter();
return colorConverter.ConvertToString(null, System.Globalization.CultureInfo.InvariantCulture, value);
}
else if(value is float)
{
return ((float)value).ToString(System.Globalization.CultureInfo.InvariantCulture);
}
else if(value is double)
{
return ((double)value).ToString(System.Globalization.CultureInfo.InvariantCulture);
}
else if(value is int)
{
return ((int)value).ToString(System.Globalization.CultureInfo.InvariantCulture);
}
else if(value is bool)
{
return ((bool)value).ToString();
}
return value.ToString();
}
19
View Source File : DataManagerConverters.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
bool convertToDate = false;
// Check if we should convert to date string format
if (context != null && context.Instance != null)
{
DataPoint dataPoint = (DataPoint)context.Instance;
if(dataPoint.series != null && dataPoint.series.IsYValueDateTime())
{
convertToDate = true;
}
}
if (destinationType == typeof(string))
{
double[] array = (double[]) value;
string result = "";
foreach(double d in array)
{
if(convertToDate)
{
result += DateTime.FromOADate(d).ToString("g", System.Globalization.CultureInfo.InvariantCulture) + ",";
}
else
{
result += d.ToString(System.Globalization.CultureInfo.InvariantCulture) + ",";
}
}
return result.TrimEnd(',');
}
return base.ConvertTo(context, culture, value, destinationType);
}
19
View Source File : PointAndFigureChart.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
private static double GetBoxSize(
Series series,
double minPrice,
double maxPrice)
{
// Check "BoxSize" custom attribute
double boxSize = 1.0;
double percentOfPriceRange = 4.0;
bool roundBoxSize = true;
if (series.IsCustomPropertySet(CustomPropertyName.BoxSize))
{
string attrValue = series[CustomPropertyName.BoxSize].Trim();
bool usePercentage = attrValue.EndsWith("%", StringComparison.Ordinal);
if (usePercentage)
{
attrValue = attrValue.Substring(0, attrValue.Length - 1);
}
bool parseSucceed = false;
if (usePercentage)
{
double percent;
parseSucceed = double.TryParse(attrValue, NumberStyles.Any, CultureInfo.InvariantCulture, out percent);
if (parseSucceed)
{
percentOfPriceRange = percent;
roundBoxSize = false;
}
}
else
{
double b = 0;
parseSucceed = double.TryParse(attrValue, NumberStyles.Any, CultureInfo.InvariantCulture, out b);
if (parseSucceed)
{
boxSize = b;
percentOfPriceRange = 0.0;
}
}
if (!parseSucceed)
{
throw (new InvalidOperationException(SR.ExceptionRenkoBoxSizeFormatInvalid));
}
}
// Calculate box size using the percentage of price range
if(percentOfPriceRange > 0.0)
{
// Set default box size
boxSize = 1.0;
// Calculate box size as percentage of price difference
if(minPrice == maxPrice)
{
boxSize = 1.0;
}
else if( (maxPrice - minPrice) < 0.000001)
{
boxSize = 0.000001;
}
else
{
boxSize = (maxPrice - minPrice) * (percentOfPriceRange / 100.0);
}
// Round calculated value
if(roundBoxSize)
{
double[] availableBoxSizes = new double[]
{ 0.000001, 0.00001, 0.0001, 0.001, 0.01, 0.1, 0.25, 0.5, 1.0, 2.0, 2.5, 3.0, 4.0, 5.0, 7.5, 10.0, 15.0, 20.0, 25.0, 50.0, 100.0, 200.0, 500.0, 1000.0, 5000.0, 10000.0, 50000.0, 100000.0, 1000000.0, 1000000.0};
for(int index = 1; index < availableBoxSizes.Length; index ++)
{
if(boxSize > availableBoxSizes[index - 1] &&
boxSize < availableBoxSizes[index])
{
boxSize = availableBoxSizes[index];
}
}
}
}
// Save current box size as a custom attribute of the original series
series["CurrentBoxSize"] = boxSize.ToString(CultureInfo.InvariantCulture);
return boxSize;
}
19
View Source File : ClockControl.cs
License : MIT License
Project Creator : AntonyCorbett
License : MIT License
Project Creator : AntonyCorbett
private static void DrawSector(Path sectorPath, double startAngle, double endAngle, bool isLargeArc)
{
var startPoint = PointOnCircle(SectorRadius, startAngle, ClockOrigin);
var endPoint = PointOnCircle(SectorRadius, endAngle, ClockOrigin);
var largeArc = isLargeArc ? "1" : "0";
// use InvariantCulture to ensure that decimal separator is '.'
sectorPath.Data = Geometry.Parse($"M{ClockRadius.ToString(CultureInfo.InvariantCulture)},{ClockRadius.ToString(CultureInfo.InvariantCulture)} L{startPoint.X.ToString(CultureInfo.InvariantCulture)},{startPoint.Y.ToString(CultureInfo.InvariantCulture)} A{SectorRadius.ToString(CultureInfo.InvariantCulture)},{SectorRadius.ToString(CultureInfo.InvariantCulture)} 0 {largeArc} 1 {endPoint.X.ToString(CultureInfo.InvariantCulture)},{endPoint.Y.ToString(CultureInfo.InvariantCulture)} z");
}
19
View Source File : MetricWidget.cs
License : GNU General Public License v3.0
Project Creator : AnyStatus
License : GNU General Public License v3.0
Project Creator : AnyStatus
public override string ToString()
{
return _value.ToString(CultureInfo.InvariantCulture);
}
19
View Source File : CurrentWeatherWidget.cs
License : GNU Affero General Public License v3.0
Project Creator : AnyStatus
License : GNU Affero General Public License v3.0
Project Creator : AnyStatus
public override string ToString()
{
switch (Scale)
{
case TemperatureScale.Celsius:
return $"{_value - 273.15:0}°C";
case TemperatureScale.Fahrenheit:
return $"{(_value - 273.15) * 1.8 + 32:0}°F";
case TemperatureScale.Kelvin:
return $"{_value}K";
default:
return _value.ToString(CultureInfo.InvariantCulture);
}
}
19
View Source File : NmsStreamMessage.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
public string ReadString()
{
CheckWriteOnlyBody();
CheckBytesInFlight();
string result;
object value = facade.Peek();
if (value == null)
result = null;
else if (value is string stringValue)
result = stringValue;
else if (value is float floatValue)
result = floatValue.ToString(CultureInfo.InvariantCulture);
else if (value is double doubleValue)
result = doubleValue.ToString(CultureInfo.InvariantCulture);
else if (value is long longValue)
result = longValue.ToString();
else if (value is int intValue)
result = intValue.ToString();
else if (value is short shortValue)
result = shortValue.ToString();
else if (value is byte byteValue)
result = byteValue.ToString();
else if (value is bool boolValue)
result = boolValue.ToString();
else if (value is char charValue)
result = charValue.ToString();
else
throw new MessageFormatException("stream value: " + value.GetType().Name + " cannot be converted to int.");
facade.Pop();
return result;
}
19
View Source File : NmsStreamMessageTest.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
[Test, Description("Set a double, then retrieve it as all of the legal type combinations to verify it is parsed correctly")]
public void TestWriteDoubleReadLegal()
{
NmsStreamMessage streamMessage = factory.CreateStreamMessage();
double value = double.MaxValue;
streamMessage.WriteDouble(value);
streamMessage.Reset();
replacedertGetStreamEntryEquals<double>(streamMessage, true, value);
replacedertGetStreamEntryEquals<string>(streamMessage, true, value.ToString(CultureInfo.InvariantCulture));
}
19
View Source File : CapabilitiesDocumentBuilder.cs
License : MIT License
Project Creator : apdevelop
License : MIT License
Project Creator : apdevelop
public XmlDoreplacedent GetTileSets(string tilemapName)
{
var doc = new XmlDoreplacedent();
var root = doc.CreateElement(String.Empty, "TileMap", String.Empty);
doc.AppendChild(root);
var versionAttribute = doc.CreateAttribute("version");
versionAttribute.Value = Utils.TileMapServiceVersion;
root.Attributes.Append(versionAttribute);
var tilemapservice = $"{this.baseUrl}/tms/{Utils.TileMapServiceVersion}/";
var tilemapserviceAttribute = doc.CreateAttribute("tilemapservice");
tilemapserviceAttribute.Value = tilemapservice;
root.Attributes.Append(tilemapserviceAttribute);
var replacedleNode = doc.CreateElement("replacedle");
replacedleNode.AppendChild(doc.CreateTextNode(tilemapName));
root.AppendChild(replacedleNode);
var abstractNode = doc.CreateElement("Abstract");
abstractNode.AppendChild(doc.CreateTextNode(tilemapName));
root.AppendChild(abstractNode);
var srs = doc.CreateElement("SRS");
srs.AppendChild(doc.CreateTextNode(Utils.EPSG3857));
root.AppendChild(srs);
const int TileSize = 256;
const double maxy = 20037508.342789;
const double maxx = 20037508.342789;
const double miny = -20037508.342789;
const double minx = -20037508.342789;
var boundingBox = doc.CreateElement("BoundingBox");
var maxyAttribute = doc.CreateAttribute("maxy");
maxyAttribute.Value = maxy.ToString("F6", CultureInfo.InvariantCulture);
boundingBox.Attributes.Append(maxyAttribute);
var maxxAttribute = doc.CreateAttribute("maxx");
maxxAttribute.Value = maxx.ToString("F6", CultureInfo.InvariantCulture);
boundingBox.Attributes.Append(maxxAttribute);
var minyAttribute = doc.CreateAttribute("miny");
minyAttribute.Value = miny.ToString("F6", CultureInfo.InvariantCulture);
boundingBox.Attributes.Append(minyAttribute);
var minxAttribute = doc.CreateAttribute("minx");
minxAttribute.Value = minx.ToString("F6", CultureInfo.InvariantCulture);
boundingBox.Attributes.Append(minxAttribute);
root.AppendChild(boundingBox);
var origin = doc.CreateElement("Origin");
var yAttribute = doc.CreateAttribute("y");
yAttribute.Value = miny.ToString("F6", CultureInfo.InvariantCulture);
origin.Attributes.Append(yAttribute);
var xAttribute = doc.CreateAttribute("x");
xAttribute.Value = minx.ToString("F6", CultureInfo.InvariantCulture);
origin.Attributes.Append(xAttribute);
root.AppendChild(origin);
var tm = Startup.TileSources[tilemapName];
var tileFormat = doc.CreateElement("TileFormat");
var extensionAttribute = doc.CreateAttribute("extension");
extensionAttribute.Value = tm.Configuration.Format;
tileFormat.Attributes.Append(extensionAttribute);
var mimetypeAttribute = doc.CreateAttribute("mime-type");
mimetypeAttribute.Value = tm.ContentType;
tileFormat.Attributes.Append(mimetypeAttribute);
var heightAttribute = doc.CreateAttribute("height");
heightAttribute.Value = TileSize.ToString(CultureInfo.InvariantCulture);
tileFormat.Attributes.Append(heightAttribute);
var widthAttribute = doc.CreateAttribute("width");
widthAttribute.Value = TileSize.ToString(CultureInfo.InvariantCulture);
tileFormat.Attributes.Append(widthAttribute);
root.AppendChild(tileFormat);
var tileSets = doc.CreateElement("TileSets");
root.AppendChild(tileSets);
for (var level = 0; level <= 18; level++) // TODO: get real existing range
{
var tileSet = doc.CreateElement("TileSet");
var href = $"{this.baseUrl}/tms/{Utils.TileMapServiceVersion}/{tm.Configuration.Name}/{tilemapName}/{level}";
var hrefAttribute = doc.CreateAttribute("href");
hrefAttribute.Value = href;
tileSet.Attributes.Append(hrefAttribute);
var orderAttribute = doc.CreateAttribute("order");
orderAttribute.Value = $"{level}";
tileSet.Attributes.Append(orderAttribute);
var unitsperpixel = (maxx - minx) / (((double)TileSize) * Math.Pow(2, level));
var unitsperpixelAttribute = doc.CreateAttribute("units-per-pixel");
unitsperpixelAttribute.Value = unitsperpixel.ToString(CultureInfo.InvariantCulture);
tileSet.Attributes.Append(unitsperpixelAttribute);
tileSets.AppendChild(tileSet);
}
return doc;
}
See More Examples