If include? == false - ruby

I have an array and a string:
$header = ["Date", "Time", "Site Name", "Computer Name"]
columnName = "esfjk sdhf sdf"
and I am checking if $header contains columnName:
return if $header.include? columnName == false
The condition above always returns true, and the code carries on, even though the array doesn't contain the string.
I also have the same issue when $hash is a hash and recordNum is a number such as 99999999 which is not in it, and I do:
return if $hash.has_key? recordNum == false
Any reason for this happening?

Precedence.
$header.include? columnName == false
is interpreted as
$header.include?(columnName == false)
that is, usually,
$header.include?(false)
which is false. So what you want to do instead is this:
$header.include?(columnName) == false
But in your particular case, I would do this (thanks, Alex Wayne):
return unless $header.include?(columnName)
And if you do that, then you can go back to the parentheses-less form:
return unless $header.include? columnName

Related

CASE WHEN conditional in HiveQL

I'm having trouble bringing a case then into HiveQL.
I have a column with data:
if column is NULL = FALSE
if the column is PEOPLE = TRUE. It returns all results as TRUE.
What's wrong with my role?
SELECT
id,
datetime,
CASE
WHEN tb_people !="" THEN 'TRUE'
ELSE 'FALSE'
END
FROM <BD>.<TABLE>
!="" is only checking for blank strings. "" and NULL are two different things. As such, what you're looking for is:
SELECT
id,
datetime,
CASE
WHEN tb_people IS NOT NULL THEN 'TRUE'
ELSE 'FALSE'
END
FROM <BD>.<TABLE>
I'd also recommend using the boolean true and false rather than string literals. This would let you replace your entire case statement with ifnotnull(tb_people) https://hive.apache.org/javadocs/r3.0.0/api/org/apache/hadoop/hive/ql/exec/vector/expressions/IsNotNull.html.

Ruby Active Record join with condition

I have a column in the Tooltype table called "deleted" which can be true or false. I only want the records which are false. I somehow only manage to check for the second table (toolunits) but not for the first (tooltype). So this WOULD work if I had a column "deleted" in my toolunits table:
obj = Tooltype.joins(:toolunits).where(toolunits: {deleted: false}).distinct
But this does not (see third line):
get '/api/tooltypes' do
if params['selector']
obj = Tooltype.joins(:toolunits).where(tooltype: {deleted: false}).distinct
else
obj = Tooltype.joins(:toolunits).distinct
end
obj.get_list() do |q|
if params['selector']
q.where(deleted: false)
end
end.serialize.first
end
How can I use the condition on the first table?
I'm thinking about two ways
Tooltype.joins(:toolunits).where(Tooltype.table_name => {deleted: false})
Tooltype.joins(:toolunits).where('tooltypes.deleted = ?', false)

c# LINQ where with nullable boolean fields

I have the following query:
where !(tf.Shipped.HasValue == true || tf.Ordered.HasValue == true || tf.Processed.HasValue == true)
Note that Shipped, Ordered and Processed are all nullable Boolean fields.
What I am trying to do is to check that if Shipped or Ordered or Processed have a value of true, they should NOT be in the result.
In my case Ordered is true but I am still getting this records. Not sure what I am doing wrong.
You're checking whether the nullable bools have a value.
If that value is false, HasValue will still be true.
You probably want to write
where !(tf.Shipped == true || tf.Ordered == true || tf.Processed == true)
Comparing nullable bools is the only case where one should write == true.
However, you probably should not be using nullable bools in the first place.
Unless you have a meaningful distinction between null and false, you should use regular bools instead and save yourself a lot of headache.

If condition in LINQ Where clause

With Linq, can I use a conditional statement inside of a Where extension method?
var query = someList.Where(a => (someCondition)? a == "something" : true);
so, if 'someCondition' is false, 'Where' will be skipped.
Yes you can like:
var query = someList.Where(a => a == "something");
if (condition)
{
query = query.Where(b => b == "something else");
}
var result = query.ToList();
Because Where is producing an IQueryable, the execution is deferred until the ToList in my example so you can chain Wheres together as much as you want and then just execute it after you have passed all your conditions.
Make use of WhereIf extenstion method avaialbe in linq
Example
if (SearchControlMain.PostingID.HasValue)
query = query.Where(q => q.PostingID == SearchControlMain.PostingID);
instead of above go for the below
query = query.WhereIf(SearchControlMain.CategoryID.HasValue, q => q.CategoryID == SearchControlMain.CategoryID);
LINQ WhereIf Extension Method
LINQ to SQL Where Clause Optional Criteria
Not sure if this is appropriate but it is quite useful, you can use ifs quite handily with conditional where clauses:
var r = (from p in productinfo.tblproduct
where p.Accountid == accountid
select p);
if (uuf1 != null)
r = r.Where(p => p.UnitUserField1 == uuf1);
if (uuf2!= null)
r = r.Where(p => p.UnitUserField2 == uuf2);
So the where clause will be amended according to what is in UUF1 or UUF2 i.e. you might have only UUF1 with info, in which case it will take that and ignore the UUF2 where clause, you might have both in which it will take both or you might not have anything in UUF1 or 2 and your where clause will just take the accountid as the where clause.
In my case there were two "conditional" where depending on search keys, so I did:
var query = db.Package.Include("SomeThing")
.Where(item => searchString1 == null || searchString1 == "" || item.Contains(searchString1))
.Where(item => searchString2 == null || searchString2 == "" || item.Contains(searchString2));
...
from item in items
where condition1
&& (condition2 ? true : condition3)
select item
This is how can you can do it with the noob Linq syntax.
This applies the condition3 only if condition2 is false.
If condition2 is true, you are essentially doing && true which has no effect on the where clause.
So it is essentially doing this:
if(condition2)
{
from item in items
where condition1
select item
else
{
from item in items
where condition1
&& condition3
select item
}
I had a scenario like this where I had to check for null within the list itself. This is what I did.
items = from p in items
where p.property1 != null //Add other if conditions
select p;
// Use items the way you would use inside the if condition
But as Kelsey pointed out this would work too -
items = items.Where(a => a.property1 != null);
I'm not sure what the question is, but a possible answer could be:
Yes,
list.Where(item => { if (Foo(item)) return true; else return false; });
It would be a complicated way of saying something simple, though.
In my case, I wanted to keep the elements which met my criteria and log the ones that didn't without iterating multiple times.
var merchantsWithLocations = allMerchants.Where(m =>
{
if (m.Locations?.Any() != true)
{
_logger.Log("Merchant {merchantId} has no locations", m.Id);
return false;
}
return true;
};
Any time you want to do a side-effect per element (such as logging), breaking out the lambda into a statement body makes it easy to reason about.

Unpassable Where Clauses LINQ-to-SQL

As I'm struggling to learn LINQ I’ve managed to generate a SQL statement with "AND (0 = 1)" as part of the where clause. I'm just wondering if this result is common in poorly written queries and is a known issues to try and avoid or if I am doing something totally backwards to end up with this.
Update
public static IEnumerable<ticket> GetTickets(stDataContext db,string subgroup, bool? active)
{
var results = from p in db.tickets
where
( active == null || p.active == active )
/*(active == null ? true :
((bool)active ? p.active : !p.active))*/ &&
p.sub_unit == db.sub_units.Where(c=>subgroup.Contains(c.sub_unit_name))
select p;
return results;
}
If I ignore the active part and just run
public static IEnumerable<ticket> GetTickets1(stDataContext db,string subgroup, bool? active)
{
return db.tickets.Where(c => c.sub_unit.sub_unit_name == subgroup);
}
It returns the groups of tickets I want ignoring the active part.
I'd pull the processing out of the ternary operators.
where ( active == null || p.active == active )
EDIT
The rest of the where clause looks funky too... why is it not just doing
&& p.sub_unit.sub_unit_name == subgroup
or
&& subgroup.Contains(p.sub_unit.sub_unit_name)
?
That is some pretty heavy abuse of the ternary operator.
This expression:
(active == null ? true :
((bool)active ? p.active : !p.active))
Is equivalent to the following logic:
bool result;
if (active == null)
{
result = true;
}
else
{
if ((bool)active)
{
result = p.active;
}
else
{
result = !p.active;
}
}
result &= ...
Think carefully about what this is doing:
If active is null, you're fine, it skips to the next condition.
If active is true, result is true at the end of the conditional.
If active is false, result is false at the end of the conditional.
In the last case, the query can never return any rows!
#Tanzelax has already supplied a simple rewrite. The main idea is that you want to compare p.active to active, not actually evaluate the condition as p.active.
This is probably caused by a null value in one you the columns you have declared as non-nullable. LINQ2SQL makes all columns non-nullable by default. Go back to the designer and change the fields to allow values to be null. Unfortunately this feature is By Design (see connect.microsoft.com link below.)
(linq) incorrect sql generated for row.column == localVar when localVar is null (should be "is null" check)

Resources