I've got this line of code:
console.log "source = #{#source.alignment} unit = #{unit.alignment}: " + (#source.alignment is not unit.alignment)
This is printing this out to the console:
source = good unit = bad: false
Why is it printing "false"? Shouldn't it be printing "true"? Logically, good "is not" bad.
This
console.log "source = #{#source.alignment} unit = #{unit.alignment}: " + (#source.alignment != unit.alignment)
prints
source = good unit = bad: true
as expected.
What's the difference? When should I use is not?
It's an operator precedence issue:
a is not b => a is (not b)
That means that this compiles to the next js:
a === !b
In your case, b is unit.alignment, and as that var exists and its value is not falsy, !unit.alignment returns false
To solve your problem, check out isnt operator in Coffeescript docs
Related
I'm developing a scala application with play framework, but i got something strange.
i can't stop the execution nor throwing an error in order to send a response for the client, it always continue the code and it always returning okay, however i made a dummy function that it should return a bad request but unfortunately it is returning OK here is what i wrote. any help will be appreciated
def foo(locale: String, orderId: Int) = Action { implicit request => {
val x=4+7;
if(x==11){
BadRequest(JsonHelper.convertToJson("Bad bad it is really bad "))
}
OK(JsonHelper.convertToJson("Well Done"))
}
}
the above code returning OK Well done.
To make your code return a BadRequest, add an else:
def foo(locale: String, orderId: Int) = Action { implicit request => {
val x = 4 + 7;
if (x == 11)
BadRequest(JsonHelper.convertToJson("Bad bad it is really bad "))
else // <---
OK(JsonHelper.convertToJson("Well Done"))
}}
Your problem is your if without curly braces.
refered to this link :https://docs.scala-lang.org/style/control-structures.html#curly-braces
if - Omit braces if you have an else clause. Otherwise, surround the
contents with curly braces even if the contents are only a single
line.
so you can just suuround the BadRequest with curly braces or add an else statement between your Bad and OK instruction. Be careful, don't forget the indentation !
edit 20/12/2017 >> un scala the last instruction is implicitly returned. Your last instruction is OK, so it returns OK.
Add explicit return statement in your if block or add an else statement.
I don't have a clue why this happens, but here is code of the file:
express = require "express"
fs = require "fs"
router = express.Router()
module.exports = (config) ->
fileRe = /^([a-zA-Z0-9-_]+)(\.(png|jpg|jpeg))?$/i
router.get '/:file', (req, res) ->
file = req.params.file
if !file or !fileRe.test file
return res.error(404).send "404 Not Found"
fileInfo = fileRe.exec file
if !fileInfo[3]
# .png is default if extension is ommited
# abc => abc.png, but abc.jpg will stay
file += ".png"
if fs.access config.destination + file, fs.F_OK, (err) ->
if err
res.status(500).send "An error occured"
else
if !fileInfo[3] or fileInfo[3] == "png"
ct = "image/png"
else if fileInfo[3] == "jpg"
ct = "image/jpg"
opts =
lastModified: false
headers:
"Content-Disposition": "inline; filename=\"#{file}\""
"Content-Type": ""
return router
I get the following error
/home/kindlyfire/Webroot/uplimg-server/src/web/view.coffee:24:9: error: unexpected if
if fs.access config.destination + file, fs.F_OK, (err) ->
^^
I looked at the spaces, no problem there. Has anybody an idea about what it might be ?
What you wrote is not valid coffeescript. Specifically, it is the commas on the line the error is pointing you to. I'd offer info on how to fix it, but I can't even tell what you were trying to accomplish here. You have to provide a way for the compiler (not to mention readers) to be able to tell, unambiguously, what divisions you want in your code:
# fine
if foo then (a, b) -> c
# also fine
if foo
(a, b) ->
c
# ??
if foo (a, b) -> c
# ????
if foo a, b -> c
Repro of the bug. Note that this is a good example of how to make a minimum reproduction of the problem. I highly, highly recommend you read a coffeescript style guide and discipline yourself to follow it. Which one is not terribly important, its the consistency that matters. Do not just randomly copy-paste stuff from the internets into your code, re-write it to follow the same style as the rest of your code. Doing so will often have the added benefit of realizing how the snippet you copied is working.
When calling a macro I have the following error in response:
code=SUB_ASSIGN
Message = Assignment failed
Location= Reduce at line 65 of file mymacro.zms
the line 65 is
/** Reduce */
var b = gda(GDA).reduce {
table: 'myTable',
start: __parameters.key + '##',
stop: __parameters.key + '##a',
page: {
pageNumber: 0,
pageSize: 100000000
},
initialValue: {
tR: tR,
count: 0
},
'columns': ['col1', 'col2'],
'function': usr:myfunc
};
Seen on Android SDK (not on JS SDK) and not 100% reproducible.
What's the meaning of this error and how can I correct it?
Thanks.
The (poorly documented) meaning of SUB_ASSIGN is that an assignment with a syntax like a.b.c = d; has failed.
More precisely, the left hand operand is made of several hierarchical sub-parts (in my example a, b, and c).
Note that SUB_ASSIGN reports a programming error, which you should guard against :
when assigning a.b.c, at least a.b must exist and be not null.
A code pattern such as this one should do the trick:
// the ?? operator returns true when an expression is defined and not null
if (! a.b ??) {
a.b = {};
}
...
a.b.c = 0;
or, shorter, if applicable :
if (! a.b ??) {
a.b = {c:0};
}
The relevant documentation for '??' can be found in the official API reference documentation
As your code does not include such a statement anyway, I suppose that the actual error does not lie in your reduce call, but inside your callback function (usr:myfunc).
Moreover, to ease further debugging :
the error report you gave does not seem to contain the full stack trace up to the callback of the 'reduce' call. This might very well be a missing/not-yet-implemented feature of the zetapush API (which you could request...).
I have a function in scala which has no return-value (so unit). This function can sometimes fail (if the user provided parameters are not valid). If I were on java, I would simply throw an exception. But on scala (although the same thing is possible), it is suggested to not use exceptions.
I perfectly know how to use Option or Try, but they all only make sense if you have something valid to return.
For example, think of a (imaginary) addPrintJob(printJob: printJob): Unit command which adds a print job to a printer. The job definition could now be invalid and the user should be notified of this.
I see the following two alternatives:
Use exceptions anyway
Return something from the method (like a "print job identifier") and then return a Option/Either/Try of that type. But this means adding a return value just for the sake of error handling.
What are the best practices here?
You are too deep into FP :-)
You want to know whether the method is successful or not - return a Boolean!
According to this Throwing exceptions in Scala, what is the "official rule" Throwing exceptions in scala is not advised as because it breaks the control flow. In my opinion you should throw an exception in scala only when something significant has gone wrong and normal flow should not be continued.
For all other cases it generally better to return the status/result of the operation that was performed. scala Option and Either serve this purpose. imho A function which does not return any value is a bad practice.
For the given example of the addPrintJob I would return an job identifier (as suggested by #marstran in comments), if this is not possible the status of addPrintJob.
The problem is that usually when you have to model things for a specific method it is not about having success or failure ( true or false ) or ( 0 or 1 - Unit exit codes wise ) or ( 0 or 1 - true or false interpolation wise ) , but about returning status info and a msg , thus the most simplest technique I use ( whenever code review naysayers/dickheads/besserwissers are not around ) is that
val msg = "unknown error has occurred during ..."
val ret = 1 // defined in the beginning of the method, means "unknown error"
.... // action
ret = 0 // when you finally succeeded to implement FULLY what THIS method was supposed to to
msg = "" // you could say something like ok , but usually end-users are not interested in your ok msgs , they want the stuff to work ...
at the end always return a tuple
return ( ret , msg )
or if you have a data as well ( lets say a spark data frame )
return ( ret , msg , Some(df))
Using return is more obvious, although not required ( for the purists ) ...
Now because ret is just a stupid int, you could quickly turn more complex status codes into more complex Enums , objects or whatnot , but the point is that you should not introduce more complexity than it is needed into your code in the beginning , let it grow organically ...
and of course the caller would call like
( ret , msg , mayBeDf ) = myFancyFunc(someparam, etc)
Thus exceptions would mean truly error situations and you will avoid messy try catch jungles ...
I know this answer WILL GET down-voted , because well there are too much guys from universities with however bright resumes writing whatever brilliant algos and stuff ending-up into the spagetti code we all are sick of and not something as simple as possible but not simpler and of course something that WORKS.
BUT, if you need only ok/nok control flow and chaining, here is bit more elaborated ok,nok example, which does really throw exception, which of course you would have to trap on an upper level , which works for spark:
/**
* a not so fancy way of failing asap, on first failing link in the control chain
* #return true if valid, false if not
*/
def isValid(): Boolean = {
val lst = List(
isValidForEmptyDF() _,
isValidForFoo() _,
isValidForBar() _
)
!lst.exists(!_()) // and fail asap ...
}
def isValidForEmptyDF()(): Boolean = {
val specsAreMatched: Boolean = true
try {
if (df.rdd.isEmpty) {
msg = "the file: " + uri + " is empty"
!specsAreMatched
} else {
specsAreMatched
}
} catch {
case jle: java.lang.UnsupportedOperationException => {
msg = msg + jle.getMessage
return false
}
case e: Exception => {
msg = msg + e.getMessage()
return false
}
}
}
Disclaimer: my colleague helped me with the fancy functions syntax ...
I'm trying to see if its possible to test for a certain result specific to a boolean value in an SQL database.
if($result = $mysqli->query("SELECT * FROM `work_orders` WHERE `is_open` = '1' "))
{
show_workorder($result);
}
I would then want to execute:
#TRUE allows this to show
if($result = True){
echo "<p> No current work orders are open. Good Work !</p>\n";
return;
}
If i change database in work_orders.is_open , the boolean is 0, meaning its "not open" .. the if statement for TRUE above, still shows...
I am sure that I'm missing something.
Seems I have solved my own question:
the if statement should just test for rows that were returned or not.
if($result->num_rows == 0)
this would allow it to show if there is nothing returned. If results are returned then it will continue moving forward.