w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Parsing file with multiple JSON entries in Scala
You dont have a valid Json file. This would be valid: [ {"name":"John","number":"005","fav_colour":"blue"}, {"name":"Mary","number":"010","fav_colour":"yellow"}, {"name":"Anna","number":"007","fav_colour":"pink"}, {"name":"Dave","number":"003","fav_colour":"purple"} ] Result: Some(List(Map(name -> John, number -> 005, fav_colour -> blue), Map(name -> Mary, number -> 010, fav_colour -> yellow), Map(name -> Anna, number -> 007, fav_colour -> pink), Map(name -> Dave, number -> 003, fav_colour -> purple))) http://www.scalakata.com/522bdbfeebb25c7f5d823c7d

Categories : Json

Parsing command line args and executing a function in scala
I'm not sure why you'd use such unusual syntax to pass return values to the following methods. I would go for a simpler solution that looks like trait ParseUtils { //Why would you return a function here? //Is it a strict constraint you need to fulfill? def parseArgs(args: Array[String]): (String, String) { val jCommander = new JCommander(Args, args.toArray: _*) if (Args.help) { jCommander.usage() System.exit(0) } //This is the return value of the method, a pair of parameters (Args.currencyType, Args.exchangeDenomination) //If you need to embed additional params, you should append them to existing one // or you could create optional values from the Args members... // e.g. (Args.currencyType, Args.exchangeDenomination, Option(Args.someOthe

Categories : Scala

Parsing List of Strings from Scala future JSON response
This will work: response.json "data" \ "id" From the documentation of the \ operator: Lookup for fieldName in the current object and all descendants.

Categories : Json

Parsing an array of json objects to scala objects with pickling
"Collections of non-primitive types are not supported" (yet) https://github.com/scala/pickling/issues/6 From what I can see, scala.pickling is still very rough around the edges. Furthermore, the default pickling format JSONPickleFormat requires some meta-data (the tpe field) and I'm guessing won't be parsing arbitrary JSON objects.

Categories : Java

Scala: How to transform a POJO like object into a SQL insert statement using Scala reflection
In your case, you can use the following codes: val o = new MyDataObj val attributes = o.getClass.getDeclaredMethods.filter { _.getReturnType != Void.TYPE }.map { method => (method.getName, method.getReturnType, method.invoke(o)) } Here I use getDeclaredMethods to get the public methods in the MyDataObj. You need to notice that getDeclaredMethods can not get methods in its parent class. For MyDataObj, getDeclaredMethods will return the following methods: public double MyDataObj.c() public boolean MyDataObj.b() public java.lang.String MyDataObj.d() public int MyDataObj.a() public void MyDataObj.c_$eq(double) public void MyDataObj.d_$eq(java.lang.String) public void MyDataObj.b_$eq(boolean) public void MyDataObj.a_$eq(int) So I add a filter to filter out irrelevant methods.

Categories : SQL

"scala.runtime in compiler mirror not found" but working when started with -Xbootclasspath/p:scala-library.jar
The easy way to configure the settings with familiar keystrokes: import scala.tools.nsc.Global import scala.tools.nsc.Settings def main(args: Array[String]) { val s = new Settings s processArgumentString "-usejavacp" val g = new Global(s) val r = new g.Run } That works for your scenario. Even easier: java -Dscala.usejavacp=true -jar ./scall.jar Bonus info, I happened to come across the enabling commit message: Went ahead and implemented classpaths as described in email to scala-internals on the theory that at this point I must know what I'm doing. ** PUBLIC SERVICE ANNOUNCEMENT ** If your code of whatever kind stopped working with this commit (most likely the error is something like "object scala not found") you can get it working again

Categories : Scala

"error: can't find main class scala.tools.nsc.MainGenericRunner" when running scala in windows
Those weird variables are called parameter extensions. they allow you to interpret a variable as a path to a file/directory and directly resolve things from that path. For example, if %1 is a path to a file dir123456file.txt, %~f1 is the fully qualified path to file.txt, %~p1 is the path to the containing directory dir123456, %~s1 is the path in short name format dir123~1file.txt, and many others... Also, %0 is always set to the path of the currently running script. So: %~fs0 is the fully qualified path, in short name format, to the current script, %%~dpsi is the manual expansion of the FOR variable %%i to a drive letter (d option) followed by the path the containing folder (p option), in short format (s option). Now, this weird looking block of code is a workaround for KB83343

Categories : Windows

scala Duration: "This class is not meant as a general purpose representation of time, it is optimized for the needs of scala.concurrent."
Time can be represented in various ways depending on your needs. I personally have used: Long — a lot of tools take it directly Updated: java.time.* thanks to @Vladimir Matveev The package is designed by the author of Joda Time (Stephen Colebourne). He says it is designed better. Joda Time java.util.Date Separate hierarchy of classes: trait Time case class ExactTime(timeMs:Long) extends Time case object Now extends Time case object ASAP extends Time case class RelativeTime(origin:Time, deltaMs:Long) extends Time Ordered time representation: case class History[T](events:List[T]) Model time. Once I had a global object Timer with var currentTime:Long: object Timer { private var currentTimeValue:Long def currentTimeMs = currentTimeValue def currentTimeMs_=(newTime:Long) { ...

Categories : Scala

Why use template engine in playframework 2 (scala) if we may stay with pure scala
Actually you should ask this question to the dev team, however consider few points: Actually you don't need to use the Play's templating engine at all, you can easily return any string with Ok() method, so according to your link you can just do something like Ok(theDate("John Doe").toString()) Play uses approach which is very typical for other MVC web-frameworks, where views are HTML based files, because... it's web dedicated framework. I can't see nothing wrong about this, sometimes I'm working with other languages/frameworks and can see that only difference in views between them is just a language-specific syntax, that's the goal! Don't also forget, that Play is bilingual system, someone could ask 'why don't use some Java lib for processing the views?' The built-in Scala XML literals a

Categories : Scala

Why can I start the Scala compiler with "java -cp scala-library.jar;. Hello World"?
Short version: you're not using the java compiler, you're using the java runtime. Long version: there's a big difference between javac and java. javac is the java compiler, which takes in java source code and outputs jvm bytecode. java is the java runtime, which takes in jvm bytecode and runs it. But one of the great things about the jvm is that you can generate bytecode for it any which way. Scala generates jvm bytecode without any java source code.

Categories : Java

scala for each loop got error when convert java to scala
override def saveOrUpdateAll(entities: Collection[T]){ import scala.collection.JavaConverters._ val session: Session = getSession() for (entity <- entities.asScala) { session.saveOrUpdate(entity) } } There is no for each loop in scala. You should wrap your collection using JavaConverters and use for-comprehension here. JavaConverters wraps Collection using Wrappers.JCollectionWrapper without memory overhead.

Categories : Java

Scala import statement at top and inside scala class
The difference is: In Option 1 the import is viable for the complete scope. i.e any class/trait/function in com.somePackage can be used anywhere inside/outside the MyClass But in case of Option 2 it can only be used inside the MyClass and not outside it because scope of import is limited to inside MyClass only.

Categories : Scala

Scala Macros: Making a Map out of fields of a class in Scala
Note that this can be done much more elegantly without the toString / c.parse business: import scala.language.experimental.macros abstract class Model { def toMap[T]: Map[String, Any] = macro Macros.toMap_impl[T] } object Macros { import scala.reflect.macros.Context def toMap_impl[T: c.WeakTypeTag](c: Context) = { import c.universe._ val mapApply = Select(reify(Map).tree, newTermName("apply")) val pairs = weakTypeOf[T].declarations.collect { case m: MethodSymbol if m.isCaseAccessor => val name = c.literal(m.name.decoded) val value = c.Expr(Select(c.resetAllAttrs(c.prefix.tree), m.name)) reify(name.splice -> value.splice).tree } c.Expr[Map[String, Any]](Apply(mapApply, pairs.toList)) } } Note also that you need the c.r

Categories : Scala

I have to compile hello.scala which has a import command "org.scala._"
Include the package name when using the scala command and run it against the class file instead of the source code scala org.scala.Hello Like Java, Scala Naming conventions indicate that classes start with an initial uppercase letter for classes, e.g. Hello

Categories : Java

Convert Java Object (that is really a Scala Map) to Scala Map
You are probably trying to cast across class loaders. You can't do this--each class loader maintains its own hierarchy (for those classes not passed off to a common parent loader). Try calling getClassLoader on both your returned map and on a freshly-created one. Incidentally, Map$Map2 is just an implementation detail--a subclass of Map for dealing with two-element maps. It casts just fine normally: scala> val m = Map(1->"one", 2 -> "two"): Object m: Object = Map(1 -> one, 2 -> two) scala> m.getClass res0: Class[_ <: Object] = class scala.collection.immutable.Map$Map2 scala> m.asInstanceOf[scala.collection.immutable.Map[Int,String]] res1: scala.collection.immutable.Map[Int,String] = Map(1 -> one, 2 -> two)

Categories : Scala

Scala: Use Java Constructor with Subclasses in Scala
Why are you using classOf[FXTaskStackElement].asInstanceOf[Class[_]] instead of just classOf[FXTaskStackElement]? Since your second argument is a Class[_], there is no suitable SUBCLASS.

Categories : Java

Scala Yield behaves differently than Scala Map
var characterMap = (for (_ <- 0 until sizeX*sizeY) yield Nil).toArray[List[ActorRef]] Is translated into: var characterMap = (0 until sizeX*sizeY).map(_ => Nil).toArray[List[ActorRef]] and this should work. Nit-picking: They are not equivalent, they are the same. for is just sugar syntax. By the way, you might want to consider: Array.fill[List[ActorRef]](sizeX*sizeY)(Nil)

Categories : Arrays

How to use Scala Virtualized in a Maven project with Scala-2.10?
the groupId of scala-library, scala-compiler is hard-coded into the plugin. The informations (version, ...) of scala-compiler are computed from the scala-library dependencies. You can open a ticket and ask to support other groupId (may be configurable one or not hard-coded). You can fork, made the change, and submit a patch / pull request. UPDATE : scala-mavent-plugin 3.1.6 include the patch from evantill (thanks) So you can override the default scalaOrganization

Categories : Scala

Scala: Use multiple constructors from Java in Scala
Now, with the help from a workmate, i have solved that problem. Instead of classOf[Button] i have to use classOf[Button].asInstanceOf[Class[_]] With this it works fine.

Categories : Java

Parsing huge (~100mb) kml (xml) file taking *hours* without any sign of actual parsing
For a huge XML file, you should not use default XML parser from Nokogiri, because it parses as DOM. A much better parsing strategy for large XML files is SAX. Luckly we are, Nokogiri supports SAX. The downside is that using a SAX parser all logic should be done with callbacks. The idea is simple: The sax parser starts to read a file and let you know whenever it finds something interesting, for example a tag opening, a tag close, or a text. You will be able to bind callbacks to these events, and extract whatever you need. Of course you don't want to use a SAX parser to load all file into the memory and work with it there - this is exactly what SAX want to avoid. You will need to do whatever you want with this file part-by-part. So this is basically a rewrite your parsing with callbacks l

Categories : Ruby

SQL Server 2008 Error - XML parsing: document parsing required too much memory
8191 attributes sounds too much. If looks you are trying to store actual data in the attributes - apparently SQL Server parser has a limitation here. see article here: http://blogs.msdn.com/b/sqlprogrammability/archive/2006/05/23/605299.aspx?Redirected=true When a type is needed for validation, the validator loads its definition from metadata and compiles it into a format suitable for quick validation. In order to prevent any one type from using too much memory, SQL Server caps the size of a compiled type at one megabyte. SQL Server compiles all types and performs this check when the schema is imported in order to avoid accepting types which exceed the limit. I would suggest changing the way you use XML and store you information inside element. see http://www.ibm.com/d

Categories : C#

Parsing a CSV file and having trouble parsing the date
If you don't know the format, you cannot parse. Its really that simple. Both these (5/4/91 and 5/4/1991) will pass any check that will check for valid dates; but only you can know if its 4th of May or 5th of April, and you can only know that if you know what was the intended format. In the end the best you can hope for is a list of valid parsable dates, a list of unparsed (but might be valid) dates. Then you have to manually go through both to see if the dates make sense. To get these lists: try: maybe_valid.append(dateutil.parser.parse(some_date)) except ValueError: probably_invalid.append(some_date)

Categories : Python

class java.lang.RuntimeException/Scala class file does not contain Scala annotation
Looks like the library is configured to compile against Scala 2.9.1. Major versions of Scala are not binary compatible. I put the necessary SBT changes here: https://github.com/mpartel/prestashop-scala-client/commit/e9a1df40bfe35518aaebac899e438b9b6fa6d728

Categories : Scala

Scala: How to pattern match scala.Long and java.lang.Long
It should work straight away: object LongTest { def test(value: Any): Boolean = value match { case l: Long => true case _ => false } def run() { println(test(1L)) println(test(new java.lang.Long(1L))) } } LongTest.run() // true and true It wasn't obvious to me that you want to match classes instead of instance. I'm not sure I understand what you actually want. Like this? object LongTest { def test(clazz: Class[_]): Boolean = clazz == classOf[Long] || clazz == classOf[java.lang.Long] def run() { println(test(1L.getClass)) println(test(new java.lang.Long(1L).getClass)) } } LongTest.run() // true and true Or as a pattern match: def test(clazz: Class[_]): Boolean = clazz match { case q if q == classOf[Long] || q == classOf[j

Categories : Scala

error parsing XML file to google maps (XML Parsing Error: junk after document element)
Your XML creation script is attempting to inform you of errors: <br /> <b>Warning</b>: DOMElement::setAttribute() [<a href='domelement.setattribute'>domelement.setattribute</a>]: string is not in UTF-8 in <b>/home/vozemg0/public_html/soshapal.com/maptst.php</b> on line <b>44</b><br /> <br /> <b>Warning</b>: DOMElement::setAttribute() [<a href='domelement.setattribute'>domelement.setattribute</a>]: string is not in UTF-8 in <b>/home/vozemg0/public_html/soshapal.com/maptst.php</b> on line <b>44</b><br /> <br /> <b>Warning</b>: DOMDocument::saveXML() [<a href='domdocument.savexml'>domdocument.savexml</a>]: output conversion failed due to con

Categories : PHP

Scala: is there a try except in scala?
I don't see any reasons why scala's try-catch doesn't fit your needs: scala> val foo = 0 foo: Int = 0 scala> val bar = try { 1 / foo } catch { case _: Exception => 1 / (foo + 1) } bar: Int = 1

Categories : Scala

what does A#B mean in scala
You may gain type from existing instance of a class: class C { type someType = Int } val c = new C type t = c.someType Or may address to the type directly without instantiating an object: C#someType This form is very usefull for type expressions where you have no space to create intermediate variables. Adding some clarifications as it was suggested in comments. Disclaimer: I have only partial understanding of how Scala's type system works. I'd tried to read documentation several times, but was able to extract only patchy knowledges from it. But I have rich experience in scala and may predict compilers behavior on individual cases well. # called type projection and type projection compliments normal hierarchical type access via . In every type expression scala implicitly uses both

Categories : Scala

Scala: grouped from right?
Then you could implement it by yourself: def rgrouped[T](xs: List[T], n: Int) = { val diff = xs.length % n if (diff == 0) xs.grouped(n).toList else { val (head, toGroup) = xs.splitAt(diff) List(head, toGroup.grouped(n).toList.head) } } Quite ugly, but should work.

Categories : Scala

Can I edit xml using scala?
The Node is immutable and this makes editing it a bit tedious. There are examples in the Scala XML book. val foo = <foo><bar>1</bar><bar>2</bar></foo> foo.copy (child = foo.child.map {case bar: scala.xml.Elem => bar.copy (child = scala.xml.Text ((bar.text.toInt + 1).toString))}) res0: scala.xml.Elem = <foo><bar>2</bar><bar>3</bar></foo>

Categories : Xml

Using generics in Scala
Functionally? Say why some 3rd-party code has the possibility to load those classes will do the following: class ThirdPatyClass(val a: Int) extends SomeClass(a) with ThirdPartyTrait An instance of Class1[ThirdPartyClass] (and a reified corresponding method1) could be used where there would be a type bound of the form [S <: ThirdPartyTrait] whereas Class2 couldn't. And, of course, depending what you do within those methods, you could return an object of type T (or anything that uses T as a bound, e.g. Class[_ <: T]) in Class1.method1. In general, with Class1 you're giving the compiler (and the developer) a possibility to preserve more information on the type of param1, in contrast with Class2 where you can only preserve the compile-time information that param1 is an instance o

Categories : Scala

Is recursion in scala very necessary?
I'm assuming that, since you say "recursion" in your title, you also mean "recursion" in your question, and not "iteration" (which cannot be chosen "over for/while loops", because those are iterative :D). You might be interested in reading Effective Scala, especially the section on control structures, which should mostly answer your question. In short: Recursion isn't "better" than iteration. Often it is easier to write a recursive algorithm for a given problem, then it is to write an iterative algorithm (of course there are cases where the opposite applies). When "tail call optimization" can be applied to a problem, the compiler actually converts it to an iterative algorithm, thus making it impossible for a StackOverflow to happen, and without performance impact. You can read about tail

Categories : Scala

What is "lifting" in Scala?
There are a few usages: PartialFunction Remember a PartialFunction[A, B] is a function defined for some subset of the domain A (as specified by the isDefinedAt method). You can "lift" a PartialFunction[A, B] into a Function[A, Option[B]]. That is, a function defined over the whole of A but whose values are of type Option[B] This is done by the explicit invocation of the method lift on PartialFunction. scala> val pf: PartialFunction[Int, Boolean] = { case i if i > 0 => i % 2 == 0} pf: PartialFunction[Int,Boolean] = <function1> scala> pf.lift res1: Int => Option[Boolean] = <function1> scala> res1(-1) res2: Option[Boolean] = None scala> res1(1) res3: Option[Boolean] = Some(false) Methods You can "lift" a method invocation into a function. This is cal

Categories : Function

What does the tilde (~) mean in this Scala example?
In Scala a ~ b means a.~(b) So it calls the method ~ on a and gives b as an argument. Also note that any operator not ending with : is left-associative. Your example revisited would be: get[Pk[Long]]("sites.id").~( // Help me parse this syntax get[String]("sites.name").~( get[BigDecimal]("sites.latitude").~( get[BigDecimal]("sites.longitude")))) map { case id ~ name ~ latitude ~ longitude => Site(id, name, latitude, longitude) }

Categories : Scala

Scala: who can explain this?
Explanation Exception isn't thrown here: ().asInstanceOf[T] because this is an unchecked cast - JVM cannot verify if it is possible to cast () into T, because it has no information about T due to type erasure. Instead, exception is thrown here Data[Integer](None).get because the result of get is cast into an Integer and that is something that JVM can verify. So, ClassCastException is actually thrown outside of get. BTW, javac always warns about unchecked casts, I don't know why scalac doesn't. Workaround To some extent, it is possible to work around type erasure here using ClassTag and reflection-based casting: import scala.reflect.{ClassTag, classTag} case class Data[T: ClassTag](value: Option[T]) { def get: T = try { doGet } catch { case e: Exception => throw

Categories : Scala

Different types in Map Scala
(a) Scala containers don't track type information for what's placed inside them, and (b) the return "type" for an apply/get method with a simple String parameter/key is going to be static for a given instance of the object the method is to be applied to. This feels very much like a design decision that needs to be rethought.

Categories : Scala

Zero arity in Scala
There are many cases where Scala treats methods and functions differently. The uniform access principle applies to method invocation, since methods are often used to mimic fields on objects, but not to function application. While b is a method of type ()Int, the code b will invoke the method when evaluated, unless the compiler expected a function type where b was used, in which case it will eta-expand the method to a function. Since c is a function of type () => Int, applying it needs to be explicit in all contexts. So, test_type(c()) should compile. The "by-name"-ness of x: => Int doesn't affect these inference/application rules; it only affects when the parameter might be evaluated. scala> object Foo { | def f(): Int = 123 | val g: () => Int = () => 123

Categories : Scala

Using an annotation in Scala
Try this instead @SuppressWarnings(Array("unused")) Also, SuppressWarnings annotation with array initializer is perfectly legal in java: @SuppressWarnings({"unused"}) That's because SuppressWarnings#value is an array. Edit There is some java-specific syntactic sugar. jls 9.7.1: If the element type is an array type and the corresponding ElementValue is not an ElementValueArrayInitializer, then an array value whose sole element is the value represented by the ElementValue is associated with the element ... In other words, it is permissible to omit the curly braces when a single-element array is to be associated with an array-valued annotation type element. But { ElementValuesopt ,opt } is illegal in scala, that's the reason why Array("unused") should be

Categories : Scala

Why no 'break with value' in Scala 2.8+?
The advantage of that over simply creating a def is minimal. def breaking: Station = { for ( (n,st) <- arr ) { if (r < n) return st else r -= n } defaultStation } breaking (Granted, I do have an implementation in my set of tools, but it's not something I use that often.)

Categories : Scala

Difference between >> and >>> in Scala
The >> operator preserves the sign (sign-extends), while >>> zeroes the leftmost bits (zero-extends). -10>>2 res0: Int = -3 -10>>>2 res1: Int = 1073741821 Try it out yourself. This is not necessary in languages like C which has signed and unsigned types, unlike Java, which also has >>> (because it has no unsigned integers).

Categories : Scala

Using `map` function on Map in Scala
In this case, mapValues does seem the more appropriate method to use. You would use the map method when you need to perform a transformation that requires knowledge of the keys (eg. converting a product reference into a product name, say). That said, the map method is more general as it gives you acces to both the keys and values for you to act upon, and you could emulate the mapValues method by simply transforming the values and passing the keys through untouched - and that is where you are going wrong in your code above. To use the map method correctly, you should be producing a (key, value) pair from your function, not just a key: val discGizmos2=gizmos.map{ case (k,v) => (k,v*0.9) } // pass the key through unchanged

Categories : Scala



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.