Cannot figure out why I'm getting error when parsing a string in Dart/Flutter with petitparser: uppercase letter expected at 1:1 - flutter

UPDATE 1: It looks like changing digit().plus() to word().plus() works. Does that seem right?
Petitparser has proven to be very powerful! I have the following flutter/dart code:
testString = '((S|71|L || S|70|L || S|69|L || S|72|L) && (F|54|L || F|52|L || H|5|L))';
final builder = ExpressionBuilder();
final primitive = (uppercase() & char('|') & digit().plus() & char('|') & uppercase()).flatten().trim();
builder.group().primitive(primitive);
builder.group()
.wrapper(char('(').trim(), char(')').trim(), (l, v, r) => v);
builder.group()
..left(string('&&').trim(), (a, op, b) => ['&&', a, b])
..left(string('||').trim(), (a, op, b) => ['||', a, b]);
final parser = builder.build().end();
final result = parser.parse(testString);
This works perfectly. However, when I change the testString slightly to the following (note the word test instead of the number 5), I get the error in the title uppercase letter expected at 1:1:
testString = '((S|71|L || S|70|L || S|69|L || S|72|L) && (F|54|L || F|52|L || H|test|L))';
I can't seem to figure out what it thinks should be an uppercase letter, or how to change the parser. I was thinking maybe it is something with the digit().plus(), since that's the part of my primitive that I'm changing, but I tried changing that to any().plus() and it shows the same error.
Can anyone help? Thanks!

Related

How to sort on DB side, if entities are not connected via Navigation (since it's not possible)

I want to have my EfCore query translated into the following SQL query:
select
c.blablabla
from
codes c
left join lookups l on c.codeId = l.entityid and l.languageCode = <variable - language code of current thread> and l.lookuptype = 'CODE'
where
..something..
order by
l.displayname
Note: tables 'codes' and 'lookups' are not connected! 'lookups' contains a lot of different lookup data in different languages!
I am stuck into limitations of EfCore (like 'NavigationExpandingExpressionVisitor' failed). I don't want to make in-memory filtering, it looks silly to me... Am I missing something obvious?
In perspective, I'd like to make universal method to help sort by displayname (or other lookup name) for different kind of entities - not only codes.
Seems like I figured it out. If there's a better approach - please let me know:
protected override IQueryable<FixCode> SortByDisplayName(IQueryable<FixCode> queryable, string languageCode = null)
{
return queryable
.GroupJoin(
DbContext.FixCodeValues.Where(x =>
x.DomainId == CentralToolConsts.Domains.CENTRAL_TOOLS
&& x.CodeName == CentralToolsFieldTypes.CODE_ORIGIN
&& (x.LanguageCode == languageCode || x.LanguageCode == CentralToolsDbLanguageCodes.English)),
//TODO: this will be a 'selector' parameter
code => code.CodeOriginId,
codeOrigin => codeOrigin.StringValue,
(c, co) => new
{
Code = c,
CodeOrigin = co
}
)
.SelectMany(
x => x.CodeOrigin.DefaultIfEmpty(),
(x, codeOrigin) => new { Code = x.Code, CodeOrigin = codeOrigin }
)
.OrderBy(x => x.CodeOrigin.ShortName)
.Select(x => x.Code);
}

EF DbContext. How to avoid caching?

Spent a lot of time, but still cann't understand how to avoid caching in DbContext.
I attached below entity model of some easy case to demonstrate what I mean.
The problem is that dbcontext caching results. For example, I have next code for querying data from my database:
using (TestContext ctx = new TestContext())
{
var res = (from b in ctx.Buildings.Where(x => x.ID == 1)
select new
{
b,
flats = from f in b.Flats
select new
{
f,
people = from p in f.People
where p.Archived == false
select p
}
}).AsEnumerable().Select(x => x.b).Single();
}
In this case, everything is fine: I got what I want (Only persons with Archived == false).
But if I add another query after it, for example, query for buildings that have people that have Archived flag set to true, I have next things, that I really cann't understand:
my previous result, that is res, will be added by data (there
will be added Persons with Archived == true too)
new result will contain absolutely all Person's, no matter what Archived equals
the code of this query is next:
using (TestContext ctx = new TestContext())
{
var res = (from b in ctx.Buildings.Where(x => x.ID == 1)
select new
{
b,
flats = from f in b.Flats
select new
{
f,
people = from p in f.People
where p.Archived == false
select p
}
}).AsEnumerable().Select(x => x.b).Single();
var newResult = (from b in ctx.Buildings.Where(x => x.ID == 1)
select new
{
b,
flats = from f in b.Flats
select new
{
f,
people = from p in f.People
where p.Archived == true
select p
}
}).AsEnumerable().Select(x => x.b).Single();
}
By the way, I set LazyLoadingEnabled to false in constructor of TestContext.
Does anybody know how to workaround this problem? How can I have in my query what I really write in my linq to entity?
P.S. #Ladislav may be you can help?
You can use the AsNoTracking method on your query.
var res = (from b in ctx.Buildings.Where(x => x.ID == 1)
select new
{
b,
flats = from f in b.Flats
select new
{
f,
people = from p in f.People
where p.Archived == false
select p
}
}).AsNoTracking().AsEnumerabe().Select(x => x.b).Single();
I also want to note that your AsEnumerable is probably doing more harm than good. If you remove it, the Select(x => x.b) will be translated to SQL. As is, you are selecting everything, then throwing away everything but x.b in memory.
have you tried something like:
ctx.Persons.Where(x => x.Flat.Building.Id == 1 && x.Archived == false);
===== EDIT =====
In this case I think you approach is, imho, really hazardous. Indeed you works on the data loaded by EF to interpret your query rather than on data resulting of the interpretation of your query. If one day EF changes is loading policy (for example with a predictive pre-loading) your approach will "send you in then wall".
For your goal, you will have to eager load the data you need to build your "filterd" entity. That is select the building, then foreach Flat select the non archived persons.
Another solution is to use too separate contexts in an "UnitOfWork" like design.

How to write this Query in LINQ

I have one LINQ query with foreach loop. Everything is fine. But it takes more time to get the value. So anybody suggest me how can i do this in LINQ query itself.
Code
NormValue = "";
c = 0;
var NormValuelist = db.BCont.Where(x => x.BId == BId && x.TNo == Tag).ToList();
foreach (var item in NormValuelist)
{
if (c == 0)
NormValue = item.NormValue;
else
NormValue += " " + item.NormValue;
c = 1;
}
Thanks
You can rewrite this query with string.Join to avoid creating multiple string objects in a loop, like this:
string NormValue = string.Join(" ", db.BCont.Where(x => x.BId == BId && x.TNo == Tag));
The number of round-trips to DB will remain the same, but the creation of List<string> and the partially concatenated string objects will be optimized out.
In addition to using String.Join, you could also use Enumerable.Aggregate:
var NormValueList =
db.BCont.Where(x => x.Bid == BId && x.TNo == Tag)
.Select(x => x.NormValue)
.Aggregate((s, x) => s + " " + x);
If you are having large items in "NormValuelist" then it would be better to use StringBuilder instead of string(NormValue)

How can I embed optional Where parameters in a Linq to EF statement?

Let's say we have a description field on my form with optional check boxes. The check boxes represent which fields to search when doing the lookup. Right now I have a matrix of look ups that call their unique version of where clause. It works but I think it smells a bit.
Here is an excerpt
// Look for part numbers decide how many fields to search and use that one.
// 0 0 X
if (!PartOpt[0] && !PartOpt[1] && PartOpt[2])
{
query = query.Where(p => (p.PartNumAlt2.Contains(partSearchRec.inventory.PartNum)));
}
// 0 X 0
if (!PartOpt[0] && PartOpt[1] && !PartOpt[2])
{
query = query.Where(p => (p.PartNumAlt.Contains(partSearchRec.inventory.PartNum)));
}
// 0 X X
if (!PartOpt[0] && PartOpt[1] && PartOpt[2])
{
query = query.Where(p => (p.PartNumAlt.Contains(partSearchRec.inventory.PartNum)
|| p.PartNumAlt2.Contains(partSearchRec.inventory.PartNum)));
}
// X 0 0
if (PartOpt[0] && !PartOpt[1] && !PartOpt[2])
{
query = query.Where(p => (p.PartNum.Contains(partSearchRec.inventory.PartNum)));
}
. . .
This goes on for a while and seems to be prone to coding errors. In each case we are looking for the same information in any of the selected fields. If I was doing this in SQL I could simply build up the WHERE clause as needed.
Once again I rubber ducked my way to an answer. Rather than throw the question away, here is what I came up with. Is it efficient?
if (partSearchRec.optPartNum || partSearchRec.optAltPartNum1 || partSearchRec.optAltPartNum2)
{
query = query.Where(p => (
(partSearchRec.optPartNum && p.PartNum.Contains(partSearchRec.inventory.PartNum))
|| (partSearchRec.optAltPartNum1 && p.PartNumAlt.Contains(partSearchRec.inventory.PartNum))
|| (partSearchRec.optAltPartNum2 && p.PartNumAlt2.Contains(partSearchRec.inventory.PartNum))));
}
Basically if any of the check boxes are set we will execute the query. Each line of the query will be processed only if the check box was checked. If the left side of an AND is false it doesn't process the right.
This is an aera that Delphi's with statement would be handy. I also learned that you can't use an array inside the LINQ statement.

Most concise way to assign a value from a variable only if it exists in CoffeeScript?

Anyone knows of a more concise/elegant way of achieving the following?
A = B if B?
Thanks.
EDIT:
I'm looking for a solution that references A and B once only. And would compile to
if (typeof B !== "undefined" && B !== null) { A = B; }
or something else similar.
To have this short helps have the following a bit more readable:
someObject[someAttribute] = (someOtherObject[someOtherAttribute] if someOtherObject[someOtherAttribute]?)
That is the motivation for my question.
You could say:
a = b ? a
For example, this:
a = 11
a = b ? a
console.log(a)
b = 23
a = b ? a
console.log(a)​
will give you 11 and 23 in the console (demo: http://jsfiddle.net/ambiguous/ngtEE/)
Maybe something like:
A=_ if (_=B)?
expanded:
if ((_ = B) != null) {
A = _;
}
This will overwrite A with what ever is in B, but only if it is not null, referencing both only once.
Not sure about Coffee Script but you can use the OR operator for this in regular javascript like so:
a = b || a