MATLAB - why is it complaining about #-folders for classdef'd objects? - oop

I've been writing OOP MATLAB code for quite some time. However, I'm now running MATLAB code on a Windows machine for the first time.
I have the following code:
classdef myClass < handle
properties
i
end
methods
function obj = myClass()
obj.i = 0;
end
function say(obj)
obj.i = obj.i + 1;
fprintf('This is time #%i you invoked me!\n', obj.i);
end
end
end
Seems pretty innocuous. I try to instantiate an object and I get this:
>> m = myClass;
Error using myClass
Error: File: myClass.m Line: 1 Column: 10
A class definition must be an "#" directory.
I've never used an #-folder in all my time writing OOP MATLAB code. My understand is it's required if class methods are written separately from the classdef file (mine's not) or if it's using the old-style MATLAB class syntax (mine's not).
I think I know what the deal is and I wanted to see if there's a workaround: My working directory is of the form
C:\Users\DangKhoa#MyCompany.com\Documents\MATLAB
Is that # throwing MATLAB off and making the computer think I'm in an #-folder? If it is, is there a workaround (aside making a new user on my computer, obviously - and that probably isn't doable)? If not, what is going on?

Looks like yes, the # in the middle of the folder is causing the error. I filed a bug report with The MathWorks.

Related

implementing "this" / "self" in a custom interpreted programming language

I'm working on a custom interpreter for fun ;)
What I have so far is assigning variables, defining and calling functions, arrays, loops, if blocks etc...
I've started adding OOP elements to my language and I'm having trouble implementing the "this" / "self" keyword.
I just cannot figure out a solution to this problem.
I've thought about a few solutions:
a class stores it's instances (as a dictionary) and when the "this" keyword appears, the interpreter ignores "private" and "public" keywords (to call a private method from a public one), creates a call to the method referenced by "this" and returns.
the "this" keyword is a reference which under the hood is the instance itself, but the method access modifiers are dropped for that call. this is similar to the first one, but I cannot think of anything better.
Also it would be nice if you knew C# (primarly) or C++, since I'm heavily relying on OOP to create my interpreter.
heres a small sample of code that I would like to implement:
struct Dog has
pub prop age;
prv def bark() do
println "woof woof";
end
pub def run(dist) do
loop 0 to $dist with "d" do
println ("the dog ran " + string $d) + " meters";
$self.bark();
end
end
end
def main(args) do
new Dog -> $dog;
7 -> $dog.age;
println $dog.age;
$dog.run 30;
end
notice that the bark() method is "prv" (private). I would like to know how can I make the struct be aware of it's instances so I can make the dog bark each time it runs (calling a private method from a public method).
Thanks in advance
Your interpreter is going to need to keep an execution stack and environment (otherwise you wouldn't know where to return to after a method is finished, etc.).
In this execution stack/env, apart from a function pointer/signature, you'd also keep the object the method is being invoked on (if any, remember about static-like functions).
This reference that you'd store would then be also accessed when de-referencing $this. And actually this is both part 1 and 2 of your idea - you could put some kind of checks like visibility of methods etc. there.
Good luck, sounds like a fun project!

Variables declared in test setup must be nilable?

I'm writing a test where I have a variable that I need to declare in the setup do.
typed: strict
frozen_string_literal: true
class BunnyTest
extend(T::Sig)
setup do
#bunny = T.let(Bunny.new, Bunny)
end
test "#hop works correctly" do
assert(#bunny.hop)
end
end
When I run the type check, I get a message saying:
The instance variable #bunny must be declared inside initialize or declared nilable
Is there a way to treat ivar declarations in setup do just like ivar declarations in #initialize?
There are a couple of alternatives for this
A rewriter
If you use Minitest, there's a rewriter in Sorbet that will make this work for you.
You could write one for your testing framework of choice
__initialize + method
This gets verbose, specially if you have more than one value you want to do this for
class BunnyTest
extend(T::Sig)
def __initialize__
#bunny = T.let(nil, Bunny)
end
setup do
#bunny = Bunny.new
end
def bunny
T.must(#bunny)
end
test "#hop works correctly" do
assert(bunny.hop)
end
end
Avoid setup
This is not responding your question, but an alternative that makes it unnecessary. I know there are cases where setup is helpful, but as a rule of thumb, I avoid it, and use explicit initialization in my test case. This makes it way easier to follow what's going on by just looking at the case, and avoids side effects/changes needed for other cases affecting the others:
class BunnyTest
extend(T::Sig)
sig {returns(Bunny)}
def bunny
Bunny.new
end
test "#hop works correctly" do
assert(bunny.hop)
end
test "can #hop twice" do
my_bunny = bunny
assert(bunny.hop)
assert(bunny.hop, "Should be able to hop a second time")
end
end

lua modules - what's the difference between using ":" and "." when defining functions? [duplicate]

This question already has answers here:
Difference between . and : in Lua
(3 answers)
Closed 8 years ago.
I'm still playing around with lua modules and I've found the following "interesting" issue that occurs depending on how you create your methods / functions inside a module.
Note the following code in a file called test_suite.lua:
local mtests = {} -- public interface
function mtests:create_widget(arg1)
print(arg1)
-- does something
assert(condition)
print("TEST PASSED")
end
return mtests
Using the above code, arg1 is always nil, no matter what I pass in when calling create_widget(). However, if I change the definition of the function to look like this:
function mtests.create_widget(arg1) -- notice the period instead of colon
print(arg1)
-- does something
assert(condition)
print("TEST PASSED")
end
then, the system displays arg1 properly.
This is how I call the method:
execute_test.lua
local x = require "test_suite"
x.create_widget(widgetname)
Can you tell me what the difference is? I've been reading: http://lua-users.org/wiki/ModuleDefinition
But I haven't come across anything that explains this to me.
Thanks.
All a colon does in a function declaration is add an implicit self argument. It's just a bit of syntactic sugar.
So if you're calling this with (assuming you assign the mtests table to foo), foo.create_widget(bar), then bar is actually assigned to self, and arg1 is left unassigned, and hence nil.
foo = {}
function foo:bar(arg)
print(self)
print(arg)
end
Calling it as foo.bar("Hello") prints this:
Hello
nil
However, calling it as foo:bar("Hello") or foo.bar(foo, "Hello") gives you this:
table: 0xDEADBEEF (some hex identifier)
Hello
It's basically the difference between static and member methods in a language like Java, C#, C++, etc.
Using : is more or less like using a this or self reference, and your object (table) does not have a arg1 defined on it (as something like a member). On the other way, using . is just like defining a function or method that is part of the table (maybe a static view if you wish) and then it uses the arg1 that was defined on it.
. defines a static method / member, a static lib, Which means you can't create a new object of it. static methods / libs are just for having some customized functions like printing or download files from the web, clearing memory and...
: Is used for object members, members that are not static. These members change something in an object, for example clearing a specified textbox, deleting an object and...
Metamethod functions(Functions that have :) can be made in lua tables or C/C++ Bindings. a metamethod function is equal to something like this on a non-static object:
function meta:Print()
self:Remove()
end
function meta.Print(self)
self:Remove()
end
Also, with . you can get a number/value that doesn't require any call from a non-static or static object. For example:
-- C:
int a = 0;
-- Lua:
print(ent.a)
-- C:
int a()
{
return 0;
}
-- Lua:
print(ent:a())
same function on a static member would be:
print(entlib.a())
Basically, each non-static object that has a function that can be called will be converted to : for better use.

Is custom generalized object serialization possible in Matlab?

I would like to save my objects as XML so that other applications can read from and write to the data files -- something that is very difficult with Matlab's binary mat files.
The underlying problem I'm running into is that Matlab's equivalent of reflection (which I've used to do similar things in .NET) is not very functional with respect to private properties. Matlab's struct(object) function offers a hack in terms of writing XML from an object because while I can't do
x = myInstance.myPrivateProperty;
...I can do
props = struct(myInstance);
x = props.myPrivateProperty;
So, I can create a pure (contains no objects) struct from any object using the code below, and then it's trivial to write an XML file using a pure struct.
But, is there any way to reverse the process? That is, to create an object instance using the data saved by the code below (that data contains a list of all non-Dependent, non-Constant, non-Transient properties of the class instance, and the name of the class)? I was thinking about having all my objects inherit from a class called XmlSerializable which would accept a struct as a single argument in the constructor and then assign all the values contained in the struct to the correspondingly-named properties. But, this doesn't work because if MyClass inherits XmlSerializable, the code in XmlSerializable isn't allowed to set the private properties of MyClass (related to How can I write generalized functions to manipulate private properties?). This would be no problem in .NET (See Is it possible to set private property via reflection?), but I'm having trouble figuring it out in Matlab.
This code creates a struct that contains all of the state information for the object(s) passed in, yet contains no object instances. The resulting struct can be trivially written to XML:
function s = toPureStruct(thing)
if isstruct(thing)
s = collapseObjects(thing);
s.classname = 'struct';
elseif isobject(thing)
s.classname = class(thing);
warning off MATLAB:structOnObject;
allprops = struct(thing);
warning on MATLAB:structOnObject
mc = metaclass(thing);
for i=1:length(mc.PropertyList)
p = mc.PropertyList(i);
if strcmp(p.Name, 'classname')
error('toStruct:PropertyNameCollision', 'Objects used in toStruct may not have a property named ''classname''');
end
if ~(p.Dependent || p.Constant || p.Transient)
if isobject(allprops.(p.Name))
s.(p.Name) = toPureStruct(allprops.(p.Name));
elseif isstruct(allprops.(p.Name))
s.(p.Name) = collapseObjects(allprops.(p.Name));
else
s.(p.Name) = allprops.(p.Name);
end
end
end
else
error(['Conversion to pure struct from ' class(thing) ' is not possible.']);
end
end
function s = collapseObjects(s)
fnames = fields(s);
for i=1:length(fnames)
f = s.(fnames{i});
if isobject(f)
s.(fnames{i}) = toPureStruct(f);
elseif isstruct(f)
s.(fnames{i}) = collapseObjects(f);
end
end
end
EDIT: One of the other "applications" I would like to read the saved files is a version control system (to track changes in parameters in configurations defined by Matlab objects), so any viable solution must be capable of producing human-intelligible text. The toPureStruct method above does this when the struct is converted to XML.
You might be able to sidestep this issue by using the new v7.3 MAT file format for your saved objects. Unlike the older MAT file formats, v7.3 is a variant of the HDF5, and there's HDF5 support and libraries in other languages. This could be a lot less work, and you'd probably get better performance too, since HDF5 is going to have a more efficient representation of numeric arrays than naive XML will.
It's not the default format; you can enable it using the -v7.3 switch to the save function.
To the best of my knowledge, what I want to do is impossible in Matlab 2011b. It might be possible, per #Andrew Janke's answer, to do something similar using Matlab's load command on binary HDF5 files that can be read and modified by other programs. But, this adds an enormous amount of complexity as Matlab's HDF5 representation of even the simplest class is extremely opaque. For instance, if I create a SimpleClass classdef in Matlab with two standard properties (prop1 and prop2), the HDF5 binary generated with the -v7.3 switch is 7k, and the expanded XML is 21k, and the text "prop1" and "prop2" do not appear anywhere. What I really want to create from that SimpleClass is this:
<root>
<classname>SimpleClass</classname>
<prop1>123</prop1>
<prop2>456</prop2>
</root>
I do not think it is possible to produce the above text from class properties in a generalized fashion in Matlab, even though it would be possible, for instance, in .NET or Java.

Using String variable as an expression

Passing commands as variables. I am creating a POP3 client and was crunching through some code when I though of something interesting.
Is it possible to pass strings of vb code to an object so that the object will execute it. I am relatively familiar with vb.net's source code being converted to Intermediate language and then being thrown into a JIT virtual machine, but I was hoping there was a simple way to implement this idea.
I want to be able to use strings
Dim Command as string
Command = "If a + b > 0 then c = a + b" '<----syntactical sugar!
System.Compiler.Something.execute(command)
If anyone has any direction, or any correction to any of the above. I appreciate your time.
Rah!
As a start you may want to check out the open source FileHelpers project.
The Runtime.ClassBuilder class in that project creates a .Net class from text, which can then be used as a normal class.