I want a Scala string to be ${foo.bar} (literally, for testing some variable substitution later).
I tried:
val str = "${foo.bar}"
val str = """${foo.bar}"""
val str = "\${foo.bar}"
val str = "$${foo.bar}"
val str = "$\{foo.bar}"
All giving compile errors like Error:(19, 15) possible missing interpolator: detected an interpolated expression or invalid escape character.
This is not a question about String interpolation (or variable substitution), This normally works without problems. Starting the Scala REPL (Scala 2.11.3, Java 1.8) works as expected. Somewhere there must be an SBT a setting (other than -Xlint or a hidden Xlint) which apparently is causing this behavior (from commandline and IntelliJ).
The s or f interpolator will emit a constant:
$ scala -Xlint
Welcome to Scala 2.12.6 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_144).
Type in expressions for evaluation. Or try :help.
scala> "${foo.bar}"
<console>:12: warning: possible missing interpolator: detected an interpolated expression
"${foo.bar}"
^
res0: String = ${foo.bar}
scala> f"$${foo.bar}"
res1: String = ${foo.bar}
It's usual to use -Xfatal-warnings to turn the warning into an error. IntelliJ reports it as an error at the source position, whereas scalac reports it as a warning, but with a summary error message that will fail a build.
\$ and \{ are invalid escape characters and will not compile. The other versions compile just fine on 2.12.6 though perhaps there are problems in earlier versions.
Related
I have a compiled re.Regex,
which I use as a regex,
but I also want to show it to the user,
for which I need it as a string.
strformat seems not to know how to do that.
re2str.nim:
import re
import strformat
let R_LICENSE = re"(?i)^.*(LICENSE|COPYING).*$"
echo fmt"We are using the regex '{R_LICENSE}' to look for a license file."
compile and run with:
nim compile --run re2str.nim
output:
re2str.nim(6, 9) template/generic instantiation of `fmt` from here
/home/user/.choosenim/toolchains/nim-1.6.4/lib/pure/strformat.nim(568, 23) Error: type mismatch: got <Regex>
but expected one of:
func `$`(x: float | float32): string
...
One solution is, to circumvent the issue
by keeping the string the regex was compiled from
available separately.
str2re.nim:
import re
import strformat
let RS_LICENSE = "(?i)^.*(LICENSE|COPYING).*$"
let R_LICENSE = re(RS_LICENSE)
echo fmt"We are using the regex '{RS_LICENSE}' to look for a license file."
compile and run with:
nim compile --run str2re.nim
output:
...
We are using the regex '(?i)^.*(LICENSE|COPYING).*$' to look for a license file.
I am editing a Groovy (3.0.10) script and I am getting a syntactic error that I do not understand:
When I try this in GroovyConsole, it seems to work just fine.
Why is IntelliJ IDEA complaining? This is with IntelliJ IDEA 2022.1.1.
The snippet in text:
final java.nio.file.Path p;
p.traverse(type: FileType.FILES, nameFilter: ~/^\.deployment$/, maxDepth: 1) { final Path dotDeploymentPath ->
println dotDeploymentPath
}
UPDATE 1
I actually got the same error from Groovy when running the script in our product:
Script4.groovy: 59: [Static type checking] - Cannot call java.nio.file.Path#traverse(java.util.Map <java.lang.String, java.lang.Object>, groovy.lang.Closure) with arguments [java.util.LinkedHashMap <java.lang.String, java.io.Serializable>, groovy.lang.Closure]
# line 59, column 9.
extensionsPath.traverse(type: FileType.FILES, nameFilter: ~/^\.deployment$/, maxDepth: 1) { final Path dotDeploymentPath ->
^
UPDATE 2
I ended up with this which seems to work just fine. I still don't understand why Groovy does not like the options as arguments of the call.
def final traverseOptions = [type: FileType.FILES, nameFilter: ~/^\.deployment$/, maxDepth: 1] as Map<String, Object>;
extensionsPath.traverse(traverseOptions) { final Path dotDeploymentPath ->
So I figured this out. The issue was that I used #CompileStatic at the top of my class. I used #CompileStatic because I misunderstood what it does. I thought it were similar to saying static class in Java. But that is not what it does. What it does instead is this, from the docs: This will let the Groovy compiler use compile time checks in the style of Java then perform static compilation, thus bypassing the Groovy meta object protocol.
(This shows how important it is to provide self contained test case. I should have known better.)
I'm trying to run a scala script through spark shell using the following command:
spark-shell -i myScriptFile.scala
I can get the above command to work when I have single-line commands, but if I have any line-breaks in the script (for readability), the spark-shell (or REPL?) interprets each of the lines as a full action. Here is a sample of my script:
import org.apache.spark.sql.types._
import java.util.Calendar
import java.text.SimpleDateFormat
// *********************** This is for Dev ***********************
val dataRootPath = "/dev/test_data"
// *********************** End of DEV specific paths ***************
val format = new SimpleDateFormat("yyyy-MM-dd")
val currentDate = format.format(Calendar.getInstance().getTime()).toString
val cc_df = spark.read.parquet(s"${dataRootPath}/cc_txns")
.filter($"TXN_DT" >= date_sub(lit(current_date), 365) && $"TXN_DT" < lit(current_date))
.filter($"AMT" >= 0)
....
System.exit(0)
When running the spark-shell with this script, I get the following error:
<console>:1: error: illegal start of definition
The syntax for the script is correct because if I start the shell and manually paste this code in with :paste, everything works fine.
I have tried ending all multi-line commands with a backslash \ but that didn't work either.
Does anyone have any suggestions on how I can keep my script multi-lined but still be able to pass it the spark-shell as an argument to start with?
Try:
val x = { some statement ...
. some statement2 ...
. idem ditto
. ...
}
You can do :paste then paste (Ctrl+V). After pasting, do Ctrl+D in the shell.
Using Scala Scripting Engine in 2.11 Milestone 7, how do I get a typed value back from the script engine? I'm getting error messages like "mypackage.Holler cannot be cast to mypackage.Holler".
Here is the use case (reduced to essentials). I want to use scripts to prepare and configure objects of a standard type that I will process in my main program. I have a trait:
package mypackage
trait Holler {
def shout: Unit
}
I have a user script in Scala, saved in the file /home/me/Foo.scala
object Foo extends mypackage.Holler {
def shout: Unit = println("Hello World!")
}
When I run this script using IMain.eval(Reader), I expect that the object Foo will be returned since it is the result of the last statement. Here is a program, including a couple useful printouts to run the script:
package mypackage
import javax.script.ScriptEngineManager
import scala.tools.nsc.interpreter.IMain
object Runner {
def main(args: Array[String]): Unit = {
// Create the script engine
val javaxEngine = new ScriptEngineManager().getEngineByName("scala")
val scalaEngine = javaEngine.asInstanceOf[IMain]
// Configure script engine to use the Java classpath
val useJavaClassPath = scalaEngine.settings.usejavacp.tryToSet(List("true"))
println("Use Java CP? " + useJavaClassPath)
val script = new java.io.FileReader("/home/me/Foo.scala")
val result = scalaEngine.eval(script)
println("Script Result Type: " + result.getClass.getName)
println("Defined Symbols: " + scalaEngine.definedSymbolList)
val myHoller = result.asInstanceOf[mypackage.Holler]
}
}
The script runs just fine under the script engine. But the result cannot be cast to Holler. The output of this program is as follows:
Use Java CP? Some(List(true))
Script Result Type: $line3.$read$$iw$$iw$Foo$
Defined Symbols: List(value engine, object iw$Foo)
Exception in thread "main" java.lang.ClassCastException: $line3.$read$$iw$$iw$Foo$ cannot be cast to mypackage.Holler
This tells me that the classpath is successfully recognized by the script engine, and that the Foo object is being constructed. But the trait mypackage.Holler (from the common classpath) inside the script is different from the trait mypackage.Holler in the main program.
If I add the following lines to the script:
Foo.shout
val result: Holler = Foo
I see:
The shout method being exercised ("Hello World!" prints out),
"result" is added to the list of defined symbols
result is clearly compatible with type Holler.
I can bind a "catcher" object to the script engine. Its code looks like this:
package mypackage
class Catcher {
var item: Holler = null
}
And I bind with
val mycatcher = new Catcher
scalaEngine.bind("catcher", mycatcher)
scalaEngine.eval("catcher = Foo")
Now "catcher" shows up in the list of defined symbols to the script engine and I can use the catcher to go into the script engine with a command like
scalaScriptEngine.eval("catcher.item = result")
But then I get strange "compile time" ClassCastExceptions saying:
mypackage.Holler cannot be cast to mypackage.Holler
If I make the "item" in the Catcher an Any, then I don't get the exception until I do
mycatcher.item.asInstanceOf[Holler]
in the main program. But I still get pretty much the same exception. It is as if two incompatible class loaders are being used with the same classpath. So how, from the main program, do I access the Foo object as an instance of Holler (which it clearly implements in the script engine)?
I'm using jBoss Rules.But I run in to memory issues after using JBoss rules. Using a profiling tool I collected heap dump
and I got the result as :
One instance of "org.drools.reteoo.ReteooStatefulSession" loaded by
"sun.misc.Launcher$AppClassLoader # 0x7f899fdb6d88" occupies 657,328,888 (78.91%) bytes.
The memory is accumulated in one instance of "org.drools.reteoo.ReteooStatefulSession"
loaded by "sun.misc.Launcher$AppClassLoader # 0x7f899fdb6d88".
Keywords
sun.misc.Launcher$AppClassLoader # 0x7f899fdb6d88
org.drools.reteoo.ReteooStatefulSession
The code I used for JBoss rules is given below.
kbase= KnowledgeBaseFactory.newKnowledgeBase();
ksession= kbase.newStatefulKnowledgeSession();
final String str = CISMSRemotingUtils.getFullConfigFilePath("change-set.xml") ;
final String filePath = str.replaceAll(" ", "%20");
aconf = KnowledgeAgentFactory .newKnowledgeAgentConfiguration();
aconf.setProperty("drools.agent.newInstance", "false");
kagent = KnowledgeAgentFactory.newKnowledgeAgent( "Agent", aconf);
kagent.applyChangeSet( ResourceFactory.newFileResource(filePath) );
kbase = kagent.getKnowledgeBase();
ksession= kbase.newStatefulKnowledgeSession();
sconf =ResourceFactory.getResourceChangeScannerService().newResourceChangeScannerConfiguration();
sconf.setProperty( "drools.resource.scanner.interval", "3600");
ResourceFactory.getResourceChangeScannerService().configure( sconf );
ResourceFactory.getResourceChangeNotifierService().start();
ResourceFactory.getResourceChangeScannerService().start();
This piece of code is given in the class constructor and rules are fired inside this class
ksession.insert(data);
ksession.fireAllRules();
I'm using drools 5.4.0
Can anyone help me to identify the problem?