I was at career fair and I was asked a question "what does this query do and in which language it is".
I told that it is in .NET LINQ, but was unable to predict what it does.
Can any one help me
I wrote in .NET and tried .
var youShould = from c
in "3%.$#9/52#2%35-%#4/#./3,!#+%23 !2#526%N#/-"
select (char)(c ^ 3 << 5);
Label1.Text = youShould.ToString();
And got this output :
System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Char,System.Char]
First of all, don't feel bad that you didn't get the answer. I know exactly what's going on here and I'd have probably just laughed and walked away if someone asked me what this did.
There's a number of things going on here, but start with the output:
var youShould = from c in "3%.$#9/52#2%35-%#4/#./3,!#+%23 !2#526%N#/-"
select (char)(c ^ 3 << 5);
Label1.Text = youShould.ToString();
>>> System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Char,System.Char]
When you run a LINQ query, or use any of the equivalent methods like Select() that return sets, what you get back is a special, internal type of object called an "iterator", specifically, an object that implements the IEnumerable interface. .NET uses these objects all over the place; for example, the foreach loop's purpose is to iterate over iterators.
One of the most important things to know about these kind of objects is that just creating one doesn't actually "do" anything. The iterator doesn't actually contain a set of things; rather, it contains the instructions needed to produce a set of things. If you try to do something like, e.g. ToString on it, the result you get won't be very useful.
However, it does tell us one thing: it tells us that this particular iterator takes a source list of type char and returns a new set, also of type char. (I know that because I know that's what the two generic parameters of a "select iterator" do.) To get the actual results out of this iterator you just need to loop over it somehow, e.g.:
foreach (var c in youShould)
{
myLabel.Text += c;
}
or, slightly easier,
myLabel.Text = new string(youShould.ToArray());
To actually figure out what it does, you have to also recognize the second fact: LINQ treats a string as a "set of characters". It is going to process each character in that string, one at a time, and perform the bit-wise operations on the value.
The long-form equivalent of that query is something like this:
var input= "3%.$#9/52#2%35-%#4/#./3,!#+%23 !2#526%N#/-";
var output = string.Empty;
foreach (var c in input)
{
var i = (int)c;
var i2 = i ^ (3 << 5);
var c2= (char)i2;
output += c2;
}
If you did the math by hand you'd get the correct output message. To save you the brain-numbing exercise, I'll just tell you: it toggles bits 5 and 6 of the ASCII value, changing each character to one further up the ASCII table. The resulting string is:
SEND YOUR RESUME TO [an email address]
Demostrative .NET Fiddle: https://dotnetfiddle.net/x7UvYA
For each character in the string, project the character by xor-ing it with (3 left shifted by 5), then cast the numeric value back to a char.
You could generate your own code strings by running the query again over an uncoded string, because if you XOR a number twice by the same value, you'll be left with the same number you started with. (e.g. x ^ y ^ y = x)
I'll leave it as an exercise to the reader to figure out what the following is:
4()3#)3#!#$5-"#4%34
I suppose it tests:
Linq to objects
Understanding of IEnumerable<T> interface and how it relates to strings
Casting
Bitwise operations
Bitwise operator precedence
Personally, I think this is a useless test that doesn't really reflect real world problems.
Related
How does one sample from a distribution in MathDotNet without having to cast to the specific distribution?
I have a distribution d which could be any random variable, being passed around as an IDistribution. Now, I wish to sample from it. I want to do this with having to do as few casts as possible on the actual distribution itself (I don't want a giant case statement with a ton of casts to really specific distribution types like Bernoulli, Normal, etc.
I have tried the following code, for an IDistribution d who is of type Bernoulli, with a mean of around 0.99:
Console.WriteLine("Mean is " + ((Bernoulli)d).Mean);
Console.WriteLine("Casted sample is " + ((Bernoulli)d).Sample());
Console.WriteLine("Sample is " + d.RandomSource.NextDouble());
The first print statement prints 0.99, as expected.
The second print statement tends to return 1, as expected, since 99% of the time it should return 1.
The third print statement seems to be giving me what looks like a uniform random variable between 0 or 1 (NB: It might not be uniform, that's just with a quick eyeball test on print statements, but it's definitely NOT Bernoulli with mean 0.99).
How can I sample generally from the appropriate distribution?
This is what I am currently doing. I would like to avoid the if statement, but for now, this works. If someone has a better answer, it would be preferable:
if (distribution is IContinuousDistribution){
value = (double)((IContinuousDistribution)distribution).Sample();
}else{
value = (double)((IDiscreteDistribution)distribution).Sample();
}
From this post (and not only) we got to the point that the ++ operator cannot be applied on expressions returning value.
And it's really obvious that 5++ is better to write as 5 + 1. I just want to summarize the whole thing around the increment/decrement operator. So let's go through these snippets of code that could be helpful to somebody stuck with the ++ first time at least.
// Literal
int x = 0++; // Error
// Constant
const int Y = 1;
double f = Y++; // error. makes sense, constants are not variables actually.
int z = AddFoo()++; // Error
Summary: ++ works for variables, properties (through a synthetic sugar) and indexers(the same).
Now the interest part - any literal expressions are optimized in CSC and, hence when we write, say
int g = 5 + 1; // This is compiled to 6 in IL as one could expect.
IL_0001: ldc.i4.6 // Pushes the integer value of 6 onto the evaluation stack as an int32.
For 5++ doesn't mean 5 becomes 6, it could be a shorthand for 5 + 1, like for x++ = x + 1
What's the real reason behind this restriction?
int p = Foo()++ //? yes you increase the return value of Foo() with 1, what's wrong with that?
Examples of code that can lead to logical issues are appreciated.
One of real-life example could be, perform one more actions than in the array.
for (int i = 0; i < GetCount()++; i++) { }
Maybe the lack of usage opts compiler teams to avoid similar features?
I don't insist this is a feature we lack of, just want to understand the dark side of this for compiler writers perhaps, though I'm not. But I know c++ allows this when returning a reference in the method. I'm neither a c++ guy(very poor knowledge) just want to get the real gist of the restriction.
Like, is it just because c# guys opted to restrict the ++ over value expressions or there are definite cases leading to unpredictable results?
In order for a feature to be worth supporting, it really needs to be useful. The code you've presented is in every case less readable than the alternative, which is just to use the normal binary addition operator. For example:
for (int i = 0; i < GetCount() + 1; i++) { }
I'm all in favour of the language team preventing you from writing unreadable code when in every case where you could do it, there's a simpler alternative.
Well before using these operators you should try to read up on how they do what they do. In particular you should understand the difference between postfix and prefix, which could help figure out what is and isn't allowed.
The ++ and -- operators modify their operands. Which means that the operand must be modifiable. If you can assign a value to the expression in question then it is modifiable, and is probably a variable(c#).
Taking a look at what these operators actually do. The postfix operators should increment after your line of code executes. As for the prefix operators, well they would need to have access to the value before the method had even been called yet. The way I read the syntax is ++lvalue (or ++variable) converting to memory operations:[read, write, read] or for lvalue++ [read, read, write] Though many compilers probably optimize secondary reads.
So looking at foo()++; the value is going to be plopped dead in the center of executing code. Which would mean the compiler would need to save the value somewhere more long-term in order for operations to be performed on said value, after the line of code has finished executing. Which is no doubt the exact reason C++ does not support this syntax either.
If you were to be returning a reference the compiler wouldn't have any trouble with the postfix. Of course in C# value types (ie. int, char, float, etc) cannot be passed by reference as they are value types.
I have a linq query which is not ordered the way I would like.
The Query:
return (from obj in context.table_orders
orderby obj.order_no
select obj.order_no.ToString() + '-' + obj.order_description).ToList<string>();
What happens is that my records are ordered alphabeticaly, is there a Linq keyword I can use so my records are ordered correctly (so order 30 comes before order 100)?
I want the result to be a list of string since this is used to populate a ComboBox.
Also some of the 'order_no' in the DB are like '2.10' and '9.1.1'.
What happens is that my records are ordered alphabeticaly, is there a Linq keyword I can use so my records are
ordered correctly (so order #30 comes before order #100)?
If I would get a cente everytime someone asks this I would be rich.
Yes, there is - simple answer: ORDER A NUMBER NOT A STRING.
so order #30 comes before order #100)
But #30 comes AFTER #100 for the simple reason that they ARE sorted alphabetically becase THEY ARE STRINGS.
Parse the string, convert the number to - well - a number, and order by it.
WHOEVER had the idea that order_no should be a string WITHOUT A FIXED LENGH (like 00030) should - well - ;) get a basic education on database modelling. I really like things like invoice numbers etc. to be strings (they are NOT numbers) but keeping them in (a) a defiable pattern and (b) checksummed (so that data entry errors are easily catched) should be basics ;)
This is the kind of issue you get with junior people defining databases and data models and not thinking about the consequences.
You are in for some pain - parse the string, order by parsing result.
If obj.order_no is a string, then convert it to a number for sorting
orderby Int32.Parse(obj.order_no)
or
orderby Decimal.Parse(obj.order_no)
of cause this works only if the string represents a valid number.
If order_no is not a valid number (e.g. "17.7-8A") then write a function that formats it to contain right aligned numbers, like "00017.007-0008A" and sort using this function
orderby FormatOrderNo(obj.order_no)
UPDATE
Since you are working with EF you cannot call this function in the EF part of your query. Convert the EF-result to an IEnumerable<T> and perform the sorting using LINQ-To-Objects
return (from obj in context.table_orders select ...)
.AsEnumerable()
.OrderBy(obj => FormatOrderNo(obj.order_no))
.ToList();
Based on what you said - that the numbers are not really numbers but rather custom sequence identifiers (i.e. you don't even know what level of depth you get) I would suggest implementing a custom comparer.
If you do this you can define what you exaclty want - and that is I believe something along these lines:
split the string on .
compare the sequences up to and including the array.length of the shorter sequence
if there was a shorter sequence and by now there is a tie, pick the shorter before the longer (i.e. 2.1 before 2.1.1)
if both sequences had the same length, by the end of the comparison you should know which one is 'bigger'
solved.
If you need inspiration on IComparer implementation an example below:
http://zootfroot.blogspot.co.uk/2009/09/natural-sort-compare-with-linq-orderby.html
I would either change the datatype if possible or add it as another firld if applicable.
If that is a no-go you can look at the solutions mentioned by others in this question but beware - The .ToList() option is nice for small tables if you are pulling everything from them but getting used to it will eventually give you a world of pain. You don't wanna get everything in the long run, either use a Where or top critera.
The other solutions are nice but to complex for my taste to accomplish the task.
You could go with shooting sql directly through LinqToSql. http://msdn.microsoft.com/en-us/library/bb399403.aspx
In the sql you are free to convert and sort however you like. Some think this is a great idea and some will tell you it it bad. You loose strong typing and gain performance. You will have to know WHY you take this kinds of decision, that is the most important thing imho.
Since nobody came up with a custom orderby function translatable into SQL, I went for the IComparer function like so:
public class OrderComparer<T> : IComparer<string>
{
#region IComparer<string> Members
public int Compare(string x, string y)
{
return GetOrderableValue(x.Split('-').First()).CompareTo(GetOrderableValue(y.Split('-').First()));
}
#endregion
private int GetOrderableValue(string value)
{
string[] splitValue = value.Split('.');
int orderableValue = 0;
if (splitValue.Length.Equals(1))
orderableValue = int.Parse(splitValue[0]) * 1000;
else if (splitValue.Length.Equals(2))
orderableValue = int.Parse(splitValue[0]) * 1000 + int.Parse(splitValue[1]) * 100;
else if (splitValue.Length.Equals(3))
orderableValue = int.Parse(splitValue[0]) * 1000 + int.Parse(splitValue[1]) * 100 + int.Parse(splitValue[2]) * 10;
else
orderableValue = int.Parse(splitValue[0]) * 1000 + int.Parse(splitValue[1]) * 100 + int.Parse(splitValue[2]) * 10 + int.Parse(splitValue[3]);
return orderableValue;
}
}
The values have a maximum of 4 levels.
Anyone has a recommandation?
int a, b, n;
...
(a, b) = (2, 3);
// 'a' is now 2 and 'b' is now 3
This sort of thing would be really helpfull in C#. In this example 'a' and 'b' arn't encapsulated together such as the X and Y of a position might be. Does this exist in some form?
Below is a less trivial example.
(a, b) = n == 4 ? (2, 3) : (3, n % 2 == 0 ? 1 : 2);
Adam Maras shows in the comments that:
var result = n == 4 ? Tuple.Create(2, 3) : Tuple.Create(3, n % 2 == 0 ? 1 : 2);
Sort of works for the example above however as he then points out it creates a new truple instead of changing the specified values.
Eric Lippert asks for use cases, therefore perhaps:
(a, b, c) = (c, a, b); // swap or reorder on one line
(x, y) = move((x, y), dist, heading);
byte (a, b, c, d, e) = (5, 4, 1, 3, 2);
graphics.(PreferredBackBufferWidth, PreferredBackBufferHeight) = 400;
notallama also has use cases, they are in his answer below.
We have considered supporting a syntactic sugar for tuples but it did not make the bar for C# 4.0. It is unlikely to make the bar for C# 5.0; the C# 5.0 team is pretty busy with getting async/await working right. We will consider it for hypothetical future versions of the language.
If you have a really solid usage case that is compelling, that would help us prioritize the feature.
use case:
it'd be really nice for working with IObservables, since those have only one type parameter. you basically want to subscribe with arbitrary delegates, but you're forced to use Action, so that means if you want multiple parameters, you have to either use tuples, or create custom classes for packing and unpacking parameters.
example from a game:
public IObservable<Tuple<GameObject, DamageInfo>> Damaged ...
void RegisterHitEffects() {
(from damaged in Damaged
where damaged.Item2.amount > threshold
select damaged.Item1)
.Subscribe(DoParticleEffect)
.AddToDisposables();
}
becomes:
void RegisterHitEffects() {
(from (gameObject, damage) in Damaged
where damage.amount > threshold
select gameObject)
.Subscribe(DoParticleEffect)
.AddToDisposables();
}
which i think is cleaner.
also, presumably IAsyncResult will have similar issues when you want to pass several values. sometimes it's cumbersome to create classes just to shuffle a bit of data around, but using tuples as they are now reduces code clarity. if they're used in the same function, anonymous types fit the bill nicely, but they don't work if you need to pass data between functions.
also, it'd be nice if the sugar worked for generic parameters, too. so:
IEnumerator<(int, int)>
would desugar to
IEnumerator<Tuple<int,int>>
The behavior that you're looking for can be found in languages that have support or syntactic sugar for tuples. C# is not among these langauges; while you can use the Tuple<...> classes to achieve similar behavior, it will come out very verbose (not clean like you're looking for.)
Deconstruction was introduced in C# 7.0:
https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/#user-content-deconstruction
The closest structure I can think of is the Tuple class in version 4.0 of the framework.
As others already wrote, C# 4 Tuples are a nice addition, but nothing really compelling to use as long as there aren't any unpacking mechanisms. What I really demand of any type I use is clarity of what it describes, on both sides of the function protocol (e.g. caller, calle sides)... like
Complex SolvePQ(double p, double q)
{
...
return new Complex(real, imag);
}
...
var solution = SolvePQ(...);
Console.WriteLine("{0} + {1}i", solution.Real, solution.Imaginary);
This is obvious and clear at both caller and callee side. However this
Tuple<double, double> SolvePQ(double p, double q)
{
...
return Tuple.Create(real, imag);
}
...
var solution = SolvePQ(...);
Console.WriteLine("{0} + {1}i", solution.Item1, solution.Item2);
Doesn't leave the slightest clue about what that solution actually is (ok, the string and the method name make it pretty obvious) at the call site. Item1 and Item2 are of the same type, which renders tooltips useless. The only way to know for certain is to "reverse engineer" your way back through SolvePQ.
Obivously, this is far fetched and everyone doing serious numerical stuff should have a Complex type (like that in the BCL).
But everytime you get split results and you want give those results distinct names for the sake of readability, you need tuple unpacking. The rewritten last two lines would be:
var (real, imaginary) = SolvePQ(...); // or var real, imaginary = SolvePQ(...);
Console.WriteLine("{0} + {1}i", real, imaginary);
This leaves no room for confusion, except for getting used to the syntax.
Creating a set of Unpack<T1, T2>(this Tuple<T1, T2>, out T1, out T2) methods would be a more idiomatic c# way of doing this.
Your example would then become
int a, b, n;
...
Tuple.Create(2, 3).Unpack(out a, out b);
// 'a' is now 2 and 'b' is now 3
which is no more complex than your proposal, and a lot clearer.
I want to evaluate a math expression which the user enters in a textbox. I have done this so far
string equation, finalString;
equation = textBox1.Text;
StringBuilder stringEvaluate = new StringBuilder(equation);
stringEvaluate.Replace("sin", "math.sin");
stringEvaluate.Replace("cos", "math.cos");
stringEvaluate.Replace("tan", "math.tan");
stringEvaluate.Replace("log", "math.log10");
stringEvaluate.Replace("e^", "math.exp");
finalString = stringEvaluate.ToString();
StringBuilder replaceI = new StringBuilder(finalString);
replaceI.Replace("x", "i");
double a;
for (int i = 0; i<5 ; i++)
{
a = double.Parse(finalStringI);
if(a<0)
break;
}
when I run this program it gives an error "Input string was not in a correct format." and highlights a=double.Parse(finalStringI);
I used a pre defined expression a=i*math.log10(i)-1.2 and it works, but when I enter the same thing in the textbox it doesn't.
I did some search and it came up with something to do with compiling the code at runtime.
any ideas how to do this?
i'm an absolute beginner.
thanks :)
The issue is within your stringEvaluate StringBuilder. When you're replacing "sin" with "math.sin", the content within stringEvaluate is still a string. You've got the right idea, but the error you're getting is because of that fact.
Math.sin is a method inside the Math class, thus it cannot be operated on as you are in your a = double.Parse(finalStringI); call.
It would be a pretty big undertaking to accomplish your goal, but I would go about it this way:
Create a class (perhaps call it Expression).
Members of the Expression class could include Lists of operators and operands, and perhaps a double called solution.
Pass this class the string at instantiation, and tear it apart using the StringBuilder class. For example, if you encounter a "sin", add Math.sin to the operator collection (of which I'd use type object).
Each operator and operand within said string should be placed within the two collections.
Create a method that evaluates the elements within the operator and operand collection accordingly. This could get sticky for complex calculations with more than 2 operators, as you would have to implement a PEMDAS-esque algorithm to re-order the collections to obey the order of operations (and thus achieve correct solutions).
Hope this helps :)
The .Parse methods (Int.Parse, double.Parse, etc) will only take a string such as "25" or "3.141" and convert it to the matching value type (int 25, or double 3.141). They will not evaluate math expressions!
You'll pretty much have to write your own text-parser and parse-tree evaluator, or explore run-time code-generation, or MSIL code-emission.
Neither topic can really be covered in the Q&A format of StackOverflow answers.
Take a look at this blog post:
http://www.c-sharpcorner.com/UploadFile/mgold/CodeDomCalculator08082005003253AM/CodeDomCalculator.aspx
It sounds like it does pretty much what you're trying to do. Evaluating math expressions is not as simple as just parsing a double (which is really only going to work for strings like "1.234", not "1 + 2.34"), but apparently it is possible.
You can use the eval function that the framework includes for JScript.NET code.
More details: http://odetocode.com/code/80.aspx
Or, if you're not scared to use classes marked "deprecated", it's really easy:
static string EvalExpression(string s)
{
return Microsoft.JScript.Eval.JScriptEvaluate(s, null, Microsoft.JScript.Vsa.VsaEngine.CreateEngine()).ToString();
}
For example, input "Math.cos(Math.PI / 3)" and the result is "0.5" (which is the correct cosine of 60 degrees)