Here are the examples of the csharp api double.TryParse(string, System.Globalization.NumberStyles, System.IFormatProvider, out double) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1008 Examples
19
View Source File : TableColumn.Types.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public override ExprLiteral FromString(string? value) =>
value == null
? throw new SqExpressException($"Value cannot be null for '{this.ColumnName.Name}' non nullable column")
: double.TryParse(value, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var result)
? SqQueryBuilder.Literal(result)
: throw new SqExpressException($"Could not parse '{value}' as double for column '{this.ColumnName.Name}'.");
19
View Source File : TableColumn.Types.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public override ExprLiteral FromString(string? value) =>
value == null
? SqQueryBuilder.Literal((double?)null)
: double.TryParse(value, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var result)
? SqQueryBuilder.Literal(result)
: throw new SqExpressException($"Could not parse '{value}' as double for column '{this.ColumnName.Name}'.");
19
View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static object FromObject(this Type targetType, object value, Encoding encoding = null)
{
if (targetType == typeof(object)) return value;
if (encoding == null) encoding = Encoding.UTF8;
var valueIsNull = value == null;
var valueType = valueIsNull ? typeof(string) : value.GetType();
if (valueType == targetType) return value;
if (valueType == typeof(byte[])) //byte[] -> guid
{
if (targetType == typeof(Guid))
{
var bytes = value as byte[];
return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? tryguid : Guid.Empty;
}
if (targetType == typeof(Guid?))
{
var bytes = value as byte[];
return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? (Guid?)tryguid : null;
}
}
if (targetType == typeof(byte[])) //guid -> byte[]
{
if (valueIsNull) return null;
if (valueType == typeof(Guid) || valueType == typeof(Guid?))
{
var bytes = new byte[16];
var guidN = ((Guid)value).ToString("N");
for (var a = 0; a < guidN.Length; a += 2)
bytes[a / 2] = byte.Parse($"{guidN[a]}{guidN[a + 1]}", NumberStyles.HexNumber);
return bytes;
}
return encoding.GetBytes(value.ToInvariantCultureToString());
}
else if (targetType.IsArray)
{
if (value is Array valueArr)
{
var targetElementType = targetType.GetElementType();
var sourceArrLen = valueArr.Length;
var target = Array.CreateInstance(targetElementType, sourceArrLen);
for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueArr.GetValue(a), encoding), a);
return target;
}
//if (value is IList valueList)
//{
// var targetElementType = targetType.GetElementType();
// var sourceArrLen = valueList.Count;
// var target = Array.CreateInstance(targetElementType, sourceArrLen);
// for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueList[a], encoding), a);
// return target;
//}
}
var func = _dicFromObject.GetOrAdd(targetType, tt =>
{
if (tt == typeof(object)) return vs => vs;
if (tt == typeof(string)) return vs => vs;
if (tt == typeof(char[])) return vs => vs == null ? null : vs.ToCharArray();
if (tt == typeof(char)) return vs => vs == null ? default(char) : vs.ToCharArray(0, 1).FirstOrDefault();
if (tt == typeof(bool)) return vs =>
{
if (vs == null) return false;
switch (vs.ToLower())
{
case "true":
case "1":
return true;
}
return false;
};
if (tt == typeof(bool?)) return vs =>
{
if (vs == null) return false;
switch (vs.ToLower())
{
case "true":
case "1":
return true;
case "false":
case "0":
return false;
}
return null;
};
if (tt == typeof(byte)) return vs => vs == null ? 0 : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(byte?)) return vs => vs == null ? null : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (byte?)tryval : null);
if (tt == typeof(decimal)) return vs => vs == null ? 0 : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(decimal?)) return vs => vs == null ? null : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (decimal?)tryval : null);
if (tt == typeof(double)) return vs => vs == null ? 0 : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(double?)) return vs => vs == null ? null : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (double?)tryval : null);
if (tt == typeof(float)) return vs => vs == null ? 0 : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(float?)) return vs => vs == null ? null : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (float?)tryval : null);
if (tt == typeof(int)) return vs => vs == null ? 0 : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(int?)) return vs => vs == null ? null : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (int?)tryval : null);
if (tt == typeof(long)) return vs => vs == null ? 0 : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(long?)) return vs => vs == null ? null : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (long?)tryval : null);
if (tt == typeof(sbyte)) return vs => vs == null ? 0 : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(sbyte?)) return vs => vs == null ? null : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (sbyte?)tryval : null);
if (tt == typeof(short)) return vs => vs == null ? 0 : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(short?)) return vs => vs == null ? null : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (short?)tryval : null);
if (tt == typeof(uint)) return vs => vs == null ? 0 : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(uint?)) return vs => vs == null ? null : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (uint?)tryval : null);
if (tt == typeof(ulong)) return vs => vs == null ? 0 : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(ulong?)) return vs => vs == null ? null : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ulong?)tryval : null);
if (tt == typeof(ushort)) return vs => vs == null ? 0 : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(ushort?)) return vs => vs == null ? null : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ushort?)tryval : null);
if (tt == typeof(DateTime)) return vs => vs == null ? DateTime.MinValue : (DateTime.TryParse(vs, out var tryval) ? tryval : DateTime.MinValue);
if (tt == typeof(DateTime?)) return vs => vs == null ? null : (DateTime.TryParse(vs, out var tryval) ? (DateTime?)tryval : null);
if (tt == typeof(DateTimeOffset)) return vs => vs == null ? DateTimeOffset.MinValue : (DateTimeOffset.TryParse(vs, out var tryval) ? tryval : DateTimeOffset.MinValue);
if (tt == typeof(DateTimeOffset?)) return vs => vs == null ? null : (DateTimeOffset.TryParse(vs, out var tryval) ? (DateTimeOffset?)tryval : null);
if (tt == typeof(TimeSpan)) return vs => vs == null ? TimeSpan.Zero : (TimeSpan.TryParse(vs, out var tryval) ? tryval : TimeSpan.Zero);
if (tt == typeof(TimeSpan?)) return vs => vs == null ? null : (TimeSpan.TryParse(vs, out var tryval) ? (TimeSpan?)tryval : null);
if (tt == typeof(Guid)) return vs => vs == null ? Guid.Empty : (Guid.TryParse(vs, out var tryval) ? tryval : Guid.Empty);
if (tt == typeof(Guid?)) return vs => vs == null ? null : (Guid.TryParse(vs, out var tryval) ? (Guid?)tryval : null);
if (tt == typeof(BigInteger)) return vs => vs == null ? 0 : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(BigInteger?)) return vs => vs == null ? null : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (BigInteger?)tryval : null);
if (tt.NullableTypeOrThis().IsEnum)
{
var tttype = tt.NullableTypeOrThis();
var ttdefval = tt.CreateInstanceGetDefaultValue();
return vs =>
{
if (string.IsNullOrWhiteSpace(vs)) return ttdefval;
return Enum.Parse(tttype, vs, true);
};
}
var localTargetType = targetType;
var localValueType = valueType;
return vs =>
{
if (vs == null) return null;
throw new NotSupportedException($"convert failed {localValueType.DisplayCsharp()} -> {localTargetType.DisplayCsharp()}");
};
});
var valueStr = valueIsNull ? null : (valueType == typeof(byte[]) ? encoding.GetString(value as byte[]) : value.ToInvariantCultureToString());
return func(valueStr);
}
19
View Source File : GrblSettingsWindow.xaml.cs
License : MIT License
Project Creator : 3RD-Dimension
License : MIT License
Project Creator : 3RD-Dimension
private async void ButtonApply_Click(object sender, RoutedEventArgs e)
{
List<Tuple<int, double>> ToSend = new List<Tuple<int, double>>();
foreach (KeyValuePair<int, double> kvp in CurrentSettings)
{
double newval;
if (!double.TryParse(SettingsBoxes[kvp.Key].Text, System.Globalization.NumberStyles.Float, Util.Constants.DecimalParseFormat, out newval))
{
MessageBox.Show($"Value \"{SettingsBoxes[kvp.Key].Text}\" is invalid for Setting \"{Util.GrblCodeTranslator.Settings[kvp.Key].Item1}\"");
return;
}
if (newval == kvp.Value)
continue;
ToSend.Add(new Tuple<int, double>(kvp.Key, newval));
}
if (SendLine == null)
return;
foreach (Tuple<int, double> setting in ToSend)
{
SendLine.Invoke($"${setting.Item1}={setting.Item2.ToString(Util.Constants.DecimalOutputFormat)}");
CurrentSettings[setting.Item1] = setting.Item2;
await Task.Delay(Properties.Settings.Default.SettingsSendDelay);
}
}
19
View Source File : SimpleJSON.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
private static JSONNode ParseElement(string token, bool quoted)
{
if (quoted)
return token;
string tmp = token.ToLower();
if (tmp == "false" || tmp == "true")
return tmp == "true";
if (tmp == "null")
return JSONNull.CreateOrGet();
double val;
if (double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out val))
return val;
else
return token;
}
19
View Source File : LoginInformationValidator.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
public (bool IsSuccess, LoginInformationDto? LoginInformation) ValidateLoginInfo(ResourceOwnerPreplacedwordValidationContext context)
{
var loginInfo = context?.Request?.Raw?["loginInfo"];
if (context.Request?.Client?.ClientId == "AdminBff")
return (true, new LoginInformationDto
{
Imei = null,
Lareplacedude = null,
Longitude = null
});
if(loginInfo == null)
{
return (false, null);
}
var query = HttpUtility.ParseQueryString(loginInfo);
var lon = query.Get("lon");
double dLon;
if (lon.IsNullOrEmpty())
{
return (false, null);
}
if (!double.TryParse(lon, out dLon))
{
return (false, null);
}
var lat = query.Get("lat");
double dLat;
if (lat.IsNullOrEmpty())
{
return (false, null);
}
if (!double.TryParse(lat, out dLat))
{
return (false, null);
}
// if dLon is not in this range -180 <= dLon <= +180
// or of dLat is not in this range -90 <= dLat <= +90
// return error
if (Math.Abs(dLon) > 180 || Math.Abs(dLat) > 90)
{
return (false, null);
}
var imei = query.Get("Imei");
if (imei.IsNullOrEmpty())
{
return (false, null);
}
return (true, new LoginInformationDto
{
Imei = imei,
Lareplacedude = dLat,
Longitude = dLon
});
}
19
View Source File : ThresholdBackgroundConverter.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var vm = value as TooltipViewModel;
if (vm == null) return null;
var brush = DefaultBrush;
if (vm.YValue > vm.HighThreshold) brush = HighThresholdBrush;
if (vm.YValue < vm.LowThreshold) brush = LowThresholdBrush;
var opacityStr = parameter as String;
if (opacityStr != null)
{
double opacity;
Double.TryParse(opacityStr, NumberStyles.Number, CultureInfo.InvariantCulture, out opacity);
brush = brush.Clone();
brush.Opacity = opacity;
}
return brush;
}
19
View Source File : ModifyAxisProperties.xaml.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private void OnMinYAxesChanged(object sender, RoutedEventArgs e)
{
double value;
var isPositiveDouble = double.TryParse((sender as TextBox).Text, NumberStyles.Float, CultureInfo.InvariantCulture, out value) && value >= 0;
if (!SetVisibleRange(yAxis, isPositiveDouble ? value : yAxis.VisibleRange.Min, yAxis.VisibleRange.Max))
{
minValueTb.Text = yAxis.VisibleRange.Min.ToString();
}
}
19
View Source File : ModifyAxisProperties.xaml.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private void OnMaxYAxesChanged(object sender, RoutedEventArgs e)
{
double value;
var isDouble = double.TryParse((sender as TextBox).Text, NumberStyles.Float, CultureInfo.InvariantCulture, out value) && value >= 0;
if (!SetVisibleRange(yAxis, yAxis.VisibleRange.Min, isDouble ? value : yAxis.VisibleRange.Max))
{
maxValueTb.Text = yAxis.VisibleRange.Max.ToString();
}
}
19
View Source File : ColorLabelProvider.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
protected override void OnPropertyChanged(string propertyName)
{
base.OnPropertyChanged(propertyName);
if (propertyName.Equals(nameof(Text)))
{
Foreground.Color = double.TryParse(Text, out double value)
? ColorGenerator.GetColor(value)
: ColorGenerator.DefaultColor;
}
}
19
View Source File : MutationCache.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
private static EffectArgument ParseEffectArgument(string filename, Effect effect, string operand)
{
var effectArgument = new EffectArgument();
effectArgument.Type = GetEffectArgumentType(effect, operand);
switch (effectArgument.Type)
{
case EffectArgumentType.Int:
if (!int.TryParse(operand, out effectArgument.IntVal))
{
if (effect.Quality != null && effect.Quality.StatType == StatType.Int && effect.Quality.StatIdx == (int)PropertyInt.ImbuedEffect && Enum.TryParse(operand, out ImbuedEffectType imbuedEffectType))
effectArgument.IntVal = (int)imbuedEffectType;
else if (Enum.TryParse(operand, out WieldRequirement wieldRequirement))
effectArgument.IntVal = (int)wieldRequirement;
else if (Enum.TryParse(operand, out Skill skill))
effectArgument.IntVal = (int)skill;
else
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse IntVal {operand}");
}
break;
case EffectArgumentType.Int64:
if (!long.TryParse(operand, out effectArgument.LongVal))
{
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse Int64Val {operand}");
}
break;
case EffectArgumentType.Double:
if (!double.TryParse(operand, out effectArgument.DoubleVal))
{
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse DoubleVal {operand}");
}
break;
case EffectArgumentType.Quality:
effectArgument.StatType = GetStatType(operand);
switch (effectArgument.StatType)
{
case StatType.Int:
if (Enum.TryParse(operand, out PropertyInt propInt))
effectArgument.StatIdx = (int)propInt;
else
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyInt.{operand}");
break;
case StatType.Int64:
if (Enum.TryParse(operand, out PropertyInt64 propInt64))
effectArgument.StatIdx = (int)propInt64;
else
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyInt64.{operand}");
break;
case StatType.Float:
if (Enum.TryParse(operand, out PropertyFloat propFloat))
effectArgument.StatIdx = (int)propFloat;
else
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyFloat.{operand}");
break;
case StatType.Bool:
if (Enum.TryParse(operand, out PropertyBool propBool))
effectArgument.StatIdx = (int)propBool;
else
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyBool.{operand}");
break;
case StatType.DataID:
if (Enum.TryParse(operand, out PropertyDataId propDID))
effectArgument.StatIdx = (int)propDID;
else
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyBool.{operand}");
break;
default:
log.Error($"MutationCache.BuildMutation({filename}) - unknown PropertyType.{operand}");
break;
}
break;
case EffectArgumentType.Random:
var match = Regex.Match(operand, @"Random\(([\d.-]+), ([\d.-]+)\)");
if (!match.Success || !float.TryParse(match.Groups[1].Value, out effectArgument.MinVal) || !float.TryParse(match.Groups[2].Value, out effectArgument.MaxVal))
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {operand}");
break;
case EffectArgumentType.Variable:
match = Regex.Match(operand, @"\[(\d+)\]");
if (!match.Success || !int.TryParse(match.Groups[1].Value, out effectArgument.IntVal))
log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {operand}");
break;
default:
log.Error($"MutationCache.BuildMutation({filename}) - unknown EffectArgumentType from {operand}");
break;
}
return effectArgument;
}
19
View Source File : TickerManager.cs
License : MIT License
Project Creator : acid-chicken
License : MIT License
Project Creator : acid-chicken
public static async Task SetGameAsTickerAsync()
{
try
{
Ticker = await ApiManager.GetTickerAsync("bitzeny", "JPY").ConfigureAwait(false);
var game = $"[{DateTimeOffset.FromUnixTimeSeconds(long.TryParse(Ticker.LastUpdated ?? "0", out long x) ? x : 0).ToLocalTime():M/d HH:mm}] {(double.TryParse(Ticker.PriceJpy ?? "0", out double y) ? y : 0):N3} JPY (hourly: {(Ticker.PercentChangeOnehour.StartsWith('-') || Ticker.PercentChangeOnehour == "0.00" ? "" : "+")}{Ticker.PercentChangeOnehour}% / daily: {(Ticker.PercentChangeTwentyfourhours.StartsWith('-') || Ticker.PercentChangeTwentyfourhours == "0.00" ? "" : "+")}{Ticker.PercentChangeTwentyfourhours}% / weekly: {(Ticker.PercentChangeSevenDays.StartsWith('-') || Ticker.PercentChangeSevenDays == "0.00" ? "" : "+")}{Ticker.PercentChangeSevenDays}%)";
await Task.WhenAll
(
DiscordClient.SetGameAsync(game),
RequestLogAsync(new LogMessage(LogSeverity.Verbose, "TickerManager", $"Set game to \"{game}\"."))
).ConfigureAwait(false);
}
catch (Exception ex)
{
await RequestLogAsync(new LogMessage(LogSeverity.Error, "TickerManager", ex.Message, ex)).ConfigureAwait(false);
}
}
19
View Source File : ExpressionUtility.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
internal static Object ConvertToCanonicalValue(
Object val,
out ValueKind kind,
out Object raw)
{
raw = null;
if (Object.ReferenceEquals(val, null))
{
kind = ValueKind.Null;
return null;
}
else if (val is Boolean)
{
kind = ValueKind.Boolean;
return val;
}
else if (val is Double)
{
kind = ValueKind.Number;
return val;
}
else if (val is String)
{
kind = ValueKind.String;
return val;
}
else if (val is INull n)
{
kind = ValueKind.Null;
raw = val;
return null;
}
else if (val is IBoolean boolean)
{
kind = ValueKind.Boolean;
raw = val;
return boolean.GetBoolean();
}
else if (val is INumber number)
{
kind = ValueKind.Number;
raw = val;
return number.GetNumber();
}
else if (val is IString str)
{
kind = ValueKind.String;
raw = val;
return str.GetString();
}
else if (val is IReadOnlyObject)
{
kind = ValueKind.Object;
return val;
}
else if (val is IReadOnlyArray)
{
kind = ValueKind.Array;
return val;
}
else if (!val.GetType().GetTypeInfo().IsClreplaced)
{
if (val is Decimal || val is Byte || val is SByte || val is Int16 || val is UInt16 || val is Int32 || val is UInt32 || val is Int64 || val is UInt64 || val is Single)
{
kind = ValueKind.Number;
return Convert.ToDouble(val);
}
else if (val is Enum)
{
var strVal = String.Format(CultureInfo.InvariantCulture, "{0:G}", val);
if (Double.TryParse(strVal, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out Double doubleValue))
{
kind = ValueKind.Number;
return doubleValue;
}
kind = ValueKind.String;
return strVal;
}
}
kind = ValueKind.Object;
return val;
}
19
View Source File : YamlObjectReader.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private Boolean MatchFloat(
Scalar scalar,
out NumberToken value)
{
// YAML 1.2 "core" schema https://yaml.org/spec/1.2/spec.html#id2804923
var str = scalar.Value;
if (!String.IsNullOrEmpty(str))
{
// Check for [-+]?(\.inf|\.Inf|\.INF)|\.nan|\.NaN|\.NAN
switch (str)
{
case ".inf":
case ".Inf":
case ".INF":
case "+.inf":
case "+.Inf":
case "+.INF":
value = new NumberToken(m_fileId, scalar.Start.Line, scalar.Start.Column, Double.PositiveInfinity);
return true;
case "-.inf":
case "-.Inf":
case "-.INF":
value = new NumberToken(m_fileId, scalar.Start.Line, scalar.Start.Column, Double.NegativeInfinity);
return true;
case ".nan":
case ".NaN":
case ".NAN":
value = new NumberToken(m_fileId, scalar.Start.Line, scalar.Start.Column, Double.NaN);
return true;
}
// Otherwise check [-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?
// Skip leading sign
var index = str[0] == '-' || str[0] == '+' ? 1 : 0;
// Check for integer portion
var length = str.Length;
var hasInteger = false;
while (index < length && str[index] >= '0' && str[index] <= '9')
{
hasInteger = true;
index++;
}
// Check for decimal point
var hasDot = false;
if (index < length && str[index] == '.')
{
hasDot = true;
index++;
}
// Check for decimal portion
var hasDecimal = false;
while (index < length && str[index] >= '0' && str[index] <= '9')
{
hasDecimal = true;
index++;
}
// Check [-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)
if ((hasDot && hasDecimal) || hasInteger)
{
// Check for end
if (index == length)
{
// Try parse
if (Double.TryParse(str, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var doubleValue))
{
value = new NumberToken(m_fileId, scalar.Start.Line, scalar.Start.Column, doubleValue);
return true;
}
// Otherwise exceeds range
else
{
ThrowInvalidValue(scalar, c_floatTag); // throws
}
}
// Check [eE][-+]?[0-9]
else if (index < length && (str[index] == 'e' || str[index] == 'E'))
{
index++;
// Skip sign
if (index < length && (str[index] == '-' || str[index] == '+'))
{
index++;
}
// Check for exponent
var hasExponent = false;
while (index < length && str[index] >= '0' && str[index] <= '9')
{
hasExponent = true;
index++;
}
// Check for end
if (hasExponent && index == length)
{
// Try parse
if (Double.TryParse(str, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out var doubleValue))
{
value = new NumberToken(m_fileId, scalar.Start.Line, scalar.Start.Column, (Double)doubleValue);
return true;
}
// Otherwise exceeds range
else
{
ThrowInvalidValue(scalar, c_floatTag); // throws
}
}
}
}
}
value = default;
return false;
}
19
View Source File : YamlObjectReader.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private Boolean MatchInteger(
Scalar scalar,
out NumberToken value)
{
// YAML 1.2 "core" schema https://yaml.org/spec/1.2/spec.html#id2804923
var str = scalar.Value;
if (!String.IsNullOrEmpty(str))
{
// Check for [0-9]+
var firstChar = str[0];
if (firstChar >= '0' && firstChar <= '9' &&
str.Skip(1).All(x => x >= '0' && x <= '9'))
{
// Try parse
if (Double.TryParse(str, NumberStyles.None, CultureInfo.InvariantCulture, out var doubleValue))
{
value = new NumberToken(m_fileId, scalar.Start.Line, scalar.Start.Column, doubleValue);
return true;
}
// Otherwise exceeds range
ThrowInvalidValue(scalar, c_integerTag); // throws
}
// Check for (-|+)[0-9]+
else if ((firstChar == '-' || firstChar == '+') &&
str.Length > 1 &&
str.Skip(1).All(x => x >= '0' && x <= '9'))
{
// Try parse
if (Double.TryParse(str, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var doubleValue))
{
value = new NumberToken(m_fileId, scalar.Start.Line, scalar.Start.Column, doubleValue);
return true;
}
// Otherwise exceeds range
ThrowInvalidValue(scalar, c_integerTag); // throws
}
// Check for 0x[0-9a-fA-F]+
else if (firstChar == '0' &&
str.Length > 2 &&
str[1] == 'x' &&
str.Skip(2).All(x => (x >= '0' && x <= '9') || (x >= 'a' && x <= 'f') || (x >= 'A' && x <= 'F')))
{
// Try parse
if (Int32.TryParse(str.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var integerValue))
{
value = new NumberToken(m_fileId, scalar.Start.Line, scalar.Start.Column, integerValue);
return true;
}
// Otherwise exceeds range
ThrowInvalidValue(scalar, c_integerTag); // throws
}
// Check for 0o[0-9]+
else if (firstChar == '0' &&
str.Length > 2 &&
str[1] == 'o' &&
str.Skip(2).All(x => x >= '0' && x <= '7'))
{
// Try parse
var integerValue = default(Int32);
try
{
integerValue = Convert.ToInt32(str.Substring(2), 8);
}
// Otherwise exceeds range
catch (Exception)
{
ThrowInvalidValue(scalar, c_integerTag); // throws
}
value = new NumberToken(m_fileId, scalar.Start.Line, scalar.Start.Column, integerValue);
return true;
}
}
value = default;
return false;
}
19
View Source File : ExpressionUtility.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
internal static Double ParseNumber(String str)
{
// Trim
str = str?.Trim() ?? String.Empty;
// Empty
if (String.IsNullOrEmpty(str))
{
return 0d;
}
// Try parse
else if (Double.TryParse(str, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out var value))
{
return value;
}
// Check for 0x[0-9a-fA-F]+
else if (str[0] == '0' &&
str.Length > 2 &&
str[1] == 'x' &&
str.Skip(2).All(x => (x >= '0' && x <= '9') || (x >= 'a' && x <= 'f') || (x >= 'A' && x <= 'F')))
{
// Try parse
if (Int32.TryParse(str.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var integer))
{
return (Double)integer;
}
// Otherwise exceeds range
}
// Check for 0o[0-9]+
else if (str[0] == '0' &&
str.Length > 2 &&
str[1] == 'o' &&
str.Skip(2).All(x => x >= '0' && x <= '7'))
{
// Try parse
var integer = default(Int32?);
try
{
integer = Convert.ToInt32(str.Substring(2), 8);
}
// Otherwise exceeds range
catch (Exception)
{
}
// Success
if (integer != null)
{
return (Double)integer.Value;
}
}
// Infinity
else if (String.Equals(str, ExpressionConstants.Infinity, StringComparison.Ordinal))
{
return Double.PositiveInfinity;
}
// -Infinity
else if (String.Equals(str, ExpressionConstants.NegativeInfinity, StringComparison.Ordinal))
{
return Double.NegativeInfinity;
}
// Otherwise NaN
return Double.NaN;
}
19
View Source File : VssApiResourceVersion.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private void FromVersionString(String apiVersionString)
{
if (String.IsNullOrEmpty(apiVersionString))
{
throw new VssInvalidApiResourceVersionException(apiVersionString);
}
// Check for a stage/resourceVersion string
int dashIndex = apiVersionString.IndexOf('-');
if (dashIndex >= 0)
{
String stageName;
// Check for a '.' which separate stage from resource version
int dotIndex = apiVersionString.IndexOf('.', dashIndex);
if (dotIndex > 0)
{
stageName = apiVersionString.Substring(dashIndex + 1, dotIndex - dashIndex - 1);
int resourceVersion;
String resourceVersionString = apiVersionString.Substring(dotIndex + 1);
if (!int.TryParse(resourceVersionString, out resourceVersion))
{
throw new VssInvalidApiResourceVersionException(apiVersionString);
}
else
{
this.ResourceVersion = resourceVersion;
}
}
else
{
stageName = apiVersionString.Substring(dashIndex + 1);
}
// Check for supported stage names
if (String.Equals(stageName, c_PreviewStageName, StringComparison.OrdinalIgnoreCase))
{
IsPreview = true;
}
else
{
throw new VssInvalidApiResourceVersionException(apiVersionString);
}
// Api version is the string before the dash
apiVersionString = apiVersionString.Substring(0, dashIndex);
}
// Trim a leading "v" for version
apiVersionString = apiVersionString.TrimStart('v');
double apiVersionValue;
if (!double.TryParse(apiVersionString, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out apiVersionValue))
{
throw new VssInvalidApiResourceVersionException(apiVersionString);
}
// Store the api version
this.ApiVersion = new Version(apiVersionValue.ToString("0.0", CultureInfo.InvariantCulture));
}
19
View Source File : IntComponent.xaml.cs
License : MIT License
Project Creator : ADeltaX
License : MIT License
Project Creator : ADeltaX
private void TxBox_TextChanged(object sender, TextChangedEventArgs e)
{
switch (_dataType)
{
case DataTypeEnum.RegUwpByte:
if (byte.TryParse(txBox.Text, out _))
FlagDataAsValid();
else
FlagDataAsInvalid();
break;
case DataTypeEnum.RegUwpInt16:
if (Int16.TryParse(txBox.Text, out _))
FlagDataAsValid();
else
FlagDataAsInvalid();
break;
case DataTypeEnum.RegUwpUint16:
if (UInt16.TryParse(txBox.Text, out _))
FlagDataAsValid();
else
FlagDataAsInvalid();
break;
case DataTypeEnum.RegUwpInt32:
if (Int32.TryParse(txBox.Text, out _))
FlagDataAsValid();
else
FlagDataAsInvalid();
break;
case DataTypeEnum.RegUwpUint32:
if (UInt32.TryParse(txBox.Text, out _))
FlagDataAsValid();
else
FlagDataAsInvalid();
break;
case DataTypeEnum.RegUwpInt64:
if (Int64.TryParse(txBox.Text, out _))
FlagDataAsValid();
else
FlagDataAsInvalid();
break;
case DataTypeEnum.RegUwpUint64:
if (UInt64.TryParse(txBox.Text, out _))
FlagDataAsValid();
else
FlagDataAsInvalid();
break;
case DataTypeEnum.RegUwpSingle:
if (Single.TryParse(txBox.Text, out _))
FlagDataAsValid();
else
FlagDataAsInvalid();
break;
case DataTypeEnum.RegUwpDouble:
if (Double.TryParse(txBox.Text, out _))
FlagDataAsValid();
else
FlagDataAsInvalid();
break;
default:
break;
}
}
19
View Source File : Expression.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static object ParseValue(string attributeName, string text)
{
// try convert from string to value type
object value;
DateTime dateTimeValue;
double doubleValue;
bool boolValue;
Guid guidValue;
if (double.TryParse(
text,
NumberStyles.Any,
CultureInfo.InvariantCulture,
out doubleValue))
{
value = doubleValue;
}
else if (DateTime.TryParse(
text,
CultureInfo.InvariantCulture,
DateTimeStyles.replacedumeLocal,
out dateTimeValue))
{
value = dateTimeValue;
}
else if (bool.TryParse(
text,
out boolValue))
{
value = boolValue;
}
else if (Guid.TryParse(
text,
out guidValue))
{
value = guidValue;
}
else if (string.Compare(text, "null", StringComparison.InvariantCultureIgnoreCase) == 0)
{
value = null;
}
else
{
value = text;
}
return value;
}
19
View Source File : SimpleJSON.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
private static JSONNode ParseElement(string token, bool quoted)
{
if (quoted)
return token;
if (token.Length <= 5)
{
string tmp = token.ToLower();
if (tmp == "false" || tmp == "true")
return tmp == "true";
if (tmp == "null")
return JSONNull.CreateOrGet();
}
double val;
if (double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out val))
return val;
else
return token;
}
19
View Source File : RedisLite.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
public static double ParseDouble(byte[] doubleBytes)
{
var doubleString = Encoding.UTF8.GetString(doubleBytes);
double d;
double.TryParse(doubleString, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out d);
return d;
}
19
View Source File : TextBoxNumericHelper.cs
License : MIT License
Project Creator : ahmed-abdelrazek
License : MIT License
Project Creator : ahmed-abdelrazek
private static void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var textBox = (TextBox)sender;
var defaultValue = GetDefaultValue(textBox);
var evenOddConstraint = GetEvenOddConstraint(textBox);
switch (GetOnlyNumeric(textBox))
{
case NumericFormat.Decimal:
{
if (decimal.TryParse(textBox.Text, out decimal number))
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
if (number % 2 != 0)
{
textBox.Text = defaultValue;
}
break;
case EvenOddConstraint.OnlyOdd:
if (number % 2 == 0)
{
textBox.Text = defaultValue;
}
break;
}
}
else
textBox.Text = defaultValue;
break;
}
case NumericFormat.Double:
{
if (double.TryParse(textBox.Text, out double number))
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
{
if (number % 2 != 0)
{
textBox.Text = defaultValue;
}
break;
}
case EvenOddConstraint.OnlyOdd:
{
if (number % 2 == 0)
{
textBox.Text = defaultValue;
}
break;
}
}
}
else
{
textBox.Text = defaultValue;
}
break;
}
case NumericFormat.Int:
{
if (int.TryParse(textBox.Text, out int number))
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
{
if (number % 2 != 0)
{
textBox.Text = defaultValue;
}
break;
}
case EvenOddConstraint.OnlyOdd:
{
if (number % 2 == 0)
{
textBox.Text = defaultValue;
}
}
break;
}
}
else
{
textBox.Text = defaultValue;
}
break;
}
case NumericFormat.Uint:
{
if (uint.TryParse(textBox.Text, out uint number))
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
{
if (number % 2 != 0)
{
textBox.Text = defaultValue;
}
break;
}
case EvenOddConstraint.OnlyOdd:
{
if (number % 2 == 0)
{
textBox.Text = defaultValue;
}
break;
}
}
}
else
{
textBox.Text = defaultValue;
}
break;
}
case NumericFormat.Natural:
{
if (uint.TryParse(textBox.Text, out uint number))
{
if (number == 0)
{
textBox.Text = defaultValue;
}
else
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
{
if (number % 2 != 0)
{
textBox.Text = defaultValue;
}
break;
}
case EvenOddConstraint.OnlyOdd:
{
if (number % 2 == 0)
{
textBox.Text = defaultValue;
}
break;
}
}
}
}
else
{
textBox.Text = defaultValue;
}
break;
}
}
}
19
View Source File : TextBoxNumericHelper.cs
License : MIT License
Project Creator : ahmed-abdelrazek
License : MIT License
Project Creator : ahmed-abdelrazek
private static void TextBox_PasteEventHandler(object sender, DataObjectPastingEventArgs e)
{
var textBox = (TextBox)sender;
if (e.DataObject.GetDataPresent(typeof(string)))
{
var clipboardText = (string)e.DataObject.GetData(typeof(string));
var newText = textBox.Text.Insert(textBox.SelectionStart, clipboardText);
var evenOddConstraint = GetEvenOddConstraint(textBox);
switch (GetOnlyNumeric(textBox))
{
case NumericFormat.Decimal:
{
if (decimal.TryParse(newText, out decimal number))
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
{
if (number % 2 != 0)
{
e.CancelCommand();
}
break;
}
case EvenOddConstraint.OnlyOdd:
{
if (number % 2 == 0)
{
e.CancelCommand();
}
break;
}
}
}
else
{
e.CancelCommand();
}
break;
}
case NumericFormat.Double:
{
if (double.TryParse(newText, out double number))
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
{
if (number % 2 != 0)
{
e.CancelCommand();
}
break;
}
case EvenOddConstraint.OnlyOdd:
{
if (number % 2 == 0)
{
e.CancelCommand();
}
break;
}
}
}
else
{
e.CancelCommand();
}
break;
}
case NumericFormat.Int:
{
if (int.TryParse(newText, out int number))
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
{
if (number % 2 != 0)
{
e.CancelCommand();
}
break;
}
case EvenOddConstraint.OnlyOdd:
{
if (number % 2 == 0)
{
e.CancelCommand();
}
break;
}
}
}
else
{
e.CancelCommand();
}
break;
}
case NumericFormat.Uint:
{
if (uint.TryParse(newText, out uint number))
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
{
if (number % 2 != 0)
{
e.CancelCommand();
}
break;
}
case EvenOddConstraint.OnlyOdd:
{
if (number % 2 == 0)
{
e.CancelCommand();
}
break;
}
}
}
else
{
e.CancelCommand();
}
break;
}
case NumericFormat.Natural:
{
if (uint.TryParse(newText, out uint number))
{
if (number == 0)
{
e.CancelCommand();
}
else
{
switch (evenOddConstraint)
{
case EvenOddConstraint.OnlyEven:
{
if (number % 2 != 0)
{
e.CancelCommand();
}
break;
}
case EvenOddConstraint.OnlyOdd:
{
if (number % 2 == 0)
{
e.CancelCommand();
}
break;
}
}
}
}
else
{
e.CancelCommand();
}
break;
}
}
}
else
{
e.CancelCommand();
}
}
19
View Source File : UtilizationJsonDispatcher.cs
License : MIT License
Project Creator : ahydrax
License : MIT License
Project Creator : ahydrax
private static double ParseDouble(string s)
{
double.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out var d);
return d;
}
19
View Source File : NumericConverters.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
Task<Optional<double>> IArgumentConverter<double>.ConvertAsync(string value, CommandContext ctx)
{
return double.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out var result)
? Task.FromResult(Optional.FromValue(result))
: Task.FromResult(Optional.FromNoValue<double>());
}
19
View Source File : JPath.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private object ParseValue()
{
char currentChar = _expression[_currentIndex];
if (currentChar == '\'')
{
return ReadQuotedString();
}
else if (char.IsDigit(currentChar) || currentChar == '-')
{
StringBuilder sb = new StringBuilder();
sb.Append(currentChar);
_currentIndex++;
while (_currentIndex < _expression.Length)
{
currentChar = _expression[_currentIndex];
if (currentChar == ' ' || currentChar == ')')
{
string numberText = sb.ToString();
if (numberText.IndexOfAny(new char[] { '.', 'E', 'e' }) != -1)
{
double d;
if (double.TryParse(numberText, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out d))
{
return d;
}
else
{
throw new JsonException("Could not read query value.");
}
}
else
{
long l;
if (long.TryParse(numberText, NumberStyles.Integer, CultureInfo.InvariantCulture, out l))
{
return l;
}
else
{
throw new JsonException("Could not read query value.");
}
}
}
else
{
sb.Append(currentChar);
_currentIndex++;
}
}
}
else if (currentChar == 't')
{
if (Match("true"))
{
return true;
}
}
else if (currentChar == 'f')
{
if (Match("false"))
{
return false;
}
}
else if (currentChar == 'n')
{
if (Match("null"))
{
return null;
}
}
throw new JsonException("Could not read query value.");
}
19
View Source File : JsonTextReader.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private void ParseNumber(ReadType readType)
{
ShiftBufferIfNeeded();
char firstChar = _chars[_charPos];
int initialPosition = _charPos;
ReadNumberIntoBuffer();
// set state to PostValue now so that if there is an error parsing the number then the reader can continue
SetPostValueState(true);
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
object numberValue;
JsonToken numberType;
bool singleDigit = (char.IsDigit(firstChar) && _stringReference.Length == 1);
bool nonBase10 = (firstChar == '0' && _stringReference.Length > 1 && _stringReference.Chars[_stringReference.StartIndex + 1] != '.' && _stringReference.Chars[_stringReference.StartIndex + 1] != 'e' && _stringReference.Chars[_stringReference.StartIndex + 1] != 'E');
if (readType == ReadType.Readreplacedtring)
{
string number = _stringReference.ToString();
// validate that the string is a valid number
if (nonBase10)
{
try
{
if (number.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
{
Convert.ToInt64(number, 16);
}
else
{
Convert.ToInt64(number, 8);
}
}
catch (Exception ex)
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number), ex);
}
}
else
{
double value;
if (!double.TryParse(number, NumberStyles.Float, CultureInfo.InvariantCulture, out value))
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
}
}
numberType = JsonToken.String;
numberValue = number;
}
else if (readType == ReadType.ReadAsInt32)
{
if (singleDigit)
{
// digit char values start at 48
numberValue = firstChar - 48;
}
else if (nonBase10)
{
string number = _stringReference.ToString();
try
{
int integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt32(number, 16) : Convert.ToInt32(number, 8);
numberValue = integer;
}
catch (Exception ex)
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid integer.".FormatWith(CultureInfo.InvariantCulture, number), ex);
}
}
else
{
int value;
ParseResult parseResult = ConvertUtils.Int32TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value);
if (parseResult == ParseResult.Success)
{
numberValue = value;
}
else if (parseResult == ParseResult.Overflow)
{
throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int32.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
}
else
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid integer.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
}
}
numberType = JsonToken.Integer;
}
else if (readType == ReadType.ReadAsDecimal)
{
if (singleDigit)
{
// digit char values start at 48
numberValue = (decimal)firstChar - 48;
}
else if (nonBase10)
{
string number = _stringReference.ToString();
try
{
// decimal.Parse doesn't support parsing hexadecimal values
long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8);
numberValue = Convert.ToDecimal(integer);
}
catch (Exception ex)
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, number), ex);
}
}
else
{
string number = _stringReference.ToString();
decimal value;
if (decimal.TryParse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out value))
{
numberValue = value;
}
else
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
}
}
numberType = JsonToken.Float;
}
else if (readType == ReadType.ReadAsDouble)
{
if (singleDigit)
{
// digit char values start at 48
numberValue = (double)firstChar - 48;
}
else if (nonBase10)
{
string number = _stringReference.ToString();
try
{
// double.Parse doesn't support parsing hexadecimal values
long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8);
numberValue = Convert.ToDouble(integer);
}
catch (Exception ex)
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid double.".FormatWith(CultureInfo.InvariantCulture, number), ex);
}
}
else
{
string number = _stringReference.ToString();
double value;
if (double.TryParse(number, NumberStyles.Float, CultureInfo.InvariantCulture, out value))
{
numberValue = value;
}
else
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid double.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
}
}
numberType = JsonToken.Float;
}
else
{
if (singleDigit)
{
// digit char values start at 48
numberValue = (long)firstChar - 48;
numberType = JsonToken.Integer;
}
else if (nonBase10)
{
string number = _stringReference.ToString();
try
{
numberValue = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8);
}
catch (Exception ex)
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number), ex);
}
numberType = JsonToken.Integer;
}
else
{
long value;
ParseResult parseResult = ConvertUtils.Int64TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value);
if (parseResult == ParseResult.Success)
{
numberValue = value;
numberType = JsonToken.Integer;
}
else if (parseResult == ParseResult.Overflow)
{
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
string number = _stringReference.ToString();
if (number.Length > MaximumJavascriptIntegerCharacterLength)
{
throw JsonReaderException.Create(this, "JSON integer {0} is too large to parse.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
}
numberValue = BigIntegerParse(number, CultureInfo.InvariantCulture);
numberType = JsonToken.Integer;
#else
throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
#endif
}
else
{
string number = _stringReference.ToString();
if (_floatParseHandling == FloatParseHandling.Decimal)
{
decimal d;
if (decimal.TryParse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out d))
{
numberValue = d;
}
else
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, number));
}
}
else
{
double d;
if (double.TryParse(number, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out d))
{
numberValue = d;
}
else
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number));
}
}
numberType = JsonToken.Float;
}
}
}
ClearRecentString();
// index has already been updated
SetToken(numberType, numberValue, false);
}
19
View Source File : JsonReader.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
internal double? ReadDoubleString(string s)
{
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null, null, false);
return null;
}
double d;
if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out d))
{
SetToken(JsonToken.Float, d, false);
return d;
}
else
{
SetToken(JsonToken.String, s, false);
throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
}
}
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 : LogEntry.cs
License : Apache License 2.0
Project Creator : alaatm
License : Apache License 2.0
Project Creator : alaatm
List<TextSpan> ExtractSpans()
{
var spans = new List<TextSpan>();
var current = 0;
foreach (Match m in _propRegex.Matches(MessageTemplate))
{
var prop = m.Groups[0].Value;
var name = m.Groups[1].Value;
name = name.Contains(':') ? name.Substring(0, name.IndexOf(':')) : name;
var value = Properties.FirstOrDefault(p => p.Name == name)?.Value;
var startIdx = MessageTemplate.IndexOf(prop, current);
var endIdx = startIdx + prop.Length;
var section = MessageTemplate.Substring(current, startIdx - current);
spans.Add(new TextSpan
{
Text = section,
});
if (!string.IsNullOrEmpty(value))
{
var isNumber = double.TryParse(value, out var _);
spans.Add(new TextSpan
{
Kind = isNumber ? "num" : "str",
Text = value,
});
}
else
{
spans.Add(new TextSpan
{
Text = prop,
});
}
current = endIdx;
}
spans.Add(new TextSpan
{
Text = MessageTemplate.Substring(current),
});
var result = spans.Where(p => !string.IsNullOrEmpty(p.Text)).ToList();
return result;
}
19
View Source File : MapboxUnitTests_ProbeExtractorCs.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
private List<TracePoint> loadTraceFixture(string fixtureName)
{
Textreplacedet fixturereplacedet = Resources.Load<Textreplacedet>(fixtureName);
List<TracePoint> trace = new List<TracePoint>();
using (StringReader sr = new StringReader(fixturereplacedet.text))
{
// skip header
sr.ReadLine();
string line;
while (null != (line = sr.ReadLine()))
{
string[] tokens = line.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (tokens.Length != 4)
{
Debug.LogWarning("trace.csv has wrong number of columns");
continue;
}
double lng;
double lat;
double bearing;
long timestamp;
if (!double.TryParse(tokens[0], NumberStyles.Any, CultureInfo.InvariantCulture, out lng)) { Debug.LogWarning("could not parse longitude"); continue; }
if (!double.TryParse(tokens[1], NumberStyles.Any, CultureInfo.InvariantCulture, out lat)) { Debug.LogWarning("could not parse lareplacedude"); continue; }
if (!double.TryParse(tokens[2], NumberStyles.Any, CultureInfo.InvariantCulture, out bearing)) { Debug.LogWarning("could not parse bearing"); continue; }
if (!long.TryParse(tokens[3], NumberStyles.Any, CultureInfo.InvariantCulture, out timestamp)) { Debug.LogWarning("could not parse timestamp"); continue; }
trace.Add(new TracePoint()
{
Longitude = lng,
Lareplacedude = lat,
Bearing = bearing,
Timestamp = timestamp
});
}
}
return trace;
}
19
View Source File : MapboxUnitTests_ProbeExtractorCs.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
private List<Probe> loadProbeFixture(string fixtureName)
{
Textreplacedet fixturereplacedet = Resources.Load<Textreplacedet>(fixtureName);
List<Probe> probes = new List<Probe>();
using (StringReader sr = new StringReader(fixturereplacedet.text))
{
// skip header
sr.ReadLine();
string line;
while (null != (line = sr.ReadLine()))
{
string[] tokens = line.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (tokens.Length != 8)
{
Debug.LogWarning("probes.csv has wrong number of columns");
continue;
}
double lng;
double lat;
long startTime;
long duration;
double speed;
double bearing;
double distance;
bool isGood;
if (!double.TryParse(tokens[0], NumberStyles.Any, CultureInfo.InvariantCulture, out lng)) { Debug.LogWarning("could not parse longitude"); continue; }
if (!double.TryParse(tokens[1], NumberStyles.Any, CultureInfo.InvariantCulture, out lat)) { Debug.LogWarning("could not parse lareplacedude"); continue; }
if (!long.TryParse(tokens[2], NumberStyles.Any, CultureInfo.InvariantCulture, out startTime)) { Debug.LogWarning("could not parse timestamp"); continue; }
if (!long.TryParse(tokens[3], NumberStyles.Any, CultureInfo.InvariantCulture, out duration)) { Debug.LogWarning("could not parse duration"); continue; }
if (!double.TryParse(tokens[4], NumberStyles.Any, CultureInfo.InvariantCulture, out speed)) { Debug.LogWarning("could not parse speed"); continue; }
if (!double.TryParse(tokens[5], NumberStyles.Any, CultureInfo.InvariantCulture, out bearing)) { Debug.LogWarning("could not parse bearing"); continue; }
if (!double.TryParse(tokens[6], NumberStyles.Any, CultureInfo.InvariantCulture, out distance)) { Debug.LogWarning("could not parse distance"); continue; }
if (!bool.TryParse(tokens[7], out isGood)) { Debug.LogWarning("could not parse good"); continue; }
probes.Add(new Probe()
{
Longitude = lng,
Lareplacedude = lat,
StartTime = startTime,
Duration = duration,
Speed = speed,
Bearing = bearing,
Distance = distance,
IsGood = isGood
});
}
}
return probes;
}
19
View Source File : LocationLogReader.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
public IEnumerator<Location> GetLocations()
{
while (true)
{
string line = string.Empty;
while (1 == 1)
{
line = _textReader.ReadLine();
// rewind if end of log (or last empty line) reached
if (null == line || string.IsNullOrEmpty(line))
{
((StreamReader)_textReader).BaseStream.Position = 0;
((StreamReader)_textReader).DiscardBufferedData();
continue;
}
// skip comments
if (line.StartsWith("#")) { continue; } else { break; }
}
string[] tokens = line.Split(Delimiter.ToCharArray());
//simple safety net: check if number of columns matches
if (tokens.Length != HeaderNames.Length)
{
Debug.LogError("unsupported log file");
yield return new Location();
}
Location location = new Location();
location.IsLocationServiceEnabled = bool.Parse(tokens[(int)LogfileColumns.LocationServiceEnabled]);
location.IsLocationServiceInitializing = bool.Parse(tokens[(int)LogfileColumns.LocationServiceInitializing]);
location.IsLocationUpdated = bool.Parse(tokens[(int)LogfileColumns.LocationUpdated]);
location.IsUserHeadingUpdated = bool.Parse(tokens[(int)LogfileColumns.UserHeadingUpdated]);
location.Provider = tokens[(int)LogfileColumns.LocationProvider];
location.ProviderClreplaced = tokens[(int)LogfileColumns.LocationProviderClreplaced];
DateTime dtDevice;
string dtDeviceTxt = tokens[(int)LogfileColumns.UtcTimeDevice];
if (DateTime.TryParseExact(dtDeviceTxt, "yyyyMMdd-HHmmss.fff", _invariantCulture, DateTimeStyles.replacedumeUniversal, out dtDevice))
{
location.TimestampDevice = UnixTimestampUtils.To(dtDevice);
}
DateTime dtLocation;
string dtLocationTxt = tokens[(int)LogfileColumns.UtcTimeOfLocation];
if (DateTime.TryParseExact(dtLocationTxt, "yyyyMMdd-HHmmss.fff", _invariantCulture, DateTimeStyles.replacedumeUniversal, out dtLocation))
{
location.Timestamp = UnixTimestampUtils.To(dtLocation);
}
double lat;
string latTxt = tokens[(int)LogfileColumns.Lareplacedude];
double lng;
string lngTxt = tokens[(int)LogfileColumns.Longitude];
if (
!double.TryParse(latTxt, NumberStyles.Any, _invariantCulture, out lat)
|| !double.TryParse(lngTxt, NumberStyles.Any, _invariantCulture, out lng)
)
{
location.LareplacedudeLongitude = Vector2d.zero;
}
else
{
location.LareplacedudeLongitude = new Vector2d(lat, lng);
}
float accuracy;
location.Accuracy = float.TryParse(tokens[(int)LogfileColumns.Accuracy], NumberStyles.Any, _invariantCulture, out accuracy) ? accuracy : 0;
float userHeading;
location.UserHeading = float.TryParse(tokens[(int)LogfileColumns.UserHeading], NumberStyles.Any, _invariantCulture, out userHeading) ? userHeading : 0;
float deviceOrientation;
location.DeviceOrientation = float.TryParse(tokens[(int)LogfileColumns.DeviceOrientation], NumberStyles.Any, _invariantCulture, out deviceOrientation) ? deviceOrientation : 0;
float speed;
location.SpeedMetersPerSecond = float.TryParse(tokens[(int)LogfileColumns.Speed], NumberStyles.Any, _invariantCulture, out speed) ? speed / 3.6f : (float?)null;
bool hasGpsFix;
location.HasGpsFix = bool.TryParse(tokens[(int)LogfileColumns.HasGpsFix], out hasGpsFix) ? hasGpsFix : (bool?)null;
int satellitesUsed;
location.SatellitesUsed = int.TryParse(tokens[(int)LogfileColumns.SatellitesUsed], out satellitesUsed) ? satellitesUsed : (int?)null;
int satellitesInView;
location.SatellitesInView = int.TryParse(tokens[(int)LogfileColumns.SatellitesInView], out satellitesInView) ? satellitesInView : (int?)null;
yield return location;
}
}
19
View Source File : Conversions.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
public static Vector2d StringToLatLon(string s)
{
var latLonSplit = s.Split(',');
if (latLonSplit.Length != 2)
{
throw new ArgumentException("Wrong number of arguments");
}
double lareplacedude = 0;
double longitude = 0;
if (!double.TryParse(latLonSplit[0], NumberStyles.Any, NumberFormatInfo.InvariantInfo, out lareplacedude))
{
throw new Exception(string.Format("Could not convert lareplacedude to double: {0}", latLonSplit[0]));
}
if (!double.TryParse(latLonSplit[1], NumberStyles.Any, NumberFormatInfo.InvariantInfo, out longitude))
{
throw new Exception(string.Format("Could not convert longitude to double: {0}", latLonSplit[0]));
}
return new Vector2d(lareplacedude, longitude);
}
19
View Source File : LightDataTableShared.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
protected void TypeValidation(ref object value, Type dataType, bool loadDefaultOnError, object defaultValue = null)
{
try
{
ValidateCulture();
if (value == null || value is DBNull)
{
value = ValueByType(dataType, defaultValue);
return;
}
if (IgnoreTypeValidation)
return;
if (dataType == typeof(byte[]) && value.GetType() == typeof(string))
{
if (value.ToString().Length % 4 == 0) // its a valid base64string
value = Convert.FromBase64String(value.ToString());
return;
}
if (dataType == typeof(int?) || dataType == typeof(int))
{
if (double.TryParse(CleanValue(dataType, value).ToString(), NumberStyles.Float, Culture, out var douTal))
value = Convert.ToInt32(douTal);
else
if (loadDefaultOnError)
value = ValueByType(dataType, defaultValue);
return;
}
if (dataType == typeof(long?) || dataType == typeof(long))
{
if (double.TryParse(CleanValue(dataType, value).ToString(), NumberStyles.Float, Culture, out var douTal))
value = Convert.ToInt64(douTal);
else
if (loadDefaultOnError)
value = ValueByType(dataType, defaultValue);
return;
}
if (dataType == typeof(float?) || dataType == typeof(float))
{
if (float.TryParse(CleanValue(dataType, value).ToString(), NumberStyles.Float, Culture, out var douTal))
value = RoundingSettings.Round(douTal);
else
if (loadDefaultOnError)
value = ValueByType(dataType, defaultValue);
return;
}
if (dataType == typeof(decimal?) || dataType == typeof(decimal))
{
if (decimal.TryParse(CleanValue(dataType, value).ToString(), NumberStyles.Float, Culture, out var decTal))
value = RoundingSettings.Round(decTal);
else
if (loadDefaultOnError)
value = ValueByType(dataType, defaultValue);
return;
}
if (dataType == typeof(double?) || dataType == typeof(double))
{
if (double.TryParse(CleanValue(dataType, value).ToString(), NumberStyles.Float, Culture, out var douTal))
value = RoundingSettings.Round(douTal);
else
if (loadDefaultOnError)
value = ValueByType(dataType, defaultValue);
return;
}
if (dataType == typeof(DateTime?) || dataType == typeof(DateTime))
{
if (DateTime.TryParse(value.ToString(), Culture, DateTimeStyles.None, out var dateValue))
{
if (dateValue < SqlDateTime.MinValue)
dateValue = SqlDateTime.MinValue.Value;
value = dateValue;
}
else
if (loadDefaultOnError)
value = ValueByType(dataType, defaultValue);
return;
}
if (dataType == typeof(bool?) || dataType == typeof(bool))
{
if (bool.TryParse(value.ToString(), out var boolValue))
value = boolValue;
else
if (loadDefaultOnError)
value = ValueByType(dataType, defaultValue);
return;
}
if (dataType == typeof(TimeSpan?) || dataType == typeof(TimeSpan))
{
if (TimeSpan.TryParse(value.ToString(), Culture, out var timeSpanValue))
value = timeSpanValue;
else
if (loadDefaultOnError)
value = ValueByType(dataType, defaultValue);
return;
}
if (dataType.IsEnum || (dataType.GenericTypeArguments?.FirstOrDefault()?.IsEnum ?? false))
{
var type = dataType;
if ((dataType.GenericTypeArguments?.FirstOrDefault()?.IsEnum ?? false))
type = (dataType.GenericTypeArguments?.FirstOrDefault());
if (value is int || value is long)
{
if (Enum.IsDefined(type, Convert.ToInt32(value)))
value = Enum.ToObject(type, Convert.ToInt32(value));
}
else if (Enum.IsDefined(type, value))
value = Enum.Parse(type, value.ToString(), true);
else if (loadDefaultOnError)
value = Activator.CreateInstance(dataType);
}
else if (dataType == typeof(Guid) || dataType == typeof(Guid?))
{
if (Guid.TryParse(value.ToString(), out Guid v))
value = v;
else if (loadDefaultOnError)
value = ValueByType(dataType, defaultValue);
} else if (dataType == typeof(string))
{
value = value.ToString();
}
}
catch (Exception ex)
{
throw new Exception($"Error: InvalidType. ColumnType is {dataType.FullName} and the given value is of type {value.GetType().FullName} Original Exception {ex.Message}");
}
}
19
View Source File : UpdatePriceSettings.cs
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick
public bool GenerateBotSettings(out MKMBotSettings s)
{
s = new MKMBotSettings();
string[] limits = textBoxPriceEstMaxChange.Text.Split(';');
double threshold, allowedChange;
for (int i = 1; i < limits.Length; i += 2)
{
if (double.TryParse(limits[i - 1], NumberStyles.Float, CultureInfo.CurrentCulture, out threshold)
&& double.TryParse(limits[i], NumberStyles.Float, CultureInfo.CurrentCulture, out allowedChange))
s.PriceMaxChangeLimits.Add(threshold, allowedChange / 100); // convert to percent
else
{
MessageBox.Show("The max price change limit pair " + limits[i - 1] + ";" + limits[i]
+ " could not be parsed as a number.", "Incorrect format of max price change format", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
limits = textBoxPriceEstMaxDiff.Text.Split(';');
for (int i = 1; i < limits.Length; i += 2)
{
if (double.TryParse(limits[i - 1], NumberStyles.Float, CultureInfo.CurrentCulture, out threshold)
&& double.TryParse(limits[i], NumberStyles.Float, CultureInfo.CurrentCulture, out allowedChange))
s.PriceMaxDifferenceLimits.Add(threshold, allowedChange / 100); // convert to percent
else
{
MessageBox.Show("The max difference limit pair " + limits[i - 1] + ";" + limits[i]
+ " could not be parsed as a number.", "Incorrect format of max difference between items", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
s.PriceMinRarePrice = decimal.ToDouble(numericUpDownPriceEstMinPrice.Value);
s.PriceMinSimilarItems = decimal.ToInt32(numericUpDownPriceEstMinN.Value);
s.PriceMaxSimilarItems = decimal.ToInt32(numericUpDownPriceEstMaxN.Value);
if (radioButtonPriceEstPriceByAvg.Checked)
{
s.PriceSetPriceBy = PriceSetMethod.ByAverage;
s.PriceFactor = (double)trackBarPriceEstAvg.Value / (trackBarPriceEstAvg.Maximum - trackBarPriceEstAvg.Minimum);
s.PriceFactorWorldwide = (double)trackBarPriceEstAvgWorld.Value / (trackBarPriceEstAvgWorld.Maximum - trackBarPriceEstAvgWorld.Minimum);
}
else if (radioButtonPriceEstByLowestPrice.Checked)
{
s.PriceSetPriceBy = PriceSetMethod.ByPercentageOfLowestPrice;
s.PriceFactor = s.PriceFactorWorldwide = decimal.ToDouble(numericUpDownPriceEstLowestPrice.Value) / 100;
}
else
{
s.PriceSetPriceBy = PriceSetMethod.ByPercentageOfHighestPrice;
s.PriceFactor = s.PriceFactorWorldwide = decimal.ToDouble(numericUpDownPriceEstHighestPrice.Value) / 100;
}
s.PriceMarkup2 = decimal.ToDouble(numericUpDownPriceMultCopies2.Value) / 100;
s.PriceMarkup3 = decimal.ToDouble(numericUpDownPriceMultCopies3.Value) / 100;
s.PriceMarkup4 = decimal.ToDouble(numericUpDownPriceMultCopies4.Value) / 100;
s.PriceMarkupCap = decimal.ToDouble(numericUpDownPriceMultCopiesCap.Value);
s.PriceIgnorePlaysets = checkBoxPricePlaysetIgnore.Checked;
if (radioButtonCondMatchOnly.Checked)
s.CondAcceptance = AcceptedCondition.OnlyMatching;
else if (radioButtonCondAcceptBetterAlways.Checked)
s.CondAcceptance = AcceptedCondition.Anything;
else
s.CondAcceptance = AcceptedCondition.SomeMatchesAbove;
s.FilterByExpansions = checkBoxFilterExpansions.Checked;
if (checkBoxFilterExpansions.Checked) // set this only if we are filtering by expansions
s.AllowedExpansions = allowedExpansionsWindow.GetSelected();
s.FilterByCountries = checkBoxFilterCountries.Checked;
if (checkBoxFilterCountries.Checked) // set this only if we are filtering by countries
s.AllowedCountryNames = allowedCountriesWindow.GetSelected();
s.IncludePrivateSellers = checkBoxFilterPrivSeller.Checked;
s.IncludeProfessionalSellers = checkBoxFilterProfSeller.Checked;
s.IncludePowersellers = checkBoxFilterPowerseller.Checked;
s.LogUpdated = checkBoxLogUpdated.Checked;
s.LogLessThanMinimum = checkBoxLogMinItems.Checked;
s.LogSmallPriceChange = checkBoxLogSmallChange.Checked;
s.LogLargePriceChangeTooLow = checkBoxLogLargeChangeLow.Checked;
s.LogLargePriceChangeTooHigh = checkBoxLogLargeChangeHigh.Checked;
s.LogHighPriceVariance = checkBoxLogHighVariance.Checked;
s.TestMode = checkBoxTestMode.Checked;
s.SearchWorldwide = checkBoxPriceEstWorldwide.Checked;
switch (comboBoxPriceEstUpdateMode.SelectedIndex)
{
case 0:
s.PriceUpdateMode = MKMBotSettings.UpdateMode.TOSS;
break;
case 1:
s.PriceUpdateMode = MKMBotSettings.UpdateMode.UpdateOnlyBelowMinPrice;
break;
case 2:
s.PriceUpdateMode = MKMBotSettings.UpdateMode.OnlyEnsureMinPrice;
break;
case 3:
s.PriceUpdateMode = MKMBotSettings.UpdateMode.UsePriceGuides;
break;
}
switch (comboBoxPriceEstMinPriceMatch.SelectedIndex)
{
case 0:
s.MyStockMinPriceMatch = MKMBotSettings.MinPriceMatch.Highest;
break;
case 1:
s.MyStockMinPriceMatch = MKMBotSettings.MinPriceMatch.Best;
break;
}
if (MKMHelpers.SAmCommercial)
{
s.SetGuideNonFoil(comboBoxPriceGuidesNonFoils.SelectedItem.ToString(), textBoxPriceGuidesNonFoil.Text);
s.SetGuideFoil(comboBoxPriceGuidesFoils.SelectedItem.ToString(), textBoxPriceGuidesFoils.Text);
s.GuideUseTOSSOnFail = checkBoxPriceGuidesTraverseNotFound.Checked;
s.GuideLogOnFail = checkBoxPriceGuidesLogNotFound.Checked;
}
return true;
}
19
View Source File : FormatExpressionBuilder.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
static bool ValidateUtcMilliseconds(string value) =>
double.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out var _);
19
View Source File : MKMHelpers.cs
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick
public static double ConvertDoubleAnySep(string toConvert)
{
if (double.TryParse(toConvert, NumberStyles.Float, CultureInfo.InvariantCulture, out double resInv))
return resInv;
if (double.TryParse(toConvert, NumberStyles.Float, CultureInfo.CurrentCulture, out double resCur))
return resCur;
return double.NaN;
}
19
View Source File : InteractiveBrokersServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private void LoadIbSecurities()
{
if (!File.Exists(@"Engine\" + @"IbSecuritiesToWatch.txt"))
{
return;
}
try
{
using (StreamReader reader = new StreamReader(@"Engine\" + @"IbSecuritiesToWatch.txt"))
{
_secIB = new List<SecurityIb>();
while (!reader.EndOfStream)
{
try
{
SecurityIb security = new SecurityIb();
string[] contrStrings = reader.ReadLine().Split('@');
security.ComboLegsDescription = contrStrings[0];
Int32.TryParse(contrStrings[1], out security.ConId);
security.Currency = contrStrings[2];
security.Exchange = contrStrings[3];
security.Expiry = contrStrings[4];
Boolean.TryParse(contrStrings[5], out security.IncludeExpired);
security.LocalSymbol = contrStrings[6];
security.Multiplier = contrStrings[7];
security.PrimaryExch = contrStrings[8];
security.Right = contrStrings[9];
security.SecId = contrStrings[10];
security.SecIdType = contrStrings[11];
security.SecType = contrStrings[12];
Double.TryParse(contrStrings[13], out security.Strike);
security.Symbol = contrStrings[14];
security.TradingClreplaced = contrStrings[15];
if (contrStrings.Length > 15 &&
string.IsNullOrEmpty(contrStrings[16]) == false)
{
security.CreateMarketDepthFromTrades = Convert.ToBoolean(contrStrings[16]);
}
_secIB.Add(security);
}
catch
{
// ignore
}
}
if (_secIB.Count == 0)
{
SecurityIb sec1 = new SecurityIb();
sec1.Symbol = "AAPL";
sec1.Exchange = "SMART";
sec1.SecType = "STK";
_secIB.Add(sec1);
SecurityIb sec2 = new SecurityIb();
sec2.Symbol = "FB";
sec2.Exchange = "SMART";
sec2.SecType = "STK";
_secIB.Add(sec2);
SecurityIb sec3 = new SecurityIb();
sec3.Symbol = "EUR";
sec3.Exchange = "IDEALPRO";
sec3.SecType = "CASH";
_secIB.Add(sec3);
SecurityIb sec4 = new SecurityIb();
sec4.Symbol = "GBP";
sec4.Exchange = "IDEALPRO";
sec4.SecType = "CASH";
_secIB.Add(sec4);
}
}
}
catch (Exception)
{
// ignored
}
}
19
View Source File : TinyJsonReader.cs
License : Apache License 2.0
Project Creator : allenai
License : Apache License 2.0
Project Creator : allenai
private void ReadNumber()
{
StringBuilder numberWord;
if (this.reusableBuilder == null)
{
this.reusableBuilder = new StringBuilder();
numberWord = this.reusableBuilder;
}
else
{
numberWord = this.reusableBuilder;
numberWord.Length = 0; // Clear
}
var isDouble = false;
var intChar = this.reader.Peek();
while (intChar != -1 && !IsWordBreak((char)intChar))
{
var c = this.ReadChar();
numberWord.Append(c);
if (c == '.' || c == 'e' || c == 'E')
{
isDouble = true;
}
intChar = this.reader.Peek();
}
var number = numberWord.ToString();
if (isDouble)
{
double parsedDouble;
Double.TryParse(number, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowExponent, System.Globalization.CultureInfo.InvariantCulture, out parsedDouble);
this.ValueType = ValueType.Double;
this.DoubleValue = parsedDouble;
}
else
{
long parsedInt;
if (Int64.TryParse(number, NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out parsedInt))
{
this.ValueType = ValueType.Long;
this.LongValue = parsedInt;
return;
}
ulong parsedULong;
if (ulong.TryParse(number, NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out parsedULong))
{
this.ValueType = ValueType.ULong;
this.ULongValue = parsedULong;
return;
}
Decimal parsedDecimal;
if (decimal.TryParse(number, NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out parsedDecimal))
{
this.ValueType = ValueType.Decimal;
this.DecimalValue = parsedDecimal;
return;
}
}
}
19
View Source File : ExpanderAngleConverter.cs
License : MIT License
Project Creator : ambleside138
License : MIT License
Project Creator : ambleside138
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double factor = 1.0;
if (parameter is { } parameterValue)
{
if (!double.TryParse(parameterValue.ToString(), out factor))
{
factor = 1.0;
}
}
return value switch
{
ExpandDirection.Left => 90 * factor,
ExpandDirection.Right => -90 * factor,
_ => 0
};
19
View Source File : DoubleConvert.cs
License : MIT License
Project Creator : amolines
License : MIT License
Project Creator : amolines
protected override double ToConvert(string value)
{
if (!double.TryParse(value,NumberStyles.Any, new CultureInfo("en-US"),out var result))
{
throw new InvalidCastConvertException(value, typeof(double));
}
return result;
}
19
View Source File : NumberBoxParser.cs
License : MIT License
Project Creator : amwx
License : MIT License
Project Creator : amwx
public static (double value, int charLen) GetNextNumber(ReadOnlySpan<char> inputSpan)
{
//TODO: Remove Regex impl (even tho this was copied from WinUI)
string input = inputSpan.ToString();
Regex rg = new Regex("^-?([^-+/*\\(\\)\\^\\s]+)");
var match = rg.Match(input);
if (match.Success)
{
// Might be a number
var matchLength = match.Value.Length;
//var parsedNum = parser.ParseDouble(input.Substring(0, matchLength));
if (double.TryParse(input.Substring(0, matchLength), System.Globalization.NumberStyles.Any, CultureInfo.CurrentCulture, out double result))
{
return (result, matchLength);
}
}
return (double.NaN, 0);
}
19
View Source File : NumberBox.cs
License : MIT License
Project Creator : amwx
License : MIT License
Project Creator : amwx
private double? ParseDouble(string txt)
{
if (double.TryParse(txt, NumberStyles.Any, CultureInfo.CurrentCulture, out double result))
{
return result;
}
return null;
}
19
View Source File : Frequency.cs
License : MIT License
Project Creator : AndreyAkinshin
License : MIT License
Project Creator : AndreyAkinshin
[PublicAPI, Pure]
public static bool TryParse(string s, FrequencyUnit unit, NumberStyles numberStyle, IFormatProvider formatProvider, out Frequency freq)
{
bool success = double.TryParse(s, numberStyle, formatProvider, out double result);
freq = new Frequency(result, unit);
return success;
}
19
View Source File : Threshold.cs
License : MIT License
Project Creator : AndreyAkinshin
License : MIT License
Project Creator : AndreyAkinshin
public static bool TryParse(string input, NumberStyles numberStyle, IFormatProvider formatProvider, out Threshold parsed)
{
if (string.IsNullOrWhiteSpace(input))
{
parsed = default;
return false;
}
var trimmed = input.Trim().ToLowerInvariant();
var number = new string(trimmed.TakeWhile(c => char.IsDigit(c) || c == '.' || c == ',').ToArray());
var unit = new string(trimmed.SkipWhile(c => char.IsDigit(c) || c == '.' || c == ',' || char.IsWhiteSpace(c)).ToArray());
if (!double.TryParse(number, numberStyle, formatProvider, out var parsedValue)
|| !ThresholdUnitExtensions.ShortNameToUnit.TryGetValue(unit, out var parsedUnit))
{
parsed = default;
return false;
}
parsed = parsedUnit == ThresholdUnit.Ratio ? Create(ThresholdUnit.Ratio, parsedValue / 100.0) : Create(parsedUnit, parsedValue);
return true;
}
19
View Source File : KagiChart.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
private static double GetReversalAmount(Series series, out double percentOfPrice)
{
// Check "ReversalAmount" custom attribute
double reversalAmount = 1.0;
percentOfPrice = 3.0;
if (series.IsCustomPropertySet(CustomPropertyName.ReversalAmount))
{
string attrValue = series[CustomPropertyName.ReversalAmount].Trim();
bool usePercentage = attrValue.EndsWith("%", StringComparison.Ordinal);
if (usePercentage)
{
attrValue = attrValue.Substring(0, attrValue.Length - 1);
}
if (usePercentage)
{
double percent;
bool parseSucceed = double.TryParse(attrValue, NumberStyles.Any, CultureInfo.InvariantCulture, out percent);
if (parseSucceed)
{
percentOfPrice = percent;
}
else
{
throw (new InvalidOperationException(SR.ExceptionKagiAttributeFormatInvalid("ReversalAmount")));
}
}
else
{
double amount;
bool parseSucceed = double.TryParse(attrValue, NumberStyles.Any, CultureInfo.InvariantCulture, out amount);
if (parseSucceed)
{
reversalAmount = amount;
percentOfPrice = 0.0;
}
else
{
throw (new InvalidOperationException(SR.ExceptionKagiAttributeFormatInvalid("ReversalAmount")));
}
}
}
return reversalAmount;
}
19
View Source File : CommonElements.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
[System.Diagnostics.Codereplacedysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.Double.TryParse(System.String,System.Globalization.NumberStyles,System.IFormatProvider,[email protected])")]
internal static double ParseDouble(string stringToParse, bool throwException)
{
Double result = 0.0;
if (throwException)
{
result = double.Parse(stringToParse, NumberStyles.Any, CultureInfo.InvariantCulture);
}
else
{
bool parseSucceed = double.TryParse(stringToParse, NumberStyles.Any, CultureInfo.InvariantCulture, out result);
if (!parseSucceed)
{
double.TryParse(stringToParse, NumberStyles.Any, CultureInfo.CurrentCulture, out result);
}
}
return result;
}
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 : PointAndFigureChart.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
private static double GetReversalAmount(
Series series)
{
// Check "ReversalAmount" custom attribute
double reversalAmount = 3.0;
if (series.IsCustomPropertySet(CustomPropertyName.ReversalAmount))
{
string attrValue = series[CustomPropertyName.ReversalAmount].Trim();
double amount;
bool parseSucceed = double.TryParse(attrValue, NumberStyles.Any, CultureInfo.InvariantCulture, out amount);
if (parseSucceed)
{
reversalAmount = amount;
}
else
{
throw (new InvalidOperationException(SR.ExceptionPointAndFigureReversalAmountInvalidFormat));
}
}
return reversalAmount;
}
See More Examples