Get value of x from equation stored in string - c#

How can I get value of x from string equation using c#.
string eq = sin(x) = 5x-2""
eq = "x=(1/5)*(sin(x)+2)"
Is it even possible?

Poor quality question aside, what you want is either to create your expression parser which will then either compile or interpret the expression, OR you could use an open source library like NCalc:
http://ncalc.codeplex.com/
This is built to do this sort of thing.

Related

C# Selenium Extract Data from span with partial ID

I am trying to create a proper XPATH syntax in C# Selenium to extract an order number on a web page. Here is what I've tried to far to grab the order number shown in the screen shot. All of these have errored out on me.
var result = driver.FindElement(By.XPath("//span[#id^='order-number-'")).Text;
var result = driver.FindElement(By.XPath("//div[#id='a-column a-span7']/h5")).Text;
var result = driver.FindElement(By.XPath("//div[#id='a-column a-span7']/span[#class='a-text-bold']")).Text;
Below is the inspection from Chrome. I am trying to grab the order number, but it will not always be the same so I cannot hard code the span id.
The driver.FindElement(By.XPath("//span[#id^='order-number-'")) would definitely match nothing since ^= is not a valid operator in XPath language. Plus, you are not closing the square brackets.
Instead, if you want to have a shorter and more readable version, use a CSS selector:
driver.FindElement(By.CssSelector("span[id^=order-number]"))
Here ^= means "starts with".
If you want to stay with XPath, use starts-with() function:
driver.FindElement(By.XPath("//span[starts-with(#id, 'order-number-')]"))
You can try this out:
var result = driver.FindElement(By.XPath("//span[contains(#id, 'order-number-')]")).Text;
It uses a "contains" on the span ID. Let me know if this helps.

Matching and replacing function expressions

I need to do some very light parsing of C# (actually transpiled Razor code) to replace a list of function calls with textual replacements.
If given a set containing {"Foo.myFunc" : "\"def\"" } it should replace this code:
var res = "abc" + Foo.myFunc(foo, Bar.otherFunc( Baz.funk()));
with this:
var res = "abc" + "def"
I don't care about the nested expressions.
This seems fairly trivial and I think I should be able to avoid building an entire C# parser using something like this for every member of the mapping set:
find expression start (e.g. Foo.myFunc)
Push()/Pop() parentheses on a Stack until Count == 0.
Mark this as expression stop
replace everything from expression start until expression stop
But maybe I don't need to ... Is there a (possibly built-in) .NET library that can do this for me? Counting is not possible in the family of languages that RE is in, but maybe the extended regex syntax in C# can handle this somehow using back references?
edit:
As the comments to this answer demonstrates simply counting brackets will not be sufficient generally, as something like trollMe("(") will throw off those algorithms. Only true parsing would then suffice, I guess (?).
The trick for a normal string will be:
(?>"(\\"|[^"])*")
A verbatim string:
(?>#"(""|[^"])*")
Maybe this can help, but I'm not sure that this will work in all cases:
<func>(?=\()((?>/\*.*?\*/)|(?>#"(""|[^"])*")|(?>"(\\"|[^"])*")|\r?\n|[^()"]|(?<open>\()|(?<-open>\)))+?(?(open)(?!))
Replace <func> with your function name.
Useless to say that trollMe("\"(", "((", #"abc""de((f") works as expected.
DEMO

What's does the dollar sign ($"string") do? [duplicate]

This question already has answers here:
What does $ mean before a string?
(11 answers)
Closed 6 years ago.
I have been looking over some C# exercises in a book and I ran across an example that stumped me. Straight from the book, the output line shows as:
Console.WriteLine($"\n\tYour result is {result}.");
The code works and the double result shows as expected. However, not understanding why the $ is there at the front of the string, I decided to remove it, and now the code outputs the name of the array {result} instead of the contents. The book doesn't explain why the $ is there, unfortunately.
I have been scouring the VB 2015 help and Google, regarding string formatting and Console.WriteLine overload methods. I am not seeing anything that explains why it is what it is. Any advice would be appreciated.
It's the new feature in C# 6 called Interpolated Strings.
The easiest way to understand it is: an interpolated string expression creates a string by replacing the contained expressions with the ToString representations of the expressions' results.
For more details about this, please take a look at MSDN.
Now, think a little bit more about it. Why this feature is great?
For example, you have class Point:
public class Point
{
public int X { get; set; }
public int Y { get; set; }
}
Create 2 instances:
var p1 = new Point { X = 5, Y = 10 };
var p2 = new Point { X = 7, Y = 3 };
Now, you want to output it to the screen. The 2 ways that you usually use:
Console.WriteLine("The area of interest is bounded by (" + p1.X + "," + p1.Y + ") and (" + p2.X + "," + p2.Y + ")");
As you can see, concatenating string like this makes the code hard to read and error-prone. You may use string.Format() to make it nicer:
Console.WriteLine(string.Format("The area of interest is bounded by({0},{1}) and ({2},{3})", p1.X, p1.Y, p2.X, p2.Y));
This creates a new problem:
You have to maintain the number of arguments and index yourself. If the number of arguments and index are not the same, it will generate a runtime error.
For those reasons, we should use new feature:
Console.WriteLine($"The area of interest is bounded by ({p1.X},{p1.Y}) and ({p2.X},{p2.Y})");
The compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.
For the full post, please read this blog.
String Interpolation
is a concept that languages like Perl have had for quite a while, and
now we’ll get this ability in C# as well. In String Interpolation, we
simply prefix the string with a $ (much like we use the # for verbatim
strings). Then, we simply surround the expressions we want to
interpolate with curly braces (i.e. { and }):
It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.
A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.
C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.
Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.
{<interpolatedExpression>[,<alignment>][:<formatString>]}
Where:
interpolatedExpression - The expression that produces a result to be formatted
alignment - The constant expression whose value defines the minimum number of characters in the string representation of the
result of the interpolated expression. If positive, the string
representation is right-aligned; if negative, it's left-aligned.
formatString - A format string that is supported by the type of the expression result.
The following code example concatenates a string where an object, author as a part of the string interpolation.
string author = "Mohit";
string hello = $"Hello {author} !";
Console.WriteLine(hello); // Hello Mohit !
Read more on C#/.NET Little Wonders: String Interpolation in C# 6

C# string masking/formatting/filtering with or without regex

Hopefully this isn't too complicated, I just can't seem to find the answer I need.
I have a string with variables in, such as: this is a %variable% string
The format of the variables within the string is arbitrary, although in this example we're using the filter %{0}%
I am wanting to match variable names to properties and ideally I don't want to loop through GetProperties, formatting and testing each name. What I'd like to do is obtain "variable" as a string and test that.
I already use RegEx to get a list of the variables in a string, using the given filter:
string regExSyntax = string.Format(syntax, #"(?<word>\w+)");
but this returns them WITH the '%' (e.g. '%variable%') and as I said, that filter is arbitrary so I can't just do a string.Replace.
This feels like it should be straight-forward....
Thanks!
"(?<word>\w+)"
Is just capturing anything alphnumeric and putting it into a named capturing group called "Word"
You might be interested in learning about lookbehind and lookahead. For example:
"(?<=%)(?<word>\w+)(?=%)"
You can make it a bit more generic with putting your filter in a seperate variable:
string Boundie = "%";
string Expression = #"(?<=" + Boundie + #")(?<word>\w+)(?=" + Boundie + #")";
I hope this is anywhere near what you are looking for.
Given that your regex syntax is: string regExSyntax = string.Format(syntax, #"(?<word>\w+)");, I assume you're then going to create a Regex and use it to match against some string:
Regex reExtractVars = new Regex(regExSyntax);
Match m = reExtractVars.Match(inputString);
while (m.Success)
{
// get the matched variable
string wholeVar = m.Value; // returns "%variable%"
// get just the "word"
string wordOnly = m.Groups["word"].Value; // returns "variable"
m = m.NextMatch();
}
Or have I completely misunderstood the problem?
Acron,
If you're going to roll-your own script parser... apart from being "a bit mad", unless that's the point of the exercise (is it?), then I strongly suggest that you KISS it... Keep It Simple Stoopid.
So what denotes a VARIABLE in your scripting syntax? Is it the percent signs? And they're fixed, yes? So %name% is a variable, but #comment# is NOT a variable... correct? The phrase "that filter is arbitrary" has me worried. What's a "filter"?
If this isn't homework then just use an existing scripting engine, with existing, well defined, well known syntax. Something like Jint, for example.
Cheers. Keith.

Parse string into a LINQ query

What method would be considered best practice for parsing a LINQ string into a query?
Or in other words, what approach makes the most sense to convert:
string query = #"from element in source
where element.Property = ""param""
select element";
into
IEnumerable<Element> = from element in source
where element.Property = "param"
select element;
assuming that source refers to an IEnumerable<Element> or IQueryable<Element> in the local scope.
Starting with .NET 4.6 you can use CSharpScript to parse Linq. Assuming the expression you want to parse is in string variable "query", this will do it:
string query = "from element in source where element.Property = ""param"" select element";
IEnumerable result = null;
try
{
var scriptOptions = ScriptOptions.Default.WithReferences(typeof(System.Linq.Enumerable).Assembly).WithImports("System.Linq");
result = await CSharpScript.EvaluateAsync<IEnumerable>(
query,
scriptOptions,
globals: global);
} catch (CompilationErrorException ex) {
//
}
Don't forget to pass your (Data)source you want to work on, with the global-variable(s) to have access to them in script parsing.
It requires some text parsing and heavy use of System.Linq.Expressions. I've done some toying with this here and here. The code in the second article is somewhat updated from the first but still rough in spots. I've continued to mess round with this on occasion and have a somewhat cleaner version that I've been meaning to post if you have any interest. I've got it pretty close to supporting a good subset of ANSI SQL 89.
You're going to need a C# language parser (at least v3.5, possibly v4.0, depending on what C# language features you wish to support in LINQ). You'll take those parser results and feed it directly into an Expression tree using a visitor pattern. I'm not sure yet but I'm willing to bet you'll also need some form of type analysis to fully generate the Expression nodes.
I'm looking for the same thing as you, but I don't really need it that badly so I haven't searched hard nor written any code along these lines.
I have written something that takes user string input and compiles it to a dynamic assembly using the Microsoft.CSharp.CSharpCodeProvider compiler provider class. If you just want to take strings of code and execute the result, this should suit you fine.
Here's the description of the console tool I wrote, LinqFilter:
http://bittwiddlers.org/?p=141
Here's the source repository. LinqFilter/Program.cs demonstrates how to use the compiler to compile the LINQ expression:
http://bittwiddlers.org/viewsvn/trunk/public/LinqFilter/?root=WellDunne
This might work for you: C# eval equivalent?
This may or may not help you, but check out LINQ Dynamic Query Library.
While this doesn't specifically give an example to answer your question I would have thought the best practice would generally be to build an expression tree from the string.
In this question I asked how to filter a linq query with a string which shows you building a portion of an expression tree. This concept however can be extended to build an entire expression tree representing your string.
See this article from Microsoft.
There are probably other better posts out there as well. Additionally I think something like RavenDB does this already in its code base for defining indexes.

Categories

Resources