w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Failing Polymorphic de-serialization in Jackson with Scala module when polymorphic types are within a Seq()
I believe there a two bugs here one related to Map the other to Seq(tuple) 1) Maps not exporting the type information on serialization 2) Seq(Tuple) ignores type information on De-Serialization Workround: - Use a wrapper class to replace tuple. @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "type") @JsonSubTypes(Array( new Type(value = classOf[B], name = "B"), new Type(value = classOf[C], name = "C"))) trait A{} case class B(value : Double) extends A case class C(value : String) extends A case class ContainerWithMap( results: Map[String, A]) case class ContainerWithTupleSeq( results: Seq[(String, A)]) case class ContainerWithWrappedSeq( results: Seq[WrapperClass]) case class WrapperClass(s : String, a : A) class ATest extends

Categories : Json

Scala v 2.10: How to get a new instance of a class (object) starting from the class name
There is a very simple answer: scala> def createInstance(clazzName: String) = Class.forName(clazzName).newInstance createInstance: (clazzName: String)Any scala> createInstance("java.lang.String") res0: Any = "" If it works for you, everything is fine. If it don't, we have to look into your class loader. This is usually the point when things will get dirty. Depending in what you want to do, look into: The cake pattern, if you want to combine your classes during compile time OSGi when you want to build a plugin infrastructure (look here for a very simple example) Google guice, if you really need dependency injection (e.g. when mixing Scala and Java code) and the cake pattern does not work for you

Categories : Scala

Add method to any instance of a class at runtime
You can't do this, basically. You can't add fields and methods to types at execution time in Java. You may want to create your own type to wrap the original type and maintain a Map<String, Objet> for additional values: public final class Annotated<T> { private final Map<String, Object> annotations = new HashMap<>(); private final T wrapped; public Annotated(T wrapped) { this.wrapped = wrapped; } public T getWrapped() { return wrapped; } public void setAnnotation(String name, Object value) { annotations.put(name, value); } public Object getAnnotation(String name) { return annotations.get(name); } } That won't help you add methods of course, but it's not clear why you'd want to... my guess

Categories : Java

How to add a SerialVersionUID to a Class[_] instance in Scala?
If I compile the following class: @SerialVersionUID(1L) object MyClass { } $ scalac MyCLass.scala $ javap -cp MyClass$ Compiled from "MyClass.scala" public final class MyClass$ { public static final MyClass$ MODULE$; public static final long serialVersionUID; public static {}; } I'm not familiar with javaassist, but this shows where you need to put the additional field, FWIW.

Categories : Scala

How to replace an instance of a base class with a derived one during runtime
Issue #01 - Value Types and Reference Types In C++, objects are value types - structures of their components. To make a reference to the value as it lives in memory, you use a pointer. C# is not like this. In C#, objects are references by default, there are no values types as far as objects are concerned. (That was a bit of a lie to make this simpler) That means that in C# this: ErrorClass error = new ErrorClass(); Is the equivalent of this in C++: ErrorClass* error = new ErrorClass(); The key difference however, is that there is no way to dereference a C# reference like you can dereference a pointer in C++. Additionally this in C#: error.ErrorNumber = 0; Is equivalent to this in C++: error->ErrorNumber = 0; Effectively what is happening is that all the pointer magic is be

Categories : C#

Is it possible in Play 2.1 to convert a JsValue to a case class instance if you only know the name of the case class at the runtime?
You need to implement a PathBinder...this should help out http://www.richard-foy.fr/blog/2012/04/09/how-to-implement-a-custom-pathbindable-with-play-2/

Categories : Scala

"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

Polymorphic instantiation in Scala using TypeTag and ClassTag
TypeTag is not yet a replacement for Manifest because it's a part of experimental and unstable Scala reflection. You definitely shouldn't use it for production as of now. For the use case you showed, where only runtime class is needed (not full type information with generics etc.), Scala 2.10 introduced ClassTag, which you can use like this: def newInstance[T: ClassTag] = implicitly[ClassTag[T]].runtimeClass.newInstance.asInstanceOf[T] or: def newInstance[T](implicit ct: ClassTag[T]) = ct.runtimeClass.newInstance.asInstanceOf[T] Anyway, Manifest isn't deprecated yet, so I guess you can still use it. EDIT: Using TypeTag to achieve the same: import scala.reflect.runtime.universe._ def newInstance[T: TypeTag] = { val clazz = typeTag[T].mirror.runtimeClass(typeOf[T]) clazz.n

Categories : Scala

How to create an object attribute from polymorphic type in scala
Your problem is in that you are returning loaded(className) which is of type Bar, not T as is required by your function type signature. Unfortunately, you cannot encode such dependence between types of map keys and values, at least not with the standard map collection. You have to perform explicit cast. Here is a working example: import scala.reflect.ClassTag class Bar class FooBar extends Bar object Test { val classMap = scala.collection.mutable.Map[Class[_], Bar]() def getInstance[T <: Bar : ClassTag]: T = { val ct = implicitly[ClassTag[T]] classMap get ct.runtimeClass match { case Some(bar) => bar.asInstanceOf[T] case None => val instance = ct.runtimeClass.newInstance().asInstanceOf[T] classMap(ct.runtimeClass) = instance ins

Categories : Scala

Looking for a good example of polymorphic serialization deserialization using jackson with scala
Ok, Got it here is a working example with scala based on Deserialize JSON with Jackson into Polymorphic by Programmer Bruce: import org.codehaus.jackson.annotate.JsonSubTypes.Type import org.codehaus.jackson.annotate.{JsonSubTypes, JsonTypeInfo} @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include= JsonTypeInfo.As.PROPERTY, property = "type" ) @JsonSubTypes(Array( new Type(value= classOf[Cat] , name = "cat"), new Type(value= classOf[Dog] , name = "dog") ) ) abstract class Animal { var name:String ="" } class Dog extends Animal{ var breed= "German Shepherd" var color = "brown" } class Cat extends Animal{ var favoriteToy:String = "nothing" } class Zoo { var animals = new Array[Animal](5) } import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility import org.c

Categories : Scala

Is it possible to obtain an yaml property at runtime?
Yes yaml.load() basically returns a java object so you can simply cast it to the appropriate type and get what you need: Yaml yaml = new Yaml(); String input = "{appName: myAppName, appVersion: myAppVerison}"; Map yamlMap = (Map)yaml.load(input); assertEquals("myAppName", yamlMap.get("appName"));

Categories : Java

How can you obtain the ilplotcube rotatation information at runtime?
Each driver creates a clone of the global scene which is constantly synched and updated with changes in its source. The rotation is done on the clone. I have not tested it, but I think, you can query objects (e.g. the plot cube) in the clone by panel.GetCurrentScene().First<ILPlotCube>(/*your filter if needed*/) This instance will reflect all changes done by the user.

Categories : Misc

Obtain Spring bean dependencies @ Runtime
You could use a ReaderEventListener to build the object grahp when the context startup. For example: public class TrackingReaderEventListener extends EmptyReaderEventListener { private Map<String, ComponentDefinition> components = new HashMap<String, ComponentDefinition>(); @Override public void componentRegistered(ComponentDefinition componentDefinition) { components.put(componentDefinition.getName(), componentDefinition); } public Map<String, ComponentDefinition> getComponentMap() { return components; } public static void main (String[] args) { TrackingReaderEventListener listener = new TrackingReaderEventListener(); ClassPathXmlApplicationContext context = new AppContext("applicationContext.xml", listene

Categories : Java

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

Is it possible to obtain the parse tree to a method in scala?
If your question is whether you can lift a method defined in a Scala object (the closest thing there is to a "static method") to a function, the answer is yes: object O { def oMethod(i: Int): String = i.toString val oFunction = oMethod _ } scala> O.oMethod(23) res0: String = 23 scala> O.oFunction(23) res1: String = 23

Categories : Scala

Obtain the symbol that a "super" call refers to in Scala
I think using of self type annotations and multiple inheritance will serve you: trait HelperTrait { def helperMethod {println("calling helperMethod of HelperTrait")} } trait PublicInterface { this: HelperTrait => def useHelperMethod { println("calling useHelperMethod of PublicInterface") helperMethod } } class ImplementationClass extends PublicInterface with HelperTrait var obj = new ImplementationClass() obj.useHelperMethod obj.helperMethod

Categories : Scala

How would one create a proper polymorphic Functor instance failing on unsafeVacuous?
It's certainly possible if you're willing to give a Functor instance that does not adhere to the functor laws (but is total): {-# LANGUAGE GADTs, KindSignatures #-} import Data.Void import Data.Void.Unsafe data F :: * -> * where C :: F Void D :: F a instance Functor F where fmap f _ = D wrong :: () wrong = case (unsafeVacuous C :: F Int) of D -> () Now evaluating wrong results in a run-time exception, even though the type-checker considers it total. Edit Because there's been so much discussion about the functoriality, let me add an informal argument why a GADT that actually performs analysis on its argument cannot be a functor. If we have data F :: * -> * where C :: ... -> F Something ... where Something is any type that isn't a plain variable, then we can

Categories : Haskell

Obtain instance weights from AdaBoostM1 in Weka
No, Weka's AdaboostM1 does not have such feature. But you could inherit the AdaBoostM1 class, copy the AdaBoostM1#buildClassifierUsingResampling method from the source, and paste it in your subclass and manipulate the double[] weights variable (as seen in line 513).

Categories : Java

Can one call an instance's method inside a class without recreating the instance within class' scope?
You have to import the global $errorhandler variable into your local scope: class AnotherClass { function __construct() { global $errorhandler; try { $not_possible = 1/0; } catch (Exception $e) { $errorhandler->log($e); # Doesn't work } } } P.S. 1/0 is not an exception, it's a runtime error. You can't catch those with a try/catch block.

Categories : PHP

Is it possible to obtain multiple elements on a page simultaneously from a WebDriver instance?
Just adding to @acdcjunior's comment that the WebDriver class is not thread safe; I've found the following issue which I believe is related to this question: Issue 6592: IE Driver returns 404: File not found If it is the same issue you're having, then one solution is to synchronise your calls the WebDriver. I solved this by creating a SynchronizedInternetExplorerDriver.java class, which synchronises calls to the underlying WebDriver. Let me know if this helps (using this SynchronizedInternetExplorerDriver, you'll (at least) be able to rule out thread issues as the cause). Code Snippet: public class SynchronizedInternetExplorerDriver extends InternetExplorerDriver { ... @Override protected Response execute(String driverCommand, Map<String, ?> parameters) { synchr

Categories : Java

Can a class instance created by another class instance access the creator's members?
You can do this, and you've almost done it, with one minor problem: class Created(): def __init__(self, creator): self.parameter = self.creator.parameter There is no self.creator. If you never need to access it again after this __init__ call, just use the creator parameter directly: class Created(): def __init__(self, creator): self.parameter = creator.parameter If you need it later, store it as self.creator, and then of course you can access it there: class Created(): def __init__(self, creator): self.creator = creator self.parameter = self.creator.parameter … although you probably don't even need to copy over parameter in that case, because you can always get to it as self.creator.parameter. This is a very common pattern. The only

Categories : Python

Make derived class instance given base class instance in Java
Make Parent instances immutable and you can just delegate to an instance of Parent. See Effective Java, Item 16: Favor composition over inheritance.

Categories : Java

C++ function that depends on base class to obtain results on derived class
The usual approach would be to use polymorphism: void func(const base& ob) { ob.doSomethingPolymorphic(); } where doSomethingPolymorphic() is a virtual member function of base.

Categories : C++

"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

Python: Child instance class of an instance of Parent Class
You are not calling __init__ in B. Using the name of the function just gives you that function object. The brackets after __init__() actually execute the function. super(B, self) returns a class, not an object (which makes sense - a class doesn't have a superinstance, it has a superclass), so you then call __class__ on that class, which results in the unexpected result. You use __class__ on self because self is an instance of the class. class B(A): def __init__(self): super(B, self).__init__() print type(self).__name__ print super(B, self).__name__ Note my use of type() over accessing __class__ - using the built-in functions is better than accessing the magic values directly. It's more readable and allows for special functionality.

Categories : Python

Python: Trying to set attributes of a class instance from output of another class instance
The following is incorrect: class photoGallery: def __init__(self, *args): self.output = 'Output from photoGallery class instance' return self.output "_init_" is the constructor for photoGallery which has the responsibility of initialising the photoGallery object. As such it doesn't make sense for it to to return anything. Get rid of return self.output and try again

Categories : Python

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

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

Polymorphic class using lambda
Use a factory function. If you can get by with just using a DbConnection for all your Actions you don't need generics: protected void WithConnection(Action<DbConnection> sqlBlock, Func<DbConnection> dbCxnFactory) { try { using (DbConnection connection = dbCxnFactory()) { connection.ConnectionString = this.ConnectionString; connection.Open(); sqlBlock(connection); } } catch (Exception ex) { Console.WriteLine(@"Exception during database connection: {0}", ex); } } If you want to specialize, some actions to SqlConnection only and some to SqlCeConnection only, then you can make it generic: protected void WithConnection<T>(Action<T> sqlBlock, Func<T> dbCxnFactory) where

Categories : C#

Scala Macros: Getting a List of TypeSymbols to be used at runtime
You have to use reifyType to create reflection artifacts in the runtime universe: import scala.language.experimental.macros import scala.reflect.macros.Context object PackageMacros { def allTypeSymbols[T](packageName: String) = macro allTypeSymbols_impl[T] def allTypeSymbols_impl[T: c.WeakTypeTag](c: Context)( packageName: c.Expr[String] ) = { import c.universe._ val pkg = packageName.tree match { case Literal(Constant(name: String)) => c.mirror.staticPackage(name) } val types = pkg.typeSignature.members.collect { case sym: ClassSymbol => c.reifyType(treeBuild.mkRuntimeUniverseRef, EmptyTree, sym.toType) }.toList val listApply = Select(reify(List).tree, newTermName("apply")) c.Expr[List[Any]](Apply(listApply, types))

Categories : Scala

What's the scala alternative to runtime-preserved annotations
Actually, Scala does have runtime-retained annotations. The difference is that they are not stored as Java annotations but are instead encoded inside the contents of binary ScalaSignature annotation (which, by itself, is a runtime-retained Java annotation). So, Scala annotations can be retrieved at runtime, but instead of using Java reflection, one must use Scala reflection: class Awesome extends StaticAnnotation @Awesome class AwesomeClass import scala.reflect.runtime.universe._ val clazz = classOf[AwesomeClass] val mirror = runtimeMirror(clazz.getClassLoader) val symbol = mirror.classSymbol(clazz) println(symbol.annotations) // prints 'List(Awesome)' Unfortunately, Scala reflection is still marked as experimental and is actually unstable at this point (SI-6240 or SI-6826 are examp

Categories : Scala

C++ Polymorphic Class Variables and Functions
Redeclare Ball as the following class Ball : public Instance { public: void update() { x += 1; } } By putting the ": public Instance" you are making Ball being a derived class of Instance and have the same public or protected attributes, it will have the depth,x and y ones without declaring them explicitly. http://www.learncpp.com/cpp-tutorial/112-basic-inheritance-in-c/

Categories : C++

Use of making the base class polymorphic?
Because you might want to store objects of different types together: std::vector<std::unique_ptr<Base>> v; v.push_back(make_unique(new DerivedA())); v.push_back(make_unique(new DerivedB())); v.push_back(make_unique(new DerivedC())); Now, if you go over that vector: for (auto& p : v) { p->foo(); } It will call foo() of DerivedA, B, and C appropriately.

Categories : C++

Using Scala reflection to find most derived runtime type
Most obvious solution would be to use the class: def checkType[A](item: A) { println("typeOf[A]: " + item.getClass) } But if you want to work with Type, then some additional work is needed: def checkType[A](item: A) { val mirror = runtimeMirror(this.getClass.getClassLoader) println("typeOf[A]: " + mirror.classSymbol(item.getClass).toType) }

Categories : Scala

Deep access of fields in Scala using runtime reflection
You're exactly right, the type of your dos is Any. FieldMirror.symbol.typeSignature is what you'd get from typeOf[Dos]. So consider returning a pair (Any, Type) from unpack to have something to pass to unpack(target, type, name). Somewhat like: case class Uno(name: String, age: Int, pets: List[String], stuff: Dos) case class Dos(foo: String) object Boom extends App { import scala.reflect.runtime.universe._ import scala.reflect.runtime.{ currentMirror => cm } import scala.reflect.ClassTag val u = Uno("Marcus", 19, List("fish", "bird"), Dos("wow")) println("NAME: " + unpack(u, "name")) // Works println("PETS: " + unpack(u, "pets")) // Works // ----- Goes Boom ------- val (dos, dosT) = unpack(u, "stuff") println("Other: " + unpack(dos, dosT, "foo")) // Boom! ...or

Categories : Scala

When I make a second instance of a class in Ruby it changes the first instance of that class
Array.new does not create a deep copy, so your boards are shared, since EMPTY_BOARD is two levels deep. In addition, keeping EMPTY_BOARD outside of your CatanBoard class probably isn't a good idea anyway from a cohesion point of view. If you introduce a private method def empty_board Array.new(19) {Array.new(0) {[]}} end private :empty_board then you can just reference this method during initialization: @board = empty_board

Categories : Ruby

How to list all fields with a custom annotation using Scala's reflection at runtime?
This can be done with a TypeTag, by filtering through the members of your input type: import reflect.runtime.universe._ def listProperties[T: TypeTag]: List[(TermSymbol, Annotation)] = { // a field is a Term that is a Var or a Val val fields = typeOf[T].members.collect{ case s: TermSymbol => s }. filter(s => s.isVal || s.isVar) // then only keep the ones with a MyProperty annotation fields.flatMap(f => f.annotations.find(_.tpe =:= typeOf[MyProperty]). map((f, _))).toList } Then: scala> class A { @MyProperty("") val a = 1 ; @MyProperty("a") var b = 2 ; var c: Long = 1L } defined class A scala> listProperties[A] res15: List[(reflect.runtime.universe.TermSymbol, reflect.runtime.universe.Annotation)] = List((variable b,MyProperty("a")), (value a,MyPro

Categories : Scala

Scala, Ord instance haskell like
Scala has type classes just like Haskell, and uses them in its standard library. Ordering, specifically, is the one you are looking for: implicit object Ordering[ABC] { def compare(x: ABC, y: ABC) = { // Write your definition here. } }

Categories : Scala

Why is it faster to call external scala compiler than use the runtime interpreter library?
There are many things left unstated (like memory settings), but you're comparing apples and oranges. The command-line script runner is not a REPL session; instead, it wraps your code in a simple object with a main method, compiles and runs that. By contrast, each interpreted line (or compilable thing) in the REPL is wrapped in an object (with the session history imported so you can refer to past results). Even modulo REPL start-up, this has performance consequences, see this issue. The simple wrap-it logic for the script runner is built into the parser. Here is how the script runner runs the compilation. Or, it looks like this is how -e is handled. Edit: your comment to your question implies that you really want fsc compile server behavior. Fire up fsc and use the compile client.

Categories : Scala



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