Cannot perform option-mapped operation with type: (Boolean, _57) => R - slick

I have next filter
type DatabaseID = Long
val filter = moderators.filter(m =>
(m.created < before) &&
(m.userType inSet userTypeList) &&
(if(true) m.mcID === mcIDFilter else true)
)
where m.mcID has Rep[Option[models.DatabaseID]] type and mcIDFilter Option[models.DatabaseID].
Why i'm getting next error?
Cannot perform option-mapped operation
with type: (Boolean, _57) => R
for base type: (Boolean, Boolean) => Boolean
_57? What is it?
I have replaced condition with true for simplicity. If i remove line with condition or replace m.mcID === mcIDFilter with just true, code compiles fine.
Also if i remove if statement, it compiles without error:
val filter = moderators.filter(m =>
(m.created < before) &&
(m.userType inSet userTypeList) &&
m.mcID === mcIDFilter
)
I found that this error appears when type one of operands have not the same type.
I also tried
val filter = moderators.filter(m =>
(m.created < before) &&
(m.userType inSet userTypeList) &&
(if(true) m.mcID === mcIDFilter else true:Rep[Boolean])
)
but without success.

Ok, i found how compile this. It's ugly, but work.
val filter = moderators.filter(m =>
(m.created < before) &&
(m.userType inSet userTypeList) &&
(if(true) m.mcID === mcIDFilter else Some(true):Rep[Option[Boolean]])
)

Related

Index of a table row when found by predicate

I'm finding a TableRow with a predicate thus:
Table.Rows[r => r.name == "blablabla"]
Is there any way to get the index of the row it finds as an int?
IndexOf method should work for that:
int index = Table.Rows.IndexOf(r => r.name == "blablabla");
To assert index:
Table.Rows.IndexOf(r => r.name == "blablabla").Should.Be(2);

If (msg.content == "Ash" || "ash") returns true for any input even if false? [duplicate]

I would like to know in this example why my condition is always true ? Thanks
function bla() {
var qix = 'z'
if (qix === 'a' || 'b' || 'c') {
console.log('condition ok!! whats wrong???')
}
}
The problem with your code is that the if expression always evaluates to true.
qix === 'a' || 'b' || 'c'
will actually become this:
false || 'b' || 'c'
as qix is set to z. Due to loose typing, JavaScript returns true for the second expression because 'b' is a truthy value. To correct that, you need to change the expression as follows:
qix === 'a' || qix === 'b' || qix === 'c'
so that it correctly means what you're expecting.
Description of expr1 || expr2 from MDN:
Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true.
o1 = true || true // t || t returns true
o2 = false || true // f || t returns true
o3 = true || false // t || f returns true
o4 = false || (3 == 4) // f || f returns false
o5 = 'Cat' || 'Dog' // t || t returns "Cat"
o6 = false || 'Cat' // f || t returns "Cat"
o7 = 'Cat' || false // t || f returns "Cat"
o8 = '' || false // f || f returns false
o9 = false || '' // f || f returns ""
So this expression from your code, assuming qix is not 'a':
qix === 'a' || 'b' || 'c'
The first term qux === 'a' is false, which of course evaluates to false. This causes it to go to the next term which is 'b'. Non-empty strings evaluate to true, so it stops there and just becomes 'b'. Now your if statement can be thought of as just:
if ('b')
Again, 'b' evaluates to true. So your conditional is effectively doing nothing.
I think you are missing two concepts.
First how the || operator works and second coercion of javascript values.
In your code:
if ('z' === 'a' || 'b' || 'c') { ----}
Will always evaluate to true.
The reason for this is that the || operator will give back the first value which coerces to true without actually coercing the value. The associativity (order which the operators are executed) is left-to-right. This means that the following happens:
First the following will be evaluated because it has higher precedence:
'z' === 'a' // false
then we have the following expression which will be evaluated left to right:
false || 'b' || 'c'
let foo = false || 'b'
console.log(foo)
Then we have the following expression:
let foo = 'b' || 'c'
console.log(foo)
So the whole expression evulates to the string 'b'
After the expression inside the if statement is evaluated to the value 'b' this in turn then gets coerced into a boolean. Every string gets converted to true and that's why the value is always true.
This is because you 'if condition' is take 3 possible option
First say qix === 'a', this is false but you asking about 'b','c' and this option are values true because you are not compare var qix with 'b' or 'c', you only asking to IF condition, that if 'b' or 'c' are value
the operator || it is used so
if(First Condition || Second Condition || third condition){
if at least one of these options is true, then enter here
}
In ECMAScript 2016 incorporates an includes() method for arrays that specifically solves the answer
if (['b', 'c', 'a'].includes(qix)) {
this is false
}
if (['z', 'c', 'a'].includes(qix)) {
this is true
}
Or you can write so
function bla() {
var qix = 'z'
if (qix === 'a' || qix === 'b' || qix === 'c') {
console.log('condition ok!! whats wrong???')
}
}
As we know || (OR Logical Operators) returns true if either operand is true. In your if condition qix === 'a' || 'b' || 'c' in their second and third operand is string and Strings are considered false if and only if they are empty otherwise true. For this reason, your condition is always true.
Need to check qix like qix ==='b'
var qix = 'z'
if (qix === 'a' || qix === 'b' || qix ==='c') {
console.log('condition ok!! whats wrong???')
}
else{
console.log('else')
}
You could use Regex: qix.match(/^(a|b|c)$/)
Should return if qix is equals to a or b or c
var qix = 'z';
if (qix.match(/^(a|b|c)$/)) {
console.log('condition ok!! whats wrong???');
} else {
console.log('else');
}
JavaScript returns true for the second or expression because 'b' is always true.
You need to check each value against qix like so:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators
var qix = 'z'
if (qix === 'a' || qix === 'b' || qix === 'c') {
console.log('condition ok!! whats wrong???')
}

how to use OR operator in nodejs

I am trying to add an if condition; Idea is If I enter the input as print or text with 4 in it, else block should be called.
if ((turnContext.activity.text.indexOf('print') == -1) || (turnContext.activity.text.indexOf('4') == -1))
Now, it goes into the if block as opposed to else.
You have to use: &&. Otherwise when the text is print, the text is not 4 entering the if block.
if ((turnContext.activity.text.indexOf('print') == -1)
&& (turnContext.activity.text.indexOf('4') == -1)) {
// not 4 nor print
} else {
// print or 4
}
The execution goes into else block if text is 'print' or string contains 4 in it.
if (turnContext.activity.text !== 'print' && turnContext.activity.text.indexOf('4') === -1) {
}

Speeding up function that compares strings

I have a function that takes two strings, s and obj. It checks if string obj can be formed from string s by removing 1 char. Implemention works okay but if becomes awfully slow when strings are larger. I was trying to figure out a way to make this piece of code work much faster. Could anyone figure out an implemention?
def check_extra_char(s: String, obj: String): Boolean = {
if(s.length != obj.length+1) return false // Automatically false if obj is not one char smaller than s
for (i <- 0 until s.length)
if (s.take(i) + s.substring(1+i) == obj) return true
return false
}
Keep comparing characters of two strings one by one when mismatch happens skip the mismatch char and keep count of mismatches. If more than 1 mismatch happens check returns false. In the worst case time complexity of the check is O(n).
def check(a: String, b: String): Boolean = {
val smallerStr = if (a.length < b.length) a else b
val largerStr = if (a.length > b.length) a else b
if (largerStr.length - smallerStr.length > 1) false
else {
def countMismatches(aIndex: Int, bIndex: Int, mismatchCount: Int): Int = {
if (bIndex < largerStr.length && aIndex < smallerStr.length) {
if (smallerStr(aIndex) != largerStr(bIndex)) {
if (mismatchCount > 1) mismatchCount
else countMismatches(aIndex, bIndex + 1, mismatchCount + 1)
}
else countMismatches(aIndex + 1, bIndex + 1, mismatchCount)
} else mismatchCount
}
countMismatches(0, 0, 0) <= 1
}
}
REPL
res12: Boolean = true
# check("zapple", "apple")
res13: Boolean = true
# check("apple", "apzple")
res14: Boolean = true
# check("apple", "apzzple")
res15: Boolean = false
# check("apple", "applez")
res16: Boolean = true
# check("apple", "applzz")
res17: Boolean = false
You can speed it up by removing extra s.take(i) + s.substring(i+1). You can go through s and compare index to its counterpart in obj. When you notice the difference, you use your s.take(i) + s.substring(i+1).
def check_extra_char(s: String, obj: String): Boolean = {
if(s.length != obj.length+1) return false // Automatically false if obj is not one char smaller than s
if(s.dropRight(1) == obj) return true // so we don't go outOfIndex later
for (i <- 0 until s.length)
if (s(i) != obj(i)){
if (s.take(i) + s.substring(1+i) == obj) return true else return false
return false
}
The problem with your code is s.take(i) + s.substring(1+i) == obj part. Both String.take(i: Int) and String.substring(start: Int, end: Int) have O(n) time-complexity.
There are numerous ways to avoid that and I am providing one of them in idiomatic scala with tail-recursion,
import scala.annotation.tailrec
def checkExtraChar(source: String, target: String): Boolean = {
val sourceLength = source.length
val targetLength = target.length
// Assumption :: source.length == target.length + 1
#tailrec
def _check(srcIndex: Int, tgtIndex: Int, mismatchFound: Boolean): Boolean = srcIndex match {
case index if index == (sourceLength - 1) && !mismatchFound => true
case index if index == (sourceLength - 1) => source(srcIndex) == target(tgtIndex)
case _ => (source(srcIndex) == target(tgtIndex), mismatchFound) match {
case (true, _) => _check(srcIndex + 1, tgtIndex + 1, mismatchFound)
case (false, false) => _check(srcIndex + 1, tgtIndex, true)
case (false, true) => false
}
}
(sourceLength == targetLength + 1) match {
case false => false
case true => _check(0, 0, false)
}
}
checkExtraChar("qwerty", "werty") // true
checkExtraChar("wqerty", "werty") // true
checkExtraChar("qqwerty", "werty") // false
Got something that should yield some improvements and is more idiomatic.
def check(s: String, obj: String): Boolean = {
if(s.length == obj.length + 1)
streamFromString(s, 0).exists { case(substring) => substring == obj }
else false
}
def streamFromString(s: String, withoutIndex: Int): Stream[String] = {
lazy val next: Stream[String] = if(withoutIndex > s.length - 1) Stream.empty else streamFromString(s, withoutIndex + 1)
s.patch(withoutIndex, Nil, 1) #:: next
}
First of all, you could use patch to create subcollections without the given element; it's defined on Seq so feel free to read up on that.
Secondly, instead of looping mindlessly and reinventing the wheel I decided to create a Stream[String] of the created patches but since Stream is a lazy collection we will create subsequent patches only as we progress through the stream.
You could replace the exists call with collectFirst that takes a PartialFunction for more control over the body but it would be an overkill in this case, imo.
streamFromString(s, 0)
.collectFirst { case (substring) if substring == obj => "" } //could be anything here really, it's all about getting Option.Some
.fold(false)(_ => true)

Apache Spark: Optimization Filter

So this is more of a design question.
Right now, I have a list of patient ids and I need to put them into one of 3 buckets.
The bucket they go into is completely based on the following RDDs
case class Diagnostic(patientID:String, date: Date, code: String)
case class LabResult(patientID: String, date: Date, testName: String, value: Double)
case class Medication(patientID: String, date: Date, medicine: String)
Right now I'm basically going to each RDD 3-4 times per patient_id per bucket to see if it goes into a bucket. This runs extremely slow, is there anything I can do to improve this?
Example is for bucket 1, I have to check if there a diagnostic, for patient_id 1 (even though there are multiple), has a code of 1 and that patient_id 1 has a medication where medicine is foo
Right now I'm doing this as two filters (one on each RDD)....
Ugly code example
if (labResult.filter({ lab =>
val testName = lab.testName
testName.contains("glucose")
}).count == 0) {
return false
} else if (labResult.filter({ lab =>
val testName = lab.testName
val testValue = lab.value
// all the built in rules
(testName == "hba1c" && testValue >= 6.0) ||
(testName == "hemoglobin a1c" && testValue >= 6.0) ||
(testName == "fasting glucose" && testValue >= 110) ||
(testName == "fasting blood glucose" && testValue >= 110) ||
(testName == "glucose" && testValue >= 110) ||
(testName == "glucose, serum" && testValue >= 110)
}).count > 0) {
return false
} else if (diagnostic.filter({ diagnosis =>
val code = diagnosis.code
(code == "790.21") ||
(code == "790.22") ||
(code == "790.2") ||
(code == "790.29") ||
(code == "648.81") ||
(code == "648.82") ||
(code == "648.83") ||
(code == "648.84") ||
(code == "648.0") ||
(code == "648.01") ||
(code == "648.02") ||
(code == "648.03") ||
(code == "648.04") ||
(code == "791.5") ||
(code == "277.7") ||
(code == "v77.1") ||
(code == "256.4") ||
(code == "250.*")
}).count > 0) {
return false
}
true

Resources