Here are the examples of the csharp api double.Parse(string, System.Globalization.NumberStyles, System.IFormatProvider) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
813 Examples
19
View Source File : ExprPlainReader.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public bool TryGetDouble(IPlainItem node, string propertyName, out double value)
{
value = default;
if (this.TryGetSubNode(node.Id, propertyName, null, out var prop) && prop.Value != null)
{
value = double.Parse(prop.Value, CultureInfo.InvariantCulture);
return true;
}
return false;
}
19
View Source File : Machine.cs
License : MIT License
Project Creator : 3RD-Dimension
License : MIT License
Project Creator : 3RD-Dimension
private void UpdateStatus(string line)
{
if (!Connected)
return;
if (line.Contains("$J="))
return;
if (line.StartsWith("[TLO:"))
{
try
{
CurrentTLO = double.Parse(line.Substring(5, line.Length - 6), Constants.DecimalParseFormat);
RaiseEvent(PositionUpdateReceived);
}
catch { RaiseEvent(NonFatalException, "Error while Parsing Status Message"); }
return;
}
try
{
//we use a Regex here so G91.1 etc don't get recognized as G91
MatchCollection mc = GCodeSplitter.Matches(line);
for (int i = 0; i < mc.Count; i++)
{
Match m = mc[i];
if (m.Groups[1].Value != "G")
continue;
double code = double.Parse(m.Groups[2].Value, Constants.DecimalParseFormat);
if (code == 17)
Plane = ArcPlane.XY;
if (code == 18)
Plane = ArcPlane.YZ;
if (code == 19)
Plane = ArcPlane.ZX;
if (code == 20)
Unit = ParseUnit.Imperial;
if (code == 21)
Unit = ParseUnit.Metric;
if (code == 90)
DistanceMode = ParseDistanceMode.Absolute;
if (code == 91)
DistanceMode = ParseDistanceMode.Incremental;
if (code == 49)
CurrentTLO = 0;
if (code == 43.1)
{
if (mc.Count > (i + 1))
{
if (mc[i + 1].Groups[1].Value == "Z")
{
CurrentTLO = double.Parse(mc[i + 1].Groups[2].Value, Constants.DecimalParseFormat);
RaiseEvent(PositionUpdateReceived);
}
i += 1;
}
}
}
}
catch { RaiseEvent(NonFatalException, "Error while Parsing Status Message"); }
}
19
View Source File : Machine.cs
License : MIT License
Project Creator : 3RD-Dimension
License : MIT License
Project Creator : 3RD-Dimension
private void ParseStatus(string line)
{
MatchCollection statusMatch = StatusEx.Matches(line);
if (statusMatch.Count == 0)
{
NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line));
return;
}
bool posUpdate = false;
bool overrideUpdate = false;
bool pinStateUpdate = false;
bool resetPins = true;
foreach (Match m in statusMatch)
{
if (m.Index == 1)
{
Status = m.Groups[1].Value;
continue;
}
if (m.Groups[1].Value == "Ov")
{
try
{
string[] parts = m.Groups[2].Value.Split(',');
FeedOverride = int.Parse(parts[0]);
RapidOverride = int.Parse(parts[1]);
SpindleOverride = int.Parse(parts[2]);
overrideUpdate = true;
}
catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
}
else if (m.Groups[1].Value == "WCO")
{
try
{
string OffsetString = m.Groups[2].Value;
if (Properties.Settings.Default.IgnoreAdditionalAxes)
{
string[] parts = OffsetString.Split(',');
if (parts.Length > 3)
{
Array.Resize(ref parts, 3);
OffsetString = string.Join(",", parts);
}
}
WorkOffset = Vector3.Parse(OffsetString);
posUpdate = true;
}
catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
}
else if (SyncBuffer && m.Groups[1].Value == "Bf")
{
try
{
int availableBytes = int.Parse(m.Groups[2].Value.Split(',')[1]);
int used = Properties.Settings.Default.ControllerBufferSize - availableBytes;
if (used < 0)
used = 0;
BufferState = used;
RaiseEvent(Info, $"Buffer State Synced ({availableBytes} bytes free)");
}
catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
}
else if (m.Groups[1].Value == "Pn")
{
resetPins = false;
string states = m.Groups[2].Value;
bool stateX = states.Contains("X");
if (stateX != PinStateLimitX)
pinStateUpdate = true;
PinStateLimitX = stateX;
bool stateY = states.Contains("Y");
if (stateY != PinStateLimitY)
pinStateUpdate = true;
PinStateLimitY = stateY;
bool stateZ = states.Contains("Z");
if (stateZ != PinStateLimitZ)
pinStateUpdate = true;
PinStateLimitZ = stateZ;
bool stateP = states.Contains("P");
if (stateP != PinStateProbe)
pinStateUpdate = true;
PinStateProbe = stateP;
}
else if (m.Groups[1].Value == "F")
{
try
{
FeedRateRealtime = double.Parse(m.Groups[2].Value, Constants.DecimalParseFormat);
posUpdate = true;
}
catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
}
else if (m.Groups[1].Value == "FS")
{
try
{
string[] parts = m.Groups[2].Value.Split(',');
FeedRateRealtime = double.Parse(parts[0], Constants.DecimalParseFormat);
SpindleSpeedRealtime = double.Parse(parts[1], Constants.DecimalParseFormat);
posUpdate = true;
}
catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
}
}
SyncBuffer = false; //only run this immediately after button press
//run this later to catch work offset changes before parsing position
Vector3 NewMachinePosition = MachinePosition;
foreach (Match m in statusMatch)
{
if (m.Groups[1].Value == "MPos" || m.Groups[1].Value == "WPos")
{
try
{
string PositionString = m.Groups[2].Value;
if (Properties.Settings.Default.IgnoreAdditionalAxes)
{
string[] parts = PositionString.Split(',');
if (parts.Length > 3)
{
Array.Resize(ref parts, 3);
PositionString = string.Join(",", parts);
}
}
NewMachinePosition = Vector3.Parse(PositionString);
if (m.Groups[1].Value == "WPos")
NewMachinePosition += WorkOffset;
if (NewMachinePosition != MachinePosition)
{
posUpdate = true;
MachinePosition = NewMachinePosition;
}
}
catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
}
}
if (posUpdate && Connected && PositionUpdateReceived != null)
PositionUpdateReceived.Invoke();
if (overrideUpdate && Connected && OverrideChanged != null)
OverrideChanged.Invoke();
if (resetPins) //no pin state received in status -> all zero
{
pinStateUpdate = PinStateLimitX | PinStateLimitY | PinStateLimitZ | PinStateProbe; //was any pin set before
PinStateLimitX = false;
PinStateLimitY = false;
PinStateLimitZ = false;
PinStateProbe = false;
}
if (pinStateUpdate && Connected && PinStateChanged != null)
PinStateChanged.Invoke();
if (Connected && StatusReceived != null)
StatusReceived.Invoke(line);
}
19
View Source File : GrblSettingsWindow.xaml.cs
License : MIT License
Project Creator : 3RD-Dimension
License : MIT License
Project Creator : 3RD-Dimension
public void LineReceived(string line)
{
// Recieve GRBL Controller Version number and display - $i
// Recieved in format [VER: ... and [OPT:
if (!line.StartsWith("$") && !line.StartsWith("[VER:") && !line.StartsWith("[OPT:"))
return;
if (line.StartsWith("$"))
{
try
{
Match m = settingParser.Match(line);
int number = int.Parse(m.Groups[1].Value);
double value = double.Parse(m.Groups[2].Value, Util.Constants.DecimalParseFormat);
// Value = Setting Value, Number = Setting Code
if (!CurrentSettings.ContainsKey(number))
{
RowDefinition rowDef = new RowDefinition();
rowDef.Height = new GridLength(25);
gridMain.RowDefinitions.Add(rowDef);
TextBox valBox = new TextBox // Value of Setting Textbox
{
Text = value.ToString(Util.Constants.DecimalOutputFormat),
VerticalAlignment = VerticalAlignment.Center
};
// Define Mouseclick for textbox to open GRBLStepsCalcWindow for setting $100, $101, $102
if (number == 100) { valBox.Name = "Set100"; valBox.MouseDoubleClick += openStepsCalc; }
else if (number == 101) { valBox.Name = "Set101"; valBox.MouseDoubleClick += openStepsCalc; }
else if (number == 102) { valBox.Name = "Set102"; valBox.MouseDoubleClick += openStepsCalc; }
Grid.SetRow(valBox, gridMain.RowDefinitions.Count - 1);
Grid.SetColumn(valBox, 1);
gridMain.Children.Add(valBox);
TextBlock num = new TextBlock
{
Text = $"${number}=",
HorizontalAlignment = HorizontalAlignment.Right,
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetRow(num, gridMain.RowDefinitions.Count - 1);
Grid.SetColumn(num, 0);
gridMain.Children.Add(num);
if (Util.GrblCodeTranslator.Settings.ContainsKey(number))
{
Tuple<string, string, string> labels = Util.GrblCodeTranslator.Settings[number];
TextBlock name = new TextBlock
{
Text = labels.Item1,
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetRow(name, gridMain.RowDefinitions.Count - 1);
Grid.SetColumn(name, 0);
gridMain.Children.Add(name);
TextBlock unit = new TextBlock
{
Text = labels.Item2,
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetRow(unit, gridMain.RowDefinitions.Count - 1);
Grid.SetColumn(unit, 2);
gridMain.Children.Add(unit);
valBox.ToolTip = $"{labels.Item1} ({labels.Item2}):\n{labels.Item3}";
}
CurrentSettings.Add(number, value);
SettingsBoxes.Add(number, valBox);
}
else
{
SettingsBoxes[number].Text = value.ToString(Util.Constants.DecimalOutputFormat);
CurrentSettings[number] = value;
}
}
catch { }
}
// If the line starts with [VER: then we know we are getting the version and options
else if (line.StartsWith("[VER:") || line.StartsWith("[OPT:"))
{
// Frist need to remove front [ and rear ]
string VerOptInput; // Input string
string[] VerOptTrimmed;
VerOptInput = line.Remove(0, 1); // Remove [ from the start
VerOptInput = VerOptInput.Remove(VerOptInput.Length - 1);
// Next, split the values in half at the : - we only want VER/OPT and then the values
VerOptTrimmed = VerOptInput.Split(':');
// Now we fill in the boxes depending on which one
switch (VerOptTrimmed[0])
{
case "VER":
controllerInfo += "Version: " + VerOptTrimmed[1];
break;
case "OPT":
// First we have to split commas
string[] optSplit;
optSplit = VerOptTrimmed[1].Split(','); // Splits Options into 3. 0=Options, 1=blockBufferSize, 2=rxBufferSize
var individualChar = optSplit[0].ToCharArray();// Now split optSplit[0] into each option character
controllerInfo += " | Options: " + VerOptTrimmed[1]; // Full Options Non-Decoded String
foreach (char c in individualChar)
{
// Lookup what each code is and display.... buildCodes Dictionary
if (Util.GrblCodeTranslator.BuildCodes.ContainsKey(c.ToString()))
{
// Now lets try and create and append to a string and then bind it to a ToolTip? or some other way
controllerInfo += Environment.NewLine + Util.GrblCodeTranslator.BuildCodes[c.ToString()];
}
}
controllerInfo += Environment.NewLine + "Block Buffer Size: " + optSplit[1];
controllerInfo += Environment.NewLine + "RX Buffer Size: " + optSplit[2];
GRBL_Controller_Info.Text = controllerInfo.ToString();
break;
}
}
}
19
View Source File : GCodeParser.cs
License : MIT License
Project Creator : 3RD-Dimension
License : MIT License
Project Creator : 3RD-Dimension
static void Parse(string line, int lineNumber)
{
MatchCollection matches = GCodeSplitter.Matches(line);
List<Word> Words = new List<Word>(matches.Count);
foreach (Match match in matches)
{
Words.Add(new Word() { Command = match.Groups[1].Value[0], Parameter = double.Parse(match.Groups[2].Value, Constants.DecimalParseFormat) });
}
for (int i = 0; i < Words.Count; i++)
{
if (Words[i].Command == 'N')
{
Words.RemoveAt(i--);
continue;
}
if (IgnoreAxes.Contains(Words[i].Command) && Properties.Settings.Default.IgnoreAdditionalAxes)
{
Words.RemoveAt(i--);
continue;
}
if (!ValidWords.Contains(Words[i].Command))
{
Warnings.Add($"ignoring unknown word (letter): \"{Words[i]}\". (line {lineNumber})");
Words.RemoveAt(i--);
continue;
}
if (Words[i].Command != 'F')
continue;
State.Feed = Words[i].Parameter;
if (State.Unit == ParseUnit.Imperial)
State.Feed *= 25.4;
Words.RemoveAt(i--);
continue;
}
for (int i = 0; i < Words.Count; i++)
{
if (Words[i].Command == 'M')
{
int param = (int)Words[i].Parameter;
if (param != Words[i].Parameter || param < 0)
throw new ParseException("M code can only have positive integer parameters", lineNumber);
Commands.Add(new MCode() { Code = param, LineNumber = lineNumber });
Words.RemoveAt(i);
i--;
continue;
}
if (Words[i].Command == 'S')
{
double param = Words[i].Parameter;
if (param < 0)
Warnings.Add($"spindle speed must be positive. (line {lineNumber})");
Commands.Add(new Spindle() { Speed = Math.Abs(param), LineNumber = lineNumber });
Words.RemoveAt(i);
i--;
continue;
}
if (Words[i].Command == 'G' && !MotionCommands.Contains(Words[i].Parameter))
{
#region UnitPlaneDistanceMode
double param = Words[i].Parameter;
if (param == 90)
{
State.DistanceMode = ParseDistanceMode.Absolute;
Words.RemoveAt(i);
i--;
continue;
}
if (param == 91)
{
State.DistanceMode = ParseDistanceMode.Incremental;
Words.RemoveAt(i);
i--;
continue;
}
if (param == 90.1)
{
State.ArcDistanceMode = ParseDistanceMode.Absolute;
Words.RemoveAt(i);
continue;
}
if (param == 91.1)
{
State.ArcDistanceMode = ParseDistanceMode.Incremental;
Words.RemoveAt(i);
i--;
continue;
}
if (param == 21)
{
State.Unit = ParseUnit.Metric;
Words.RemoveAt(i);
i--;
continue;
}
if (param == 20)
{
State.Unit = ParseUnit.Imperial;
Words.RemoveAt(i);
i--;
continue;
}
if (param == 17)
{
State.Plane = ArcPlane.XY;
Words.RemoveAt(i);
i--;
continue;
}
if (param == 18)
{
State.Plane = ArcPlane.ZX;
Words.RemoveAt(i);
i--;
continue;
}
if (param == 19)
{
State.Plane = ArcPlane.YZ;
Words.RemoveAt(i);
i--;
continue;
}
if (param == 4)
{
if (Words.Count >= 2 && Words[i + 1].Command == 'P')
{
if (Words[i + 1].Parameter < 0)
Warnings.Add($"dwell time must be positive. (line {lineNumber})");
Commands.Add(new Dwell() { Seconds = Math.Abs(Words[i + 1].Parameter), LineNumber = lineNumber });
Words.RemoveAt(i + 1);
Words.RemoveAt(i);
i--;
continue;
}
}
Warnings.Add($"ignoring unknown command G{param}. (line {lineNumber})");
Words.RemoveAt(i--);
#endregion
}
}
if (Words.Count == 0)
return;
int MotionMode = State.LastMotionMode;
if (Words.First().Command == 'G')
{
MotionMode = (int)Words.First().Parameter;
State.LastMotionMode = MotionMode;
Words.RemoveAt(0);
}
if (MotionMode < 0)
throw new ParseException("no motion mode active", lineNumber);
double UnitMultiplier = (State.Unit == ParseUnit.Metric) ? 1 : 25.4;
Vector3 EndPos = State.Position;
if (State.DistanceMode == ParseDistanceMode.Incremental && State.PositionValid.Any(isValid => !isValid))
{
throw new ParseException("incremental motion is only allowed after an absolute position has been established (eg. with \"G90 G0 X0 Y0 Z5\")", lineNumber);
}
if ((MotionMode == 2 || MotionMode == 3) && State.PositionValid.Any(isValid => !isValid))
{
throw new ParseException("arcs (G2/G3) are only allowed after an absolute position has been established (eg. with \"G90 G0 X0 Y0 Z5\")", lineNumber);
}
#region FindEndPos
{
int Incremental = (State.DistanceMode == ParseDistanceMode.Incremental) ? 1 : 0;
for (int i = 0; i < Words.Count; i++)
{
if (Words[i].Command != 'X')
continue;
EndPos.X = Words[i].Parameter * UnitMultiplier + Incremental * EndPos.X;
Words.RemoveAt(i);
State.PositionValid[0] = true;
break;
}
for (int i = 0; i < Words.Count; i++)
{
if (Words[i].Command != 'Y')
continue;
EndPos.Y = Words[i].Parameter * UnitMultiplier + Incremental * EndPos.Y;
Words.RemoveAt(i);
State.PositionValid[1] = true;
break;
}
for (int i = 0; i < Words.Count; i++)
{
if (Words[i].Command != 'Z')
continue;
EndPos.Z = Words[i].Parameter * UnitMultiplier + Incremental * EndPos.Z;
Words.RemoveAt(i);
State.PositionValid[2] = true;
break;
}
}
#endregion
if (MotionMode != 0 && State.Feed <= 0)
{
throw new ParseException("feed rate undefined", lineNumber);
}
if (MotionMode == 1 && State.PositionValid.Any(isValid => !isValid))
{
Warnings.Add($"a feed move is used before an absolute position is established, height maps will not be applied to this motion. (line {lineNumber})");
}
if (MotionMode <= 1)
{
if (Words.Count > 0)
Warnings.Add($"motion command must be last in line (ignoring unused words {string.Join(" ", Words)} in block). (line {lineNumber})");
Line motion = new Line();
motion.Start = State.Position;
motion.End = EndPos;
motion.Feed = State.Feed;
motion.Rapid = MotionMode == 0;
motion.LineNumber = lineNumber;
State.PositionValid.CopyTo(motion.PositionValid, 0);
Commands.Add(motion);
State.Position = EndPos;
return;
}
double U, V;
bool IJKused = false;
switch (State.Plane)
{
default:
U = State.Position.X;
V = State.Position.Y;
break;
case ArcPlane.YZ:
U = State.Position.Y;
V = State.Position.Z;
break;
case ArcPlane.ZX:
U = State.Position.Z;
V = State.Position.X;
break;
}
#region FindIJK
{
int ArcIncremental = (State.ArcDistanceMode == ParseDistanceMode.Incremental) ? 1 : 0;
for (int i = 0; i < Words.Count; i++)
{
if (Words[i].Command != 'I')
continue;
switch (State.Plane)
{
case ArcPlane.XY:
U = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.X;
break;
case ArcPlane.YZ:
throw new ParseException("current plane is YZ, I word is invalid", lineNumber);
case ArcPlane.ZX:
V = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.X;
break;
}
IJKused = true;
Words.RemoveAt(i);
break;
}
for (int i = 0; i < Words.Count; i++)
{
if (Words[i].Command != 'J')
continue;
switch (State.Plane)
{
case ArcPlane.XY:
V = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Y;
break;
case ArcPlane.YZ:
U = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Y;
break;
case ArcPlane.ZX:
throw new ParseException("current plane is ZX, J word is invalid", lineNumber);
}
IJKused = true;
Words.RemoveAt(i);
break;
}
for (int i = 0; i < Words.Count; i++)
{
if (Words[i].Command != 'K')
continue;
switch (State.Plane)
{
case ArcPlane.XY:
throw new ParseException("current plane is XY, K word is invalid", lineNumber);
case ArcPlane.YZ:
V = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Z;
break;
case ArcPlane.ZX:
U = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Z;
break;
}
IJKused = true;
Words.RemoveAt(i);
break;
}
}
#endregion
#region ResolveRadius
for (int i = 0; i < Words.Count; i++)
{
if (Words[i].Command != 'R')
continue;
if (IJKused)
throw new ParseException("both IJK and R notation used", lineNumber);
if (State.Position == EndPos)
throw new ParseException("arcs in R-notation must have non-coincident start and end points", lineNumber);
double Radius = Words[i].Parameter * UnitMultiplier;
if (Radius == 0)
throw new ParseException("radius can't be zero", lineNumber);
double A, B;
switch (State.Plane)
{
default:
A = EndPos.X;
B = EndPos.Y;
break;
case ArcPlane.YZ:
A = EndPos.Y;
B = EndPos.Z;
break;
case ArcPlane.ZX:
A = EndPos.Z;
B = EndPos.X;
break;
}
A -= U; //(AB) = vector from start to end of arc along the axes of the current plane
B -= V;
//see grbl/gcode.c
double h_x2_div_d = 4.0 * (Radius * Radius) - (A * A + B * B);
if (h_x2_div_d < 0)
{
throw new ParseException("arc radius too small to reach both ends", lineNumber);
}
h_x2_div_d = -Math.Sqrt(h_x2_div_d) / Math.Sqrt(A * A + B * B);
if (MotionMode == 3 ^ Radius < 0)
{
h_x2_div_d = -h_x2_div_d;
}
U += 0.5 * (A - (B * h_x2_div_d));
V += 0.5 * (B + (A * h_x2_div_d));
Words.RemoveAt(i);
break;
}
#endregion
if (Words.Count > 0)
Warnings.Add($"motion command must be last in line (ignoring unused words {string.Join(" ", Words)} in block). (line {lineNumber})");
Arc arc = new Arc();
arc.Start = State.Position;
arc.End = EndPos;
arc.Feed = State.Feed;
arc.Direction = (MotionMode == 2) ? ArcDirection.CW : ArcDirection.CCW;
arc.U = U;
arc.V = V;
arc.LineNumber = lineNumber;
arc.Plane = State.Plane;
Commands.Add(arc);
State.Position = EndPos;
return;
}
19
View Source File : ValueMember.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
private static object ParseDefaultValue(Type type, object value)
{
if(true)
{
Type tmp = Helpers.GetUnderlyingType(type);
if (tmp != null) type = tmp;
}
switch (Helpers.GetTypeCode(type))
{
case ProtoTypeCode.Boolean:
case ProtoTypeCode.Byte:
case ProtoTypeCode.Char: // char.Parse missing on CF/phone7
case ProtoTypeCode.DateTime:
case ProtoTypeCode.Decimal:
case ProtoTypeCode.Double:
case ProtoTypeCode.Int16:
case ProtoTypeCode.Int32:
case ProtoTypeCode.Int64:
case ProtoTypeCode.SByte:
case ProtoTypeCode.Single:
case ProtoTypeCode.String:
case ProtoTypeCode.UInt16:
case ProtoTypeCode.UInt32:
case ProtoTypeCode.UInt64:
case ProtoTypeCode.TimeSpan:
case ProtoTypeCode.Uri:
case ProtoTypeCode.Guid:
{
value = value + "";
}
break;
}
if (value is string)
{
string s = (string)value;
if (Helpers.IsEnum(type)) return Helpers.ParseEnum(type, s);
switch (Helpers.GetTypeCode(type))
{
case ProtoTypeCode.Boolean: return bool.Parse(s);
case ProtoTypeCode.Byte: return byte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
case ProtoTypeCode.Char: // char.Parse missing on CF/phone7
if (s.Length == 1) return s[0];
throw new FormatException("Single character expected: \"" + s + "\"");
case ProtoTypeCode.DateTime: return DateTime.Parse(s, CultureInfo.InvariantCulture);
case ProtoTypeCode.Decimal: return decimal.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.Double: return double.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.Int16: return short.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.Int32: return int.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.Int64: return long.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.SByte: return sbyte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
case ProtoTypeCode.Single: return float.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.String: return s;
case ProtoTypeCode.UInt16: return ushort.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.UInt32: return uint.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.UInt64: return ulong.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.TimeSpan: return TimeSpan.Parse(s);
case ProtoTypeCode.Uri: return s; // Uri is decorated as string
case ProtoTypeCode.Guid: return new Guid(s);
}
}
#if FEAT_IKVM
if (Helpers.IsEnum(type)) return value; // return the underlying type instead
System.Type convertType = null;
switch(Helpers.GetTypeCode(type))
{
case ProtoTypeCode.SByte: convertType = typeof(sbyte); break;
case ProtoTypeCode.Int16: convertType = typeof(short); break;
case ProtoTypeCode.Int32: convertType = typeof(int); break;
case ProtoTypeCode.Int64: convertType = typeof(long); break;
case ProtoTypeCode.Byte: convertType = typeof(byte); break;
case ProtoTypeCode.UInt16: convertType = typeof(ushort); break;
case ProtoTypeCode.UInt32: convertType = typeof(uint); break;
case ProtoTypeCode.UInt64: convertType = typeof(ulong); break;
case ProtoTypeCode.Single: convertType = typeof(float); break;
case ProtoTypeCode.Double: convertType = typeof(double); break;
case ProtoTypeCode.Decimal: convertType = typeof(decimal); break;
}
if(convertType != null) return Convert.ChangeType(value, convertType, CultureInfo.InvariantCulture);
throw new ArgumentException("Unable to process default value: " + value + ", " + type.FullName);
#else
if (Helpers.IsEnum(type)) return Enum.ToObject(type, value);
return Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
#endif
}
19
View Source File : FdbTuplePackers.cs
License : MIT License
Project Creator : abdullin
License : MIT License
Project Creator : abdullin
public static double DeserializeDouble(Slice slice)
{
if (slice.IsNullOrEmpty) return 0;
byte type = slice[0];
switch (type)
{
case FdbTupleTypes.Nil:
{
return 0;
}
case FdbTupleTypes.Utf8:
{
return Double.Parse(FdbTupleParser.ParseUnicode(slice), CultureInfo.InvariantCulture);
}
case FdbTupleTypes.Single:
{
return (double)FdbTupleParser.ParseSingle(slice);
}
case FdbTupleTypes.Double:
{
return FdbTupleParser.ParseDouble(slice);
}
}
if (type <= FdbTupleTypes.IntPos8 && type >= FdbTupleTypes.IntNeg8)
{
return checked((double)DeserializeInt64(slice));
}
throw new FormatException(String.Format("Cannot convert tuple segment of type 0x{0:X} into a Double", type));
}
19
View Source File : FdbConverters.cs
License : MIT License
Project Creator : abdullin
License : MIT License
Project Creator : abdullin
private static void RegisterDefaultConverters()
{
//TODO: there is too much generic type combinations! need to refactor this ...
RegisterUnsafe<bool, Slice>((value) => Slice.FromByte(value ? (byte)1 : default(byte)));
RegisterUnsafe<bool, byte[]>((value) => Slice.FromByte(value ? (byte)1 : default(byte)).GetBytes());
RegisterUnsafe<bool, string>((value) => value ? "true" : "false");
RegisterUnsafe<bool, sbyte>((value) => value ? (sbyte)1 : default(sbyte));
RegisterUnsafe<bool, byte>((value) => value ? (byte)1 : default(byte));
RegisterUnsafe<bool, short>((value) => value ? (short)1 : default(short));
RegisterUnsafe<bool, ushort>((value) => value ? (ushort)1 : default(ushort));
RegisterUnsafe<bool, int>((value) => value ? 1 : default(int));
RegisterUnsafe<bool, uint>((value) => value ? 1U : default(uint));
RegisterUnsafe<bool, long>((value) => value ? 1L : default(long));
RegisterUnsafe<bool, ulong>((value) => value ? 1UL : default(ulong));
RegisterUnsafe<bool, double>((value) => value ? 0.0d : 1.0d);
RegisterUnsafe<bool, float>((value) => value ? 0.0f : 1.0f);
RegisterUnsafe<int, Slice>((value) => Slice.FromInt32(value));
RegisterUnsafe<int, byte[]>((value) => Slice.FromInt32(value).GetBytes());
RegisterUnsafe<int, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<int, bool>((value) => value != 0);
RegisterUnsafe<int, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<int, byte>((value) => checked((byte)value));
RegisterUnsafe<int, short>((value) => checked((short)value));
RegisterUnsafe<int, ushort>((value) => checked((ushort)value));
RegisterUnsafe<int, uint>((value) => (uint)value);
RegisterUnsafe<int, long>((value) => value);
RegisterUnsafe<int, ulong>((value) => (ulong)value);
RegisterUnsafe<int, double>((value) => value);
RegisterUnsafe<int, float>((value) => checked((float)value));
RegisterUnsafe<int, FdbTupleAlias>((value) => (FdbTupleAlias)value);
RegisterUnsafe<uint, Slice>((value) => Slice.FromUInt64(value));
RegisterUnsafe<uint, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
RegisterUnsafe<uint, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<uint, bool>((value) => value != 0);
RegisterUnsafe<uint, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<uint, byte>((value) => checked((byte)value));
RegisterUnsafe<uint, short>((value) => checked((short)value));
RegisterUnsafe<uint, ushort>((value) => checked((ushort)value));
RegisterUnsafe<uint, int>((value) => (int)value);
RegisterUnsafe<uint, long>((value) => value);
RegisterUnsafe<uint, ulong>((value) => value);
RegisterUnsafe<uint, double>((value) => value);
RegisterUnsafe<uint, float>((value) => checked((float)value));
RegisterUnsafe<long, Slice>((value) => Slice.FromInt64(value));
RegisterUnsafe<long, byte[]>((value) => Slice.FromInt64(value).GetBytes());
RegisterUnsafe<long, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<long, bool>((value) => value != 0);
RegisterUnsafe<long, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<long, byte>((value) => checked((byte)value));
RegisterUnsafe<long, short>((value) => checked((short)value));
RegisterUnsafe<long, ushort>((value) => checked((ushort)value));
RegisterUnsafe<long, int>((value) => checked((int)value));
RegisterUnsafe<long, uint>((value) => (uint)value);
RegisterUnsafe<long, ulong>((value) => (ulong)value);
RegisterUnsafe<long, double>((value) => checked((double)value));
RegisterUnsafe<long, float>((value) => checked((float)value));
RegisterUnsafe<long, TimeSpan>((value) => TimeSpan.FromTicks(value));
RegisterUnsafe<long, Uuid64>((value) => new Uuid64(value));
RegisterUnsafe<long, System.Net.IPAddress>((value) => new System.Net.IPAddress(value));
RegisterUnsafe<ulong, Slice>((value) => Slice.FromUInt64(value));
RegisterUnsafe<ulong, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
RegisterUnsafe<ulong, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<ulong, bool>((value) => value != 0);
RegisterUnsafe<ulong, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<ulong, byte>((value) => checked((byte)value));
RegisterUnsafe<ulong, short>((value) => checked((short)value));
RegisterUnsafe<ulong, ushort>((value) => checked((ushort)value));
RegisterUnsafe<ulong, int>((value) => checked((int)value));
RegisterUnsafe<ulong, uint>((value) => checked((uint)value));
RegisterUnsafe<ulong, long>((value) => checked((long)value));
RegisterUnsafe<ulong, double>((value) => checked((double)value));
RegisterUnsafe<ulong, float>((value) => checked((float)value));
RegisterUnsafe<ulong, Uuid64>((value) => new Uuid64(value));
RegisterUnsafe<ulong, TimeSpan>((value) => TimeSpan.FromTicks(checked((long)value)));
RegisterUnsafe<short, Slice>((value) => Slice.FromInt32(value));
RegisterUnsafe<short, byte[]>((value) => Slice.FromInt32(value).GetBytes());
RegisterUnsafe<short, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<short, bool>((value) => value != 0);
RegisterUnsafe<short, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<short, byte>((value) => checked((byte)value));
RegisterUnsafe<short, ushort>((value) => checked((ushort)value));
RegisterUnsafe<short, int>((value) => value);
RegisterUnsafe<short, uint>((value) => checked((uint)value));
RegisterUnsafe<short, long>((value) => value);
RegisterUnsafe<short, ulong>((value) => checked((ulong)value));
RegisterUnsafe<short, double>((value) => value);
RegisterUnsafe<short, float>((value) => value);
RegisterUnsafe<short, FdbTupleAlias>((value) => (FdbTupleAlias)value);
RegisterUnsafe<ushort, Slice>((value) => Slice.FromUInt64(value));
RegisterUnsafe<ushort, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
RegisterUnsafe<ushort, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<ushort, bool>((value) => value != 0);
RegisterUnsafe<ushort, byte>((value) => checked((byte)value));
RegisterUnsafe<ushort, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<ushort, short>((value) => checked((short)value));
RegisterUnsafe<ushort, int>((value) => value);
RegisterUnsafe<ushort, uint>((value) => value);
RegisterUnsafe<ushort, long>((value) => value);
RegisterUnsafe<ushort, ulong>((value) => value);
RegisterUnsafe<ushort, double>((value) => value);
RegisterUnsafe<ushort, float>((value) => value);
RegisterUnsafe<byte, Slice>((value) => Slice.FromInt32(value));
RegisterUnsafe<byte, byte[]>((value) => Slice.FromInt32(value).GetBytes());
RegisterUnsafe<byte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<byte, bool>((value) => value != 0);
RegisterUnsafe<byte, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<byte, short>((value) => value);
RegisterUnsafe<byte, ushort>((value) => value);
RegisterUnsafe<byte, int>((value) => value);
RegisterUnsafe<byte, uint>((value) => value);
RegisterUnsafe<byte, long>((value) => value);
RegisterUnsafe<byte, ulong>((value) => value);
RegisterUnsafe<byte, double>((value) => value);
RegisterUnsafe<byte, float>((value) => value);
RegisterUnsafe<byte, FdbTupleAlias>((value) => (FdbTupleAlias)value);
RegisterUnsafe<sbyte, Slice>((value) => Slice.FromInt64(value));
RegisterUnsafe<sbyte, byte[]>((value) => Slice.FromInt64(value).GetBytes());
RegisterUnsafe<sbyte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
RegisterUnsafe<sbyte, bool>((value) => value != 0);
RegisterUnsafe<sbyte, byte>((value) => checked((byte)value));
RegisterUnsafe<sbyte, short>((value) => value);
RegisterUnsafe<sbyte, ushort>((value) => checked((ushort)value));
RegisterUnsafe<sbyte, int>((value) => value);
RegisterUnsafe<sbyte, uint>((value) => checked((uint)value));
RegisterUnsafe<sbyte, long>((value) => value);
RegisterUnsafe<sbyte, ulong>((value) => checked((ulong)value));
RegisterUnsafe<sbyte, double>((value) => value);
RegisterUnsafe<sbyte, float>((value) => value);
RegisterUnsafe<float, Slice>((value) => Slice.FromSingle(value));
RegisterUnsafe<float, byte[]>((value) => Slice.FromSingle(value).GetBytes());
RegisterUnsafe<float, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
RegisterUnsafe<float, bool>((value) => !(value == 0f || float.IsNaN(value)));
RegisterUnsafe<float, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<float, byte>((value) => checked((byte)value));
RegisterUnsafe<float, short>((value) => checked((short)value));
RegisterUnsafe<float, ushort>((value) => checked((ushort)value));
RegisterUnsafe<float, int>((value) => checked((int)value));
RegisterUnsafe<float, uint>((value) => (uint)value);
RegisterUnsafe<float, long>((value) => checked((long)value));
RegisterUnsafe<float, ulong>((value) => (ulong)value);
RegisterUnsafe<float, double>((value) => value);
RegisterUnsafe<double, Slice>((value) => Slice.FromDouble(value));
RegisterUnsafe<double, byte[]>((value) => Slice.FromDouble(value).GetBytes());
RegisterUnsafe<double, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
RegisterUnsafe<double, bool>((value) => !(value == 0d || double.IsNaN(value)));
RegisterUnsafe<double, sbyte>((value) => checked((sbyte)value));
RegisterUnsafe<double, byte>((value) => checked((byte)value));
RegisterUnsafe<double, short>((value) => checked((short)value));
RegisterUnsafe<double, ushort>((value) => checked((ushort)value));
RegisterUnsafe<double, int>((value) => checked((int)value));
RegisterUnsafe<double, uint>((value) => (uint)value);
RegisterUnsafe<double, long>((value) => checked((long)value));
RegisterUnsafe<double, ulong>((value) => (ulong)value);
RegisterUnsafe<double, float>((value) => checked((float)value));
RegisterUnsafe<string, Slice>((value) => Slice.FromString(value));
RegisterUnsafe<string, byte[]>((value) => Slice.FromString(value).GetBytes());
RegisterUnsafe<string, bool>((value) => !string.IsNullOrEmpty(value));
RegisterUnsafe<string, sbyte>((value) => string.IsNullOrEmpty(value) ? default(sbyte) : SByte.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, byte>((value) => string.IsNullOrEmpty(value) ? default(byte) : Byte.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, short>((value) => string.IsNullOrEmpty(value) ? default(short) : Int16.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, ushort>((value) => string.IsNullOrEmpty(value) ? default(ushort) : UInt16.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, int>((value) => string.IsNullOrEmpty(value) ? default(int) : Int32.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, uint>((value) => string.IsNullOrEmpty(value) ? default(uint) : UInt32.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, long>((value) => string.IsNullOrEmpty(value) ? default(long) : Int64.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, ulong>((value) => string.IsNullOrEmpty(value) ? default(ulong) : UInt64.Parse(value, CultureInfo.InvariantCulture));
RegisterUnsafe<string, float>((value) => string.IsNullOrEmpty(value) ? default(float) : Single.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
RegisterUnsafe<string, double>((value) => string.IsNullOrEmpty(value) ? default(double) : Double.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
RegisterUnsafe<string, Guid>((value) => string.IsNullOrEmpty(value) ? default(Guid) : Guid.Parse(value));
RegisterUnsafe<string, Uuid128>((value) => string.IsNullOrEmpty(value) ? default(Uuid128) : Uuid128.Parse(value));
RegisterUnsafe<string, Uuid64>((value) => string.IsNullOrEmpty(value) ? default(Uuid64) : Uuid64.Parse(value));
RegisterUnsafe<string, System.Net.IPAddress>((value) => string.IsNullOrEmpty(value) ? default(System.Net.IPAddress) : System.Net.IPAddress.Parse(value));
RegisterUnsafe<byte[], Slice>((value) => Slice.Create(value));
RegisterUnsafe<byte[], string>((value) => value == null ? default(string) : value.Length == 0 ? String.Empty : System.Convert.ToBase64String(value));
RegisterUnsafe<byte[], bool>((value) => value != null && value.Length > 0);
RegisterUnsafe<byte[], sbyte>((value) => value == null ? default(sbyte) : Slice.Create(value).ToSByte());
RegisterUnsafe<byte[], byte>((value) => value == null ? default(byte) : Slice.Create(value).ToByte());
RegisterUnsafe<byte[], short>((value) => value == null ? default(short) : Slice.Create(value).ToInt16());
RegisterUnsafe<byte[], ushort>((value) => value == null ? default(ushort) : Slice.Create(value).ToUInt16());
RegisterUnsafe<byte[], int>((value) => value == null ? 0 : Slice.Create(value).ToInt32());
RegisterUnsafe<byte[], uint>((value) => value == null ? 0U : Slice.Create(value).ToUInt32());
RegisterUnsafe<byte[], long>((value) => value == null ? 0L : Slice.Create(value).ToInt64());
RegisterUnsafe<byte[], ulong>((value) => value == null ? 0UL : Slice.Create(value).ToUInt64());
RegisterUnsafe<byte[], Guid>((value) => value == null || value.Length == 0 ? default(Guid) : new Uuid128(value).ToGuid());
RegisterUnsafe<byte[], Uuid128>((value) => value == null || value.Length == 0 ? default(Uuid128) : new Uuid128(value));
RegisterUnsafe<byte[], Uuid64>((value) => value == null || value.Length == 0 ? default(Uuid64) : new Uuid64(value));
RegisterUnsafe<byte[], TimeSpan>((value) => value == null ? TimeSpan.Zero : TimeSpan.FromTicks(Slice.Create(value).ToInt64()));
RegisterUnsafe<byte[], System.Net.IPAddress>((value) => value == null || value.Length == 0 ? default(System.Net.IPAddress) : new System.Net.IPAddress(value));
RegisterUnsafe<Guid, Slice>((value) => Slice.FromGuid(value));
RegisterUnsafe<Guid, byte[]>((value) => Slice.FromGuid(value).GetBytes());
RegisterUnsafe<Guid, string>((value) => value.ToString("D", null));
RegisterUnsafe<Guid, Uuid128>((value) => new Uuid128(value));
RegisterUnsafe<Guid, bool>((value) => value != Guid.Empty);
RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(new Uuid128(value).ToByteArray()));
RegisterUnsafe<Uuid128, Slice>((value) => value.ToSlice());
RegisterUnsafe<Uuid128, byte[]>((value) => value.ToByteArray());
RegisterUnsafe<Uuid128, string>((value) => value.ToString("D", null));
RegisterUnsafe<Uuid128, Guid>((value) => value.ToGuid());
RegisterUnsafe<Uuid128, bool>((value) => value != Uuid128.Empty);
RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(value.ToByteArray()));
RegisterUnsafe<Uuid64, Slice>((value) => value.ToSlice());
RegisterUnsafe<Uuid64, byte[]>((value) => value.ToByteArray());
RegisterUnsafe<Uuid64, string>((value) => value.ToString("D", null));
RegisterUnsafe<Uuid64, long>((value) => value.ToInt64());
RegisterUnsafe<Uuid64, ulong>((value) => value.ToUInt64());
RegisterUnsafe<Uuid64, bool>((value) => value.ToInt64() != 0L);
RegisterUnsafe<TimeSpan, Slice>((value) => Slice.FromInt64(value.Ticks));
RegisterUnsafe<TimeSpan, byte[]>((value) => Slice.FromInt64(value.Ticks).GetBytes());
RegisterUnsafe<TimeSpan, long>((value) => value.Ticks);
RegisterUnsafe<TimeSpan, ulong>((value) => checked((ulong)value.Ticks));
RegisterUnsafe<TimeSpan, double>((value) => value.TotalSeconds);
RegisterUnsafe<TimeSpan, bool>((value) => value == TimeSpan.Zero);
RegisterUnsafe<System.Net.IPAddress, Slice>((value) => value != null ? Slice.Create(value.GetAddressBytes()) : Slice.Nil);
RegisterUnsafe<System.Net.IPAddress, byte[]>((value) => value != null ? value.GetAddressBytes() : null);
RegisterUnsafe<System.Net.IPAddress, string>((value) => value != null ? value.ToString() : null);
RegisterUnsafe<FdbTupleAlias, byte>((value) => (byte)value);
RegisterUnsafe<FdbTupleAlias, int>((value) => (int)value);
RegisterUnsafe<FdbTupleAlias, Slice>((value) => Slice.FromByte((byte)value));
//REVIEW: this should go in the Tuples layer !
RegisterUnsafe<Slice, byte[]>((value) => value.GetBytes());
RegisterUnsafe<Slice, string>((value) => value.ToUnicode());
RegisterUnsafe<Slice, bool>((value) => value.ToBool());
RegisterUnsafe<Slice, sbyte>((value) => value.ToSByte());
RegisterUnsafe<Slice, byte>((value) => value.ToByte());
RegisterUnsafe<Slice, short>((value) => value.ToInt16());
RegisterUnsafe<Slice, ushort>((value) => value.ToUInt16());
RegisterUnsafe<Slice, int>((value) => value.ToInt32());
RegisterUnsafe<Slice, uint>((value) => value.ToUInt32());
RegisterUnsafe<Slice, long>((value) => value.ToInt64());
RegisterUnsafe<Slice, ulong>((value) => value.ToUInt64());
RegisterUnsafe<Slice, Guid>((value) => value.ToGuid());
RegisterUnsafe<Slice, Uuid128>((value) => value.ToUuid128());
RegisterUnsafe<Slice, Uuid64>((value) => value.ToUuid64());
RegisterUnsafe<Slice, TimeSpan>((value) => TimeSpan.FromTicks(value.ToInt64()));
RegisterUnsafe<Slice, FdbTupleAlias>((value) => (FdbTupleAlias)value.ToByte());
RegisterUnsafe<Slice, System.Net.IPAddress>((value) => !value.IsNullOrEmpty ? new System.Net.IPAddress(value.GetBytes()) : null);
}
19
View Source File : IntComponent.xaml.cs
License : MIT License
Project Creator : ADeltaX
License : MIT License
Project Creator : ADeltaX
public byte[] GetValueData()
{
switch (_dataType)
{
case DataTypeEnum.RegUwpByte:
return FromByte(byte.Parse(txBox.Text), _timestamp);
case DataTypeEnum.RegUwpInt16:
return FromInt16(short.Parse(txBox.Text), _timestamp);
case DataTypeEnum.RegUwpUint16:
return FromUInt16(ushort.Parse(txBox.Text), _timestamp);
case DataTypeEnum.RegUwpInt32:
return FromInt32(int.Parse(txBox.Text), _timestamp);
case DataTypeEnum.RegUwpUint32:
return FromUInt32(uint.Parse(txBox.Text), _timestamp);
case DataTypeEnum.RegUwpInt64:
return FromInt64(long.Parse(txBox.Text), _timestamp);
case DataTypeEnum.RegUwpUint64:
return FromUInt64(ulong.Parse(txBox.Text), _timestamp);
case DataTypeEnum.RegUwpSingle:
return FromSingle(float.Parse(txBox.Text), _timestamp);
case DataTypeEnum.RegUwpDouble:
return FromDouble(double.Parse(txBox.Text), _timestamp);
default:
return null;
}
}
19
View Source File : IRCompiler.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a
License : GNU General Public License v3.0
Project Creator : Aekras1a
static double ParseR8(Token token) {
return double.Parse(token.Image);
}
19
View Source File : RedisFloat.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
static double FromString(string input)
{
return Double.Parse(input, NumberStyles.Float, CultureInfo.InvariantCulture);
}
19
View Source File : DlnaClient.cs
License : MIT License
Project Creator : aguang-xyz
License : MIT License
Project Creator : aguang-xyz
public async Task<DlnaGetTransportInfoResponse> GetTransportInfoAsync()
{
// Send SOAP request.
var result = await SendAsync(
ServiceTypes.AvTransport,
SoapActions.GetTransportInfo,
XElementFactory.GetTransportInfo());
// Parse result and return.
return new DlnaGetTransportInfoResponse
{
CurrentState =
result.XPathSelectElement("//*[local-name() = 'CurrentTransportState']")?.Value,
CurrentStatus =
result.XPathSelectElement("//*[local-name() = 'CurrentTransportStatus']")?.Value,
CurrentSpeed =
double.Parse(result.XPathSelectElement("//*[local-name() = 'CurrentSpeed']")?.Value ?? "1")
};
}
19
View Source File : NpcSpawnHelper.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama
License : GNU General Public License v3.0
Project Creator : AHeroicLlama
public static CSVFile ProcessNPCSpawns(CSVFile locationFile, List<Location> spawnChances)
{
string npcSpawnHeader = "npc,spawnClreplaced,locationFormID,chance";
List<CSVRow> rows = new List<CSVRow>();
foreach (CSVRow row in locationFile.rows)
{
string rowNPC = row.GetCellFromColumn("property");
string rowFormID = row.GetCellFromColumn("locationFormID");
// Calculate the 'clreplaced' (Main or Sub)
string rowClreplaced;
if (rowNPC.Contains("Main"))
{
rowClreplaced = "Main";
}
else if (rowNPC.Contains("Sub"))
{
rowClreplaced = "Sub";
}
else
{
continue;
}
rowNPC = TrimNPCName(rowNPC);
// Get the overall spawning odds for this location
double locationOverallOdds = 0;
foreach (Location spawnChance in spawnChances)
{
if (spawnChance.locationFormID == rowFormID)
{
locationOverallOdds = spawnChance.GetOdds(rowClreplaced);
}
}
// The NPC spawn chance is its individual chance over the sum spawn chances of the given location
double rowSpawnChance = double.Parse(row.GetCellFromColumn("value")) / locationOverallOdds;
rows.Add(new CSVRow(rowNPC + "," + rowClreplaced + "," + rowFormID + "," + rowSpawnChance, npcSpawnHeader));
}
return new CSVFile("SeventySix_NPCSpawn.csv", string.Join(",", npcSpawnHeader), rows);
}
19
View Source File : MissionParameterParser.cs
License : MIT License
Project Creator : ahydrax
License : MIT License
Project Creator : ahydrax
public static (object value, ErrorType error, bool ok) ParseParameter(Type parameterType, string parameterValue)
{
switch (parameterType)
{
case var t when t == typeof(string):
return (parameterValue, ErrorType.No, true);
case var t when t == typeof(bool):
return TryParse(JsonConvert.DeserializeObject<bool>, parameterValue);
case var t when t == typeof(byte):
return TryParse(x => byte.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture), parameterValue);
case var t when t == typeof(sbyte):
return TryParse(x => sbyte.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
parameterValue);
case var t when t == typeof(char):
return TryParse(x => x[0], parameterValue);
case var t when t == typeof(decimal):
return TryParse(x => decimal.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
parameterValue);
case var t when t == typeof(double):
return TryParse(x => double.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
parameterValue);
case var t when t == typeof(float):
return TryParse(x => float.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
parameterValue);
case var t when t == typeof(int):
return TryParse(x => int.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture), parameterValue);
case var t when t == typeof(uint):
return TryParse(x => uint.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture), parameterValue);
case var t when t == typeof(long):
return TryParse(x => long.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture), parameterValue);
case var t when t == typeof(ulong):
return TryParse(x => ulong.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
parameterValue);
case var t when t == typeof(short):
return TryParse(x => short.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
parameterValue);
case var t when t == typeof(ushort):
return TryParse(x => ushort.Parse(x, NumberStyles.Any, CultureInfo.InvariantCulture),
parameterValue);
case var t when t == typeof(DateTime):
return TryParse(
x => DateTimeOffset.ParseExact(x, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None)
.UtcDateTime,
parameterValue);
case var t when t == typeof(DateTimeOffset):
return TryParse(
x => DateTimeOffset.ParseExact(x, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None),
parameterValue);
case var t when t == typeof(Guid):
return TryParse(Guid.Parse, parameterValue);
case var t when t.IsEnum:
return TryParse(x => Enum.Parse(parameterType, x), parameterValue);
case var pctx when pctx == typeof(PerformContext):
case var jct when jct == typeof(IJobCancellationToken):
case var ct when ct == typeof(CancellationToken):
return (null, ErrorType.No, true);
case var t when t.CanBeInstantiated():
return TryParse(x => JsonConvert.DeserializeObject(parameterValue, t), parameterValue);
default:
return (null, ErrorType.Unsupported, false);
}
}
19
View Source File : RestClient.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
private void UpdateBucket(BaseRestRequest request, RestResponse response, TaskCompletionSource<bool> ratelimitTcs)
{
var bucket = request.RateLimitBucket;
if (response.Headers == null)
{
if (response.ResponseCode != 429) // do not fail when ratelimit was or the next request will be scheduled hitting the rate limit again
this.FailInitialRateLimitTest(request, ratelimitTcs);
return;
}
var hs = response.Headers;
if (hs.TryGetValue("X-RateLimit-Global", out var isglobal) && isglobal.ToLowerInvariant() == "true")
{
if (response.ResponseCode != 429)
this.FailInitialRateLimitTest(request, ratelimitTcs);
return;
}
var r1 = hs.TryGetValue("X-RateLimit-Limit", out var usesmax);
var r2 = hs.TryGetValue("X-RateLimit-Remaining", out var usesleft);
var r3 = hs.TryGetValue("X-RateLimit-Reset", out var reset);
var r4 = hs.TryGetValue("X-Ratelimit-Reset-After", out var resetAfter);
var r5 = hs.TryGetValue("X-Ratelimit-Bucket", out var hash);
if (!r1 || !r2 || !r3 || !r4)
{
//If the limits were determined before this request, make the bucket initial again.
if (response.ResponseCode != 429)
this.FailInitialRateLimitTest(request, ratelimitTcs, ratelimitTcs == null);
return;
}
var clienttime = DateTimeOffset.UtcNow;
var resettime = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).AddSeconds(double.Parse(reset, CultureInfo.InvariantCulture));
var servertime = clienttime;
if (hs.TryGetValue("Date", out var raw_date))
servertime = DateTimeOffset.Parse(raw_date, CultureInfo.InvariantCulture).ToUniversalTime();
var resetdelta = resettime - servertime;
//var difference = clienttime - servertime;
//if (Math.Abs(difference.TotalSeconds) >= 1)
//// this.Logger.LogMessage(LogLevel.DebugBaseDiscordClient.RestEventId, $"Difference between machine and server time: {difference.TotalMilliseconds.ToString("#,##0.00", CultureInfo.InvariantCulture)}ms", DateTime.Now);
//else
// difference = TimeSpan.Zero;
if (request.RateLimitWaitOverride.HasValue)
resetdelta = TimeSpan.FromSeconds(request.RateLimitWaitOverride.Value);
var newReset = clienttime + resetdelta;
if (this.UseResetAfter)
{
bucket.ResetAfter = TimeSpan.FromSeconds(double.Parse(resetAfter, CultureInfo.InvariantCulture));
newReset = clienttime + bucket.ResetAfter.Value + (request.RateLimitWaitOverride.HasValue
? resetdelta
: TimeSpan.Zero);
bucket.ResetAfterOffset = newReset;
}
else
bucket.Reset = newReset;
var maximum = int.Parse(usesmax, CultureInfo.InvariantCulture);
var remaining = int.Parse(usesleft, CultureInfo.InvariantCulture);
if (ratelimitTcs != null)
{
// initial population of the ratelimit data
bucket.SetInitialValues(maximum, remaining, newReset);
_ = Task.Run(() => ratelimitTcs.TrySetResult(true));
}
else
{
// only update the bucket values if this request was for a newer interval than the one
// currently in the bucket, to avoid issues with concurrent requests in one bucket
// remaining is reset by TryResetLimit and not the response, just allow that to happen when it is time
if (bucket._nextReset == 0)
bucket._nextReset = newReset.UtcTicks;
}
this.UpdateHashCaches(request, bucket, hash);
}
19
View Source File : LeetxParser.cs
License : MIT License
Project Creator : aivarasatk
License : MIT License
Project Creator : aivarasatk
public async Task<TorrentQueryResult> ParsePageForTorrentEntriesAsync(string pageContents)
{
return await Task.Run(() =>
{
try
{
_logger.Information("Leetx parsing");
var htmlAgility = new HtmlDoreplacedent();
htmlAgility.LoadHtml(pageContents);
var tableRows = htmlAgility.DoreplacedentNode.SelectNodes("//table[@clreplaced='table-list table table-responsive table-striped']/tbody/tr");//gets table rows that contain torrent data
if (NoTableEntries(tableRows))
return new TorrentQueryResult { IsLastPage = true };
var result = new List<TorrentEntry>();
foreach (var dataRow in tableRows)
{
var dataColumns = dataRow.SelectNodes("td");
if (dataColumns == null || dataColumns.Count != DataColumnCount)
{
_logger.Warning($"Could not find all columns for torrent {Environment.NewLine} {dataRow.OuterHtml}");
continue;
}
var replacedleNode = dataColumns[LeetxTorrentIndexer.Name]
.SelectNodes("a")?
.FirstOrDefault(a => a.Attributes.Any(atr => atr.Name == "href" && atr.Value.Contains("torrent")));
if (replacedleNode == null)
{
_logger.Warning($"Could not find replacedle node for torrent {Environment.NewLine} {dataColumns[LeetxTorrentIndexer.Name].OuterHtml}");
continue;
}
var replacedle = replacedleNode.InnerText;
if (string.IsNullOrEmpty(replacedle))//empty replacedle entry makes no sense. log and skip
{
_logger.Warning($"Empty replacedle from {Environment.NewLine}{replacedleNode.OuterHtml}");
continue;
}
var torrentUri = replacedleNode.Attributes.FirstOrDefault(a => a.Name == "href")?.Value;
if (string.IsNullOrEmpty(torrentUri))
{
_logger.Warning($"Empty torrent uri from{Environment.NewLine}{replacedleNode.OuterHtml}");
continue;
}
var magnetLink = string.Empty;
if (!int.TryParse(dataColumns[LeetxTorrentIndexer.Seeders].InnerText, out var seeders))
_logger.Warning($"Could not parse seeders {Environment.NewLine}{dataColumns[LeetxTorrentIndexer.Seeders].OuterHtml}");
if (!int.TryParse(dataColumns[LeetxTorrentIndexer.Leechers].InnerText, out var leechers))
_logger.Warning($"Could not parse leechers {Environment.NewLine}{dataColumns[LeetxTorrentIndexer.Leechers].OuterHtml}");
var date = dataColumns[LeetxTorrentIndexer.Date].InnerText;
var size = dataColumns[LeetxTorrentIndexer.Size].InnerHtml.Substring(0, dataColumns[LeetxTorrentIndexer.Size].InnerHtml.IndexOf('<'));
var uploader = dataColumns[LeetxTorrentIndexer.Uploader].SelectSingleNode("a")?.InnerText;
var splitSize = size.Split(' ');
result.Add(new TorrentEntry
{
replacedle = replacedle,
TorrentUri = TrimUriStart(torrentUri),
TorrentMagnet = magnetLink,
Date = ParseDate(date, _formats),
Size = new SizeEnreplacedy
{
Value = double.Parse(splitSize[0], CultureInfo.InvariantCulture),
Postfix = splitSize[1]
},
Uploader = uploader,
Seeders = seeders,
Leechers = leechers,
Source = TorrentSource.Leetx
});
}
var pagination = htmlAgility.DoreplacedentNode.SelectSingleNode("//div[@clreplaced='pagination']");
return new TorrentQueryResult
{
TorrentEntries = result,
IsLastPage = pagination == null || !pagination.InnerHtml.Contains("href")
};
}
catch(Exception ex)
{
_logger.Warning("1337X parse exception", ex);
throw;
}
});
}
19
View Source File : KickassParser.cs
License : MIT License
Project Creator : aivarasatk
License : MIT License
Project Creator : aivarasatk
public async Task<TorrentQueryResult> ParsePageForTorrentEntriesAsync(string pageContents)
{
return await Task.Run(() =>
{
try
{
_logger.Information("Kickreplaced parsing");
var htmlAgility = LoadedHtmlDoreplacedent(pageContents);
var tableRows = htmlAgility.DoreplacedentNode.SelectNodes("//tr[@clreplaced='odd'] | //tr[@clreplaced='even']");//gets table rows that contain torrent data
if (NoTableEntries(tableRows))
return new TorrentQueryResult { IsLastPage = true };
var result = new List<TorrentEntry>();
foreach (var row in tableRows)
{
var columns = row.SelectNodes("td");
if (columns == null || columns.Count != DataColumnCount)
{
_logger.Warning($"Could not find all columns for torrent {Environment.NewLine} {row.OuterHtml}");
continue;
}
var replacedleNode = columns[KickreplacedTorrentIndexer.Name]
.SelectSingleNode("div/div/a[@clreplaced='cellMainLink']");
if (replacedleNode == null)
{
_logger.Warning($"Could not find replacedle node for torrent {Environment.NewLine} {columns[KickreplacedTorrentIndexer.Name].OuterHtml}");
continue;
}
var replacedle = replacedleNode.InnerText.Trim();
if (string.IsNullOrEmpty(replacedle))//empty replacedle entry makes no sense. log and skip
{
_logger.Warning($"Empty replacedle from {Environment.NewLine}{replacedleNode.OuterHtml}");
continue;
}
var torrentUri = replacedleNode.Attributes.FirstOrDefault(a => a.Name == "href")?.Value;
if (string.IsNullOrEmpty(torrentUri))
{
_logger.Warning($"Empty torrent uri from{Environment.NewLine}{replacedleNode.OuterHtml}");
continue;
}
var magnetLink = string.Empty;
if (!int.TryParse(columns[KickreplacedTorrentIndexer.Seeders].InnerText, out var seeders))
_logger.Warning($"Could not parse seeders {Environment.NewLine}{columns[KickreplacedTorrentIndexer.Seeders].OuterHtml}");
if (!int.TryParse(columns[KickreplacedTorrentIndexer.Leechers].InnerText, out var leechers))
_logger.Warning($"Could not parse leechers {Environment.NewLine}{columns[KickreplacedTorrentIndexer.Leechers].OuterHtml}");
var date = columns[KickreplacedTorrentIndexer.Date].InnerText.Trim();
var size = columns[KickreplacedTorrentIndexer.Size].InnerText.Trim();
var uploader = columns[KickreplacedTorrentIndexer.Uploader].InnerText.Trim();
var splitSize = size.Split(' ');
result.Add(new TorrentEntry
{
replacedle = replacedle,
TorrentUri = TrimUriStart(torrentUri),
TorrentMagnet = magnetLink,
Date = ParseDate(date),
Size = new SizeEnreplacedy
{
Value = double.Parse(splitSize[0], CultureInfo.InvariantCulture),
Postfix = splitSize[1]
},
Uploader = uploader,
Seeders = seeders,
Leechers = leechers,
Source = TorrentSource.Kickreplaced
});
}
var pagination = htmlAgility.DoreplacedentNode.SelectSingleNode("//div[@clreplaced='pages botmarg5px floatright']");
return new TorrentQueryResult
{
TorrentEntries = result,
IsLastPage = IsLastPage(pagination)
};
}
catch (Exception ex)
{
_logger.Warning("Kickreplaced parse exception", ex);
throw;
}
});
}
19
View Source File : RargbParser.cs
License : MIT License
Project Creator : aivarasatk
License : MIT License
Project Creator : aivarasatk
public async Task<TorrentQueryResult> ParsePageForTorrentEntriesAsync(string pageContents)
{
return await Task.Run(() =>
{
try
{
_logger.Information("RARGB parsing");
var htmlAgility = LoadedHtmlDoreplacedent(pageContents);
var tableRows = htmlAgility.DoreplacedentNode.SelectNodes("//tr[@clreplaced='lista2']");//gets table rows that contain torrent data
if (NoTableEntries(tableRows))
return new TorrentQueryResult { IsLastPage = true };
var result = new List<TorrentEntry>();
foreach (var row in tableRows)
{
var columns = row.SelectNodes("td");
if(columns == null || columns.Count != DataColumnCount)
{
_logger.Warning($"Could not find all columns for torrent {Environment.NewLine} {row.OuterHtml}");
continue;
}
var replacedleNode = columns[RargbTorrentIndexer.Name]
.SelectSingleNode("a");
if (replacedleNode == null)
{
_logger.Warning($"Could not find replacedle node for torrent {Environment.NewLine} {columns[RargbTorrentIndexer.Name].OuterHtml}");
continue;
}
var replacedle = replacedleNode.InnerText;
if (string.IsNullOrEmpty(replacedle))//empty replacedle entry makes no sense. log and skip
{
_logger.Warning($"Empty replacedle from {Environment.NewLine}{replacedleNode.OuterHtml}");
continue;
}
var torrentUri = replacedleNode.Attributes.FirstOrDefault(a => a.Name == "href")?.Value;
if (string.IsNullOrEmpty(torrentUri))
{
_logger.Warning($"Empty torrent uri from{Environment.NewLine}{replacedleNode.OuterHtml}");
continue;
}
var magnetLink = string.Empty;
if (!int.TryParse(columns[RargbTorrentIndexer.Seeders].InnerText, out var seeders))
_logger.Warning($"Could not parse seeders {Environment.NewLine}{columns[RargbTorrentIndexer.Seeders].OuterHtml}");
if (!int.TryParse(columns[RargbTorrentIndexer.Leechers].InnerText, out var leechers))
_logger.Warning($"Could not parse leechers {Environment.NewLine}{columns[RargbTorrentIndexer.Leechers].OuterHtml}");
var date = columns[RargbTorrentIndexer.Date].InnerText;
var size = columns[RargbTorrentIndexer.Size].InnerText;
var uploader = columns[RargbTorrentIndexer.Uploader].InnerText;
var splitSize = size.Split(' ');
result.Add(new TorrentEntry
{
replacedle = replacedle,
TorrentUri = TrimUriStart(torrentUri),
TorrentMagnet = magnetLink,
Date = DateTime.Parse(date),
Size = new SizeEnreplacedy
{
Value = double.Parse(splitSize[0], CultureInfo.InvariantCulture),
Postfix = splitSize[1]
},
Uploader = uploader,
Seeders = seeders,
Leechers = leechers,
Source = TorrentSource.Rargb
});
}
var pagination = htmlAgility.DoreplacedentNode.SelectSingleNode("//div[@id='pager_links']");
return new TorrentQueryResult
{
TorrentEntries = result,
IsLastPage = IsLastPage(pagination)
};
}
catch(Exception ex)
{
_logger.Warning("RARGB parse exception", ex);
throw;
}
});
}
19
View Source File : DeviceLocationProvider.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
IEnumerator PollLocationRoutine()
{
#if UNITY_EDITOR
while (!UnityEditor.EditorApplication.isRemoteConnected)
{
// exit if we are not the selected location provider
if (null != LocationProviderFactory.Instance && null != LocationProviderFactory.Instance.DefaultLocationProvider)
{
if (!this.Equals(LocationProviderFactory.Instance.DefaultLocationProvider))
{
yield break;
}
}
Debug.LogWarning("Remote device not connected via 'Unity Remote'. Waiting ..." + Environment.NewLine + "If Unity seems to be stuck here make sure 'Unity Remote' is running and restart Unity with your device already connected.");
yield return _wait1sec;
}
#endif
//request runtime fine location permission on Android if not yet allowed
#if UNITY_ANDROID
if (!_locationService.isEnabledByUser)
{
UniAndroidPermission.RequestPermission(AndroidPermission.ACCESS_FINE_LOCATION);
//wait for user to allow or deny
while (!_gotPermissionRequestResponse) { yield return _wait1sec; }
}
#endif
if (!_locationService.isEnabledByUser)
{
Debug.LogError("DeviceLocationProvider: Location is not enabled by user!");
_currentLocation.IsLocationServiceEnabled = false;
SendLocation(_currentLocation);
yield break;
}
_currentLocation.IsLocationServiceInitializing = true;
_locationService.Start(_desiredAccuracyInMeters, _updateDistanceInMeters);
Input.compreplaced.enabled = true;
int maxWait = 20;
while (_locationService.status == LocationServiceStatus.Initializing && maxWait > 0)
{
yield return _wait1sec;
maxWait--;
}
if (maxWait < 1)
{
Debug.LogError("DeviceLocationProvider: " + "Timed out trying to initialize location services!");
_currentLocation.IsLocationServiceInitializing = false;
_currentLocation.IsLocationServiceEnabled = false;
SendLocation(_currentLocation);
yield break;
}
if (_locationService.status == LocationServiceStatus.Failed)
{
Debug.LogError("DeviceLocationProvider: " + "Failed to initialize location services!");
_currentLocation.IsLocationServiceInitializing = false;
_currentLocation.IsLocationServiceEnabled = false;
SendLocation(_currentLocation);
yield break;
}
_currentLocation.IsLocationServiceInitializing = false;
_currentLocation.IsLocationServiceEnabled = true;
#if UNITY_EDITOR
// HACK: this is to prevent Android devices, connected through Unity Remote,
// from reporting a location of (0, 0), initially.
yield return _wait1sec;
#endif
System.Globalization.CultureInfo invariantCulture = System.Globalization.CultureInfo.InvariantCulture;
while (true)
{
var lastData = _locationService.lastData;
var timestamp = lastData.timestamp;
///////////////////////////////
// oh boy, Unity what are you doing???
// on some devices it seems that
// Input.location.status != LocationServiceStatus.Running
// nevertheless new location is available
//////////////////////////////
//Debug.LogFormat("Input.location.status: {0}", Input.location.status);
_currentLocation.IsLocationServiceEnabled =
_locationService.status == LocationServiceStatus.Running
|| timestamp > _lastLocationTimestamp;
_currentLocation.IsUserHeadingUpdated = false;
_currentLocation.IsLocationUpdated = false;
if (!_currentLocation.IsLocationServiceEnabled)
{
yield return _waitUpdateTime;
continue;
}
// device orientation, user heading get calculated below
_deviceOrientationSmoothing.Add(Input.compreplaced.trueHeading);
_currentLocation.DeviceOrientation = (float)_deviceOrientationSmoothing.Calculate();
//_currentLocation.LareplacedudeLongitude = new Vector2d(lastData.lareplacedude, lastData.longitude);
// HACK to get back to double precision, does this even work?
// https://forum.unity.com/threads/precision-of-location-longitude-is-worse-when-longitude-is-beyond-100-degrees.133192/#post-1835164
double lareplacedude = double.Parse(lastData.lareplacedude.ToString("R", invariantCulture), invariantCulture);
double longitude = double.Parse(lastData.longitude.ToString("R", invariantCulture), invariantCulture);
Vector2d previousLocation = new Vector2d(_currentLocation.LareplacedudeLongitude.x, _currentLocation.LareplacedudeLongitude.y);
_currentLocation.LareplacedudeLongitude = new Vector2d(lareplacedude, longitude);
_currentLocation.Accuracy = (float)Math.Floor(lastData.horizontalAccuracy);
// sometimes Unity's timestamp doesn't seem to get updated, or even jump back in time
// do an additional check if location has changed
_currentLocation.IsLocationUpdated = timestamp > _lastLocationTimestamp || !_currentLocation.LareplacedudeLongitude.Equals(previousLocation);
_currentLocation.Timestamp = timestamp;
_lastLocationTimestamp = timestamp;
if (_currentLocation.IsLocationUpdated)
{
if (_lastPositions.Count > 0)
{
// only add position if user has moved +1m since we added the previous position to the list
CheapRuler cheapRuler = new CheapRuler(_currentLocation.LareplacedudeLongitude.x, CheapRulerUnits.Meters);
Vector2d p = _currentLocation.LareplacedudeLongitude;
double distance = cheapRuler.Distance(
new double[] { p.y, p.x },
new double[] { _lastPositions[0].y, _lastPositions[0].x }
);
if (distance > 1.0)
{
_lastPositions.Add(_currentLocation.LareplacedudeLongitude);
}
}
else
{
_lastPositions.Add(_currentLocation.LareplacedudeLongitude);
}
}
// if we have enough positions calculate user heading ourselves.
// Unity does not provide bearing based on GPS locations, just
// device orientation based on Compreplaced.Heading.
// nevertheless, use compreplaced for intial UserHeading till we have
// enough values to calculate ourselves.
if (_lastPositions.Count < _maxLastPositions)
{
_currentLocation.UserHeading = _currentLocation.DeviceOrientation;
_currentLocation.IsUserHeadingUpdated = true;
}
else
{
Vector2d newestPos = _lastPositions[0];
Vector2d oldestPos = _lastPositions[_maxLastPositions - 1];
CheapRuler cheapRuler = new CheapRuler(newestPos.x, CheapRulerUnits.Meters);
// distance between last and first position in our buffer
double distance = cheapRuler.Distance(
new double[] { newestPos.y, newestPos.x },
new double[] { oldestPos.y, oldestPos.x }
);
// positions are minimum required distance apart (user is moving), calculate user heading
if (distance >= _minDistanceOldestNewestPosition)
{
float[] lastHeadings = new float[_maxLastPositions - 1];
for (int i = 1; i < _maxLastPositions; i++)
{
// atan2 increases angle CCW, flip sign of latDiff to get CW
double latDiff = -(_lastPositions[i].x - _lastPositions[i - 1].x);
double lngDiff = _lastPositions[i].y - _lastPositions[i - 1].y;
// +90.0 to make top (north) 0�
double heading = (Math.Atan2(latDiff, lngDiff) * 180.0 / Math.PI) + 90.0f;
// stay within [0..360]� range
if (heading < 0) { heading += 360; }
if (heading >= 360) { heading -= 360; }
lastHeadings[i - 1] = (float)heading;
}
_userHeadingSmoothing.Add(lastHeadings[0]);
float finalHeading = (float)_userHeadingSmoothing.Calculate();
//fix heading to have 0� for north, 90� for east, 180� for south and 270� for west
finalHeading = finalHeading >= 180.0f ? finalHeading - 180.0f : finalHeading + 180.0f;
_currentLocation.UserHeading = finalHeading;
_currentLocation.IsUserHeadingUpdated = true;
}
}
_currentLocation.TimestampDevice = UnixTimestampUtils.To(DateTime.UtcNow);
SendLocation(_currentLocation);
yield return _waitUpdateTime;
}
}
19
View Source File : GPosRecord.cs
License : Apache License 2.0
Project Creator : alexreinert
License : Apache License 2.0
Project Creator : alexreinert
internal override void ParseRecordData(byte[] resultData, int currentPosition, int length)
{
Longitude = Double.Parse(DnsMessageBase.ParseText(resultData, ref currentPosition), CultureInfo.InvariantCulture);
Lareplacedude = Double.Parse(DnsMessageBase.ParseText(resultData, ref currentPosition), CultureInfo.InvariantCulture);
Alreplacedude = Double.Parse(DnsMessageBase.ParseText(resultData, ref currentPosition), CultureInfo.InvariantCulture);
}
19
View Source File : Parser.cs
License : MIT License
Project Creator : andersnm
License : MIT License
Project Creator : andersnm
private static bool TryParseCondition(string token, out Condition result)
{
var tokenizer = new Tokenizer(token);
if (tokenizer.ReadString("<=") ||
tokenizer.ReadString("<>") ||
tokenizer.ReadString("<") ||
tokenizer.ReadString(">=") ||
tokenizer.ReadString(">") ||
tokenizer.ReadString("="))
{
var conditionPosition = tokenizer.Position;
var op = tokenizer.Substring(0, conditionPosition);
if (ReadConditionValue(tokenizer))
{
var valueString = tokenizer.Substring(conditionPosition, tokenizer.Position - conditionPosition);
result = new Condition()
{
Operator = op,
Value = double.Parse(valueString, CultureInfo.InvariantCulture)
};
return true;
}
}
result = null;
return false;
}
19
View Source File : frmMap.cs
License : GNU Lesser General Public License v3.0
Project Creator : andisturber
License : GNU Lesser General Public License v3.0
Project Creator : andisturber
private void button1_Click(object sender, EventArgs e)
{
Location.Longitude = double.Parse(label3.Text);
Location.Lareplacedude = double.Parse(label4.Text);
Close();
}
19
View Source File : LogiDevice.cs
License : GNU General Public License v3.0
Project Creator : andyvorld
License : GNU General Public License v3.0
Project Creator : andyvorld
private async Task<double> GetProtocolVer()
{
try
{
(RequestStatus resRequestStatus, HidData resData) = await WriteReadRequestAsync(HidLength.Short, 0x01, 0x00, 0x10, new byte[] {0x00, 0x00, 0x88});
if (resRequestStatus == RequestStatus.Errored)
{
throw _lastException;
}
if (resRequestStatus == RequestStatus.TimedOut)
{
throw new LogiDeviceException("Device Timedout");
}
string verStr = $"{resData.Param(0):X}.{resData.Param(1):X}";
return double.Parse(verStr, NumberStyles.Any, CultureInfo.InvariantCulture);
}
catch (LogiDeviceException)
{
return 1.0;
}
}
19
View Source File : App.xaml.cs
License : MIT License
Project Creator : AngelGarcia13
License : MIT License
Project Creator : AngelGarcia13
private MapperConfiguration GetMapperConfiguration()
{
const string imagesExtension = "jpg";
var config = new MapperConfiguration(cfg =>
{
cfg.AllowNullCollections = true;
//MotelServices
cfg.CreateMap<Framework.APIs.Models.MotelResponseService, Domain.Motels.MotelService>()
.ForMember(dest => dest.Name, source => source.MapFrom(src => src.Service))
.ForMember(dest => dest.Description, source => source.MapFrom(src => src.DescriptionDetail))
.ForMember(dest => dest.Price, source => source.MapFrom(src => src.Price));
//Motel
cfg.CreateMap<Framework.APIs.Models.MotelResponse, Domain.Motels.Motel>()
.ForMember(dest => dest.Name, source => source.MapFrom(src => src.Name))
.ForMember(dest => dest.Id, source => source.MapFrom(src => int.Parse(src.Id)))
.ForMember(dest => dest.Lareplacedude, source => source.MapFrom(src => double.Parse(src.Lareplacedude)))
.ForMember(dest => dest.Longitude, source => source.MapFrom(src => double.Parse(src.Longitude)))
.ForMember(dest => dest.Services, source => source.MapFrom(src => src.MotelServices))
.ForMember(dest => dest.Images, source => source.MapFrom(src => src.Images.Select(i => new Domain.Motels.MotelImage
{
Url = $"{i}.{imagesExtension}"
})))
.ForMember(dest => dest.Phones, source => source.MapFrom(src => src.Phones.Select(p => new Domain.Motels.MotelPhone
{
Number = p
})));
});
config.replacedertConfigurationIsValid();
return config;
}
19
View Source File : AxisScale.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
private void ControlChange(object sender, System.EventArgs e)
{
Chart1.ChartAreas["Default"].AxisY.IsLogarithmic = LogCheck.Checked;
if(LogCheck.Checked)
{
AutoCheck.Enabled = false;
AutoCheck.Checked = true;
}
else
AutoCheck.Enabled = true;
this.MaxValue.Enabled = !AutoCheck.Checked;
this.MinValue.Enabled = !AutoCheck.Checked;
if(this.MaxValue.SelectedIndex >= 0 &&
this.MinValue.SelectedIndex >= 0 &&
!AutoCheck.Checked)
{
double maxval= double.Parse(this.MaxValue.SelectedItem.ToString());
double minval= double.Parse(this.MinValue.SelectedItem.ToString());
Chart1.ChartAreas["Default"].AxisY.Maximum = maxval;
Chart1.ChartAreas["Default"].AxisY.Minimum = minval;
}
else
{
Chart1.ChartAreas["Default"].AxisY.Maximum = double.NaN;
Chart1.ChartAreas["Default"].AxisY.Minimum = double.NaN;
}
}
19
View Source File : AxisCrossing.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
private void ControlChange(object sender, System.EventArgs e)
{
System.Windows.Forms.DataVisualization.Charting.Axis AxisX;
System.Windows.Forms.DataVisualization.Charting.Axis AxisY;
AxisX = Chart1.ChartAreas["Default"].AxisX;
AxisY = Chart1.ChartAreas["Default"].AxisY;
// Set Crossing value for X axis
if(this.CrossingX.SelectedIndex >= 0)
{
string sel = CrossingX.SelectedItem.ToString();
switch (sel)
{
case "Auto":
AxisX.Crossing = Double.NaN;
break;
case "Max":
AxisX.Crossing = Double.MaxValue;
break;
case "Min":
AxisX.Crossing = Double.MinValue;
break;
default:
AxisX.Crossing = Double.Parse( this.CrossingX.SelectedItem.ToString() );
break;
}
}
// Set Reverse value for X axis
AxisX.IsReversed = ReverseXCheck.Checked;
// Set Crossing value for Y axis
if(this.CrossingY.SelectedIndex >= 0)
{
string sel = CrossingY.SelectedItem.ToString();
switch(sel)
{
case "Auto":
AxisY.Crossing = Double.NaN;
break;
case "Max":
AxisY.Crossing = Double.MaxValue;
break;
case "Min":
AxisY.Crossing = Double.MinValue;
break;
default:
AxisY.Crossing = Double.Parse( this.CrossingY.SelectedItem.ToString() );
break;
}
}
// Set Reverse value for Y axis
AxisY.IsReversed = ReverseYCheck.Checked;
foreach( Series series in Chart1.Series)
{
if(this.ChartTypes.SelectedIndex >= 0)
{
series.ChartType = (SeriesChartType) Enum.Parse( typeof(SeriesChartType), this.ChartTypes.SelectedItem.ToString(), true );
}
else
{
series.ChartType = SeriesChartType.Column;
}
}
}
19
View Source File : GridLinesTicks.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
private void ControlSelectedIndexChanged(object sender, System.EventArgs e)
{
// Disable all elements
Chart1.ChartAreas["Default"].AxisX.MajorGrid.Enabled = false;
Chart1.ChartAreas["Default"].AxisX.MajorTickMark.Enabled = false;
Chart1.ChartAreas["Default"].AxisX.MinorGrid.Enabled = false;
Chart1.ChartAreas["Default"].AxisX.MinorTickMark.Enabled = false;
// Enable Major selected element
if(Major.SelectedIndex >= 0)
{
switch( Major.SelectedItem.ToString())
{
case "Grid Lines":
Chart1.ChartAreas["Default"].AxisX.MajorGrid.Enabled = true;
break;
case "Tick Marks":
Chart1.ChartAreas["Default"].AxisX.MajorTickMark.Enabled = true;
break;
}
}
// Enable Minor selected element
if(Minor.SelectedIndex >= 0)
{
switch( Minor.SelectedItem.ToString() )
{
case "Grid Lines":
Chart1.ChartAreas["Default"].AxisX.MinorGrid.Enabled = true;
break;
case "Tick Marks":
Chart1.ChartAreas["Default"].AxisX.MinorTickMark.Enabled = true;
break;
}
}
// Set Grid lines and tick marks interval
if(MajorInterval.SelectedIndex >= 0)
{
Chart1.ChartAreas["Default"].AxisX.MajorGrid.Interval = double.Parse( MajorInterval.SelectedItem.ToString() );
Chart1.ChartAreas["Default"].AxisX.MajorTickMark.Interval = double.Parse( MajorInterval.SelectedItem.ToString() );
}
if(MinorInterval.SelectedIndex >= 0)
{
Chart1.ChartAreas["Default"].AxisX.MinorGrid.Interval = double.Parse( MinorInterval.SelectedItem.ToString() );
Chart1.ChartAreas["Default"].AxisX.MinorTickMark.Interval = double.Parse( MinorInterval.SelectedItem.ToString() );
}
// Set Line Color
if(MajorLineColor.SelectedIndex >= 0)
{
Chart1.ChartAreas["Default"].AxisX.MajorGrid.LineColor = Color.FromName(MajorLineColor.SelectedItem.ToString());
Chart1.ChartAreas["Default"].AxisX.MajorTickMark.LineColor = Color.FromName(MajorLineColor.SelectedItem.ToString());
}
if(MinorLineColor.SelectedIndex >= 0)
{
Chart1.ChartAreas["Default"].AxisX.MinorGrid.LineColor = Color.FromName(MinorLineColor.SelectedItem.ToString());
Chart1.ChartAreas["Default"].AxisX.MinorTickMark.LineColor = Color.FromName(MinorLineColor.SelectedItem.ToString());
}
// Set Line Style
if(MajorLineDashStyle.SelectedIndex >= 0)
{
Chart1.ChartAreas["Default"].AxisX.MajorGrid.LineDashStyle = (ChartDashStyle)ChartDashStyle.Parse(typeof(ChartDashStyle), MajorLineDashStyle.SelectedItem.ToString());
Chart1.ChartAreas["Default"].AxisX.MajorTickMark.LineDashStyle = (ChartDashStyle)ChartDashStyle.Parse(typeof(ChartDashStyle), MajorLineDashStyle.SelectedItem.ToString());
}
if(MinorLineDashStyle.SelectedIndex >= 0)
{
Chart1.ChartAreas["Default"].AxisX.MinorGrid.LineDashStyle = (ChartDashStyle)ChartDashStyle.Parse(typeof(ChartDashStyle), MinorLineDashStyle.SelectedItem.ToString());
Chart1.ChartAreas["Default"].AxisX.MinorTickMark.LineDashStyle = (ChartDashStyle)ChartDashStyle.Parse(typeof(ChartDashStyle), MinorLineDashStyle.SelectedItem.ToString());
}
// Set Line Width
if(MajorLineWidth.SelectedIndex >= 0)
{
Chart1.ChartAreas["Default"].AxisX.MajorGrid.LineWidth = int.Parse(MajorLineWidth.SelectedItem.ToString());
Chart1.ChartAreas["Default"].AxisX.MajorTickMark.LineWidth = int.Parse(MajorLineWidth.SelectedItem.ToString());
}
if(MinorLineWidth.SelectedIndex >= 0)
{
Chart1.ChartAreas["Default"].AxisX.MinorGrid.LineWidth = int.Parse(MinorLineWidth.SelectedItem.ToString());
Chart1.ChartAreas["Default"].AxisX.MinorTickMark.LineWidth = int.Parse(MinorLineWidth.SelectedItem.ToString());
}
}
19
View Source File : LogarithmicScale.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
private void SetData()
{
// If the Major Interval is not set get out
if( this.MajorInterval.Text == "" )
{
return;
}
// The logarithmic scale is enabled
if( this.Logaritmic.Checked == true )
{
// Enable combo boxes
this.Base.Enabled = true;
this.MajorInterval.Enabled = true;
this.MinorInterval.Enabled = true;
// Enable logarithmic scale
Chart1.ChartAreas[0].AxisY.IsLogarithmic = true;
// Set logarithmic base
if( this.Base.Text == "10" || this.Base.Text == "2" )
{
Chart1.ChartAreas[0].AxisY.LogarithmBase = double.Parse( this.Base.Text );
}
else
{
Chart1.ChartAreas[0].AxisY.LogarithmBase = Math.E;
}
// Set the interval for the axis and minor intervals
// for gridlines and tick marks.
if( this.Base.Text == "10" && this.Logaritmic.Checked == true )
{
this.MinorInterval.Enabled = true;
Chart1.ChartAreas[0].AxisY.Interval = double.Parse( this.MajorInterval.Text );
Chart1.ChartAreas[0].AxisY.MinorTickMark.Interval = double.Parse( this.MinorInterval.Text );
Chart1.ChartAreas[0].AxisY.MinorGrid.Interval = double.Parse( this.MinorInterval.Text );
Chart1.ChartAreas[0].AxisY.MinorGrid.Enabled = true;
Chart1.ChartAreas[0].AxisY.MinorTickMark.Enabled = true;
}
else
{
this.MinorInterval.Enabled = false;
Chart1.ChartAreas[0].AxisY.Interval = double.Parse( this.MajorInterval.Text );
Chart1.ChartAreas[0].AxisY.MinorTickMark.Interval = 0;
Chart1.ChartAreas[0].AxisY.MinorGrid.Interval = 0;
Chart1.ChartAreas[0].AxisY.MinorGrid.Enabled = false;
Chart1.ChartAreas[0].AxisY.MinorTickMark.Enabled = false;
}
}
else
{
// Logarithmic axis are disabled
Chart1.ChartAreas[0].AxisY.IsLogarithmic = false;
this.Base.Enabled = false;
this.MajorInterval.Enabled = false;
this.MinorInterval.Enabled = false;
Chart1.ChartAreas[0].AxisY.MinorGrid.Interval = 0;
Chart1.ChartAreas[0].AxisY.MinorTickMark.Interval = 0;
Chart1.ChartAreas[0].AxisY.LogarithmBase = 10;
Chart1.ChartAreas[0].AxisY.Interval = 0;
Chart1.ChartAreas[0].AxisY.MinorGrid.Enabled = true;
Chart1.ChartAreas[0].AxisY.MinorTickMark.Enabled = true;
}
}
19
View Source File : PieCollectedData.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
private void UpdateChartSettings()
{
if(!this.loadingData)
{
// Set chart type
chart1.Series["Default"].ChartType = (SeriesChartType) Enum.Parse( typeof(SeriesChartType), comboBoxChartType.Text, true );
// Populate series data
double[] yValues = {65.62, 2.1, 85.73, 11.42, 34.45, 75.54, 5.7, 4.1};
string[] xValues = {"France", "replacedan", "USA", "Italy", "Germany", "Canada", "Russia", "Spain"};
chart1.Series["Default"].Points.DataBindXY(xValues, yValues);
// Remove supplemental series and chart area if they already exsist
if(chart1.Series.Count > 1)
{
chart1.Series.RemoveAt(1);
chart1.ChartAreas.RemoveAt(1);
// Reset automatic position for the default chart area
chart1.ChartAreas["Default"].Position.Auto = true;
}
// Check if supplemental chart should be shown
if(!checkBoxOriginalChart.Checked)
{
chart1.Series["Default"]["PieLabelStyle"] = "Inside";
// Set the percentage of the total series values. This value determines
// if the data point value is a "small" value and should be shown as collected.
pieHelper.CollectedPercentage = double.Parse(comboBoxCollectedPercentage.Text);
// Indicates if small segments should be shown as one "collected" segment in
// the original series.
pieHelper.ShowCollectedDataAsOneSlice = checkBoxcollectSmallSegments.Checked;
// Size ratio between the original and supplemental chart areas.
// Value of 1.0f indicates that same area size will be used.
if(comboBoxsupplementalSize.SelectedIndex == 0)
{
pieHelper.SupplementedAreaSizeRatio = 0.9f;
}
else if(comboBoxsupplementalSize.SelectedIndex == 1)
{
pieHelper.SupplementedAreaSizeRatio = 1.0f;
}
else if(comboBoxsupplementalSize.SelectedIndex == 2)
{
pieHelper.SupplementedAreaSizeRatio = 1.1f;
}
// Set position in relative coordinates ( 0,0 - top left corner; 100,100 - bottom right corner)
// where original and supplemental pie charts should be placed.
pieHelper.ChartAreaPosition = new RectangleF(3f, 3f, 93f, 96f);
// Show supplemental pie for the "Default" series
pieHelper.ShowSmallSegmentsreplacedupplementalPie("Default");
}
else
{
chart1.Series["Default"]["PieLabelStyle"] = "Outside";
chart1.Series["Default"].LabelBackColor = Color.Empty;
}
// Enable/Disable controls
comboBoxChartType.Enabled = !checkBoxOriginalChart.Checked;
comboBoxCollectedPercentage.Enabled = !checkBoxOriginalChart.Checked;
comboBoxsupplementalSize.Enabled = !checkBoxOriginalChart.Checked;
checkBoxcollectSmallSegments.Enabled = !checkBoxOriginalChart.Checked;
}
}
19
View Source File : ChartInDataPoint.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
public void CreateChartInSeriesPoints(Chart chart, Series series, string chartType)
{
//****************************************************
//** Check if series uses X values or they all set
//** to zeros (in this case use point index as X value)
//****************************************************
bool zeroXValues = true;
foreach(DataPoint point in series.Points)
{
if(point.XValue != 0.0)
{
zeroXValues = false;
break;
}
}
//****************************************************
//** Calculate bubble scaling variables required to
//** for the bubble size calculations.
//****************************************************
bool bubbleChart = false;
// Minimum/Maximum bubble size
double maxPossibleBubbleSize = 15F;
double minPossibleBubbleSize = 3F;
float maxBubleSize = 0f;
float minBubleSize = 0f;
// Current min/max size of the bubble size
double minAll = double.MaxValue;
double maxAll = double.MinValue;
// Bubble size difference value
double valueDiff = 0;
double valueScale = 1;
// Check for the Bubble chart type
if( series.ChartType == SeriesChartType.Bubble )
{
bubbleChart = true;
// Check if custom attributes are set to specify scale
if(series.IsCustomPropertySet("BubbleScaleMin"))
{
minAll = Math.Min(minAll, Double.Parse(series["BubbleScaleMin"]));
}
if(series.IsCustomPropertySet("BubbleScaleMax"))
{
maxAll = Math.Max(maxAll, Double.Parse(series["BubbleScaleMax"]));
}
// Calculate bubble scale
double minSer = double.MaxValue;
double maxSer = double.MinValue;
foreach( Series ser in chart.Series )
{
if( ser.ChartType == SeriesChartType.Bubble && ser.ChartArea == series.ChartArea )
{
foreach(DataPoint point in ser.Points)
{
minSer = Math.Min(minSer, point.YValues[1]);
maxSer = Math.Max(maxSer, point.YValues[1]);
}
}
}
if(minAll == double.MaxValue)
{
minAll = minSer;
}
if(maxAll == double.MinValue)
{
maxAll = maxSer;
}
// Calculate maximum bubble size
SizeF areaSize = chart.ChartAreas[series.ChartArea].Position.Size;
// Convert relative coordinates to absolute coordinates
areaSize.Width = areaSize.Width * (chart.Width - 1) / 100F;
areaSize.Height = areaSize.Height * (chart.Height - 1) / 100F;
maxBubleSize = (float)(Math.Min(areaSize.Width, areaSize.Height) / (100.0/maxPossibleBubbleSize));
minBubleSize = (float)(Math.Min(areaSize.Width, areaSize.Height) / (100.0/minPossibleBubbleSize));
// Calculate scaling variables depending on the Min/Max values
if(maxAll == minAll)
{
valueScale = 1;
valueDiff = minAll - (maxBubleSize - minBubleSize)/2f;
}
else
{
valueScale = (maxBubleSize - minBubleSize) / (maxAll - minAll);
valueDiff = minAll;
}
}
//****************************************************
//** Create chart area for each data point
//****************************************************
int pointIndex = 0;
Random random = new Random();
foreach(DataPoint point in series.Points)
{
//****************************************************
//** Create chart area and set visual attributes
//****************************************************
ChartArea areaPoint = chart.ChartAreas.Add(series.Name + "_" + pointIndex.ToString());
areaPoint.BackColor = Color.Transparent;
areaPoint.BorderWidth = 0;
areaPoint.AxisX.LineWidth = 0;
areaPoint.AxisY.LineWidth = 0;
areaPoint.AxisX.MajorGrid.Enabled = false;
areaPoint.AxisX.MajorTickMark.Enabled = false;
areaPoint.AxisX.LabelStyle.Enabled = false;
areaPoint.AxisY.MajorGrid.Enabled = false;
areaPoint.AxisY.MajorTickMark.Enabled = false;
areaPoint.AxisY.LabelStyle.Enabled = false;
//****************************************************
//** Create data series in the chart area
//****************************************************
Series seriesPoint = chart.Series.Add(series.Name + "_" + pointIndex.ToString());
seriesPoint.ChartArea = areaPoint.Name;
seriesPoint.ChartType = (SeriesChartType) Enum.Parse( typeof(SeriesChartType), chartType, true );
seriesPoint.IsVisibleInLegend = false;
seriesPoint.BorderColor = Color.FromArgb(64,64,64);
seriesPoint.ShadowOffset = 2;
seriesPoint.Palette = ChartColorPalette.Pastel;
//****************************************************
//** Populate data series.
//** TODO: For this sample each series is populated
//** with random data. Do your own series population
//** here.
//****************************************************
for(int sliceIndex = 0; sliceIndex < 5; sliceIndex++)
{
seriesPoint.Points.AddY(random.Next(2,20));
}
//****************************************************
//** Set chart area position and inner plot position
//****************************************************
// Set chart area inner plot position
areaPoint.InnerPlotPosition = new ElementPosition(3, 3, 94, 94);
// Position chart area over the data point
PointF position = PointF.Empty;
position.X = (float)chart.ChartAreas[series.ChartArea].AxisX.GetPosition(zeroXValues ? (pointIndex + 1) : point.XValue);
position.Y = (float)chart.ChartAreas[series.ChartArea].AxisY.GetPosition(point.YValues[0]);
float pieSize = (point.MarkerSize < 15) ? 15 : point.MarkerSize;;
if(bubbleChart)
{
pieSize = (float)((point.YValues[1] - valueDiff) * valueScale) + minBubleSize;
}
pieSize = pieSize * 100F / ((float)(chart.Width - 1));
areaPoint.Position = new ElementPosition(position.X - pieSize/2f, position.Y - pieSize/2f, pieSize, pieSize);
// Increase point index
++pointIndex;
}
}
19
View Source File : Dialog.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
private void button1_Click(object sender, System.EventArgs e)
{
try
{
double newValue = double.Parse( YValue.Text );
if(newValue > 0)
ChartRef.Series[0].Points[pointIndex].YValues[0] = newValue;
else
ChartRef.Series[0].Points[pointIndex].YValues[0] = 0.5;
}
catch
{
}
ChartRef.Series[0].Points[pointIndex].Label = Label.Text;
ChartRef.Series[0].Points[pointIndex].Color = Color.FromName(PointColor.SelectedItem.ToString());
ChartRef.Series[0].Points[pointIndex].BorderColor = Color.FromName(BorderColor.SelectedItem.ToString());
ChartRef.Series[0].Points[pointIndex].MarkerColor = Color.FromName(MarkerColor.SelectedItem.ToString());
ChartRef.Series[0].Points[pointIndex].MarkerBorderColor = Color.FromName(MarkerBorderColor.SelectedItem.ToString());
ChartRef.Invalidate();
this.Close();
}
19
View Source File : BasicZooming.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
private void comboBoxFrom_SelectedIndexChanged(object sender, System.EventArgs e)
{
if(comboBoxFrom.Text != String.Empty)
{
if(comboBoxTo.Text == String.Empty)
{
comboBoxTo.SelectedIndex = 0;
}
// Zoom into the axis
if(comboBoxAxis.Text == "X" || comboBoxAxis.Text == "X and Y")
{
chart1.ChartAreas["Default"].AxisX.ScaleView.Zoom(double.Parse(comboBoxFrom.Text), double.Parse(comboBoxTo.Text));
}
if(comboBoxAxis.Text == "Y" || comboBoxAxis.Text == "X and Y")
{
chart1.ChartAreas["Default"].AxisY.ScaleView.Zoom(double.Parse(comboBoxFrom.Text), double.Parse(comboBoxTo.Text));
}
}
}
19
View Source File : AxisLabelsInterval.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
private void Intervals()
{
if(
PointsNumberList.SelectedItem == null ||
XAxisIntervalList.SelectedItem == null ||
YAxisIntervalList.SelectedItem == null
)
{
return;
}
Chart1.BackColor = Color.White;
// Set interval and interval type for the Y axis
if(YAxisIntervalList.GereplacedemText(YAxisIntervalList.SelectedItem) != "Auto")
{
SetAxisInterval(Chart1.ChartAreas["Default"].AxisY, double.Parse(YAxisIntervalList.GereplacedemText(YAxisIntervalList.SelectedItem)), DateTimeIntervalType.Number);
}
else
{
SetAxisInterval(Chart1.ChartAreas["Default"].AxisY, Double.NaN, DateTimeIntervalType.Auto, Double.NaN, DateTimeIntervalType.Auto);
}
// Set interval and interval type for the X axis
if(XAxisIntervalList.GereplacedemText(XAxisIntervalList.SelectedItem) == "Every Week (Starting Sunday)")
{
SetAxisInterval(Chart1.ChartAreas["Default"].AxisX, 1, DateTimeIntervalType.Weeks);
}
else if(XAxisIntervalList.GereplacedemText(XAxisIntervalList.SelectedItem) == "Every Week (Starting Monday)")
{
SetAxisInterval(Chart1.ChartAreas["Default"].AxisX, 1, DateTimeIntervalType.Weeks, 1, DateTimeIntervalType.Days);
}
else if(XAxisIntervalList.GereplacedemText(XAxisIntervalList.SelectedItem) == "Every 2 Weeks")
{
SetAxisInterval(Chart1.ChartAreas["Default"].AxisX, 2, DateTimeIntervalType.Weeks);
}
else if(XAxisIntervalList.GereplacedemText(XAxisIntervalList.SelectedItem) == "Every Month (Starting at 1st)")
{
SetAxisInterval(Chart1.ChartAreas["Default"].AxisX, 1, DateTimeIntervalType.Months);
}
else if(XAxisIntervalList.GereplacedemText(XAxisIntervalList.SelectedItem) == "Every Month (Starting at 15th)")
{
SetAxisInterval(Chart1.ChartAreas["Default"].AxisX, 1, DateTimeIntervalType.Months, 14, DateTimeIntervalType.Days);
}
else if(XAxisIntervalList.GereplacedemText(XAxisIntervalList.SelectedItem) == "Auto")
{
SetAxisInterval(Chart1.ChartAreas["Default"].AxisX, Double.NaN, DateTimeIntervalType.Auto, Double.NaN, DateTimeIntervalType.Auto);
}
}
19
View Source File : PointAndFigureChart.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
protected override void DrawColumn2D(
ChartGraphics graph,
Axis vAxis,
RectangleF rectSize,
DataPoint point,
Series ser)
{
// Get box size
double boxSize = double.Parse(ser["CurrentBoxSize"], CultureInfo.InvariantCulture);
double boxSizeRel = vAxis.GetLogValue(vAxis.ViewMinimum);
boxSizeRel = vAxis.GetLinearPosition(boxSizeRel);
boxSizeRel = Math.Abs(boxSizeRel -
vAxis.GetLinearPosition(vAxis.GetLogValue(vAxis.ViewMinimum + boxSize)));
// Draw a series of Xs or Os
for(float positionY = rectSize.Y; positionY < rectSize.Bottom - (float)(boxSizeRel - boxSizeRel/4.0); positionY += (float)boxSizeRel)
{
// Get position of symbol
RectangleF position = RectangleF.Empty;
position.X = rectSize.X;
position.Y = positionY;
position.Width = rectSize.Width;
position.Height = (float)boxSizeRel;
// Get absolute position and add 1 pixel spacing
position = graph.GetAbsoluteRectangle(position);
int spacing = 1 + point.BorderWidth / 2;
position.Y += spacing;
position.Height -= 2 * spacing;
// Calculate shadow position
RectangleF shadowPosition = new RectangleF(position.Location, position.Size);
shadowPosition.Offset(ser.ShadowOffset, ser.ShadowOffset);
if(point.IsCustomPropertySet("PriceUpPoint"))
{
// Draw shadow
if(ser.ShadowOffset != 0)
{
graph.DrawLineAbs(
ser.ShadowColor,
point.BorderWidth,
ChartDashStyle.Solid,
new PointF(shadowPosition.Left, shadowPosition.Top),
new PointF(shadowPosition.Right, shadowPosition.Bottom));
graph.DrawLineAbs(
ser.ShadowColor,
point.BorderWidth,
ChartDashStyle.Solid,
new PointF(shadowPosition.Left, shadowPosition.Bottom),
new PointF(shadowPosition.Right, shadowPosition.Top));
}
// Draw 'X' symbol
graph.DrawLineAbs(
point.Color,
point.BorderWidth,
ChartDashStyle.Solid,
new PointF(position.Left, position.Top),
new PointF(position.Right, position.Bottom));
graph.DrawLineAbs(
point.Color,
point.BorderWidth,
ChartDashStyle.Solid,
new PointF(position.Left, position.Bottom),
new PointF(position.Right, position.Top));
}
else
{
// Draw circles when price is dropping
if(ser.ShadowOffset != 0)
{
graph.DrawCircleAbs(
new Pen(ser.ShadowColor, point.BorderWidth),
null,
shadowPosition,
1,
false);
}
// Draw 'O' symbol
graph.DrawCircleAbs(
new Pen(point.Color, point.BorderWidth),
null,
position,
1,
false);
}
}
}
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 : SmallScrollSize.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
private void comboBoxSmallScrollSize_SelectedIndexChanged(object sender, System.EventArgs e)
{
// Set small scroll size and Min. size
if(comboBoxSmallScrollSize.Text == "Auto")
{
comboBoxSmallScrollMinSize.Enabled = true;
chart1.ChartAreas["Default"].AxisX.ScaleView.SmallScrollSize = double.NaN;
}
else
{
comboBoxSmallScrollMinSize.Enabled = false;
if(comboBoxSmallScrollSize.Text != "")
{
chart1.ChartAreas["Default"].AxisX.ScaleView.SmallScrollSize = double.Parse(comboBoxSmallScrollSize.Text);
}
}
if(comboBoxSmallScrollMinSize.Text != "")
{
chart1.ChartAreas["Default"].AxisX.ScaleView.SmallScrollMinSize = double.Parse(comboBoxSmallScrollMinSize.Text);
}
}
19
View Source File : PointAndFigureChart.cs
License : MIT License
Project Creator : AngeloCresta
License : MIT License
Project Creator : AngeloCresta
static private void OnCustomize(Object sender, EventArgs e)
{
bool chartResized = false;
Chart chart = (Chart)sender;
// Loop through all series
foreach(Series series in chart.Series)
{
// Check for the PointAndFigure chart type
if(series.Name.StartsWith("POINTANDFIGURE_ORIGINAL_DATA_", StringComparison.Ordinal))
{
// Get original series
Series pointAndFigureSeries = chart.Series[series.Name.Substring(29)];
// Check if proportional symbol custom attribute is set
bool proportionalSymbols = true;
string attrValue = pointAndFigureSeries[CustomPropertyName.ProportionalSymbols];
if(attrValue != null && String.Compare( attrValue, "True", StringComparison.OrdinalIgnoreCase ) != 0 )
{
proportionalSymbols = false;
}
if(proportionalSymbols &&
pointAndFigureSeries.Enabled &&
pointAndFigureSeries.ChartArea.Length > 0)
{
// Resize chart
if(!chartResized)
{
chartResized = true;
chart.chartPicture.Resize(chart.chartPicture.ChartGraph, false);
}
// Find series chart area, X & Y axes
ChartArea chartArea = chart.ChartAreas[pointAndFigureSeries.ChartArea];
Axis axisX = chartArea.GetAxis(AxisName.X, pointAndFigureSeries.XAxisType, pointAndFigureSeries.XSubAxisName);
Axis axisY = chartArea.GetAxis(AxisName.Y, pointAndFigureSeries.YAxisType, pointAndFigureSeries.YSubAxisName);
// Symbols are drawn only in 2D mode
if(!chartArea.Area3DStyle.Enable3D)
{
// Get current box size
double boxSize = double.Parse(
pointAndFigureSeries["CurrentBoxSize"],
CultureInfo.InvariantCulture);
// Calculate symbol width and height
double boxYSize = Math.Abs(
axisY.GetPosition(axisY.Minimum) -
axisY.GetPosition(axisY.Minimum + boxSize) );
double boxXSize = Math.Abs(
axisX.GetPosition(1.0) -
axisX.GetPosition(0.0) );
boxXSize *= 0.8;
// Get absolute size in pixels
SizeF markSize = chart.chartPicture.ChartGraph.GetAbsoluteSize(
new SizeF((float)boxXSize, (float)boxYSize));
// Calculate number of empty points that should be added
int pointCount = 0;
if(markSize.Width > markSize.Height)
{
pointCount = (int)(pointAndFigureSeries.Points.Count * (markSize.Width / markSize.Height));
}
// Add empty points
DataPoint emptyPoint = new DataPoint(pointAndFigureSeries);
emptyPoint.IsEmpty = true;
emptyPoint.AxisLabel = " ";
while(pointAndFigureSeries.Points.Count < pointCount)
{
pointAndFigureSeries.Points.Add(emptyPoint);
}
// Always use zeros for Y values of empty points
pointAndFigureSeries[CustomPropertyName.EmptyPointValue] = "Zero";
// RecalculateAxesScale chart are data
chartArea.ReCalcInternal();
}
}
}
}
}
19
View Source File : App.xaml.cs
License : MIT License
Project Creator : anjoy8
License : MIT License
Project Creator : anjoy8
private async Task SendCurrentLocation()
{
var location = new Location
{
Lareplacedude = double.Parse(_settingsService.Lareplacedude, CultureInfo.InvariantCulture),
Longitude = double.Parse(_settingsService.Longitude, CultureInfo.InvariantCulture)
};
var locationService = ViewModelLocator.Resolve<ILocationService>();
await locationService.UpdateUserLocation(location, _settingsService.AuthAccessToken);
}
19
View Source File : ValueMember.cs
License : MIT License
Project Creator : AnotherEnd15
License : MIT License
Project Creator : AnotherEnd15
private static object ParseDefaultValue(Type type, object value)
{
{
Type tmp = Helpers.GetUnderlyingType(type);
if (tmp != null) type = tmp;
}
if (value is string s)
{
if (Helpers.IsEnum(type)) return Helpers.ParseEnum(type, s);
switch (Helpers.GetTypeCode(type))
{
case ProtoTypeCode.Boolean: return bool.Parse(s);
case ProtoTypeCode.Byte: return byte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
case ProtoTypeCode.Char: // char.Parse missing on CF/phone7
if (s.Length == 1) return s[0];
throw new FormatException("Single character expected: \"" + s + "\"");
case ProtoTypeCode.DateTime: return DateTime.Parse(s, CultureInfo.InvariantCulture);
case ProtoTypeCode.Decimal: return decimal.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.Double: return double.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.Int16: return short.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.Int32: return int.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.Int64: return long.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.SByte: return sbyte.Parse(s, NumberStyles.Integer, CultureInfo.InvariantCulture);
case ProtoTypeCode.Single: return float.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.String: return s;
case ProtoTypeCode.UInt16: return ushort.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.UInt32: return uint.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.UInt64: return ulong.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture);
case ProtoTypeCode.TimeSpan: return TimeSpan.Parse(s);
case ProtoTypeCode.Uri: return s; // Uri is decorated as string
case ProtoTypeCode.Guid: return new Guid(s);
}
}
if (Helpers.IsEnum(type)) return Enum.ToObject(type, value);
return Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
}
19
View Source File : ExcelConditionalFormattingHelper.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
public static double GetAttributeDouble(
XmlNode node,
string attribute)
{
try
{
var value = node.Attributes[attribute].Value;
return double.Parse(value, NumberStyles.Number, CultureInfo.InvariantCulture);
}
catch
{
return double.NaN;
}
}
19
View Source File : Value.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
{
ValidateArguments(arguments, 1);
var val = ArgToString(arguments, 0).TrimEnd(' ');
double result = 0d;
if (Regex.IsMatch(val, $"^[\\d]*({Regex.Escape(_groupSeparator)}?[\\d]*)?({Regex.Escape(_decimalSeparator)}[\\d]*)?[ ?% ?]?$"))
{
if (val.EndsWith("%"))
{
val = val.TrimEnd('%');
result = double.Parse(val) / 100;
}
else
{
result = double.Parse(val);
}
return CreateResult(result, DataType.Decimal);
}
if (double.TryParse(val, NumberStyles.Float, CultureInfo.CurrentCulture, out result))
{
return CreateResult(result, DataType.Decimal);
}
var timeSeparator = Regex.Escape(_timeSeparator);
if (Regex.IsMatch(val, @"^[\d]{1,2}" + timeSeparator + @"[\d]{2}(" + timeSeparator + @"[\d]{2})?$"))
{
var timeResult = _timeValueFunc.Execute(val);
if (timeResult.DataType == DataType.Date)
{
return timeResult;
}
}
var dateResult = _dateValueFunc.Execute(val);
if (dateResult.DataType == DataType.Date)
{
return dateResult;
}
return CreateResult(ExcelErrorValue.Create(eErrorType.Value), DataType.ExcelError);
}
19
View Source File : DateExpression.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
public override CompileResult Compile()
{
var date = double.Parse(ExpressionString);
return new CompileResult(DateTime.FromOADate(date), DataType.Date);
}
19
View Source File : DecimalExpression.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
public override CompileResult Compile()
{
double result = _compiledValue.HasValue ? _compiledValue.Value : double.Parse(ExpressionString, CultureInfo.InvariantCulture);
result = _negate ? result * -1 : result;
return new CompileResult(result, DataType.Decimal);
}
19
View Source File : IntegerExpression.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
public override CompileResult Compile()
{
double result = _compiledValue.HasValue ? _compiledValue.Value : double.Parse(ExpressionString, CultureInfo.InvariantCulture);
result = _negate ? result*-1 : result;
return new CompileResult(result, DataType.Integer);
}
19
View Source File : JsActionsTests.cs
License : Apache License 2.0
Project Creator : aquality-automation
License : Apache License 2.0
Project Creator : aquality-automation
[Test]
public void Should_BePossibleTo_ScrollBy()
{
var point = new Point(50, 40);
var homeDemoSiteForm = new HomeDemoSiteForm();
homeDemoSiteForm.Open();
homeDemoSiteForm.FirstScrollableExample.JsActions.ScrollBy(point.X, point.Y);
var currentCoordinates = AqualityServices.Browser
.ExecuteScriptFromFile<IList<object>>("Resources.GetScrollCoordinates.js",
homeDemoSiteForm.FirstScrollableExample.GetElement()).
Select(item => (int)Math.Round(double.Parse(item.ToString())))
.ToList();
var actualPoint = new Point(currentCoordinates[0], currentCoordinates[1]);
replacedert.AreEqual(point, actualPoint, $"Current coordinates should be '{point}'");
}
19
View Source File : JsActionsTests.cs
License : Apache License 2.0
Project Creator : aquality-automation
License : Apache License 2.0
Project Creator : aquality-automation
[Test]
public void Should_BePossibleTo_ScrollToTheCenter()
{
const int accuracy = 1;
var welcomeForm = new WelcomeForm();
welcomeForm.Open();
welcomeForm.GetExampleLink(AvailableExample.Dropdown).JsActions.ScrollToTheCenter();
var windowSize = AqualityServices.Browser.ExecuteScriptFromFile<object>("Resources.GetWindowSize.js").ToString();
var currentY = AqualityServices.Browser.ExecuteScriptFromFile<object>("Resources.GetElementYCoordinate.js",
welcomeForm.GetExampleLink(AvailableExample.Dropdown).GetElement()).ToString();
var coordinateRelatingWindowCenter = double.Parse(windowSize) / 2 - double.Parse(currentY);
replacedert.LessOrEqual(Math.Abs(coordinateRelatingWindowCenter), accuracy, "Upper bound of element should be in the center of the page");
}
19
View Source File : TransferFunction.cs
License : MIT License
Project Creator : ar1st0crat
License : MIT License
Project Creator : ar1st0crat
public static TransferFunction FromCsv(Stream stream, char delimiter = ',')
{
using (var reader = new StreamReader(stream))
{
var content = reader.ReadLine();
var numerator = content.Split(delimiter)
.Select(s => double.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture))
.ToArray();
content = reader.ReadLine();
var denominator = content.Split(delimiter)
.Select(s => double.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture))
.ToArray();
return new TransferFunction(numerator, denominator);
}
}
19
View Source File : GhEnergySystem.cs
License : GNU General Public License v3.0
Project Creator : architecture-building-systems
License : GNU General Public License v3.0
Project Creator : architecture-building-systems
private List<object> ReadViewModel()
{
var result = new List<object>();
foreach (var ct in _viewModel.ConversionTechnologies)
if (ct.IsParametricDefined)
{
result.Add(ct.ConversionTech);
}
else
{
var specificCapitalCost = double.Parse(ct.SpecificCapitalCost);
var specificEmbodiedEmissions = double.Parse(ct.SpecificEmbodiedEmissions);
var lifetime = double.Parse(ct.Lifetime);
var efficiency = double.Parse(ct.Efficiency);
var capacity = double.Parse(ct.Capacity);
var heatToPowerRatio = double.Parse(ct.HeatToPowerRatio);
var distributionLosses = double.Parse(ct.DistributionLosses);
switch (ct.Name)
{
case "Photovoltaic (PV)":
ct.AvailableSurfaces = _viewModel.SurfacesForConversion(ct);
foreach (var sm in ct.SelectedSurfaces)
result.Add(new Photovoltaic(specificCapitalCost, specificEmbodiedEmissions, lifetime, sm.Mesh,
"FIXME: PV",
efficiency));
break;
case "Solar Thermal (ST)":
ct.AvailableSurfaces = _viewModel.SurfacesForConversion(ct);
foreach (var sm in ct.SelectedSurfaces)
result.Add(new SolarThermal(specificCapitalCost, specificEmbodiedEmissions, lifetime, sm.Mesh,
"FIXME: ST",
efficiency));
break;
case "Boiler (Gas)":
result.Add(new GasBoiler(specificCapitalCost, specificEmbodiedEmissions, lifetime, capacity,
efficiency));
break;
case "CHP":
result.Add(new CombinedHeatPower(specificCapitalCost, specificEmbodiedEmissions, lifetime, capacity,
heatToPowerRatio,
efficiency));
break;
case "Chiller (Electricity)":
result.Add(
new Chiller(specificCapitalCost, specificEmbodiedEmissions, lifetime, capacity, efficiency));
break;
case "ASHP (Electricity)":
result.Add(new AirSourceHeatPump(specificCapitalCost, specificEmbodiedEmissions, lifetime, capacity,
efficiency));
break;
case "Heat Exchanger":
result.Add(new HeatCoolingExchanger(specificCapitalCost, specificEmbodiedEmissions, lifetime,
capacity, distributionLosses));
break;
case "Cooling Exchanger":
result.Add(new HeatCoolingExchanger(specificCapitalCost, specificEmbodiedEmissions, lifetime,
capacity, distributionLosses,
false, true));
break;
default:
throw new Exception($"Don't know how to read {ct.Name}");
}
}
foreach (var emitter in _viewModel.Emitters)
{
var specificInvestmentCost = double.Parse(emitter.SpecificCapitalCost);
var specificEmbodiedEmissions = double.Parse(emitter.SpecificEmbodiedEmissions);
var lifetime = double.Parse(emitter.Lifetime);
var inletTemperature = double.Parse(emitter.SupplyTemperature);
var returnTemperature = double.Parse(emitter.ReturnTemperature);
switch (emitter.Name)
{
case "Radiator":
result.Add(new Radiator(specificInvestmentCost, specificEmbodiedEmissions, lifetime, emitter.IsHeating,
emitter.IsCooling,
inletTemperature, returnTemperature));
break;
case "Air diffuser":
result.Add(new AirDiffuser(specificInvestmentCost, specificEmbodiedEmissions, lifetime, emitter.IsHeating,
emitter.IsCooling,
inletTemperature, returnTemperature));
break;
}
}
return result;
}
19
View Source File : Extensions.cs
License : MIT License
Project Creator : arqueror
License : MIT License
Project Creator : arqueror
public static double ParseDouble(this string s)
{
const NumberStyles styles = NumberStyles.Float | NumberStyles.AllowThousands;
var format = NumberFormatInfo.InvariantInfo;
return double.Parse(s, styles, format);
}
19
View Source File : AnchorManager.cs
License : MIT License
Project Creator : ARUnityBook
License : MIT License
Project Creator : ARUnityBook
public void EarlyUpdate()
{
_SetNewTrackingState(Frame.TrackingState, SessionManager.Instance.MotionTrackingManager.IsLocalized);
const string POSE_HISTORY_EVENT_KEY = "EXPERIMENTAL_PoseHistoryChanged";
double earliestTimestamp = double.MaxValue;
for (int i = 0; i < SessionManager.Instance.TangoEvents.Count; i++)
{
var tangoEvent = SessionManager.Instance.TangoEvents[i];
if (tangoEvent.key == POSE_HISTORY_EVENT_KEY && double.Parse(tangoEvent.value) < earliestTimestamp)
{
earliestTimestamp = double.Parse(tangoEvent.value);
}
}
// Update the pose of anchors.
if (earliestTimestamp < double.MaxValue)
{
for (int i = 0; i < m_anchors.Count; i++)
{
m_anchors[i].m_updateTracking(earliestTimestamp);
}
for (int i = 0; i < m_nonLocalizedAnchors.Count; i++)
{
m_nonLocalizedAnchors[i].m_updateTracking(earliestTimestamp);
}
}
}
See More Examples