BUGs error message - winbugs

I am new to WinBUGS/OpenBUGS and having difficulty de-bugging my code. The error message is "expected variable name". However I could not find any variable, which is not defined. My code is as follows:
model {
y[1:3]~dmulti(p[1:3],M)
p[1:3]~ddirch(alpha[])
}
list (
y=c(383465, 467074, 142852), M=993391
)

I have found the errors as follows:
1.The space can't follow the "list". Therefore, it should be
list(
y=c(383465, 467074, 142852), M=993391
)
2.The full codes should add the definition for alpha[] as follows:
model {
y[1:3]~dmulti(p[1:3],M)
p[1:3]~ddirch(alpha[])
for (r in 1:3){alpha[r]<-1}
}
list(
y=c(383465, 467074, 142852), M=993391
)
This seems a small problem, which occurs in the newcomers!!

Related

Keep getting 'Unexpected identifier' when running tests

I am trying to copy a tutorial for a Wordle solving bot but its just not going well. whenever I try to run a test on the code it doesn't work at certain points, I'll either get 'Uncaught SyntaxError: Unexpected identifier'. I'm doing this on UIlicious.
Here's what I've got so far:
I.goTo("https://www.powerlanguage.co.uk/wordle/")
I.click("reject")
I.see("Guess the Wordle")
I.click('/html/body', 40, 80)
let guessWord = null
for(Let r=0 ; r<6 ; ++r) {
guessWord = solver.suggestWord(gameState)
I.type(guessWord);
I.pressEnter()
I.wait(2)
}
let rowList = document.querySelector("game-app").shadowRoot. //
querySelector("game-theme-manager"). //
querySelector("#board").querySelectorAll("game-row");
you are probably referring to the article I wrote here : https://uilicious.com/blog/automate-wordle-via-uilicious/
This test script, is designed specifically to use uilicious.com, so you will need to edit and run it through the platform.
You can do so via the snippet here : https://snippet.uilicious.com/test/public/N5qZKraAaBsAgFuSN8wxCL
If you have syntax error there, do let me know with a snippet link - and I will try to help you respectively.
Also the snippet you provided so far, excludes the "solver" class which was initialised much further down.

How to indiciate a failure for a function with a void result

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 ...

Play! + Scala: Split string by commnas then Foreach loop

I have a long string similar to this:
"tag1, tag2, tag3, tag4"
Now in my play template I would like to create a foreach loop like this:
#posts.foreach { post =>
#for(tag <- #post.tags.split(",")) {
<span>#tag</span>
}
}
With this, I'm getting this error: ')' expected but '}' found.
I switched ) for a } & it just throws back more errors.
How would I do this in Play! using Scala?
Thx in advance
With the help of #Xyzk, here's the answer: stackoverflow.com/questions/13860227/split-string-assignment
Posting this because the answer marked correct isn't necessarily true, as pointed out in my comment. There are only two things wrong with the original code. One, the foreach returns Unit, so it has no output. The code should actually run, but nothing would get printed to the page. Two, you don't need the magic # symbol within #for(...).
This will work:
#for(post <- posts)
#for(tag <- post.tags.split(",")) {
<span>#tag</span>
}
}
There is in fact nothing wrong with using other functions in play templates.
This should be the problem
#for(tag <- post.tags.split(",")) {
<span>#tag</span>
}

Play! 2 scala: Adding an error to a form in the controller code proper

I have some validation on input data which I really would prefer to handle in the controller code, because:
It only applies in very specific circumstances, so cluttering the verifying function in the form definition would lower code cohesion.
It produces collateral results which I need to use elsewhere in the controller.
What's a clean way form producing a new Form like the one just bound with an additional (field or general) error message in the success branch of Form.fold?
To illustrate, I would like something like the (non-existent) Form.withError method I'm calling here:
val form= myForm.bindFromRequest
form.fold(
errors => BadRequest(view(errors))
{
case(data, button) =>
button match {
case Some("save") =>
val r= costlyFunction(data)
if (r.isOk) {
doSomethingWith(r)
Ok(...)
}
else {
val f= form.withError("my custom error")
BadRequest(view(f))
}
case ...
}
}
Found it myself:
val f= Form(form.mapping, form.data,
Seq(new play.api.data.FormError("error.key", "my error")), form.value)
Apologies for the noise -- leaving it here in case someone else gets stuck as I did.
Shorter alternative:
val f= form.withError("error.key", "my error")), form.value)

How to further improve error messages in Scala parser-combinator based parsers?

I've coded a parser based on Scala parser combinators:
class SxmlParser extends RegexParsers with ImplicitConversions with PackratParsers {
[...]
lazy val document: PackratParser[AstNodeDocument] =
((procinst | element | comment | cdata | whitespace | text)*) ^^ {
AstNodeDocument(_)
}
[...]
}
object SxmlParser {
def parse(text: String): AstNodeDocument = {
var ast = AstNodeDocument()
val parser = new SxmlParser()
val result = parser.parseAll(parser.document, new CharArrayReader(text.toArray))
result match {
case parser.Success(x, _) => ast = x
case parser.NoSuccess(err, next) => {
tool.die("failed to parse SXML input " +
"(line " + next.pos.line + ", column " + next.pos.column + "):\n" +
err + "\n" +
next.pos.longString)
}
}
ast
}
}
Usually the resulting parsing error messages are rather nice. But sometimes it becomes just
sxml: ERROR: failed to parse SXML input (line 32, column 1):
`"' expected but `' found
^
This happens if a quote characters is not closed and the parser reaches the EOT. What I would like to see here is (1) what production the parser was in when it expected the '"' (I've multiple ones) and (2) where in the input this production started parsing (which is an indicator where the opening quote is in the input). Does anybody know how I can improve the error messages and include more information about the actual internal parsing state when the error happens (perhaps something like a production rule stacktrace or whatever can be given reasonably here to better identify the error location). BTW, the above "line 32, column 1" is actually the EOT position and hence of no use here, of course.
I don't know yet how to deal with (1), but I was also looking for (2) when I found this webpage:
https://wiki.scala-lang.org/plugins/viewsource/viewpagesrc.action?pageId=917624
I'm just copying the information:
A useful enhancement is to record the input position (line number and column number) of the significant tokens. To do this, you must do three things:
Make each output type extend scala.util.parsing.input.Positional
invoke the Parsers.positioned() combinator
Use a text source that records line and column positions
and
Finally, ensure that the source tracks positions. For streams, you can simply use scala.util.parsing.input.StreamReader; for Strings, use scala.util.parsing.input.CharArrayReader.
I'm currently playing with it so I'll try to add a simple example later
In such cases you may use err, failure and ~! with production rules designed specifically to match the error.