Here are the examples of the csharp api double.Parse(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1259 Examples
19
Source : MathConverter.cs
with MIT License
from antfu
with MIT License
from antfu
private void EvaluateMathString(ref string mathEquation, ref List<double> numbers, int index)
{
// Loop through each mathemtaical token in the equation
string token = GetNextToken(mathEquation);
while (token != string.Empty)
{
// Remove token from mathEquation
mathEquation = mathEquation.Remove(0, token.Length);
// If token is a grouping character, it affects program flow
if (_grouping.Contains(token))
{
switch (token)
{
case "(":
EvaluateMathString(ref mathEquation, ref numbers, index);
break;
case ")":
return;
}
}
// If token is an operator, do requested operation
if (_operators.Contains(token))
{
// If next token after operator is a parenthesis, call method recursively
string nextToken = GetNextToken(mathEquation);
if (nextToken == "(")
{
EvaluateMathString(ref mathEquation, ref numbers, index + 1);
}
// Verify that enough numbers exist in the List<double> to complete the operation
// and that the next token is either the number expected, or it was a ( meaning
// that this was called recursively and that the number changed
if (numbers.Count > (index + 1) &&
(double.Parse(nextToken) == numbers[index + 1] || nextToken == "("))
{
switch (token)
{
case "+":
numbers[index] = numbers[index] + numbers[index + 1];
break;
case "-":
numbers[index] = numbers[index] - numbers[index + 1];
break;
case "*":
numbers[index] = numbers[index] * numbers[index + 1];
break;
case "/":
numbers[index] = numbers[index] / numbers[index + 1];
break;
case "%":
numbers[index] = numbers[index] % numbers[index + 1];
break;
}
numbers.RemoveAt(index + 1);
}
else
{
// Handle Error - Next token is not the expected number
throw new FormatException("Next token is not the expected number");
}
}
token = GetNextToken(mathEquation);
}
}
19
Source : SystemExtentionsMethods.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
public static System.Boolean IsNumeric(this System.Object Expression)
{
if (Expression == null || Expression is DateTime)
return false;
if (Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
return true;
try
{
if (Expression is string)
Double.Parse(Expression as string);
else
Double.Parse(Expression.ToString());
return true;
}
catch { } // just dismiss errors but return false
return false;
}
19
Source : LinuxMachineInfo.cs
with MIT License
from aprilyush
with MIT License
from aprilyush
public MemoryMetrics GetMetrics()
{
string output = ShellHelper.Bash("free -m");
var lines = output.Split("\n");
var memory = lines[1].Split(" ", StringSplitOptions.RemoveEmptyEntries);
var metrics = new MemoryMetrics();
metrics.RAMTotal = double.Parse(memory[1]);
metrics.RAMUsed = double.Parse(memory[2]);
metrics.RAMFree = double.Parse(memory[3]);
metrics.RAMRate = Math.Ceiling(100 * metrics.RAMUsed / metrics.RAMTotal);
return metrics;
}
19
Source : WindowsMachineInfo.cs
with MIT License
from aprilyush
with MIT License
from aprilyush
public MemoryMetrics GetMetrics()
{
string output = ShellHelper.Cmd("wmic", "OS get FreePhysicalMemory,TotalVisibleMemorySize /Value");
var lines = output.Trim().Split("\n");
var freeMemoryParts = lines[0].Split("=", StringSplitOptions.RemoveEmptyEntries);
var totalMemoryParts = lines[1].Split("=", StringSplitOptions.RemoveEmptyEntries);
var metrics = new MemoryMetrics();
metrics.RAMTotal = Math.Round(double.Parse(totalMemoryParts[1]) / 1024, 0);
metrics.RAMFree = Math.Round(double.Parse(freeMemoryParts[1]) / 1024, 0);
metrics.RAMUsed = metrics.RAMTotal - metrics.RAMFree;
metrics.RAMRate =Math.Ceiling(100*metrics.RAMUsed / metrics.RAMTotal);
return metrics;
}
19
Source : JsActions.cs
with Apache License 2.0
from aquality-automation
with Apache License 2.0
from aquality-automation
public Point GetViewPortCoordinates()
{
var coordinates = ExecuteScript<IList<object>>(JavaScript.GetViewPortCoordinates)
.Select(item => double.Parse(item.ToString()))
.ToArray();
return new Point((int)Math.Round(coordinates[0]), (int)Math.Round(coordinates[1]));
}
19
Source : OxyPlotBase.cs
with GNU General Public License v3.0
from architecture-building-systems
with GNU General Public License v3.0
from architecture-building-systems
public static double? ReadDouble(this Dictionary<string, string> plotParameters, string key)
{
try
{
return double.Parse(plotParameters[key]);
}
catch (Exception)
{
return null;
}
}
19
Source : MtlParser.cs
with MIT License
from arcplus
with MIT License
from arcplus
private static Reflectivity GetReflectivity(string val)
{
if (String.IsNullOrEmpty(val)) return null;
var strs = val.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (strs.Length == 3)
{
var r = double.Parse(strs[0]);
var g = double.Parse(strs[1]);
var b = double.Parse(strs[2]);
return new Reflectivity(new Color(r, g, b));
}
//TODO:
return null;
}
19
Source : ObjParser.cs
with MIT License
from arcplus
with MIT License
from arcplus
public ObjModel GetModel()
{
if(_model == null)
{
var modelName = "Unreplacedled";
if (!String.IsNullOrEmpty(_objFile))
{
modelName = Path.GetFileNameWithoutExtension(_objFile);
}
_model = new ObjModel { Name = modelName };
while(!_reader.EndOfStream)
{
var line = _reader.ReadLine().Trim();
if (String.IsNullOrEmpty(line)) continue;
if (line.StartsWith("#")) continue;
if (StartWith(line, "mtllib"))
{
_model.MatFilename = line.Substring(6).Trim();
}
else if (StartWith(line, "v"))
{
var vStr = line.Substring(1).Trim();
var strs = SplitLine(vStr);
var v = new Vec3(double.Parse(strs[0]), double.Parse(strs[1]), double.Parse(strs[2]));
_model.Vertices.Add(v);
}
else if (StartWith(line, "vn"))
{
var vnStr = line.Substring(2).Trim();
var strs = SplitLine(vnStr);
var vn = new Vec3(double.Parse(strs[0]), double.Parse(strs[1]), double.Parse(strs[2]));
_model.Normals.Add(vn);
}
else if (StartWith(line, "vt"))
{
var vtStr = line.Substring(2).Trim();
var strs = SplitLine(vtStr);
var vt = new Vec2(double.Parse(strs[0]), double.Parse(strs[1]));
_model.Uvs.Add(vt);
}
else if (StartWith(line, "g"))
{
var gStr = line.Substring(1).Trim();
var g = new Geometry { Id = gStr };
_model.Geometries.Add(g);
}
else if (StartWith(line, "usemtl"))
{
var umtl = line.Substring(6).Trim();
var g = GetGeometry();
var face = new Face { MatName = umtl };
g.Faces.Add(face);
}
else if (StartWith(line, "f"))
{
var fStr = line.Substring(1).Trim();
var g = GetGeometry();
Face face = GetFace(g);
var strs = SplitLine(fStr);
if (strs.Length < 3) continue; // ignore face that has less than 3 vertices
if (strs.Length == 3)
{
var v1 = GetVertex(strs[0]);
var v2 = GetVertex(strs[1]);
var v3 = GetVertex(strs[2]);
var f = new FaceTriangle(v1, v2, v3);
face.Triangles.Add(f);
}
else if (strs.Length == 4)
{
var v1 = GetVertex(strs[0]);
var v2 = GetVertex(strs[1]);
var v3 = GetVertex(strs[2]);
var f = new FaceTriangle(v1, v2, v3);
face.Triangles.Add(f);
var v4 = GetVertex(strs[3]);
var ff = new FaceTriangle(v1, v3, v4);
face.Triangles.Add(ff);
}
else //if (strs.Length > 4)
{
var points = new List<Vec3>();
for(var i = 0;i<strs.Length;i++)
{
var vv = GetVertex(strs[i]);
var p = _model.Vertices[vv.V-1];
points.Add(p);
}
var planeAxis = GeomUtil.ComputeProjectTo2DArguments(points);
if (planeAxis != null)
{
var points2D = GeomUtil.CreateProjectPointsTo2DFunction(planeAxis, points);
var indices = PolygonPipeline.Triangulate(points2D, null);
if (indices.Length == 0)
{
// TODO:
}
for(var i = 0; i < indices.Length-2;i+=3)
{
var vv1 = GetVertex(strs[indices[i]]);
var vv2 = GetVertex(strs[indices[i + 1]]);
var vv3 = GetVertex(strs[indices[i + 2]]);
var ff = new FaceTriangle(vv1, vv2, vv3);
face.Triangles.Add(ff);
}
}
else
{
// TODO:
}
}
}
else
{
//var strs = SplitLine(line);
}
}
if (!String.IsNullOrEmpty(_model.MatFilename))
{
var dir = Path.GetDirectoryName(_objFile);
var matFile = Path.Combine(dir, _model.MatFilename);
using (var mtlParser = new MtlParser(matFile, _encoding))
{
var mats = mtlParser.GetMats();
_model.Materials.AddRange(mats);
}
}
}
return _model;
}
19
Source : DoubleValueComparer.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public bool Compare(string expectedValue, object actualValue)
{
if (string.IsNullOrWhiteSpace(expectedValue))
return actualValue == null;
if (actualValue == null) return false;
var parsed = double.Parse(expectedValue);
return _aboutEqual((double)actualValue, parsed);
}
19
Source : Add_attribute.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
public static void Transform(ref TreeNode tree, Dictionary<string, object> parameterValues, Action<double> progressAction)
{
string[] nodeElements = (string[])parameterValues["Node:"];
TreeNode node = tree.GetLastCommonAncestor(nodeElements);
if (node == null)
{
throw new Exception("Could not find the requested node! If you have changed the Name of some nodes, please select the node again!");
}
string attributeName = (string)parameterValues["Attribute:"];
string attrType = (string)parameterValues["Attribute type:"];
string attrValue = (string)parameterValues["New value:"];
bool applyToChildren = (bool)parameterValues["Apply recursively to all children"];
if (!applyToChildren)
{
if (attributeName == "Name" && attrType == "String")
{
node.Name = attrValue;
}
else if (attributeName == "Support" && attrType == "Number")
{
node.Support = double.Parse(attrValue);
}
else if (attributeName == "Length" && attrType == "Number")
{
node.Length = double.Parse(attrValue);
}
else if (!string.IsNullOrEmpty(attrType))
{
if (attrType == "String")
{
node.Attributes[attributeName] = attrValue;
}
else if (attrType == "Number")
{
node.Attributes[attributeName] = double.Parse(attrValue);
}
}
}
else
{
foreach (TreeNode child in node.GetChildrenRecursiveLazy())
{
if (attributeName == "Name" && attrType == "String")
{
child.Name = attrValue;
}
else if (attributeName == "Support" && attrType == "Number")
{
child.Support = double.Parse(attrValue);
}
else if (attributeName == "Length" && attrType == "Number")
{
child.Length = double.Parse(attrValue);
}
else if (!string.IsNullOrEmpty(attrType))
{
if (attrType == "String")
{
child.Attributes[attributeName] = attrValue;
}
else if (attrType == "Number")
{
child.Attributes[attributeName] = double.Parse(attrValue);
}
}
}
}
}
19
Source : Add_attribute_from_attachment.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
public static void Transform(ref TreeNode tree, Dictionary<string, object> parameterValues, Action<double> progressAction)
{
Attachment attachment = (Attachment)parameterValues["Taxon list:"];
if (attachment != null)
{
string[] taxonListString = attachment.GetLines();
string attributeName = (string)parameterValues["Attribute:"];
string attrType = (string)parameterValues["Attribute type:"];
string attrValue = (string)parameterValues["New value:"];
int applyTo = (int)parameterValues["Apply to:"];
string matchAttribute = (string)parameterValues["Match attribute:"];
string matchAttributeType = (string)parameterValues["Match attribute type:"];
double[] taxonListDouble = null;
if (matchAttributeType == "Number")
{
double elDouble = double.NaN;
taxonListDouble = (from el in taxonListString where double.TryParse(el, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out elDouble) && !double.IsNaN(elDouble) select elDouble).ToArray();
}
if (applyTo == 0 || applyTo == 1 || applyTo == 2)
{
TreeNode lca = null;
if (applyTo == 2)
{
if (matchAttributeType == "String")
{
lca = GetLCA(tree, taxonListString, matchAttribute);
}
else if (matchAttributeType == "Number")
{
lca = GetLCA(tree, taxonListDouble, matchAttribute);
}
}
foreach (TreeNode leaf in tree.GetLeaves())
{
TreeNode node = leaf;
bool matches = false;
if (matchAttributeType == "String")
{
if (node.Attributes.TryGetValue(matchAttribute, out object attrObject) && attrObject is string matchAttrValue && !string.IsNullOrEmpty(matchAttrValue))
{
matches = taxonListString.Contains(matchAttrValue);
}
}
else if (matchAttributeType == "Number")
{
if (node.Attributes.TryGetValue(matchAttribute, out object attrObject) && attrObject is double matchAttrValue && !double.IsNaN(matchAttrValue))
{
matches = taxonListDouble.Contains(matchAttrValue);
}
}
if (matches)
{
TreeNode targetNode = applyTo == 0 ? node.Parent : applyTo == 1 ? null : lca?.Parent;
while (node != targetNode)
{
if (attributeName == "Name" && attrType == "String")
{
node.Name = attrValue;
}
else if (attributeName == "Support" && attrType == "Number")
{
node.Support = double.Parse(attrValue);
}
else if (attributeName == "Length" && attrType == "Number")
{
node.Length = double.Parse(attrValue);
}
else if (!string.IsNullOrEmpty(attrType))
{
if (attrType == "String")
{
node.Attributes[attributeName] = attrValue;
}
else if (attrType == "Number")
{
node.Attributes[attributeName] = double.Parse(attrValue);
}
}
node = node.Parent;
}
}
}
}
else if (applyTo == 3 || applyTo == 4)
{
TreeNode node = null;
if (matchAttributeType == "String")
{
node = GetLCA(tree, taxonListString, matchAttribute);
}
else if (matchAttributeType == "Number")
{
node = GetLCA(tree, taxonListDouble, matchAttribute);
}
if (node == null)
{
throw new Exception("Could not find the requested ancestor!");
}
if (applyTo == 3)
{
if (attributeName == "Name" && attrType == "String")
{
node.Name = attrValue;
}
else if (attributeName == "Support" && attrType == "Number")
{
node.Support = double.Parse(attrValue);
}
else if (attributeName == "Length" && attrType == "Number")
{
node.Length = double.Parse(attrValue);
}
else if (!string.IsNullOrEmpty(attrType))
{
if (attrType == "String")
{
node.Attributes[attributeName] = attrValue;
}
else if (attrType == "Number")
{
node.Attributes[attributeName] = double.Parse(attrValue);
}
}
}
else
{
foreach (TreeNode child in node.GetChildrenRecursiveLazy())
{
if (attributeName == "Name" && attrType == "String")
{
child.Name = attrValue;
}
else if (attributeName == "Support" && attrType == "Number")
{
child.Support = double.Parse(attrValue);
}
else if (attributeName == "Length" && attrType == "Number")
{
child.Length = double.Parse(attrValue);
}
else if (!string.IsNullOrEmpty(attrType))
{
if (attrType == "String")
{
child.Attributes[attributeName] = attrValue;
}
else if (attrType == "Number")
{
child.Attributes[attributeName] = double.Parse(attrValue);
}
}
}
}
}
}
}
19
Source : Change_attribute.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
public static void Transform(ref TreeNode tree, Dictionary<string, object> parameterValues, Action<double> progressAction)
{
string[] nodeElements = (string[])parameterValues["Node:"];
TreeNode node = tree.GetLastCommonAncestor(nodeElements);
if (node == null)
{
throw new Exception("Could not find the requested node! If you have changed the Name of some nodes, please select the node again!");
}
string attributeName = (string)parameterValues["Attribute:"];
string attrType = (string)parameterValues["Attribute type:"];
string attrValue = (string)parameterValues["New value:"];
if (attributeName == "Name" && attrType == "String")
{
node.Name = attrValue;
}
else if (attributeName == "Support" && attrType == "Number")
{
node.Support = double.Parse(attrValue);
}
else if (attributeName == "Length" && attrType == "Number")
{
node.Length = double.Parse(attrValue);
}
else if (!string.IsNullOrEmpty(attrType))
{
if (attrType == "String")
{
node.Attributes[attributeName] = attrValue;
}
else if (attrType == "Number")
{
node.Attributes[attributeName] = double.Parse(attrValue);
}
}
}
19
Source : Prune_node.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
public static void Transform(ref TreeNode tree, Dictionary<string, object> parameterValues, Action<double> progressAction)
{
double position = (double)parameterValues["Position:"];
bool leaveParent = (bool)parameterValues["Leave one-child parent"];
int mode = (int)parameterValues["Mode:"];
bool keepNodeNames = (bool)parameterValues["Keep pruned node names"];
string storeAttributeName = (string)parameterValues["Attribute name:"];
if (mode == 0)
{
string[] nodeElements = (string[])parameterValues["Node:"];
TreeNode node = tree.GetLastCommonAncestor(nodeElements);
PruneNode(node, ref tree, position, leaveParent, keepNodeNames, storeAttributeName);
}
else if (mode == 1)
{
List<TreeNode> nodes = tree.GetChildrenRecursive();
string attributeName = (string)parameterValues["Attribute:"];
string attrType = (string)parameterValues["Attribute type:"];
string attrValue = (string)parameterValues["Value:"];
double numberNeedle = attrType == "Number" ? double.Parse(attrValue) : -1;
int comparisonType = attrType == "String" ? (int)parameterValues["Comparison type:"] : (int)parameterValues["Comparison type: "];
bool regex = (bool)parameterValues["Regex"];
StringComparison comparison = StringComparison.InvariantCulture;
RegexOptions options = RegexOptions.CultureInvariant;
switch (comparisonType)
{
case 0:
comparison = StringComparison.InvariantCulture;
options = RegexOptions.CultureInvariant;
break;
case 1:
comparison = StringComparison.InvariantCultureIgnoreCase;
options = RegexOptions.IgnoreCase | RegexOptions.CultureInvariant;
break;
case 2:
comparison = StringComparison.CurrentCulture;
options = RegexOptions.None;
break;
case 3:
comparison = StringComparison.CurrentCultureIgnoreCase;
options = RegexOptions.IgnoreCase;
break;
}
Regex reg = regex ? new Regex(attrValue, options) : null;
for (int i = nodes.Count - 1; i >= 0; i--)
{
bool matched = false;
if (nodes[i].Attributes.TryGetValue(attributeName, out object attributeValue))
{
if (attrType == "String" && attributeValue is string actualValue)
{
if (regex)
{
if (reg.IsMatch(actualValue))
{
matched = true;
}
}
else
{
if (actualValue.Contains(attrValue, comparison))
{
matched = true;
}
}
}
else if (attrType == "Number" && attributeValue is double actualNumber)
{
switch (comparisonType)
{
case 0:
if (actualNumber == numberNeedle)
{
matched = true;
}
break;
case 1:
if (actualNumber < numberNeedle)
{
matched = true;
}
break;
case 2:
if (actualNumber > numberNeedle)
{
matched = true;
}
break;
}
}
}
if (matched)
{
PruneNode(nodes[i], ref tree, position, leaveParent, keepNodeNames, storeAttributeName);
}
}
}
}
19
Source : Replace_attribute.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
public static void Transform(ref TreeNode tree, Dictionary<string, object> parameterValues, Action<double> progressAction)
{
List<TreeNode> nodes = tree.GetChildrenRecursive();
bool applyToChildren = (bool)parameterValues["Apply recursively to all children"];
string attributeName = (string)parameterValues["Attribute:"];
string attrType = (string)parameterValues["Attribute type:"];
string attrValue = (string)parameterValues["Value:"];
double numberNeedle = attrType == "Number" ? double.Parse(attrValue) : -1;
string replacementName = (string)parameterValues["Attribute: "];
string replacementType = (string)parameterValues["Attribute type: "];
string replacementValue = (string)parameterValues["Value: "];
int comparisonType = attrType == "String" ? (int)parameterValues["Comparison type:"] : (int)parameterValues["Comparison type: "];
bool regex = (bool)parameterValues["Regex"];
StringComparison comparison = StringComparison.InvariantCulture;
RegexOptions options = RegexOptions.CultureInvariant;
switch (comparisonType)
{
case 0:
comparison = StringComparison.InvariantCulture;
options = RegexOptions.CultureInvariant;
break;
case 1:
comparison = StringComparison.InvariantCultureIgnoreCase;
options = RegexOptions.IgnoreCase | RegexOptions.CultureInvariant;
break;
case 2:
comparison = StringComparison.CurrentCulture;
options = RegexOptions.None;
break;
case 3:
comparison = StringComparison.CurrentCultureIgnoreCase;
options = RegexOptions.IgnoreCase;
break;
}
Regex reg = regex ? new Regex(attrValue, options) : null;
foreach (TreeNode node in nodes)
{
bool matched = false;
if (node.Attributes.TryGetValue(attributeName, out object attributeValue))
{
if (attrType == "String" && attributeValue is string actualValue)
{
if (regex)
{
if (reg.IsMatch(actualValue))
{
matched = true;
}
}
else
{
if (actualValue.Contains(attrValue, comparison))
{
matched = true;
}
}
}
else if (attrType == "Number" && attributeValue is double actualNumber)
{
switch (comparisonType)
{
case 0:
if (actualNumber == numberNeedle)
{
matched = true;
}
break;
case 1:
if (actualNumber < numberNeedle)
{
matched = true;
}
break;
case 2:
if (actualNumber > numberNeedle)
{
matched = true;
}
break;
}
}
}
if (matched)
{
string currentReplacementValue = replacementValue;
if (attrType == "String" && replacementType == "String" && (attributeName.Equals(replacementName, StringComparison.OrdinalIgnoreCase) || regex))
{
if (!regex)
{
currentReplacementValue = ((string)attributeValue).Replace(attrValue, replacementValue, comparison);
}
else
{
currentReplacementValue = reg.Replace(((string)attributeValue), replacementValue);
}
}
if (!applyToChildren)
{
if (replacementName == "Name" && replacementType == "String")
{
node.Name = currentReplacementValue;
}
else if (replacementName == "Support" && replacementType == "Number")
{
node.Support = double.Parse(currentReplacementValue);
}
else if (replacementName == "Length" && replacementType == "Number")
{
node.Length = double.Parse(currentReplacementValue);
}
else if (!string.IsNullOrEmpty(replacementType))
{
if (replacementType == "String")
{
node.Attributes[replacementName] = currentReplacementValue;
}
else if (replacementType == "Number")
{
node.Attributes[replacementName] = double.Parse(currentReplacementValue);
}
}
}
else
{
foreach (TreeNode child in node.GetChildrenRecursiveLazy())
{
if (replacementName == "Name" && replacementType == "String")
{
child.Name = currentReplacementValue;
}
else if (replacementName == "Support" && replacementType == "Number")
{
child.Support = double.Parse(currentReplacementValue);
}
else if (replacementName == "Length" && replacementType == "Number")
{
child.Length = double.Parse(currentReplacementValue);
}
else if (!string.IsNullOrEmpty(replacementType))
{
if (replacementType == "String")
{
child.Attributes[replacementName] = currentReplacementValue;
}
else if (replacementType == "Number")
{
child.Attributes[replacementName] = double.Parse(currentReplacementValue);
}
}
}
}
}
}
}
19
Source : Polytomise_node.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
public static void Transform(ref TreeNode tree, Dictionary<string, object> parameterValues, Action<double> progressAction)
{
int mode = (int)parameterValues["Mode:"];
bool allChildren = (bool)parameterValues["Apply recursively to all children"];
if (mode == 0)
{
string[] nodeElements = (string[])parameterValues["Node:"];
TreeNode node = tree.GetLastCommonAncestor(nodeElements);
if (node == null)
{
throw new Exception("Could not find the requested node! If you have changed the Name of some nodes, please select the node again!");
}
PolytomiseNode(node, allChildren);
}
else if (mode == 1)
{
List<TreeNode> nodes = tree.GetChildrenRecursive();
string attributeName = (string)parameterValues["Attribute:"];
string attrType = (string)parameterValues["Attribute type:"];
string attrValue = (string)parameterValues["Value:"];
double numberNeedle = attrType == "Number" ? double.Parse(attrValue) : -1;
int comparisonType = attrType == "String" ? (int)parameterValues["Comparison type:"] : (int)parameterValues["Comparison type: "];
bool regex = (bool)parameterValues["Regex"];
StringComparison comparison = StringComparison.InvariantCulture;
RegexOptions options = RegexOptions.CultureInvariant;
switch (comparisonType)
{
case 0:
comparison = StringComparison.InvariantCulture;
options = RegexOptions.CultureInvariant;
break;
case 1:
comparison = StringComparison.InvariantCultureIgnoreCase;
options = RegexOptions.IgnoreCase | RegexOptions.CultureInvariant;
break;
case 2:
comparison = StringComparison.CurrentCulture;
options = RegexOptions.None;
break;
case 3:
comparison = StringComparison.CurrentCultureIgnoreCase;
options = RegexOptions.IgnoreCase;
break;
}
Regex reg = regex ? new Regex(attrValue, options) : null;
foreach (TreeNode node in nodes)
{
bool matched = false;
if (node.Attributes.TryGetValue(attributeName, out object attributeValue))
{
if (attrType == "String" && attributeValue is string actualValue)
{
if (regex)
{
if (reg.IsMatch(actualValue))
{
matched = true;
}
}
else
{
if (actualValue.Contains(attrValue, comparison))
{
matched = true;
}
}
}
else if (attrType == "Number" && attributeValue is double actualNumber)
{
switch (comparisonType)
{
case 0:
if (actualNumber == numberNeedle)
{
matched = true;
}
break;
case 1:
if (actualNumber < numberNeedle)
{
matched = true;
}
break;
case 2:
if (actualNumber > numberNeedle)
{
matched = true;
}
break;
}
}
}
if (matched)
{
PolytomiseNode(node, allChildren);
}
}
}
}
19
Source : PreferencesPage.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
private void AddParameter(string name, string data, List<Func<bool>> applyChanges, Grid pageContent, int currRow)
{
string controlType = data.Substring(0, data.IndexOf(":"));
string controlParameters = data.Substring(data.IndexOf(":") + 1);
if (controlType == "CheckBox")
{
string parameterName = name;
bool defaultValue = Convert.ToBoolean(controlParameters);
if (!GlobalSettings.Settings.AdditionalSettings.TryGetValue(parameterName, out object valueObject))
{
GlobalSettings.Settings.AdditionalSettings.Add(parameterName, defaultValue);
}
else
{
if (valueObject is JsonElement element)
{
defaultValue = element.GetBoolean();
GlobalSettings.Settings.AdditionalSettings[parameterName] = defaultValue;
}
else
{
defaultValue = (bool)valueObject;
}
}
CheckBox control = new CheckBox() { Content = parameterName, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left, Margin = new Thickness(0, 0, 0, 10), IsChecked = defaultValue, FontSize = 14 };
Grid.SetRow(control, currRow);
Grid.SetColumnSpan(control, 2);
pageContent.Children.Add(control);
applyChanges.Add(() =>
{
GlobalSettings.Settings.AdditionalSettings[parameterName] = control.IsChecked == true;
return false;
});
}
else
{
string parameterName = name;
TextBlock blk = new TextBlock() { Text = parameterName, Margin = new Thickness(0, 0, 10, 10), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 14 };
Grid.SetRow(blk, currRow);
pageContent.Children.Add(blk);
if (controlType == "ComboBox")
{
int defaultIndex = int.Parse(controlParameters.Substring(0, controlParameters.IndexOf("[")));
controlParameters = controlParameters.Substring(controlParameters.IndexOf("["));
List<string> items = System.Text.Json.JsonSerializer.Deserialize<List<string>>(controlParameters, Modules.DefaultSerializationOptions);
if (!GlobalSettings.Settings.AdditionalSettings.TryGetValue(parameterName, out object valueObject))
{
GlobalSettings.Settings.AdditionalSettings.Add(parameterName, defaultIndex);
}
else
{
if (valueObject is JsonElement element)
{
defaultIndex = element.GetInt32();
GlobalSettings.Settings.AdditionalSettings[parameterName] = defaultIndex;
}
else
{
defaultIndex = (int)valueObject;
}
}
ComboBox box = new ComboBox() { Margin = new Thickness(0, 0, 0, 10), Items = items, SelectedIndex = defaultIndex, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, MinWidth = 200, FontSize = 14 };
Grid.SetRow(box, currRow);
Grid.SetColumn(box, 1);
pageContent.Children.Add(box);
applyChanges.Add(() =>
{
GlobalSettings.Settings.AdditionalSettings[parameterName] = box.SelectedIndex;
return false;
});
}
else if (controlType == "TextBox")
{
string defaultValue = controlParameters;
if (!GlobalSettings.Settings.AdditionalSettings.TryGetValue(parameterName, out object valueObject))
{
GlobalSettings.Settings.AdditionalSettings.Add(parameterName, defaultValue);
}
else
{
if (valueObject is JsonElement element)
{
defaultValue = element.GetString();
GlobalSettings.Settings.AdditionalSettings[parameterName] = defaultValue;
}
else
{
defaultValue = (string)valueObject;
}
}
TextBox box = new TextBox() { Margin = new Thickness(0, 0, 0, 10), Padding = new Thickness(5, 2, 5, 2), Text = defaultValue, VerticalContentAlignment = Avalonia.Layout.VerticalAlignment.Center, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, MinWidth = 200, FontSize = 14, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left };
Grid.SetRow(box, currRow);
Grid.SetColumn(box, 1);
pageContent.Children.Add(box);
applyChanges.Add(() =>
{
GlobalSettings.Settings.AdditionalSettings[parameterName] = box.Text;
return false;
});
}
else if (controlType == "NumericUpDown")
{
double defaultValue = double.Parse(controlParameters.Substring(0, controlParameters.IndexOf("[")));
controlParameters = controlParameters.Substring(controlParameters.IndexOf("["));
string[] range = System.Text.Json.JsonSerializer.Deserialize<string[]>(controlParameters, Modules.DefaultSerializationOptions);
double minRange = double.Parse(range[0], System.Globalization.CultureInfo.InvariantCulture);
double maxRange = double.Parse(range[1], System.Globalization.CultureInfo.InvariantCulture);
double increment = (maxRange - minRange) * 0.01;
if (range.Length > 2)
{
increment = double.Parse(range[2], System.Globalization.CultureInfo.InvariantCulture);
}
if (double.IsNaN(increment) || double.IsInfinity(increment))
{
increment = 1;
}
string formatString = Extensions.GetFormatString(increment);
if (range.Length > 3)
{
formatString = range[3];
}
if (!GlobalSettings.Settings.AdditionalSettings.TryGetValue(parameterName, out object valueObject))
{
GlobalSettings.Settings.AdditionalSettings.Add(parameterName, defaultValue);
}
else
{
if (valueObject is JsonElement element)
{
defaultValue = element.GetDouble();
GlobalSettings.Settings.AdditionalSettings[parameterName] = defaultValue;
}
else
{
defaultValue = (double)valueObject;
}
}
NumericUpDown nud = new NumericUpDown() { Margin = new Thickness(0, 0, 0, 10), Minimum = minRange, Maximum = maxRange, Increment = increment, Value = defaultValue, FormatString = formatString, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, MinWidth = 200, FontSize = 14, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left };
Grid.SetRow(nud, currRow);
Grid.SetColumn(nud, 1);
pageContent.Children.Add(nud);
applyChanges.Add(() =>
{
GlobalSettings.Settings.AdditionalSettings[parameterName] = nud.Value;
return false;
});
}
else if (controlType == "FileSize")
{
long defaultValue = long.Parse(controlParameters);
if (!GlobalSettings.Settings.AdditionalSettings.TryGetValue(parameterName, out object valueObject))
{
GlobalSettings.Settings.AdditionalSettings.Add(parameterName, defaultValue);
}
else
{
if (valueObject is JsonElement element)
{
defaultValue = element.GetInt64();
GlobalSettings.Settings.AdditionalSettings[parameterName] = defaultValue;
}
else
{
defaultValue = (long)valueObject;
}
}
FileSizeControl.FileSizeUnit unit;
if (defaultValue < 1024)
{
unit = FileSizeControl.FileSizeUnit.B;
}
else
{
double longSize = defaultValue / 1024.0;
if (longSize < 1024)
{
unit = FileSizeControl.FileSizeUnit.kiB;
}
else
{
longSize /= 1024.0;
if (longSize < 1024)
{
unit = FileSizeControl.FileSizeUnit.MiB;
}
else
{
longSize /= 1024.0;
unit = FileSizeControl.FileSizeUnit.GiB;
}
}
}
FileSizeControl control = new FileSizeControl() { Margin = new Thickness(0, 0, 0, 10), Value = defaultValue, Unit = unit, MinWidth = 200, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 14, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left };
Grid.SetRow(control, currRow);
Grid.SetColumn(control, 1);
pageContent.Children.Add(control);
applyChanges.Add(() =>
{
GlobalSettings.Settings.AdditionalSettings[parameterName] = control.Value;
return false;
});
}
else if (controlType == "Slider")
{
double defaultValue = double.Parse(controlParameters.Substring(0, controlParameters.IndexOf("[")));
controlParameters = controlParameters.Substring(controlParameters.IndexOf("["));
string[] range = System.Text.Json.JsonSerializer.Deserialize<string[]>(controlParameters, Modules.DefaultSerializationOptions);
double minRange = double.Parse(range[0], System.Globalization.CultureInfo.InvariantCulture);
double maxRange = double.Parse(range[1], System.Globalization.CultureInfo.InvariantCulture);
double increment = (maxRange - minRange) * 0.01;
if (double.IsNaN(increment) || double.IsInfinity(increment))
{
increment = 1;
}
if (!GlobalSettings.Settings.AdditionalSettings.TryGetValue(parameterName, out object valueObject))
{
GlobalSettings.Settings.AdditionalSettings.Add(parameterName, defaultValue);
}
else
{
if (valueObject is JsonElement element)
{
defaultValue = element.GetDouble();
GlobalSettings.Settings.AdditionalSettings[parameterName] = defaultValue;
}
else
{
defaultValue = (double)valueObject;
}
}
Grid sliderGrid = new Grid();
sliderGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
sliderGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
Grid.SetRow(sliderGrid, currRow);
Grid.SetColumn(sliderGrid, 1);
pageContent.Children.Add(sliderGrid);
Slider slid = new Slider() { Margin = new Thickness(0, 0, 0, 10), Minimum = minRange, Maximum = maxRange, Value = defaultValue, LargeChange = increment, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 14 };
sliderGrid.Children.Add(slid);
NumericUpDown valueBlock = null;
if (range.Length > 2)
{
valueBlock = new NumericUpDown() { VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Margin = new Thickness(5, 0, 0, 10), Value = slid.Value, FormatString = range[2], Minimum = minRange, Maximum = maxRange, Increment = increment, MinWidth = 100, FontSize = 14, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left };
Grid.SetColumn(valueBlock, 1);
sliderGrid.Children.Add(valueBlock);
}
else
{
valueBlock = new NumericUpDown() { VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Margin = new Thickness(5, 0, 0, 10), Value = slid.Value, FormatString = Extensions.GetFormatString(increment), Minimum = minRange, Maximum = maxRange, Increment = increment, MinWidth = 100, FontSize = 14, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left };
Grid.SetColumn(valueBlock, 1);
sliderGrid.Children.Add(valueBlock);
}
slid.PropertyChanged += (s, e) =>
{
if (e.Property == Slider.ValueProperty)
{
valueBlock.Value = slid.Value;
}
};
if (valueBlock != null)
{
valueBlock.ValueChanged += (s, e) =>
{
slid.Value = valueBlock.Value;
};
}
applyChanges.Add(() =>
{
GlobalSettings.Settings.AdditionalSettings[parameterName] = valueBlock.Value;
return false;
});
}
else if (controlType == "Font")
{
string[] font = System.Text.Json.JsonSerializer.Deserialize<string[]>(controlParameters, Modules.DefaultSerializationOptions);
VectSharp.Font fnt = new VectSharp.Font(new VectSharp.FontFamily(font[0]), double.Parse(font[1], System.Globalization.CultureInfo.InvariantCulture));
if (!GlobalSettings.Settings.AdditionalSettings.TryGetValue(parameterName, out object valueObject))
{
GlobalSettings.Settings.AdditionalSettings.Add(parameterName, fnt);
}
else
{
if (valueObject is JsonElement element)
{
font = element.GetString().Split(',');
fnt = new VectSharp.Font(new VectSharp.FontFamily(font[0]), double.Parse(font[1], System.Globalization.CultureInfo.InvariantCulture));
GlobalSettings.Settings.AdditionalSettings[parameterName] = fnt;
}
else
{
fnt = (VectSharp.Font)valueObject;
}
}
FontButton but = new FontButton(false) { FontSize = 14, Font = fnt, Margin = new Thickness(0, 0, 0, 10), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left };
Grid.SetRow(but, currRow);
Grid.SetColumn(but, 1);
pageContent.Children.Add(but);
applyChanges.Add(() =>
{
GlobalSettings.Settings.AdditionalSettings[parameterName] = but.Font;
return false;
});
}
else if (controlType == "Point")
{
double[] point = System.Text.Json.JsonSerializer.Deserialize<double[]>(controlParameters, Modules.DefaultSerializationOptions);
Grid grid = new Grid();
grid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
grid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
grid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));
grid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
VectSharp.Point pt = new VectSharp.Point(point[0], point[1]);
if (!GlobalSettings.Settings.AdditionalSettings.TryGetValue(parameterName, out object valueObject))
{
GlobalSettings.Settings.AdditionalSettings.Add(parameterName, pt);
}
else
{
if (valueObject is JsonElement element)
{
string str = element.GetString();
string[] pointStr = str.Split(',');
pt = new VectSharp.Point(double.Parse(pointStr[0], System.Globalization.CultureInfo.InvariantCulture), double.Parse(pointStr[1], System.Globalization.CultureInfo.InvariantCulture));
GlobalSettings.Settings.AdditionalSettings[parameterName] = pt;
}
else
{
pt = (VectSharp.Point)valueObject;
}
}
NumericUpDown nudX = new NumericUpDown() { Margin = new Thickness(5, 0, 0, 10), Increment = 1, Value = pt.X, FormatString = Extensions.GetFormatString(point[0]), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 14, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left, MinWidth = 100 };
NumericUpDown nudY = new NumericUpDown() { Margin = new Thickness(5, 0, 0, 10), Increment = 1, Value = pt.Y, FormatString = Extensions.GetFormatString(point[1]), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 14, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left, MinWidth = 100 };
TextBlock blkX = new TextBlock() { Text = "X:", VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Margin = new Thickness(5, 0, 0, 10), FontSize = 14 };
TextBlock blkY = new TextBlock() { Text = "Y:", VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Margin = new Thickness(5, 0, 0, 10), FontSize = 14 };
Grid.SetColumn(blkY, 2);
Grid.SetColumn(grid, 1);
Grid.SetColumn(nudX, 1);
Grid.SetColumn(nudY, 3);
grid.Children.Add(blkX);
grid.Children.Add(nudX);
grid.Children.Add(blkY);
grid.Children.Add(nudY);
Grid.SetRow(grid, currRow);
Grid.SetColumn(grid, 1);
pageContent.Children.Add(grid);
applyChanges.Add(() =>
{
GlobalSettings.Settings.AdditionalSettings[parameterName] = new VectSharp.Point(nudX.Value, nudY.Value);
return false;
});
}
else if (controlType == "Colour")
{
int[] colour = System.Text.Json.JsonSerializer.Deserialize<int[]>(controlParameters, Modules.DefaultSerializationOptions);
VectSharp.Colour col = VectSharp.Colour.FromRgba((byte)colour[0], (byte)colour[1], (byte)colour[2], (byte)colour[3]);
if (!GlobalSettings.Settings.AdditionalSettings.TryGetValue(parameterName, out object valueObject))
{
GlobalSettings.Settings.AdditionalSettings.Add(parameterName, col);
}
else
{
if (valueObject is JsonElement element)
{
col = VectSharp.Colour.FromCSSString(element.GetString()) ?? VectSharp.Colour.FromRgba(0, 0, 0, 0);
GlobalSettings.Settings.AdditionalSettings[parameterName] = col;
}
else
{
col = (VectSharp.Colour)valueObject;
}
}
ColorButton but = new ColorButton() { Color = col.ToAvalonia(), Margin = new Thickness(0, 0, 0, 10), HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left, FontSize = 14, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
Grid.SetRow(but, currRow);
Grid.SetColumn(but, 1);
pageContent.Children.Add(but);
applyChanges.Add(() =>
{
GlobalSettings.Settings.AdditionalSettings[parameterName] = but.Color.ToVectSharp();
return false;
});
}
else if (controlType == "Dash")
{
double[] dash = System.Text.Json.JsonSerializer.Deserialize<double[]>(controlParameters, Modules.DefaultSerializationOptions);
VectSharp.LineDash lineDash = new VectSharp.LineDash(dash[0], dash[1], dash[2]);
if (!GlobalSettings.Settings.AdditionalSettings.TryGetValue(parameterName, out object valueObject))
{
GlobalSettings.Settings.AdditionalSettings.Add(parameterName, lineDash);
}
else
{
if (valueObject is JsonElement element)
{
string str = element.GetString();
string[] dashStr = str.Split(',');
lineDash = new VectSharp.LineDash(double.Parse(dashStr[0], System.Globalization.CultureInfo.InvariantCulture), double.Parse(dashStr[1], System.Globalization.CultureInfo.InvariantCulture), double.Parse(dashStr[2], System.Globalization.CultureInfo.InvariantCulture));
GlobalSettings.Settings.AdditionalSettings[parameterName] = lineDash;
}
else
{
lineDash = (VectSharp.LineDash)valueObject;
}
}
DashControl control = new DashControl() { LineDash = lineDash, Margin = new Thickness(0, 0, 0, 10), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 14 };
Grid.SetRow(control, currRow);
Grid.SetColumn(control, 1);
pageContent.Children.Add(control);
applyChanges.Add(() =>
{
GlobalSettings.Settings.AdditionalSettings[parameterName] = control.LineDash;
return false;
});
}
}
}
19
Source : ModuleUtils.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
private static List<object> DeserializeList(string serializedList)
{
List<string[]> allObjects = System.Text.Json.JsonSerializer.Deserialize<List<string[]>>(serializedList, Modules.DefaultSerializationOptions);
List<object> tbr = new List<object>();
foreach (string[] currObject in allObjects)
{
if (currObject[0] == "bool")
{
tbr.Add(System.Text.Json.JsonSerializer.Deserialize<bool>(currObject[1], Modules.DefaultSerializationOptions));
}
else if (currObject[0] == "int")
{
tbr.Add(System.Text.Json.JsonSerializer.Deserialize<int>(currObject[1], Modules.DefaultSerializationOptions));
}
if (currObject[0] == "string")
{
tbr.Add(System.Text.Json.JsonSerializer.Deserialize<string>(currObject[1], Modules.DefaultSerializationOptions));
}
if (currObject[0] == "double")
{
try
{
if (currObject[1] != "Infinity")
{
tbr.Add(System.Text.Json.JsonSerializer.Deserialize<double>(currObject[1], Modules.DefaultSerializationOptions));
}
else
{
tbr.Add(double.Parse(currObject[1]));
}
}
catch
{
tbr.Add(double.Parse(currObject[1]));
}
}
else if (currObject[0] == "gradient")
{
tbr.Add(Gradient.DeserializeJson(currObject[1]));
}
}
return tbr;
}
19
Source : Scale_bar.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
public static Point[] PlotAction(TreeNode tree, Dictionary<string, object> parameterValues, Dictionary<string, Point> coordinates, Graphics graphics)
{
Point scalePoint;
if (!coordinates.TryGetValue("68e25ec6-5911-4741-8547-317597e1b792", out scalePoint))
{
if (!coordinates.TryGetValue("95b61284-b870-48b9-b51c-3276f7d89df1", out scalePoint))
{
if (!coordinates.TryGetValue("d0ab64ba-3bcd-443f-9150-48f6e85e97f3", out scalePoint))
{
throw new Exception("The coordinates module is not supported!");
}
else
{
scalePoint = new Point(scalePoint.X, 0);
}
}
}
List<TreeNode> nodes = tree.GetChildrenRecursive();
double minX = double.MaxValue;
double maxX = double.MinValue;
double minY = double.MaxValue;
double maxY = double.MinValue;
void updateMaxMin(Point pt)
{
minX = Math.Min(minX, pt.X);
maxX = Math.Max(maxX, pt.X);
minY = Math.Min(minY, pt.Y);
maxY = Math.Max(maxY, pt.Y);
}
static Point sumPoint(Point pt1, Point pt2)
{
return new Point(pt1.X + pt2.X, pt1.Y + pt2.Y);
}
static Point rotatePoint(Point pt, double angle)
{
return new Point(pt.X * Math.Cos(angle) - pt.Y * Math.Sin(angle), pt.X * Math.Sin(angle) + pt.Y * Math.Cos(angle));
}
for (int i = 0; i < nodes.Count; i++)
{
updateMaxMin(coordinates[nodes[i].Id]);
}
updateMaxMin(coordinates[Modules.RootNodeId]);
double maxLength = tree.LongestDownstreamLength();
int digits = (int)(double)parameterValues["Digits:"];
double scaleSize = double.Parse((maxLength * (double)parameterValues["Scale size:"]).ToString(digits));
double actualScaleLength = Math.Sqrt((scalePoint.X * scalePoint.X) + (scalePoint.Y * scalePoint.Y)) * scaleSize;
double scaleThickness = (double)parameterValues["Line thickness:"];
double angle = (double)parameterValues["Angle:"] * Math.PI / 180;
while (Math.Abs(angle) > Math.PI)
{
angle -= 2 * Math.PI * Math.Sign(angle);
}
Colour colour = (Colour)parameterValues["Colour:"];
Point delta = (Point)parameterValues["Position:"];
Point point = new Point((minX + maxX) * 0.5 + delta.X, maxY + 15 + scaleThickness * 0.5 + 4.5 + delta.Y);
graphics.Save();
graphics.Translate(point);
graphics.Rotate(angle);
GraphicsPath scalePath = new GraphicsPath().MoveTo(-actualScaleLength * 0.5, -scaleThickness * 0.5 - 4.5).LineTo(-actualScaleLength * 0.5, scaleThickness * 0.5 + 4.5);
scalePath.MoveTo(-actualScaleLength * 0.5, 0).LineTo(actualScaleLength * 0.5, 0);
scalePath.MoveTo(actualScaleLength * 0.5, -scaleThickness * 0.5 - 4.5).LineTo(actualScaleLength * 0.5, scaleThickness * 0.5 + 4.5);
graphics.StrokePath(scalePath, colour, scaleThickness, LineCaps.Round);
Font fnt = (Font)parameterValues["Font:"];
string scaleText = scaleSize.ToString(digits);
if (Math.Abs(angle) < Math.PI / 2)
{
graphics.FillText(-fnt.MeasureText(scaleText).Width * 0.5, 5 + scaleThickness * 0.5 + 4.5, scaleText, fnt, colour);
}
else
{
graphics.Save();
graphics.Rotate(Math.PI);
graphics.FillText(-fnt.MeasureText(scaleText).Width * 0.5, -(5 + scaleThickness * 0.5 + 4.5) - fnt.MeasureText(scaleText).Height, scaleText, fnt, colour);
graphics.Restore();
}
graphics.Restore();
minX = double.MaxValue;
maxX = double.MinValue;
minY = double.MaxValue;
maxY = double.MinValue;
updateMaxMin(sumPoint(point, rotatePoint(new Point(-actualScaleLength * 0.5, -scaleThickness * 0.5 - 4.5), angle)));
updateMaxMin(sumPoint(point, rotatePoint(new Point(actualScaleLength * 0.5, -scaleThickness * 0.5 - 4.5), angle)));
updateMaxMin(sumPoint(point, rotatePoint(new Point(actualScaleLength * 0.5, scaleThickness * 0.5 + 4.5), angle)));
updateMaxMin(sumPoint(point, rotatePoint(new Point(-actualScaleLength * 0.5, scaleThickness * 0.5 + 4.5), angle)));
updateMaxMin(sumPoint(point, rotatePoint(new Point(-fnt.MeasureText(scaleText).Width * 0.5, 5 + scaleThickness * 0.5 + 4.5 + fnt.MeasureText(scaleText).Height), angle)));
updateMaxMin(sumPoint(point, rotatePoint(new Point(fnt.MeasureText(scaleText).Width * 0.5, 5 + scaleThickness * 0.5 + 4.5 + fnt.MeasureText(scaleText).Height), angle)));
if (double.IsNaN(minX))
{
minX = 0;
}
if (double.IsNaN(minY))
{
minY = 0;
}
if (double.IsNaN(maxX))
{
maxX = 0;
}
if (double.IsNaN(maxY))
{
maxY = 0;
}
return new Point[] { new Point(minX, minY), new Point(maxX, maxY) };
}
19
Source : GlobalSettings.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
internal static void SetSetting(string settingName, string settingValue)
{
switch (settingName)
{
case "AutosaveInterval":
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.AutosaveInterval = new TimeSpan(0, 10, 0);
}
else
{
GlobalSettings.Settings.AutosaveInterval = TimeSpan.Parse(settingValue);
}
break;
case "DragInterval":
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.DragInterval = 250;
}
else
{
GlobalSettings.Settings.DragInterval = int.Parse(settingValue);
}
break;
case "KeepRecentFilesFor":
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.KeepRecentFilesFor = 30;
}
else
{
GlobalSettings.Settings.KeepRecentFilesFor = int.Parse(settingValue);
}
break;
case "DrawTreeWhenOpened":
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.DrawTreeWhenOpened = true;
}
else
{
GlobalSettings.Settings.DrawTreeWhenOpened = Convert.ToBoolean(settingValue);
}
break;
case "ShowLegacyUpDownArrows":
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.ShowLegacyUpDownArrows = false;
}
else
{
GlobalSettings.Settings.ShowLegacyUpDownArrows = Convert.ToBoolean(settingValue);
}
break;
case "SelectionColour":
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.SelectionColour = Colour.FromRgb(35, 127, 255);
}
else
{
GlobalSettings.Settings.SelectionColour = Colour.FromCSSString(settingValue) ?? Colour.FromRgb(35, 127, 255);
}
break;
case "BackgroundColour":
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.BackgroundColour = Colour.FromRgb(240, 244, 250);
}
else
{
GlobalSettings.Settings.BackgroundColour = Colour.FromCSSString(settingValue) ?? Colour.FromRgb(240, 244, 250);
}
break;
case "ModuleRepositoryBaseUri":
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.ModuleRepositoryBaseUri = GlobalSettings.DefaultModuleRepository;
}
else
{
GlobalSettings.Settings.ModuleRepositoryBaseUri = settingValue;
}
break;
case "UpdateCheckMode":
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.UpdateCheckMode = GlobalSettings.UpdateCheckModes.ProgramAndAllModules;
}
else
{
GlobalSettings.Settings.UpdateCheckMode = (GlobalSettings.UpdateCheckModes)Enum.Parse(typeof(GlobalSettings.UpdateCheckModes), settingValue);
}
break;
case "InterfaceStyle":
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.InterfaceStyle = Modules.IsMac ? InterfaceStyles.MacOSStyle : InterfaceStyles.WindowsStyle;
}
else
{
GlobalSettings.Settings.InterfaceStyle = (GlobalSettings.InterfaceStyles)Enum.Parse(typeof(GlobalSettings.InterfaceStyles), settingValue);
}
break;
case "RibbonStyle":
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.RibbonStyle = Modules.IsWindows ? RibbonStyles.Colourful : RibbonStyles.Grey;
}
else
{
GlobalSettings.Settings.RibbonStyle = (GlobalSettings.RibbonStyles)Enum.Parse(typeof(GlobalSettings.RibbonStyles), settingValue);
}
break;
default:
{
bool found = false;
foreach (KeyValuePair<string, string> kvp in GlobalSettings.Settings.AdditionalSettingsList)
{
string name = kvp.Key;
string data = kvp.Value;
if (name == settingName)
{
string controlType = data.Substring(0, data.IndexOf(":"));
string controlParameters = data.Substring(data.IndexOf(":") + 1);
if (controlType == "CheckBox")
{
bool defaultValue = Convert.ToBoolean(controlParameters);
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.AdditionalSettings[name] = defaultValue;
}
else
{
GlobalSettings.Settings.AdditionalSettings[name] = Convert.ToBoolean(settingValue);
}
}
else if (controlType == "ComboBox")
{
int defaultIndex = int.Parse(controlParameters.Substring(0, controlParameters.IndexOf("[")));
controlParameters = controlParameters.Substring(controlParameters.IndexOf("["));
List<string> items = System.Text.Json.JsonSerializer.Deserialize<List<string>>(controlParameters, Modules.DefaultSerializationOptions);
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.AdditionalSettings[name] = defaultIndex;
}
else
{
int index = items.IndexOf(settingValue);
if (index < 0)
{
index = defaultIndex;
}
GlobalSettings.Settings.AdditionalSettings[name] = index;
}
}
else if (controlType == "TextBox")
{
string defaultValue = controlParameters;
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.AdditionalSettings[name] = defaultValue;
}
else
{
GlobalSettings.Settings.AdditionalSettings[name] = settingValue;
}
}
else if (controlType == "NumericUpDown")
{
double defaultValue = double.Parse(controlParameters.Substring(0, controlParameters.IndexOf("[")));
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.AdditionalSettings[name] = defaultValue;
}
else
{
GlobalSettings.Settings.AdditionalSettings[name] = double.Parse(settingValue, System.Globalization.CultureInfo.InvariantCulture);
}
}
else if (controlType == "FileSize")
{
long defaultValue = long.Parse(controlParameters);
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.AdditionalSettings[name] = defaultValue;
}
else
{
GlobalSettings.Settings.AdditionalSettings[name] = long.Parse(settingValue, System.Globalization.CultureInfo.InvariantCulture);
}
}
else if (controlType == "Slider")
{
double defaultValue = double.Parse(controlParameters.Substring(0, controlParameters.IndexOf("[")));
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.AdditionalSettings[name] = defaultValue;
}
else
{
GlobalSettings.Settings.AdditionalSettings[name] = double.Parse(settingValue, System.Globalization.CultureInfo.InvariantCulture);
}
}
else if (controlType == "Font")
{
string[] font = System.Text.Json.JsonSerializer.Deserialize<string[]>(controlParameters, Modules.DefaultSerializationOptions);
VectSharp.Font fnt = new VectSharp.Font(new VectSharp.FontFamily(font[0]), double.Parse(font[1], System.Globalization.CultureInfo.InvariantCulture));
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.AdditionalSettings[name] = fnt;
}
else
{
string[] splitSettingValue = settingValue.Split(',');
VectSharp.Font newFont = new VectSharp.Font(new VectSharp.FontFamily(splitSettingValue[0]), double.Parse(splitSettingValue[1], System.Globalization.CultureInfo.InvariantCulture));
GlobalSettings.Settings.AdditionalSettings[name] = double.Parse(settingValue, System.Globalization.CultureInfo.InvariantCulture);
}
}
else if (controlType == "Point")
{
double[] point = System.Text.Json.JsonSerializer.Deserialize<double[]>(controlParameters, Modules.DefaultSerializationOptions);
VectSharp.Point pt = new VectSharp.Point(point[0], point[1]);
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.AdditionalSettings[name] = pt;
}
else
{
string[] splitSettingValue = settingValue.Split(',');
VectSharp.Point newPoint = new VectSharp.Point(double.Parse(splitSettingValue[0], System.Globalization.CultureInfo.InvariantCulture), double.Parse(splitSettingValue[1], System.Globalization.CultureInfo.InvariantCulture));
GlobalSettings.Settings.AdditionalSettings[name] = newPoint;
}
}
else if (controlType == "Colour")
{
int[] colour = System.Text.Json.JsonSerializer.Deserialize<int[]>(controlParameters, Modules.DefaultSerializationOptions);
VectSharp.Colour col = VectSharp.Colour.FromRgba((byte)colour[0], (byte)colour[1], (byte)colour[2], (byte)colour[3]);
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.AdditionalSettings[name] = col;
}
else
{
GlobalSettings.Settings.AdditionalSettings[name] = Colour.FromCSSString(settingValue) ?? col;
}
}
else if (controlType == "Dash")
{
double[] dash = System.Text.Json.JsonSerializer.Deserialize<double[]>(controlParameters, Modules.DefaultSerializationOptions);
VectSharp.LineDash lineDash = new VectSharp.LineDash(dash[0], dash[1], dash[2]);
if (string.IsNullOrEmpty(settingValue))
{
GlobalSettings.Settings.AdditionalSettings[name] = lineDash;
}
else
{
string[] splitSettingValue = settingValue.Split(',');
VectSharp.LineDash newDash = new VectSharp.LineDash(double.Parse(splitSettingValue[0], System.Globalization.CultureInfo.InvariantCulture), double.Parse(splitSettingValue[1], System.Globalization.CultureInfo.InvariantCulture), double.Parse(splitSettingValue[2], System.Globalization.CultureInfo.InvariantCulture));
GlobalSettings.Settings.AdditionalSettings[name] = newDash;
}
}
found = true;
break;
}
}
if (!found)
{
throw new ArgumentException("There is no global setting named \"" + settingName + "\"!");
}
}
break;
}
}
19
Source : Check.cs
with MIT License
from arttonoyan
with MIT License
from arttonoyan
public static double AsDouble(object obj)
{
if (obj == null || obj == DBNull.Value)
return 0;
return double.Parse(obj.ToString());
}
19
Source : Check.cs
with MIT License
from arttonoyan
with MIT License
from arttonoyan
public static double? AsNullableDouble(object obj)
{
if (obj == null || obj == DBNull.Value)
return null;
return double.Parse(obj.ToString());
}
19
Source : RaidProtectionRule.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
protected virtual void Fill(Dictionary<string, string> pairs)
{
Enabled = bool.Parse(pairs["Enabled"]);
MaxOffenseCount = int.Parse(pairs["MaxOffenseCount"]);
OffenseWindow = TimeSpan.FromSeconds(double.Parse(pairs["OffenseWindow"]));
Delete = bool.Parse(pairs["Delete"]);
}
19
Source : SpamRule.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
protected override void Fill(Dictionary<string, string> pairs)
{
base.Fill(pairs);
Window = TimeSpan.FromSeconds(double.Parse(pairs["Window"]));
Threshold = int.Parse(pairs["Threshold"]);
}
19
Source : SignalBitsDesc.cs
with GNU General Public License v3.0
from astand
with GNU General Public License v3.0
from astand
public void ParseFromVectorDbcString(string line)
{
// split signal line into two
var halfsplit = Regex.Split(line, DbcHalfPattern);
// split 2nd half of signal
var split2ndpart = Regex.Split(halfsplit[2], DbcSignalSecondHalfPattern);
var rawsplit = Regex.Split(split2ndpart[0].Trim(), VectorDbcPattern);
// split 1st half of signal
halfsplit = Regex.Split(halfsplit[0], @"[^\w]+");
try
{
//// This is invariant
//NumberFormatInfo format = new NumberFormatInfo();
//// Set the decimal seperator
//format.NumberDecimalSeparator = ".";
FieldName = halfsplit[2];
StartBit = int.Parse(rawsplit[0]);
LengthBit = int.Parse(rawsplit[1]);
//Factor = double.Parse(rawsplit[3], format);
//Offset = double.Parse(rawsplit[4], format);
Factor = double.Parse(rawsplit[3]);
Offset = double.Parse(rawsplit[4]);
RawOffset = (int)(Offset / Factor);
//MinValue = double.Parse(rawsplit[5], format);
//MaxValue = double.Parse(rawsplit[6], format);
MinValue = double.Parse(rawsplit[5]);
MaxValue = double.Parse(rawsplit[6]);
Order = (rawsplit[2].Contains("1")) ? BitLayout.Intel : BitLayout.Motorolla;
Signed = (rawsplit[2].Contains("-"));
SigType = GetSigType();
}
catch (Exception e)
{
Console.WriteLine($"(!)Parsing exception occured in line'{line}'.{Environment.NewLine}" +
$"Text: {e.Message}");
}
FieldUnit = "-";
if (split2ndpart.Length == 3)
{
FieldUnit = split2ndpart[1];
}
var receivers = Regex.Split(split2ndpart.Last().Trim(), VectorDbcPattern);
Receivers.Clear();
foreach (var rx in receivers)
{
Receivers.Add(rx);
}
}
19
Source : StringReader.cs
with MIT License
from AtomicBlom
with MIT License
from AtomicBlom
public double ReadDouble()
{
var start = Cursor;
while (CanRead() && IsAllowedNumber(Peek()))
{
Skip();
}
var number = String.Substring(start, Cursor - start);
if (number.Length == 0)
{
throw CommandSyntaxException.BuiltInExceptions.ReaderExpectedDouble().CreateWithContext(this);
}
try
{
return double.Parse(number);
}
catch (FormatException)
{
Cursor = start;
throw CommandSyntaxException.BuiltInExceptions.ReaderInvalidDouble().CreateWithContext(this, number);
}
}
19
Source : Program.cs
with MIT License
from atsushieno
with MIT License
from atsushieno
public static int Main (string [] args)
{
string in_device_id = null, out_device_id = null;
string backend_name = null;
bool in_raw = false, out_raw = false;
double microphone_latency = 0.2; // seconds
foreach (var arg in args) {
switch (arg) {
case "--in_raw":
in_raw = true;
continue;
case "--out_raw":
out_raw = true;
continue;
default:
if (arg.StartsWith ("--backend:"))
backend_name = arg.Substring (arg.IndexOf (':') + 1);
else if (arg.StartsWith ("--in-device:"))
in_device_id = arg.Substring (arg.IndexOf (':') + 1);
else if (arg.StartsWith ("--out-device:"))
out_device_id = arg.Substring (arg.IndexOf (':') + 1);
else if (arg.StartsWith ("--latency:"))
microphone_latency = double.Parse (arg.Substring (arg.IndexOf (':') + 1));
continue;
}
}
var api = new SoundIO ();
var backend = backend_name == null ? SoundIOBackend.None : (SoundIOBackend)Enum.Parse (typeof (SoundIOBackend), backend_name);
if (backend == SoundIOBackend.None)
api.Connect ();
else
api.ConnectBackend (backend);
Console.WriteLine ("backend: " + api.CurrentBackend);
api.FlushEvents ();
var in_device = in_device_id == null ? api.GetInputDevice (api.DefaultInputDeviceIndex) :
Enumerable.Range (0, api.InputDeviceCount)
.Select (i => api.GetInputDevice (i))
.FirstOrDefault (d => d.Id == in_device_id && d.IsRaw == in_raw);
if (in_device == null) {
Console.Error.WriteLine ("Input device " + in_device_id + " not found.");
return 1;
}
Console.WriteLine ("input device: " + in_device.Name);
if (in_device.ProbeError != 0) {
Console.Error.WriteLine ("Cannot probe input device " + in_device_id + ".");
return 1;
}
var out_device = out_device_id == null ? api.GetOutputDevice (api.DefaultOutputDeviceIndex) :
Enumerable.Range (0, api.OutputDeviceCount)
.Select (i => api.GetOutputDevice (i))
.FirstOrDefault (d => d.Id == out_device_id && d.IsRaw == out_raw);
if (out_device == null) {
Console.Error.WriteLine ("Output device " + out_device_id + " not found.");
return 1;
}
Console.WriteLine ("output device: " + out_device.Name);
if (out_device.ProbeError != 0) {
Console.Error.WriteLine ("Cannot probe output device " + out_device_id + ".");
return 1;
}
out_device.SortDeviceChannelLayouts ();
var layout = SoundIODevice.BestMatchingChannelLayout (out_device, in_device);
if (layout.IsNull)
throw new InvalidOperationException ("channel layouts not compatible"); // panic()
var sample_rate = prioritized_sample_rates.FirstOrDefault (sr => in_device.SupportsSampleRate (sr) && out_device.SupportsSampleRate (sr));
if (sample_rate == default (int))
throw new InvalidOperationException ("incompatible sample rates"); // panic()
var fmt = prioritized_formats.FirstOrDefault (f => in_device.SupportsFormat (f) && out_device.SupportsFormat (f));
if (fmt == default (SoundIOFormat))
throw new InvalidOperationException ("incompatible sample formats"); // panic()
var instream = in_device.CreateInStream ();
instream.Format = fmt;
instream.SampleRate = sample_rate;
instream.Layout = layout;
instream.SoftwareLatency = microphone_latency;
instream.ReadCallback = (fmin, fmax) => read_callback (instream, fmin, fmax);
instream.Open ();
var outstream = out_device.CreateOutStream ();
outstream.Format = fmt;
outstream.SampleRate = sample_rate;
outstream.Layout = layout;
outstream.SoftwareLatency = microphone_latency;
outstream.WriteCallback = (fmin, fmax) => write_callback (outstream, fmin, fmax);
outstream.UnderflowCallback = () => underflow_callback (outstream);
outstream.Open ();
int capacity = (int) (microphone_latency * 2 * instream.SampleRate * instream.BytesPerFrame);
ring_buffer = api.CreateRingBuffer (capacity);
var buf = ring_buffer.WritePointer;
int fill_count = (int) (microphone_latency * outstream.SampleRate * outstream.BytesPerFrame);
// FIXME: there should be more efficient way for memset()
for (int i = 0; i < fill_count; i++)
Marshal.WriteByte (buf, i, 0);
ring_buffer.AdvanceWritePointer (fill_count);
instream.Start ();
outstream.Start ();
for (;;)
api.WaitEvents ();
outstream.Dispose ();
instream.Dispose ();
in_device.RemoveReference ();
out_device.RemoveReference ();
api.Dispose ();
return 0;
}
19
Source : Program.cs
with MIT License
from atsushieno
with MIT License
from atsushieno
public static int Main (string [] args)
{
string device_id = null;
string backend_name = null;
bool raw = false;
string stream_name = null;
double latency = 0.0;
int sample_rate = 0;
foreach (var arg in args) {
switch (arg) {
case "--raw":
raw = true;
continue;
default:
if (arg.StartsWith ("--backend:"))
backend_name = arg.Substring (arg.IndexOf (':') + 1);
else if (arg.StartsWith ("--device:"))
device_id = arg.Substring (arg.IndexOf (':') + 1);
else if (arg.StartsWith ("--name:"))
stream_name = arg.Substring (arg.IndexOf (':') + 1);
else if (arg.StartsWith ("--latency:"))
latency = double.Parse (arg.Substring (arg.IndexOf (':') + 1));
else if (arg.StartsWith ("--sample_rate:"))
sample_rate = int.Parse (arg.Substring (arg.IndexOf (':') + 1));
continue;
}
}
var api = new SoundIO ();
var backend = backend_name == null ? SoundIOBackend.None : (SoundIOBackend)Enum.Parse (typeof (SoundIOBackend), backend_name);
if (backend == SoundIOBackend.None)
api.Connect ();
else
api.ConnectBackend (backend);
Console.WriteLine ("backend: " + api.CurrentBackend);
api.FlushEvents ();
var device = device_id == null ? api.GetOutputDevice (api.DefaultOutputDeviceIndex) :
Enumerable.Range (0, api.OutputDeviceCount)
.Select (i => api.GetOutputDevice (i))
.FirstOrDefault (d => d.Id == device_id && d.IsRaw == raw);
if (device == null) {
Console.Error.WriteLine ("Output device " + device_id + " not found.");
return 1;
}
Console.WriteLine ("output device: " + device.Name);
if (device.ProbeError != 0) {
Console.Error.WriteLine ("Cannot probe device " + device_id + ".");
return 1;
}
var outstream = device.CreateOutStream ();
outstream.WriteCallback = (min,max) => write_callback (outstream, min, max);
outstream.UnderflowCallback = () => underflow_callback (outstream);
if (stream_name != null)
outstream.Name = stream_name;
outstream.SoftwareLatency = latency;
if (sample_rate != 0)
outstream.SampleRate = sample_rate;
if (device.SupportsFormat (SoundIODevice.Float32NE)) {
outstream.Format = SoundIODevice.Float32NE;
write_sample = write_sample_float32ne;
} else if (device.SupportsFormat (SoundIODevice.Float64NE)) {
outstream.Format = SoundIODevice.Float64NE;
write_sample = write_sample_float64ne;
} else if (device.SupportsFormat (SoundIODevice.S32NE)) {
outstream.Format = SoundIODevice.S32NE;
write_sample = write_sample_s32ne;
} else if (device.SupportsFormat (SoundIODevice.S16NE)) {
outstream.Format = SoundIODevice.S16NE;
write_sample = write_sample_s16ne;
} else {
Console.Error.WriteLine ("No suitable format available.");
return 1;
}
outstream.Open ();
Console.Error.WriteLine ("Software latency: " + outstream.SoftwareLatency);
Console.Error.WriteLine (
@"
'p\n' - pause
'u\\n' - unpause
'P\\n' - pause from within callback
'c\\n' - clear buffer
'q\\n' - quit");
if (outstream.LayoutErrorMessage != null)
Console.Error.WriteLine ("Unable to set channel layout: " + outstream.LayoutErrorMessage);
outstream.Start ();
for (; ; ) {
api.FlushEvents ();
int c = Console.Read ();
if (c == 'p') {
outstream.Pause (true);
Console.Error.WriteLine ("pause");
} else if (c == 'P') {
want_pause = true;
} else if (c == 'u') {
want_pause = false;
outstream.Pause (false);
Console.Error.WriteLine ("resume");
} else if (c == 'c') {
outstream.ClearBuffer ();
Console.Error.WriteLine ("clear buffer");
} else if (c == 'q') {
break;
}
}
outstream.Dispose ();
device.RemoveReference ();
api.Dispose ();
return 0;
}
19
Source : ChartMetadata.cs
with MIT License
from audfx
with MIT License
from audfx
public void Set(string name, string value)
{
switch (name)
{
case "replacedle": replacedle = value; return;
case "artist": Artist = value; return;
case "effect": EffectedBy = value; return;
case "jacket": JacketPath = value; return;
case "illustrator": Illustrator = value; return;
case "difficulty":
{
var dif = Difficulty.Light;
if (value == "challenge")
dif = Difficulty.Challenge;
else if (value == "extended")
dif = Difficulty.Extended;
else if (value == "infinite")
dif = Difficulty.Infinite;
Difficulty = dif;
} return;
case "level": Level = int.Parse(value); return;
case "t": BeatsPerMinute = value; return;
case "beat":
if (value.TrySplit('/', out string n, out string d))
{
Numerator = int.Parse(n);
Denominator = int.Parse(d);
}
return;
case "m":
{
if (value.TrySplit(';', out string nofx, out string fx))
{
MusicFileNoFx = nofx;
MusicFile = fx;
if (fx.TrySplit(';', out fx, out string _))
{ // do something with the last file
}
}
else MusicFileNoFx = value;
} return;
case "mvol": MusicVolume = int.Parse(value); return;
case "o": OffsetMillis = int.Parse(value); return;
case "po": PreviewOffsetMillis = int.Parse(value); return;
case "plength": PreviewLengthMillis = int.Parse(value); return;
case "pfiltergain": PFilterGain = int.Parse(value); return;
case "filtertype": FilterType = value; return;
case "chokkakuvol": SlamVolume = int.Parse(value); return;
case "tags": Tags = value; return;
case "to": HiSpeedBpm = double.Parse(value); return;
}
}
19
Source : PSEntity.cs
with MIT License
from Autodesk
with MIT License
from Autodesk
public MM DistanceTo(PSEnreplacedy otherEnreplacedy)
{
object[] values;
try
{
values = _powerSHAPE.ActiveDoreplacedent.MinDist(CompositeID, otherEnreplacedy.CompositeID);
}
catch (Exception ex)
{
throw new Exception("Failed to determine distance between objects", ex);
}
if (values.Length != 2 || int.Parse(values[0].ToString()) == -1)
{
throw new Exception("Failed to determine distance between objects");
}
return double.Parse(values[1].ToString());
}
19
Source : ConfigUtility.cs
with GNU General Public License v3.0
from autodotua
with GNU General Public License v3.0
from autodotua
public static double GetDouble(string key, double defaultValue)
{
bool hasValue = configs.TryGetValue(key, out string value);
return hasValue ? double.Parse(value) : defaultValue;
}
19
Source : FileUtility.cs
with GNU General Public License v3.0
from autodotua
with GNU General Public License v3.0
from autodotua
public static long? GetFileSize(string value)
{
if (long.TryParse(value, out long result))
{
return result;
}
if (Regex.IsMatch(value.ToUpper(), @"^(?<num>[0-9]+(\.[0-9]+)?) *(?<unit>B|KB|MB|GB|TB)"))
{
var match = Regex.Match(value.ToUpper(), @"^(?<num>[0-9]+(\.[0-9]+)?) *(?<unit>B|KB|MB|GB|TB)");
double num = double.Parse(match.Groups["num"].Value);
string unit = match.Groups["unit"].Value;
num *= unit switch
{
"B" => 1.0,
"KB" => 1024.0,
"MB" => 1024.0 * 1024,
"GB" => 1024.0 * 1024 * 1024,
"TB" => 1024.0 * 1024 * 1024 * 1024,
_ => throw new Exception()
};
return Convert.ToInt64(num);
}
19
Source : Converters.cs
with GNU General Public License v3.0
from autodotua
with GNU General Public License v3.0
from autodotua
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (double)value - double.Parse(parameter as string);
}
19
Source : ParseExtensions.cs
with Apache License 2.0
from AutomateThePlanet
with Apache License 2.0
from AutomateThePlanet
public static double ToDouble(this string value)
{
return double.Parse(value);
}
19
Source : NumberControlDataHandler.cs
with Apache License 2.0
from AutomateThePlanet
with Apache License 2.0
from AutomateThePlanet
public void ValidateValueIs(Number element, string expectedValue) => element.ValidateNumberIs(double.Parse(expectedValue));
19
Source : CosmosDB.cs
with MIT License
from Avanade
with MIT License
from Avanade
public string ConvertDynamicTags(string jsonString)
{
DateTime today = DateTime.Today;
DateTime now = DateTime.UtcNow;
jsonString = jsonString.Replace("{{TODAY}}", today.ToString("yyyy-MM-dd"));
jsonString = jsonString.Replace("{{NOW}}", now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"));
MatchCollection todays = Regex.Matches(jsonString, @"\{{TODAY[\-|\+][0-9]+}}", RegexOptions.None);
foreach (Match item in todays)
{
DateTime newDate = today.AddDays(Double.Parse(Regex.Match(item.Value, @"[\-|\+][0-9]+").Value));
jsonString = jsonString.Replace(item.Value, newDate.ToString("yyyy-MM-dd"));
}
MatchCollection nows = Regex.Matches(jsonString, @"\{{NOW[\-|\+][0-9]+}}", RegexOptions.None);
foreach (Match item in nows)
{
DateTime newDate = now.AddMinutes(Double.Parse(Regex.Match(item.Value, @"[\-|\+][0-9]+").Value));
jsonString = jsonString.Replace(item.Value, newDate.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"));
}
return jsonString;
}
19
Source : MockData.cs
with MIT License
from Avanade
with MIT License
from Avanade
private static string ConvertDynamicTags(string jsonString)
{
DateTime today = DateTime.Today;
DateTime now = DateTime.UtcNow;
jsonString = jsonString.Replace("{{TODAY}}", today.ToString("yyyy-MM-dd"));
jsonString = jsonString.Replace("{{NOW}}", now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"));
MatchCollection todays = Regex.Matches(jsonString, @"\{{TODAY[\-|\+][0-9]+}}", RegexOptions.None);
foreach (Match item in todays)
{
DateTime newDate = today.AddDays(Double.Parse(Regex.Match(item.Value, @"[\-|\+][0-9]+").Value));
jsonString = jsonString.Replace(item.Value, newDate.ToString("yyyy-MM-dd"));
}
MatchCollection nows = Regex.Matches(jsonString, @"\{{NOW[\-|\+][0-9]+}}", RegexOptions.None);
foreach (Match item in nows)
{
DateTime newDate = now.AddMinutes(Double.Parse(Regex.Match(item.Value, @"[\-|\+][0-9]+").Value));
jsonString = jsonString.Replace(item.Value, newDate.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"));
}
return jsonString;
}
19
Source : HlsValueConverter.cs
with MIT License
from ay2015
with MIT License
from ay2015
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// Validate params
if (value == null) throw new ArgumentNullException("value");
if (parameter == null) throw new ArgumentNullException("parameter");
// Get HLS values of color preplaceded in
var brush = (SolidColorBrush) value;
var rgbColorIn = brush.Color;
var hlsColor = RgbToHls(rgbColorIn);
// Adjust color by factor preplaceded in
var brightnessAdjustment = Double.Parse((parameter.ToString()));
hlsColor.L *= brightnessAdjustment;
// Return result
var rgbColorOut = HlsToRgb(hlsColor);
var brushOut = new SolidColorBrush();
brushOut.Color = rgbColorOut;
return brushOut;
}
19
Source : DoubleToRoundDoubleConverter.cs
with MIT License
from ay2015
with MIT License
from ay2015
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
if (parameter != null)
{
double digits = parameter.ToDouble();
double number = Double.Parse(value.ToString());
if (digits.Equals(Double.NaN) && Math.Abs(number) <
Math.Pow(10, Digits) && number != 0)
{
return Math.Round(number, (int)Math.Floor
(Digits - Math.Log10(Math.Abs(number))));
}
else if (digits.Equals(Double.NaN) && Math.Abs(number) >=
Math.Pow(10, Digits))
{
return Math.Round(number, 0);
}
else if (!digits.Equals(Double.NaN))
{
return Math.Round(number, (int)digits);
}
}
return value;
}
catch
{
return value;
}
}
19
Source : SaveDuringPlay.cs
with MIT License
from azsumas
with MIT License
from azsumas
static object LeafObjectFromString(Type type, string value, GameObject[] roots)
{
if (type == typeof(Single))
return float.Parse(value);
if (type == typeof(Double))
return double.Parse(value);
if (type == typeof(Boolean))
return Boolean.Parse(value);
if (type == typeof(string))
return value;
if (type == typeof(Int32))
return Int32.Parse(value);
if (type == typeof(UInt32))
return UInt32.Parse(value);
if (type.IsSubclreplacedOf(typeof(Component)))
{
// Try to find the named game object
GameObject go = ObjectTreeUtil.FindObjectFromFullName(value, roots);
return (go != null) ? go.GetComponent(type) : null;
}
if (type.IsSubclreplacedOf(typeof(GameObject)))
{
// Try to find the named game object
return GameObject.Find(value);
}
return null;
}
19
Source : TaskFetcher.cs
with MIT License
from Azure99
with MIT License
from Azure99
private void GetProblemInfo(string pid, out int timeLimit, out int memoryLimit, out bool spj)
{
string requestBody = $"getprobleminfo=1&pid={pid}";
string response = HttpPost(requestBody);
string[] infos = Regex.Split(response, "\r\n|\r|\n");
timeLimit = (int) (double.Parse(infos[0]) * 1000);
memoryLimit = int.Parse(infos[1]) * 1024;
spj = int.Parse(infos[2]) == 1;
}
19
Source : StringParseExt.cs
with MIT License
from baba-s
with MIT License
from baba-s
public static double ToDouble( this string s )
{
return double.Parse( s );
}
19
Source : DoDPOParser_v2.cs
with MIT License
from badamczewski
with MIT License
from badamczewski
public List<POLine_v2> Parse(string[] lines)
{
List<POLine_v2> transactionLines = new List<POLine_v2>(1000);
POLine_v2 poLine = new POLine_v2();
State state = State.ID;
foreach (var line in lines)
{
if (string.IsNullOrEmpty(line))
{
if (state >= State.Note)
{
transactionLines.Add(poLine);
state = State.ID;
}
continue;
}
switch (state)
{
case State.ID:
{
poLine.ID = int.Parse(line);
state++;
break;
}
case State.DateTime:
{
var dt = line.Split('T');
poLine.PODateTime.Date = dt[0];
poLine.PODateTime.Time = dt[1];
state++;
break;
}
case State.Amount:
{
poLine.Amount = double.Parse(line);
state++;
break;
}
case State.Note:
{
poLine.Note += line;
state++;
break;
}
}
}
return transactionLines;
}
19
Source : DoDPOParser_v5.cs
with MIT License
from badamczewski
with MIT License
from badamczewski
public DoDPOLines_v5 Parse(string[] lines, out int index)
{
DoDPOLines_v5 transactionLines = new DoDPOLines_v5(1000);
int offset = 0;
index = 0;
State state = State.ID;
foreach (var line in lines)
{
if (string.IsNullOrEmpty(line))
{
if (state >= State.Note)
{
state = State.ID;
index++;
}
continue;
}
switch (state)
{
case State.ID:
{
transactionLines.ID[index] = int.Parse(line);
state++;
break;
}
case State.DateTime:
{
var dt = line.Split('T');
transactionLines.Date[index] = dt[0];
transactionLines.Time[index] = dt[1];
state++;
break;
}
case State.Amount:
{
transactionLines.Amount[index] = double.Parse(line);
state++;
break;
}
case State.Note:
{
offset += line.Length;
transactionLines.NoteOffset[index] = offset;
transactionLines.AllNotes.Append(line);
state++;
break;
}
}
}
return transactionLines;
}
19
Source : OOPParser_Fast.cs
with MIT License
from badamczewski
with MIT License
from badamczewski
public List<POLine> Parse(string[] lines)
{
List<POLine> transactionLines = new List<POLine>(1000);
POLine poLine = new POLine();
State state = State.ID;
foreach (var line in lines)
{
if (string.IsNullOrEmpty(line))
{
if (state >= State.Note)
{
transactionLines.Add(poLine);
poLine = new POLine();
state = State.ID;
}
continue;
}
switch (state)
{
case State.ID:
{
poLine.ID = int.Parse(line);
state++;
break;
}
case State.DateTime:
{
var dt = line.Split('T');
poLine.Date = dt[0];
poLine.Time = dt[1];
state++;
break;
}
case State.Amount:
{
poLine.Amount = double.Parse(line);
state++;
break;
}
case State.Note:
{
poLine.Note += line;
state++;
break;
}
}
}
return transactionLines;
}
19
Source : OOPParser_Slow.cs
with MIT License
from badamczewski
with MIT License
from badamczewski
public List<POLine> Parse(string text)
{
List<POLine> transactionLines = new List<POLine>();
var groups = matchPOLine.GetGroupNames();
foreach (Match m in matchPOLine.Matches(text))
{
POLine line = new POLine();
var id = m.Groups["id"].Value;
var date = m.Groups["date"].Value;
var time = m.Groups["time"].Value;
var amount = m.Groups["amount"].Value;
var note = m.Groups["note"].Value;
line.ID = int.Parse(id);
line.Date = date;
line.Time = time;
line.Amount = double.Parse(amount);
line.Note = note;
transactionLines.Add(line);
}
return transactionLines;
}
19
Source : DoDPOParser_v1.cs
with MIT License
from badamczewski
with MIT License
from badamczewski
public List<POLine_v1> Parse(string[] lines)
{
List<POLine_v1> transactionLines = new List<POLine_v1>(1000);
POLine_v1 poLine = new POLine_v1();
State state = State.ID;
foreach (var line in lines)
{
if (string.IsNullOrEmpty(line))
{
if (state >= State.Note)
{
transactionLines.Add(poLine);
state = State.ID;
}
continue;
}
switch (state)
{
case State.ID:
{
poLine.ID = int.Parse(line);
state++;
break;
}
case State.DateTime:
{
var dt = line.Split('T');
poLine.Date = dt[0];
poLine.Time = dt[1];
state++;
break;
}
case State.Amount:
{
poLine.Amount = double.Parse(line);
state++;
break;
}
case State.Note:
{
poLine.Note += line;
state++;
break;
}
}
}
return transactionLines;
}
19
Source : DoDPOParser_v1a.cs
with MIT License
from badamczewski
with MIT License
from badamczewski
public POLine_v1[] Parse(string[] lines, out int index)
{
index = 0;
POLine_v1[] transactionLines = new POLine_v1[1000];
POLine_v1 poLine = new POLine_v1();
State state = State.ID;
foreach (var line in lines)
{
if (string.IsNullOrEmpty(line))
{
if (state >= State.Note)
{
transactionLines[index] = poLine;
state = State.ID;
index++;
}
continue;
}
switch (state)
{
case State.ID:
{
poLine.ID = int.Parse(line);
state++;
break;
}
case State.DateTime:
{
var dt = line.Split('T');
poLine.Date = dt[0];
poLine.Time = dt[1];
state++;
break;
}
case State.Amount:
{
poLine.Amount = double.Parse(line);
state++;
break;
}
case State.Note:
{
poLine.Note += line;
state++;
break;
}
}
}
return transactionLines;
}
19
Source : DoDPOParser_v2a.cs
with MIT License
from badamczewski
with MIT License
from badamczewski
public POLine_v2[] Parse(string[] lines, out int index)
{
index = 0;
POLine_v2[] transactionLines = new POLine_v2[1000];
POLine_v2 poLine = new POLine_v2();
State state = State.ID;
foreach (var line in lines)
{
if (string.IsNullOrEmpty(line))
{
if (state >= State.Note)
{
transactionLines[index] = poLine;
state = State.ID;
index++;
}
continue;
}
switch (state)
{
case State.ID:
{
poLine.ID = int.Parse(line);
state++;
break;
}
case State.DateTime:
{
var dt = line.Split('T');
poLine.PODateTime.Date = dt[0];
poLine.PODateTime.Time = dt[1];
state++;
break;
}
case State.Amount:
{
poLine.Amount = double.Parse(line);
state++;
break;
}
case State.Note:
{
poLine.Note += line;
state++;
break;
}
}
}
return transactionLines;
}
19
Source : DoDPOParser_v3.cs
with MIT License
from badamczewski
with MIT License
from badamczewski
public List<POLine_v3> Parse(string[] lines)
{
List<POLine_v3> transactionLines = new List<POLine_v3>(1000);
POLine_v3 poLine = new POLine_v3();
State state = State.ID;
foreach (var line in lines)
{
if (string.IsNullOrEmpty(line))
{
if (state >= State.Note)
{
transactionLines.Add(poLine);
state = State.ID;
}
continue;
}
switch (state)
{
case State.ID:
{
poLine.POData.ID = int.Parse(line);
state++;
break;
}
case State.DateTime:
{
var dt = line.Split('T');
poLine.POData.Date = dt[0];
poLine.POData.Time = dt[1];
state++;
break;
}
case State.Amount:
{
poLine.Amount = double.Parse(line);
state++;
break;
}
case State.Note:
{
poLine.POData.Note += line;
state++;
break;
}
}
}
return transactionLines;
}
19
Source : DoDPOParser_v3a.cs
with MIT License
from badamczewski
with MIT License
from badamczewski
public POLine_v3[] Parse(string[] lines, out int index)
{
index = 0;
var transactionLines = new POLine_v3[1000];
POLine_v3 poLine = new POLine_v3();
State state = State.ID;
foreach (var line in lines)
{
if (string.IsNullOrEmpty(line))
{
if (state >= State.Note)
{
transactionLines[index] = poLine;
state = State.ID;
index++;
}
continue;
}
switch (state)
{
case State.ID:
{
poLine.POData.ID = int.Parse(line);
state++;
break;
}
case State.DateTime:
{
var dt = line.Split('T');
poLine.POData.Date = dt[0];
poLine.POData.Time = dt[1];
state++;
break;
}
case State.Amount:
{
poLine.Amount = double.Parse(line);
state++;
break;
}
case State.Note:
{
poLine.POData.Note += line;
state++;
break;
}
}
}
return transactionLines;
}
See More Examples