Is there a function similar to Math.Max for Entity Framework? - entity-framework

I have an entity framework query as follows;
From T In Db.MyTable
Where (T.Col1 - T.Col2) + T.Col3 - T.Col4 > 0 _
Select T
I now need to make sure that the bracketed part '(T.Col1 - T.Col2)' does not go below zero.
In .Net, I'd code it as follows (but obviously EF does not like Math.Max).
From T In Db.MyTable
Where Math.Max(T.Col1 - T.Col2,0) + T.Col3 - T.Col4 > 0 _
Select T
Is there an easy way to do this? I am using EF 2.0 (not the latest, just released version).
Thanks in advance

Max isn't supported, but Abs is; will that do? Otherwise you'll have to use a ternary expression. In C#, I'd do:
from t in Db.MyTable
let m = t.Col1 >= t.Col2 ? t.Col1 - t.Col2 : 0
where m + t.Col3 - t.Col4 > 0
However, this will be inefficient at the DB level unless you have an expression index. So I'd suggest a computed column instead.

Related

NDepend: how to limit JustMyCode to the methods used by x?

The official documentation explains how to limit JustMyCode by exclusion using notmycode
notmycode from m in Methods where
m.SourceFileDeclAvailable &&
m.SourceDecls.First().SourceFile.FileName.ToLower().EndsWith(".designer.cs")
select m
I'd like to limit JustMyCode to only the methods returned by this query
from m in Methods
let depth0 = m.DepthOfIsUsedBy("InsertMuk(Int32,Int32,BetCoupon,Boolean,Boolean,Boolean,DateTime&,Boolean)")
where depth0 >= 0 orderby depth0
select new { m, depth0 }
Will it redefine the codebase for all the other queries?
This query should work, assuming you disable all other notmycode queries and also that you provide Namespace.ClassName in the string:
notmycode
let methodsUsed = Methods.Where(m1 => m1.DepthOfIsUsedBy("Namespace.ClassName.InsertMuk(Int32,Int32,BetCoupon,Boolean,Boolean,Boolean,DateTime&,Boolean)") >= 0)
from m in Methods.Except(methodsUsed )
select m

How to create a functional or where clause from a list of where clauses in kdb?

I have the following where clauses :
q)).tst.wc
(max$["b"];((/:;like);`Col1;(enlist;"0009D000";"00080000")))
(like;`Col2;,"B0000000999")
I want to crate the following query:
,(|;(max$["b"];((/:;like);`Col1;(enlist;"0009D000";"00080000")));(like;`Col2;,"B0000000999"))
I tried
(or;.tst.wc) //doesn't work
(or; first each .tst.wc) // doesn't work
(or;.tst.wc 0;.tst.wc 1) // works
however I cannot use the last one because I don't know how many where clauses will be there. Any suggestions?
You can just append them to or as follows:
q)(or),.tst.wc
|
($["b"];((/:;like);`Col1;(enlist;"0009D000";"00080000")))
(like;`Col2;,"B0000000999")
q)(or;.tst.wc 0;.tst.wc 1)~(or),.tst.wc
1b
EDIT: if you have an unknown number of where clauses and they all need an "or" between them all then you can use:
(or;;)/[.tst.wc]
however this where clause will fast become inefficient as nested "or"s are not optimal query filtering - each clause needs to be applied to the entire length of the table
so the best I could find so far was :
{[x;y]$[x~();(or;y);x,enlist y]}/[();.tst.wc]
... ready to accept and upvote a better answer ...
What about using any? If I understand you correctly you are creating any number of or conditions.
t:([]a:til 10;b:`a`b`c`d`e`f`g`h`i`j;c:10*til 10);
.tst.wc:((=;`a;0);(=;`b;enlist `d);(=;`c;90));
?[t;enlist ((any),enlist (enlist),.tst.wc);0b;()!()]
a b c
------
0 a 0
3 d 30
9 j 90
// also works with one
.tst.wc2:enlist (=;`a;0);
?[t;enlist ((any),enlist (enlist),.tst.wc2);0b;()!()]
a b c
-----
0 a 0

Julia (JuMP): Indicator constraints with multiple conditional values (is a boolean expression possible?)

I want to implement a constraint depending on the change of values in my binary decision variable, x, over "time".
I am trying to implement a minimum operating time constraint for a unit commitment optimization problem for power systems. x is representing the unit activation where 0 and 1 show that a power unit, n, at a certain time, t, respectively is shut off or turned on.
For this, indicator constraints seem to be a promising solution and with the inspiration of a similar problem the implementation seemed quite straightforward.
So, since boolean operators are introduced (! and ¬), I prematurely wanted to express the change in a boolean way:
#constraint(m, xx1[n=1:N,t=2:T], (!x[n,t-1] && x[n,t]) => {next(t, 1) + next(t, 2) == 2})
Saying: if unit was deactivated before but now is on, then demand the unit to be active for the next 2 times.
Where next(t, i) = x[((t - 1 + i) % T) + 1].
I got the following error:
LoadError: MethodError: no method matching !(::VariableRef)
Closest candidates are:
!(!Matched::Missing) at missing.jl:100
!(!Matched::Bool) at bool.jl:33
!(!Matched::Function) at operators.jl:896
I checked that the indicator constraint is working properly with a single term only.
Question: Is this possible or is there another obvious solution?
Troubleshooting and workarounds: I have tried the following (please correct me if my diagnosis is wrong):
Implement change as an expression: indicator constraints only work with binary integer variables.
Implement change as another variable relating to x. I have found a solution but it is quite sketchy, which is documented in a Julia discourse. The immediate problem, found from the solution, is that indicator constraints do not work as bi-implication but only one way, LHS->RHS. Please see the proper approach given by #Oscar Dowson.
You can get the working code from github.
The trick is to find constraint(s) that have an equivalent truth-table:
# Like
(!x[1] && x[2]) => {z == 1}
# Is equivalent to:
z >= -x[1] + x[2]
# Proof
-x[1] + x[2] = sum <= z
--------------------------
- 0 + 0 = 0 <= 0
- 1 + 0 = -1 <= 0
- 0 + 1 = 1 <= 1
- 1 + 1 = 0 <= 0
I was recommended MOSEK Modeling Cookbook to help working out the correct formulation of constraints.
See eventually the thread here from where I got the answer for further details.

NDpend Variable Calculations

Trying to use a custom NDepend variable in place of a constant and cannot work out some of the intricacies of the NDepend syntax around the let keyword.
One of the built in queries is:
warnif count > 0 from m in JustMyCode.Methods where
m.CyclomaticComplexity > 30 ||
m.ILCyclomaticComplexity > 60 ||
m.ILNestingDepth > 6
orderby m.CyclomaticComplexity descending,
m.ILCyclomaticComplexity descending,
m.ILNestingDepth descending
select new { m, m.CyclomaticComplexity,
m.ILCyclomaticComplexity,
m.ILNestingDepth }
Whereas what I really want to do is not use a 0 constant value and base that on the codebase instead. Something along the lines of:
let tenPercent = (JustMyCode.Methods.Count() / 100 * 10)
warnif count > tenPercent from m in JustMyCode.Methods where
m.CyclomaticComplexity > 30 ||
...
Is this even possible?
You can write something like this...
warnif percentage > 10
from m in Application.Methods where
m.CyclomaticComplexity > 2
select new { m, m.CyclomaticComplexity }
...but this feature is kinda hidden (percentage keyword doesn't appear in intellisense) because it is not polished yet. The percentage base is the total number of methods (including abstract methods, third-party methods, generated methods...) and this base number is actually not configurable. Also the constant value (10 here) cannot be an expression.

NHibernate Delete with date arithmatic using HQL

I've looked around and can't find too much. But is it possible to do something like this using HQL in nHibernate:
Session.CreateQuery(#"DELETE FROM MyObject mo
WHERE (mo.AlteredDate + mo.ExpiryDetails.ExpiryTimestamp) < :pNow")
.SetDateTime("pNow", DateTime.Now);
So basically I want to delete all MyObjects from the database where the last time the object was altered (mo.AlteredDate - a DateTime) plus an amount of time such as 2 days and 5 hours (ExpiryDetails.ExpiryTimestamp) is less than now.
Or is it best to retrieve the objects and do the caculation in code using the .NET framework?
Super late to answer, but I did something like this & it works:
IQuery query = Session.CreateQuery("select x from OBJECT x where x.DateTimeForCompare > :dateTimeForCompare2");
query.SetDateTime("dateTimeForCompare2", DateTime.Today);
IList<OBJECT> xx = query.List<OBJECT>();