java.util.NoSuchElementException when using inject method of groovy List - list

i try to get the AND logic among boolean elments from groovy list .
def list=[true,false,true];
For example , when i apply inject as following :
list.inject{a,b->a && b};
i get
true && false && true=false
However , when i apply this closure to an empty list i get this error message
Cannot call inject() on an empty collection without passing an initial value.
How can passing initial value to avoid this exception ?
thanks

Inject with no initial parameter uses the first element in the list as the initial value, and then runs the closure over all further elements in the list.
If the list is empty, it cannot get the initial value, so you need to specify an initial parameter to inject:
ie:
list.inject( true ) { a, b -> a && b }
This will return true for empty lists, but in your original example will return false, as it will evaluate:
true && true && false && true
Obviously, if you're doing or instead of and, you should pass false as the inital parameter:
list.inject( false ) { a, b -> a || b }

Related

nextflow (groovy) check if item in Channel list

I am struggling to use an if/else on a containsAll() statement. It returns the correct true false value when tested with println(), but when put in an if statement it seems to always evaluate to true -- see below.
def examine_phenotype(pheno){
condition_values = \
Channel
.fromPath(pheno)
.splitCsv(header: true, sep: ',')
.map{ row ->
def condition = row.condition
return condition
}
.toList().view()
println(condition_values.containsAll('control'))
if(condition_values.containsAll('control')){
exit 1, "eval true"
}else{
exit 1, "eval false"
}
}
Console output for two different files, one with 'control' and one without 'control' in the column 'condition', which is the point of the function.
[normal, normal, normal, tumor, tumor, tumor]
DataflowInvocationExpression(value=false)
eval true
[control, control, control, tumor, tumor, tumor]
DataflowInvocationExpression(value=true)
eval true
Using collect() instead of toList() where each item within condition_values is enclosed with single quotes did not resolve the issue either. The clue might be in DataflowInvocationExpression but I am not up to speed on Groovy yet and am not sure how to proceed.
Testing the conditional within the function was not working, but applying filter{} and ifEmpty{} was able to produce the desired check:
ch_phenotype = Channel.empty()
if(pheno_path){
pheno_file = file(pheno_path)
ch_phenotype = examine_phenotype(pheno_file)
ch_phenotype.filter{ it =~/control/ }
.ifEmpty{ exit 1, "no control values in condition column"}
}
def examine_phenotype(pheno){
Channel
.fromPath(pheno)
.splitCsv(header: true, sep: ',')
.map{ row ->
def condition = row.condition
return condition
}
.toList()
}

Postman test fails test for array when array with one item is returned

I have a postman test case:
pm.test("Check for property of type null or array", function(){
var isNullOrArray = (property === null || typeof(property) === "array");
pm.expect(isNullOrArray, "property is of type " + typeof(property)).to.be.true;
});
Unfortunately, when I mock a response that returns an array with only one item like this:
"property": [
{
"user_id": 1234,
"is_true": false
}
]
The test fails and in the logs I can see that typeof(property) is an object.
The test seems to work with other responses that have more than one item in the array. What's wrong with my test? Is typeof(property) === "array" even possible? Or is it possible the array is not recognized because there is just the one object inside of it?
use array.isArray instead , in javascript type of array returns object as everything is an object in javascript except primitive types ( means only immutable data types are considered as non objects )
pm.test("Check for property of type null or array", function(){
var isNullOrArray = (property === null || Aarray.isArray(property));
pm.expect(isNullOrArray, "property is of type " + typeof(property)).to.be.true;
});
https://developer.mozilla.org/en-US/docs/Glossary/Primitive , array is not primitve data type so is considered as an object
a = [1,2,3]
b =a
a[2] = 5
console.log(b)
you can see that changing 'a' changes 'b' as they are mutable , and thus its a object

How to get the list of all booleans set to true?

I have a table model named History and all its attributes are boolean.
How can I select only the attributes set to true?
I tried
History.select {|h| h == true}
what am I missing?
For all ones with all true:
boolean_columns = Model.columns.map(&:name) - %w(id created_at updated_at)
Model.where(boolean_columns.zip([true].cycle).to_h)
Attributes only works on an instance, and in that case you probably just want to query it.
For a single one:
Model.first.attributes.select { |_, v| v == true }
The reason I do v == true instead of v is because you want explicit boolean true, not necessarily truthy.

For Loop only looked for first element of a list while using if condition within the loop. (Python 2.7)

def has23(nums):
for i in nums:
if i == 2 or i == 3:
return True
else:
return False
print has23([4,3])
The function has to return True if list in the parameter has either 2 or 3 in it. The output resulted 'False' even though the list has 3 in it.
Why?
return ends the function and returns back to the place where the function was called. That you happened to be in a for loop inside the function isn't relevant anymore.
A function can only return once.

In Lua what does an if statement with only one argument mean?

I've been taught to program in Java. Lua is new to me and I've tried to do my homework but am not sure what an if statement of the following nature means.
The code is as follows:
local function getMinHeight(self)
local minHeight = 0
for i=1, minimizedLines do
local line = select(9+i, self:GetRegions())
**if(line) then
minHeight = minHeight + line:GetHeight() + 2.5
end**
end
if(minHeight == 0) then
minHeight = select(2, self:GetFont()) + 2.5
end
return minHeight
end
The if statement with the ** before and after is the part I'm not sure about. I don't know what the if statement is checking. If the line is not nil? If the line exists? If what?
In Lua, anything that's not nil or false evaluates to true in a conditional.
If the line is not nil? If the line exists?
Yes to both, because they kinda mean the same thing.
The select function returns a specific argument from it's list of arguments. It's used primarily with ..., but in this case it's being used to select the (i+9)th value returned by self:GetRegions. If there is no such value (for instance, if GetRegions only returns 5 values), then select returns nil.
if(line) is checking to see that it got a value back from select.
if(line) is being used as a shortcut for if(line ~= nil), since nil evaluates to false in a conditional.
It's worth pointing out that this shortcut is not always appropriate. For instance, we can iterate all the values in a table like this:
key, val = next(lookup)
while key do
print(key, val)
key, val = next(lookup, key)
end
However, this will fail if one of the table's keys happens be false:
lookup = {
["fred"] = "Fred Flinstone",
[true] = "True",
[false] = "False",
}
So we have to explicitly check for nil:
key, val = next(lookup)
while key ~= nil do
print(key, val)
key, val = next(lookup, key)
end
As Mud says, in lua anything other than nil and false is considered truthy. So the if above will pass as long as line is not nil or false.
That said, it worries me a bit the way you have phrased the question - "an if with only one argument".
First, it's not called "argument" - it's called expression. And in most languages is always one. In java, for example, you could do something like this:
bool found = false
...
if(found) {
...
}
ifs only care about the final value of the expression; they don't care whether it's a single variable or a more complex construction.