I would like to use the read option of TasksExecuted in a timer callback function. How could I proceed? Here is my program draft:
period=5
a = timer('ExecutionMode','fixedRate','Period',period,'TimerFcn',{#time_append,period,TasksExecuted, HR, fictiveFolderName},'TasksToExecute',3 );
start(a);
function time_append(obj,event,period,TasksExecuted, HR, fictiveFolderName)
HR_freq=1;
print(TasksExecuted);
i_init=TasksExecuted*period*HR_freq+1
i_end=(TasksExecuted+1)*period*HR_freq
writematrix(HR(i_init:i_end),strcat(fictiveFolderName,'\HR.csv'),'WriteMode','append');
end
where HR is a 100x1 doubles matrix and fictiveFolderName an existing folder containing a csv file called HR. I get the error Unrecognized function or variable 'TasksExecuted'. There is only little information about read-only properties of callback functions available in the documentation.
How can I use the read property of TasksExecuted?
The property you are after is a property of the timer object. Within your callback function you would have access to it as obj.TasksExecuted.
You won’t have access to it when creating the timer object (the line a=timer… where you get an error), because then the timer object doesn’t exist yet.
Related
I am trying to raise an event in Matlab. It is working, but not as i expected. What is going on is that the source object is passed as parameter do the event handler and i can't access my object properties inside the event handler.
Here is my class:
classdef MyClass < handle
properties
Name = 'a';
end
events
Changed
end
methods
function obj = MyClass(current)
if exist('current','var')
addlistener(current,'Changed',#ChangedHandle);
end
end
function obj = Change(obj,value)
notify(obj,'Changed');
end
function obj = ChangedHandle(obj,value)
disp(obj.Name);
end
end
end
These are the command lines to reproduce whats going on:
a = MyClass();
b = MyClass(a);
b.Name = 'b';
a.Change(3);
This is returning "a" and i want it to return "b".
Regards
The listener callback you specify receives details of the object raising the event. The fact that the listener has been created during the creation of a different object is not an intrinsic property of the listener – unless you effectively embed this in the design of your callback.
In your example, #ChangedHandle only works as a callback because it happens to be a method of the class current belongs to. If a and b belonged to different classes the problem would be more obvious: if ChangedHandle was a method only of a, it wouldn't know anything about the Name property of b. And if only a method of b, the listener bound to a would have only the function handle without any reference to the instance b of the class to which ChangeHandle belongs.
As described in the listener callback documentation you can use a method of the specific object instance current as an event listener using the syntax #current.ChangedHandle.
This method then receives callback arguments in the format callbackMethod(obj,src,evnt), so you need to add an argument to the definition of ChangedHandle. The first argument obj will be the instance referenced by current when the listener is created, so the line disp(obj.Name) will then produce the intended result without modification.
The reference to a received by the callback in the example will still be passed to the new callback – this is a fundamental behaviour of listener callbacks – but it will now be accessible from the second argument src.
In your addlistener code you are not telling the listener which object you want to call the method on, so what Matlab does it will apply the listener to the current object since thats all that was passed into the function, you can check this by changing the code to:
addlistener(current,'Changed',#(h,evt)current.ChangedHandle);
if you want it to run the code for the other class b (obj), then you use:
addlistener(current,'Changed',#(h,evt)obj.ChangedHandle);
I'm sorry I'm new to LUA scripts and I have to work on code written by others.
Please don't focus on code, my problem is only about included files and priority evaluating which function has to be called, in case of overriding.
Let's say I have a file Terrain.lua containing a class Terrain, which has a function Terrain:generate() and Terrain:generate() calls Terrain:getLatitude().
Terrain was included in a script MyScript.lua, which overrided Terrain:getLatitude() as follows:
include("Terrain");
function Terrain:getLatitude()
new code;
end
function myFunction()
local myTerrain = Terrain.create();
myTerrain.generate();
end
This has the effect of overriding getLatitude(): when myTerrain.generate() is called, generate() is the code from the included "Terrain", but getLatitude() is the local function with the new code, even if called by a function from the included class.
Now let's say I want to put some of the code in an external file Custom.lua. Custom (and not MyScript) has to override getLatitude().
This is the situation:
Terrain.lua contains Terrain class and these functions
Terrain.create()
Terrain.generate()
Terrain.getLatitude()
MyScript.lua is the script being executed, and include Custom:
include("Custom");
function myFunction()
return customFunction()
end
Custom.lua contains:
include("Terrain");
function Terrain:getLatitude()
new code;
end
function customFunction()
local myTerrain = Terrain.create();
myTerrain.generate();
end
Now, if I call customFunction() from MyScript, getLatitude() from Terrain is used, instead of getLatitude() from Custom. I assume ovveride is possible only inside the currenti file being executed? How can I achieve overriding in an included file?
I hope this example is enough to understand my problem, without posting a lot of code. Thank you.
Firstly, some corrections: there is no local function's in your question; include is not part of any lua standard, what that function actually does may be quite important.
Finally, Lua does not have actual class system, what you use in the question is merely a syntactic sugar (misleading and confusing as I find it) over table assignments. Lua is an interpreted language, so what may seem to you as a class definition is not a static structure known from the very beginning of the program execution but a code that gets executed from the top of the file to the bottom.
Thus, if we assume that include is similar to the require, then the your question code will be equivalent to the following:
do--terrain.lua
Terrain = {
create=function()
local created_object
--some code to assign value to created_object
return created_object
end
}
Terrain.generate = function(self) end
Terrain.getLatitude = function(this_is_a_self_too)
--some code that uses `also_self` as a reference to the object when called as object:generate()
end
--do end block is essentially an equivalent of file, its local variables are not seen outside
--global variables it has assigned (like `terrain`) will stay accessible AFTER its end
--changes it done to global variables will also remain
end
do--Custom.lua
Terrain.getLatitude = function(this)--this is the assignment to a field in a table stored in the global variable Terrain
--this function will replace the one assigned to the `getLatitude` field
end
customFunction = function()
local myTerrain = Terrain.create();
myTerrain.generate();--this one probably needs `:` instead of `.`
--depends on actual code inside terrain.lua
end
end
do--MyScript.lua
myFunction= function()
return customFunction() --this line calls the global variable customFunction
end
end
Thus if your actual setup is similar to the one in question, then the "override" will take effect after the Custom.lua is executed and for all the subsequent calls to the Terrain.getLatitude regardless of whether or not they've called the file. (And any later file can override it again, and all calls after that will be using the new one)
It is probably more complicated to do a limited override in this setup. That again depends on the actual details of how your team has defined the Terrain class and the class system itself.
How would I change color of a GUI component, specifically a static text box, after a certain timer period (say 3 seconds) using a timer?
I tried
t = timer('TimerFcn', set(handles.tag,'BackgroundColor','red'),'StartDelay',3);
start(t);
But it returns this error:
One or more outputs not assigned to set during callback.
I already know it means that set is not giving an input argument to the timer fcn. The problem is that a 7 segment display using this technique was already developed previously. But this is not working now.
'TimerFcn' parameter should define a callback - it has to be in one of the following forms:
String, function handle, or cell array defining the timer callback
function
You should specify your callback as a function handle, accepting [at least] two arguments (timer object / event):
If you specify this property using a function handle, when MATLAB
executes the callback it passes the timer object and an event
structure to the callback function.
You can use anonymous function for that, and simply ignore both arguments:
handles.tag = uicontrol('Style', 'text', 'String', 'Some text');
t = timer('TimerFcn', #(~,~) set(handles.tag,'BackgroundColor','red'), 'StartDelay',3);
start(t);
For performance tests I need a way to measure the time needed for a form to load its definition from the DFM. All existing forms inherit a custom form class.
To capture the current time, this base class needs overriden methods as "extension points":
start of the deserialization process
after the deserialization (can be implemented by overriding the Loaded procedure)
the moment just before the execution of the OnFormCreate event
So the log for TMyForm.Create(nil) could look like:
- 00.000 instance created
- 00.010 before deserialization
- 01.823 after deserialization
- 02.340 before OnFormCreate
Which TObject (or TComponent) methods are best suited? Maybe there are other extension points in the form creation process, please feel free to make suggestions.
Background: for some of our app forms which have a very basic structure (with some PageControls and QuantumGrids) I realized that it is not database access and other stuff in OnFormShow but the construction which took most of the time (around 2 seconds) which makes me wonder where this time is spent. As a reference object I will also build a mock form which has a similar structure but no code or datamodule connections and measure its creation time.
The best place for "instance created" is TObject.NewInstance.
In Delphi 2009 the best place for "before deserialization" is TCustomForm.InitializeNewForm. If that isn't available override TCustomForm.CreateNew and grab the time immediately before it returns.
You're correct that the best place for "after deserialization" is TComponent.Loaded.
For "before OnFormCreate" override TObject.AfterConstructor and get the time immediately before calling the inherited method. If you want the total construction time, grab the final time after that inherited call returns. That will include both the OnFormCreate and any initial activation time. Alternatively, you could just override TForm.DoCreate, if you're not overriding that anywhere else.
Let's assume that the loading of the form's DFM is the main time part of the construction of the form, we could add a constructor to the form like:
constructor TMyForm.Create( AOwner: TComponent );
var
S, E: Int64;
begin
QueryPerformanceCounter( S );
inherited Create( AOwner ); // here is the dfm loading
QueryPerformanceCounter( E );
// Log using the classname and the time in QPC ticks.
LogQPCTime( ClassName, E - S );
end;
I have read where an event is triggered on another thread from the one that created the controls on a Windows Form.
Therefore, the event handler can't directly update the controls (like changing a button's color).
I read the explainations about Invoke or BeginInvoke being needed.
My question: Why can't an event handler just be passed 'this' as an agrument.
'this' being the form whose controls have buttons that want THEIR COLORS CHANGED !! ;)
I can swear I've seen instances where a delegate can take a 'this' - but maybe not...
There's nothing stopping an event handler on another thread just going in and screwing around with the internal state of the button.
However, it causes bad things to happen - as an example, what would happen if you changed a property of a control while something else was also trying to write to it?
Only one thread should be screwing around with the internal state of an object at a time - if you call methods directly on that object from another thread, you can't guarantee that something else isn't doing the same.
Invoke gets around this by not calling it directly - instead it says to the thread that 'owns' the object "Hey, could you call this method on that object when you've got a moment?", thus ensuring that the method is only called when the object is in a consistent state.
If you are handling an event with an instance method in the form, you already have a "this" parameter. Say something like this:
Public Class MyForm
Inherits Form
Private port As New SerialPort()
Private Sub RegisterHandlers()
AddHandler port.DataReceived, AddressOf ProcessData
End Sub
Private Sub ProcessData(ByVal sender As Object, ByVal e As EventArgs)
If Me.InvokeRequired Then
'marshal to required thread
Exit Sub
End If
'do stuff on the form thread
End Sub
End Class