I have this code:
String query = "a == someRandomWord && b != 2";
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
SimpleBindings variables = new SimpleBindings();
variables.put("a", "someRandomWord");
variables.put("b", 1);
System.out.println(engine.eval(query, variables));
It gives me an error because I'm not allowed to pass String as a parameter.
How can I compare String objects with .eval() function?
String query = "a == p && a != 2";
^^^
this is not a string but a variable
Either use 'yourString' or \"yourString\" (as you need to escape it in Java), e.g.
String query = "a == 'someRandomWord' && b != 2";
Alternatively: supply also the binding for p as was suggested in the comments.
Related
Thanks for any help.
I am currently trying to get a DXL script to return all occurrences for a certain word in the module in the outlink. The outlink "test" will need to be a wild card, if possible, to find all other outlnks that have the word "test" unsure on if that's possible. The attribute in the outlink will be "Compliance". Maybe need a while loop?
Link outlnk
string tmn = ""
string Status = ""
int Count = 0
for outlnk in obj-> "*" do
{
tmn = fullName source(outlnk)
Object tgt = source(outlnk)
if(matches("Test", tmn))
{
Status = tgt."Compliance"
if (Status == "Compliant"){
Count++
}
}
}
display Count""
I tried to get the above code to work with the below while loop. But can not figure out the correct syntax.
Regexp Check = regexp2 "Compliant"
while (!null Status && Check Status)
{ Status = Status[end 0 + 1:]
Count++
}
I need to change the output of a method a bit: Execute the function, and if it's a empty string, then convert it to a "1". How can i write this short on just one line?
var = some_really_long_method(foo)
var = "1" if var == ""
I tried below, but that does call the method twice, right?
var = some_really_long_method(foo) == "" ? "1" : some_really_long_method(foo)
You could use Object#then:
def some_really_long_method
p 'called'
p res = ["", "10"].sample
res
end
var = some_really_long_method.then { |m| m == "" ? '1' : m }
You can check for yourself that the method is called once.
Newlines are optional in Ruby, they can always be replaced with either an expression separator (;), a keyword (e.g. then, do), or sometimes just whitespace.
Therefore, every program, no matter how complex, can always be written in one line, just by removing the linebreaks:
var = some_really_long_method(foo); var = "1" if var == ""
var = "1" if (var = some_really_long_method(foo)) == ""
I'm using the Code::Blocks IDE and whenever I try to build the file this code brings up an error:
{
cin >> input ;
locale loc;
for (string::size_type i=0; i<input.length(); ++i)
input[i] = tolower(input[i],loc);}
{
if (input == "not")
"" != "";
else if (input == "and")
"" && "";
else if (input == "or")
"" || "";
else if (input == "yes")
input = true;
else if (input == "no")
input = false;
}
The error occurs where I try to make the word "no" equal to the Boolean operator false.
This brings up this error:
Projects\Samantha\main.cpp|40|error: ambiguous overload for 'operator=' (operand types are 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' and 'bool')|
Now I've tried searching for this problem but I haven't been able to find anything to help me. If someone could please help me to figure what the problem is and how I can fix it I would be very appreciative.
The problem is that you are trying to assign a Boolean to a string.
You have two options here
Create a bool variable where you will store your false value
assign a string literal instead of a boolean input = "false";
Please note that the first three ifs are doing nothing since you are performing logical operations on empty string literals and not storing the result anywhere.
I'd also recommend to avoid using if() conditions without following braces since that is an error-prone, difficult to maintain and difficult to read approach.
else if (input == "yes")
{
booleanVariable = true;
}
I am trying to write some logic to determine if all values of a certain property of an object in a collection are numeric and greater than zero. I can easily write this using ForEach but I'd like to do it using Linq to Object. I tried this:
var result = entity.Reports.Any(
x =>
x.QuestionBlock == _question.QuestionBlock
&& (!string.IsNullOrEmpty(x.Data)) && Int32.TryParse(x.Data, out tempVal)
&& Int32.Parse(x.Data) > 0);
It does not work correctly. I also tried this, hoping that the TryParse() on Int32 will return false the first time it encounter a string that cannot be parsed into an int. But it appears the out param will contain the first value string value that can be parsed into an int.
var result = entity.GranteeReportDataModels.Any(
x =>
x.QuestionBlock == _question.QuestionBlock
&& (!string.IsNullOrEmpty(x.Data)) && Int32.TryParse(x.Data, out tempVal));
Any help is greatly appreciated!
If you want to test if "all" values meet a condition, you should use the All extension method off IEnumerable<T>, not Any. I would write it like this:
var result = entity.Reports.All(x =>
{
int result = 0;
return int.TryParse(x.Data, out result) && result > 0;
});
I don't believe you need to test for an null or empty string, because int.TryPrase will return false if you pass in a null or empty string.
var allDataIsNatural = entity.Reports.All(r =>
{
int i;
if (!int.TryParse(r.Data, out i))
{
return false;
}
return i > 0;
});
Any will return when the first row is true but, you clearly say you would like to check them all.
You can use this extension which tries to parse a string to int and returns a int?:
public static int? TryGetInt(this string item)
{
int i;
bool success = int.TryParse(item, out i);
return success ? (int?)i : (int?)null;
}
Then this query works:
bool all = entity.Reports.All(x => {
if(x.QuestionBlock != _question.QuestionBlockint)
return false;
int? data = x.Data.TryGetInt();
return data.HasValue && data.Value > 0;
});
or more readable (a little bit less efficient):
bool all = entityReports
.All(x => x.Data.TryGetInt().HasValue && x.Data.TryGetInt() > 0
&& x.QuestionBlock == _question.QuestionBlockint);
This approach avoids using a local variable as out parameter which is an undocumented behaviour in Linq-To-Objects and might stop working in future. It's also more readable.
I want to generate dynamic query to check manage the where clause with number of parameters available...if some parameter is null i don't want to include it in the where clause
var test = from p in _db.test
where if(str1 != null){p.test == str} else i dnt wanna check p.test
I have around 14 parameters for the where clause
need help,
thanks
You can do it in steps:
// set up the "main query"
var test = from p in _db.test select _db.test;
// if str1 is not null, add a where-condition
if(str1 != null)
{
test = test.Where(p => p.test == str);
}
In addition to #Fredrik's answer, you can also use the short-circuit rules when evaluating boolean expressions like so:
var test = from p in _db.test
where str1 == null || p.test == str1;
Edit If you have lots of strings to test, (str1, str2, etc...) then you can use the following, which will be translated to an SQL IN clause:
var strings = new List<string>();
if (str1 != null) strings.Add(str1);
if (str2 != null) strings.Add(str2);
if (str3 != null) strings.Add(str3);
...
var test = from p in _db.test
where strings.Contains(p.test);
It's even easier if your strings are already in a collection (which, if you've got 14 of them, I assume they would be...)
Consider param1 and param2 are the parameters. Your query should be as under:
string param1 = "Value1";
string param2 = "Value2";
var q = from bal in context.FxBalanceDetails
where (string.IsNullOrEmpty(param1) || bal.Column1 == param1)
&& (string.IsNullOrEmpty(param2) || bal.Column2 == param2)
select bal;
This will ensure that the where clause gets applied for the particular parameter only when it is not null.
var test =
from p in _db.test
where p.str1 != null ? p.str1 : ""
select p;
Do you check the strings against the same Field of the entity?
If so you can write something like:
var strings = new[] { "foo", "bar", "ok", "", null };
var query = dataContext.YourTable.AsQueryable();
query = strings.Where(s => !string.IsNullOrEmpty(s))
.ToList()
.Aggregate(query, (q, s) => q.Where(e => e.YourField == s));
EDIT:
The previous solution is overcomplicated:
var strings = new[] { "foo", "bar", "ok", "", null }.Where(s => !string.IsNullOrEmpty(s))
.ToList();
var query = dataContext.YourTable.Where(e => strings.Contains(e.YourField));