Recognizing a S3 (?) class from a package in an S4 class definition - class

I have some troubles getting a class from an older packages been recognized by the S4 class definition. I keep on getting the error
Error in makePrototypeFromClassDef(properties, ClassDef, immediate, where) :
in making the prototype for class "Tsvmm" elements of the prototype failed to
match the corresponding slot class: dates (class "dates" )
In addition: Warning message:
undefined slot classes in definition of "Tsvmm": dates(class "dates")
A reproducible example:
require(chron)
setClass(
Class="Tsvmm",
representation=representation(
data = "data.frame",
dates = "dates"
),
prototype=prototype(
data = data.frame(),
dates = chron(0)
)
)
When trying class(chron(0)), the answer is "dates" "times". using is.numeric(chron(0)), the answer is TRUE. Yet, when I set the class of slot dates as "numeric", I get the same error without the warning message.
I have the feeling I'm overlooking something obvious, but I couldn't find it in the documentation yet. Anybody any pointers?
PS: I know the chron package is at least peculiar, but I have good reasons to use this. Plus, the problem is likely to occur with other packages. See this as an example for a general question. So please, don't tell me to use the Date or POSIXt classes. That's a hack I'm using now.

It seems that you need setOldClass to make methods believe dates is a real class.

I've got a similar problem because Gtk2 objects (e.g., Gtk2::GtkBuilder) are not S4 classes whereas I wanted one instance of such an object in my own code. I think I worked arround a the situation by removing the prototype() thing and using an "initialize()" method.

Related

Documentation comment for loop variable in Xcode

I know that we can use
/// index variable
var i = 0
as a documentation comment for a single variable.
How can we do the same for a loop variable?
The following does not work:
var array = [0]
/// index variable
for i in array.indices {
// ...
}
or
var array = [0]
for /** index variable */ i in array.indices {
// ...
}
Background:
The reason why I don’t use "good" variable names is that I’m implementing a numerical algorithm which is derived using mathematical notation. It has in this case only single letter variable names. In order to better see the connection between the derivation and the implementation I use the same variable names.
Now I want to comment on the variables in code.
The use of /// is primarily intended for use of documenting the API of of a class, struct, etc. in Swift.
So if used before a class, func, a var/let in a class/struct, etc. you are attaching documentation to that code aspect that Xcode understands how to show inline. It doesn’t know how to pickup that information for things inside of function since at this time that is not the intention of /// (it may work for simple var/let but not likely fully on purpose).
Instead use a simple // code comment for the benefit of any those working in the code however avoid over documenting the code since good code is likely fairly self explaining to anyone versed in the language and adding unneeded documentations can get in the way of just reading the code.
This is a good reference for code documentation in Swift at this time Swift Documentation
I woud strongly push back on something like this if I saw it in a PR. i is a massively well adopted "term of art" for loop indices. Generally, if your variable declaration name needs to be commented, you need a better variable name. There are some exceptions, such as when it stores data with complicated uses/invariants that can't be captured in a better way in a type system.
I think commenting is one area that beginners get wrong, mainly from being misled by teachers or by not yet fully understanding the purpose of comments. Comments don't exist to create an english based, psuedo-programming language in which your entire app will be duplicated. Understanding the programming language is a minimal expectation out of contributors to a project. Absolutely no comments should be explaining programming language features. E.g. var x: Int = 0 // declares a new mutable variable called x, to the Int value 0, with the exception of tutorials for learning Swift.
Commenting in this manner might seem like it's helpful, because you could argue it explains things for beginners. That may be the case, but it's suffocating for all other readers. Imagine if novel had to define all the English words they used.
Instead, the goal of documentation to explain the purpose and the use of things. To answer such questions as:
Why did you implement something this way, and not another way?
What purpose does this method serve?
When will this method of my delegate be called?
Case Study: Equatable
For a good example, take a look at the documentation of Equatable
Some things to notice:
It's written for an audience of Swift developers. It uses many things, which it does not explain such as, arrays, strings, constants, variable declaration, assignment, if statements, method calls (such as Array.contains(_:)), string interpolation, the print function.
It explains the general purpose of this protocol.
It explains how to use this protocol
It explains how you can adopt this protocol for your own use
It documents contractual requirements that cannot be enforced by the type system.
Since equality between instances of Equatable types is an equivalence relation, any of your custom types that conform to Equatable must satisfy three conditions, for any values a, b, and c:
a == a is always true (Reflexivity)
a == b implies b == a (Symmetry)
a == b and b == c implies a == c (Transitivity)
It explains possible misconceptions about the protocol ("Equality is Separate From Identity")

Updating data in SORM seems possible (even though I was told it aimed at immutable data...)

I was told that SORM aims at immutable data. It's not written on the website - at least not in the main parts I was looking at, so I was a bit surprized of the rigidity of the claim. I was just aware it would recommend to do so. But maybe I was just missing something.
The examples tell you to use a ".copy(propery = newvalue)" before calling a Db.save() on the object. So thats a hint.
I was interrested in what would happen if I would just change the data and update it in the database. Strangely the following just worked fine:
case class Agent( var name : String )
object Db extends Instance(
entities = Set( Entity[Agent]() ),
url = "jdbc:h2:mem:hansi"
)
class SORMTest extends FunSuite {
test("Update") {
// Store values in the db:
val agent = Db.save( Agent("test") )
agent.name = "hansi"
Db.save(agent)
}
It produced an update statement in the database that changed the name property for the corresponding id.
Is it kind of crazy to do so? Any comments from the developers?
I was told that SORM aims at immutable data. It's not written on the website
It's stated plenty of times that SORM strongly follows functional programming idioms. This implies operation on immutable data-structures only.
The examples tell you to use a ".copy(propery = newvalue)" before calling a Db.save() on the object.
That's where you're wrong. The examples tell you to use .copy(..) to get an updated immutable value of the object it's called on, calling it before calling a Db.save() per se as in the following:
agent.copy(name = "new name")
Db.save(agent)
will have absolutely no effect, because, once again, .copy() doesn't mutate the object it's called on, instead it returns an updated copy of this object. So the proper use is the following:
val updatedAgent = agent.copy(name = "new name")
Db.save(updatedAgent)
or simply:
Db.save( agent.copy(name = "new name") )
But the fact is all the above has to do with SORM only as much as it has to do with functional programming in Scala in general. This is really a very basic stuff about how case classes are supposed to be used. So please do yourself a favor and introduce yourself to basics of functional programming. This will wipe out all the questions on SORM you've already had and, I'm sure, plenty of those which are comming up otherwise.
Your example works and it's supposed to, but it doesn't change the fact that it goes against the basic idioms of functional programming and as such is an unidiomatic use of SORM.

What does the "extends {..}" clause in Scala object definition, without superclass name, do?

I found this code example in Programming in Scala, 2nd Ed. (Chapter 25, Listing 25.11):
object PrefixMap extends {
def empty[T] = ...
def apply[T](kvs: (String, T)*): PrefixMap[T] = ...
...
}
Why is the extends clause there without a superclass name? It looks like extending an anonymous class, but for what purpose? The accompanying text doesn't explain or even mention this construct anywhere. The code actually compiles and apparently works perfectly with or without it.
OTOH I found the exact same code on several web pages, including this (which looks like the original version of the chapter in the book). I doubt that a typo could have passed below the radars of so many readers up to now... so am I missing something?
I tried to google it, but struggled even to find proper search terms for it. So could someone explain whether this construct has a name and/or practical use in Scala?
Looks like a print error to me. It will work all the same, though, which probably helped hide it all this time.
Anyway, that object is extending a structural type, though it could also be an early initialization, if you had with XXX at the end. MMmmm. It looks more like an early initialization without any class or trait to be initialized later, actually... structure types do not contain code, I think.

Python: outside function applying changes to a class object's unique namespace

My question is how to program in Python (2.6) a function that uses a namespace of an object, while the function is defined outside the object/class. In addition, that function should only change the variables in the object's namespace; it should not take over the namespace (because with multiple objects they will all use the same namespace).
My reason for pursuing this, is because I wish to write a very small class, where during construction all necessary functions for future use are already given and subsequent function calls (self.__call__) on the object itself can be directly applied.
I realize that this idea is not very pythonic (as they say), and I have thought of various other solutions (such as putting the functions in another class and connecting them), but I can't help but feel that each of these solutions is a lot more work than I would think makes sense.
One simple way that accomplishes what I want is the following:
class A:
def __init__(self, some_dict, func_a):
self.memory = some_dict
self.__call__ = func_a
def test_func(obj, some_input):
if some_input in obj.memory :
return obj.memory[some_input]
else :
obj.memory[some_input] = 0. # some default value
return 0.
first_object = A({}, test_func)
print first_object(first_object, '3')
This will work fine, but what aches me is that when I make function calls to the object, I will also have to give the object itself (see the last line). I hope to be able make calls as such:
print first_object('3')
So far, my ideas were unsuccesful to avoid this (e.g. copying the function method and link its namespace by self.__call__.memory = self.memory). I wish to find something to change the def __init__ part to 'adopt' a function and link their namespaces.
I have rigorously searched for an answer on the internet, but a definite solution has not yet been found. The following http://www.velocityreviews.com/forums/t738476-inserting-class-namespace-into-method-scope.html seeks the same, but is also not succesfull.
Anyone have a solution to tackle this?

How to get the class of a singleton object at compile time?

Consider something like this:
object Singleton
val cls: Class[Singleton] = ???
What do I have to write instead of ????
I tried classOf[Singleton], classOf[Singleton.type], Singleton.type, but nothing worked.
(I know of course about getClass, the runtime version of classOf, but that's not what I'm asking.)
Here a solution, but it's not pretty ...
object Singleton
val cls : Class[Singleton] = Singleton.getClass.asInstanceOf[Class[Singleton]]
Edit: completed the solution after reading another question/answer: Scala equivalent of Java java.lang.Class<T> Object
Note1: type erasure would prevent this from being particularly useful, e.g. in pattern matching. See referenced question/answer, above, for a good explanation
Note2: the scala -explaintypes flag is quite handy in understanding type errors.
HTH
You are not alone with this problem. The answer is: There is currently no way to avoid a Singleton.getClass. See this comment for more information why classOf[Singleton] does not work