Access MVEL ASTNode info - mvel

After compiling an MVEL expression, I can access the top ASTNode.
ExpressionCompiler compiler = new ExpressionCompiler(<expression>, true);
ASTNode node = compiler.compile().getFirstNode();
However, I would like to have full access to the ASTNode info, including its left and right child nodes.
ASTNode left = node.getLeftNode();
ASTNode right = node.getRightNode();
...
Is there a way to do it?

If an expression has a binary operator, for example, (a + b), the corresponding ASTNode is of type BineryOperation. Therefore, the following code can be used to solve the issue:
ExpressionCompiler compiler = new ExpressionCompiler("a + b", true);
ASTNode node = compiler.compile().getFirstNode();
BinaryOperation biOptNode= (BinaryOperation)node;
ASTNode left = biOptNode.getLeftNode();
ASTNode right = biOptNode.getRightNode();

Related

using flatbuffers.Builder.Create*()

I want to use flatbuf to save aquadtree structure. here is my fbs file
namespace com.generated;
struct Obj {
hash:int;
geohash:uint64;
}
table Tree {
obj:[Obj];
id:int;
nodes:[Tree];
}
root_type Tree;
and here is the code that I am using to make objects
var builder = new flatbuffers.Builder(0)
var Tree = com.generated.Tree;
var Obj = com.generated.Obj;
Tree.startTree(builder);
Tree.addId(builder, builder.createInt(1));
Tree.addObj(builder, Obj.createObj(builder, 36, 42));
var offset = Tree.endTree(builder);
Tree.startTree(builder);
Tree.addId(builder, builder.createInt(1));
Tree.addObj(builder, Obj.createObj(builder, 36, 42));
offset = Tree.endTree(builder);
builder.finish(offset);
well in code above I have two problems, First the builder.createInt(1) does not exist. So I do not know how I can create an Integer. And my second problem is with the making an array of Trees, I am currently after Tree.end start another Tree with the same builder. Is this the correct way to do that?

LINQ Does not contain a definition for 'union'

what is wrong with this linq query that show me the error of Does not contain a definition for 'union'
(from rev in db.vM29s
where Years.Contains(rev.FinancialYear) && rev.Exclude=="No"
group rev by new { rev.RevenueCode, rev.FinancialYear } into g
select new
{
Revenuecode = g.Key.RevenueCode,
totalRevenue = g.Sum(x => x.RevenueAmount),
RevenueEnglish = (from a in db.RevenueCodes where a._RevenueCode == g.Key.RevenueCode select a.RevenueEng).FirstOrDefault(),
// MinorCode = (from a in db.MinorCodes where a._MinorCode == g.Key.MinorCode select a.MinorEng),
RevenueDari = (from a in db.RevenueCodes where a._RevenueCode == g.Key.RevenueCode select a.RevenueDari).FirstOrDefault(),
Yearss = g.Key.FinancialYear
}
)
.Union
(from u in db.rtastable
where Years.Contains(u.Year)
group u by new { u.objectcode, u.Year } into g
select new
{
Revenuecode = g.Key.objectcode,
totalRevenue = g.Sum(x => x.amount),
RevenueEnglish = (from a in db.RevenueCodes where a._RevenueCode == g.Key.objectcode select a.RevenueEng).FirstOrDefault(),
// MinorCode = (from a in db.MinorCodes where a._MinorCode == g.Key.MinorCode select a.MinorEng),
RevenueDari = (from a in db.RevenueCodes where a._RevenueCode == g.Key.objectcode select a.RevenueDari).FirstOrDefault(),
Yearss = g.Key.Year
}
)
.ToList();
If you included using System.Linq; and both Anonymous Types have exactly the same property names + property types, then what you did should work.
Yet it does not work. The solution is to check your Anonymous Types for subtle property name differences and/or subtle property type differences.
E.g. even an int vs a smallint or double or decimal will cause this build error:
'System.Collections.Generic.IEnumerable<AnonymousType#1>' does not contain a definition for 'Union' and the best extension method overload 'System.Linq.Queryable.Union(System.Linq.IQueryable, System.Collections.Generic.IEnumerable)' has some invalid arguments
Switching to .Concat() will not fix this: it has the same (obvious) restriction that the types on both sides must be compatible.
After you fix the naming or typing problem, I would recommend that you consider switching to .Concat(). The reason: .Union() will call .Equals() on all objects to eliminate duplicates, but that is pointless because no two Anonymous Objects that were created independently will ever be the same object (even if their contents would be the same).
If it was your specific intention to eliminate duplicates, then you need to create a class that holds your data and that implements .Equals() in a way that makes sense.
You should use Concat or using addRange if the data is allready in memory.

Entity Framework filter data by string sql

I am storing some filter data in my table. Let me make it more clear: I want to store some where clauses and their values in a database and use them when I want to retrieve data from a database.
For example, consider a people table (entity set) and some filters on it in another table:
"age" , "> 70"
"gender" , "= male"
Now when I retrieve data from the people table I want to get these filters to filter my data.
I know I can generate a SQL query as a string and execute that but is there any other better way in EF, LINQ?
One solution is to use Dynamic Linq Library , using this library you can have:
filterTable = //some code to retrive it
var whereClause = string.Join(" AND ", filterTable.Select(x=> x.Left + x.Right));
var result = context.People.Where(whereClause).ToList();
Assuming that filter table has columns Left and Right and you want to join filters by AND.
My suggestion is to include more details in the filter table, for example separate the operators from operands and add a column that determines the join is And or OR and a column that determines the other row which joins this one. You need a tree structure if you want to handle more complex queries like (A and B)Or(C and D).
Another solution is to build expression tree from filter table. Here is a simple example:
var arg = Expression.Parameter(typeof(People));
Expression whereClause;
for(var row in filterTable)
{
Expression rowClause;
var left = Expression.PropertyOrField(arg, row.PropertyName);
//here a type cast is needed for example
//var right = Expression.Constant(int.Parse(row.Right));
var right = Expression.Constant(row.Right, left.Member.MemberType);
switch(row.Operator)
{
case "=":
rowClause = Expression.Equal(left, right);
break;
case ">":
rowClause = Expression.GreaterThan(left, right);
break;
case ">=":
rowClause = Expression.GreaterThanOrEqual(left, right);
break;
}
if(whereClause == null)
{
whereClause = rowClause;
}
else
{
whereClause = Expression.AndAlso(whereClause, rowClause);
}
}
var lambda = Expression.Lambda<Func<People, bool>>(whereClause, arg);
context.People.Where(lambda);
this is very simplified example, you should do many validations type casting and ... in order to make this works for all kind of queries.
This is an interesting question. First off, make sure you're honest with yourself: you are creating a new query language, and this is not a trivial task (however trivial your expressions may seem).
If you're certain you're not underestimating the task, then you'll want to look at LINQ expression trees (reference documentation).
Unfortunately, it's quite a broad subject, I encourage you to learn the basics and ask more specific questions as they come up. Your goal is to interpret your filter expression records (fetched from your table) and create a LINQ expression tree for the predicate that they represent. You can then pass the tree to Where() calls as usual.
Without knowing what your UI looks like here is a simple example of what I was talking about in my comments regarding Serialize.Linq library
public void QuerySerializeDeserialize()
{
var exp = "(User.Age > 7 AND User.FirstName == \"Daniel\") OR User.Age < 10";
var user = Expression.Parameter(typeof (User), "User");
var parsExpression =
System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] {user}, null, exp);
//Convert the Expression to JSON
var query = e.ToJson();
//Deserialize JSON back to expression
var serializer = new ExpressionSerializer(new JsonSerializer());
var dExp = serializer.DeserializeText(query);
using (var context = new AppContext())
{
var set = context.Set<User>().Where((Expression<Func<User, bool>>) dExp);
}
}
You can probably get fancier using reflection and invoking your generic LINQ query based on the types coming in from the expression. This way you can avoid casting the expression like I did at the end of the example.

Access Instance-property in Coffeescript within nested

so I am using express within a node-app. As my app is getting bigger I want to put my routes into extra files. I seem to be able to get hold of the bugDB if I just get rid of the intermediate get object. But I can't access the bugDB in the inner object. Any suggestions? Maybe there is even a more nice code pattern for how to accomplish this more elegantly.
I would appreachate your help. Thanks in advance. (As I am not a native speaker I couldn't find others with a similar problem, if you know how to phrase the question better, please show me the way :) )
BUGROUTER.COFFEE
class BugsRouter
constructor: (#bugDB)-> // instance-variable with databaselink
return
get:{
allBugs: (req, res)=>
console.log "db", #bugDB // this gives me undefined
// is "this" in the get context?
#bugDB.allDocs {include_docs: true}, (err, response)->
res.json 200, response
}
module.exports = BugsRouter
SERVER.COFFEE
BugsRouter = require "./routes/BUGROUTER"
bugsRouter = new BugsRouter(bugDB)
console.log bugsRouter.bugDB # this is working
app.get "/bugs/all", bugsRouter.get.allBugs
Sub-objects don't work like that. When you say this:
class C
p:
f: ->
Then p is just a plain object that happens to be a property on C's prototype, it will have no special idea of what # should be inside f. And if you try to use a fat-arrow instead:
class C
p:
f: =>
then you're accidentally creating a namespaced class function called f so # will be C when f is called. In either case, saying:
c = new C
c.p.f()
is the same as:
c = new C
p = c.p
p.f()
so f will be called in the context of p rather than c.
You can get around this if you don't mind manually binding the functions inside get when your constructor is called:
constructor: (#bugDB) ->
#get = { }
for name, func of #constructor::get
#get[name] = func.bind(#)
This assumes that you have Function.bind available. If you don't then you can use any of the other binding techniques (_.bind, $.proxy, ...). The #get = { } trick is needed to ensure that you don't accidentally modify the prototype's version of #get; if you're certain that you'll only be creating one instance of your BugsRouter then you could use this instead:
constructor: (#bugDB) ->
for name, func of #get
#get[name] = func.bind(#)
to bind the functions inside the prototype's version of get rather than the instance's local copy.
You can watch this simplified demo to see what's going on with # in various cases, keep an eye on the #flag values to see the accidental prototype modification caused by not using #get = { } and #constructor::get:
class C1
get:
f: -> console.log('C1', #)
class C2
get:
f: => console.log('C2', #)
class C3
constructor: ->
#flag = Math.random()
for name, func of #get
#get[name] = func.bind(#)
get:
f: -> console.log('C3', #)
class C4
constructor: ->
#flag = Math.random()
#get = { }
for name, func of #constructor::get
#get[name] = func.bind(#)
get:
f: -> console.log('C4', #)
for klass in [C1, C2, C3, C3, C4, C4]
o = new klass
o.get.f()
Live version of the above: http://jsfiddle.net/ambiguous/8XR7Z/
Hmm, seems like I found a better solution after all:
class Test
constructor: ->
#testVariable = "Have a nice"
return
Object.defineProperties #prototype,
get:
enumerable :true
get:->
{
day: => #testVariable + " day"
week: => #testVariable + " day"
}
console.log (new Test()).get.day()
This allows me to call (new Test()).get.day() the way I wanted.
Live version at: JSFiddle

Problems translating an SQL query to LINQ in VS Lightswitch

So, I am having an issue with an SQL query that is translated LINQ (and works - tested), but that same LINQ query does not work in Lightswitch. Of course I did not expect to work straight out, but I am struggling to properly convert it.
So here is a image of the tables that I base my query on:
http://dl.dropbox.com/u/46287356/tables.PNG
(sorry for outside link, but not enough rep points :))
The SQL query is the following:
SELECT WorkingUnits.Name AS WUName, ContractPositions.WUInstanceId,
Materials.Cost, BillingValues.Value, BillingValues.PricePerUnit
FROM WorkingUnits
INNER JOIN
Materials ON WorkingUnits.Id = Materials.Material_WorkingUnit
INNER JOIN ContractPositions ON
Materials.Id = ContractPositions.ContractPosition_Material
INNER JOIN BillingValues ON
ContractPositions.Id = BillingValues.BillingValue_ContractPosition
Now, I have transformed this to LINQ in the following way:
var query = from wu in this.DataWorkspace.ApplicationData.WorkingUnits
join m in this.DataWorkspace.ApplicationData.Materials on
new { Id = WorkingUnits.Id } equals new { Id = m.Material_WorkingUnit }
join cp in this.DataWorkspace.ApplicationData.ContractPositions on
new { Id = m.Id } equals new { Id = cp.ContractPosition_Material }
join bv in this.DataWorkspace.ApplicationData.BillingValues on
new { Id = cp.Id } equals new { Id = bv.BillingValue_ContractPosition }
select new
{
usage = bv.Value * bv.PricePerUnit,
totalCost = (bv.Value * bv.PricePerUnit) * m.Cost,
amount = (bv.Value*bv.PricePerUnit) * m.Cost / wu.WUPrice
};
Notice that I have changed a few things - like section of colums, as I do not need that in Lightswitch.
So while this works agains the SQL server, Lightswitch complains that I must consider explicitly specifying the type of the range variable 'WorkingUnits'.
I tried to cast it, but then there are other errors such as:
'int' does not contain a definition for 'Id' and no extension method 'Id'
accepting a first argument of type 'int' could be found (are you missing
a using directive or an assembly reference?)
So my questions is, how do I properly convert that query and expect it to work?
Also, If we take that my database is setup correctly, do I even need to use 'joins' in the LINQ?
Any ideas are appreciated!
try something like this
var query = from wu in this.DataWorkspace.ApplicationData.WorkingUnits
join m in this.DataWorkspace.ApplicationData.Materials on
wu.Id equals m.WorkingUnitID }
join cp in this.DataWorkspace.ApplicationData.ContractPositions on
m.Id equals cp.ContractPosition_Material
join bv in this.DataWorkspace.ApplicationData.BillingValues on
cp.Id equals bv.BillingValue_ContractPosition
select new
{
usage = bv.Value * bv.PricePerUnit,
totalCost = (bv.Value * bv.PricePerUnit) * m.Cost,
amount = (bv.Value*bv.PricePerUnit) * m.Cost / wu.WUPrice
};
What about starting at the bottom (BillingValues) and working your way up using the entity references?
eg
var query = from bv in this.DataWorkspace.ApplicationData.BillingValues
let m = bv.ContractPosition.Material
let wu = m.WorkingUnit
select new
{
usage = bv.Value * bv.PricePerUnit,
totalCost = (bv.Value * bv.PricePerUnit) * m.Cost,
amount = (bv.Value*bv.PricePerUnit) * m.Cost / wu.WUPrice
};