How to update a MATLAB GUI in the background? - multithreading

I have a MATLAB GUI and a separate application that writes data to a file.
I'd like my MATLAB GUI to check the file periodically, and update the GUI when it changes.
In Java, I'd use a SwingUtils.Timer(sp?) object to do something like this. Does MATLAB have timer functionality? I could write a java class and do it I suppose, but want something quick and dirty for a demo, preferably pure MATLAB.

You can create timer objects in MATLAB using the TIMER function. For example, this creates a timer object which should execute the function myFcn once every 10 seconds after the timer is started:
timerObject = timer('TimerFcn',#myFcn,'ExecutionMode','fixedRate',...
'Period',10.0);
Timers are started and stopped using the functions START and STOP. You should also always remember to delete them with DELETE when you're done using them. You can find more info on using timers in the MATLAB documentation.
It is worth noting, that if you are wanting to update axes object in a GUIDE GUI, there's an additional bit of "trickery" needed to make this work. You must either change the HandleVisibility property of the axes object in GUIDE, or you must explicitly acquire the handle. To do this, change the timerObject construction as follows (This is assuming the axes window in your GUIDE generated GUI is called axes1):
timerData.axes = handles.axes1;
timerData.n = 1; % some state needed for the plots.
timerObject = timer('TimerFcn',#myFcn,...
'ExecutionMode','fixedRate',...
'Period',10.0,...
'UserData', timerData);
then in myFcn, we need to reference the axes object. Specifically:
function [] = myFcn(timerObj, event)
timerData = get(timerObj, 'UserData');
plot(timerData.axes, (1:n)/n, sin(20*2*pi*(1:n)/n));
line( (1:n)/n, cos(20*2*pi*(1:n)/n, 'Parent', timerData.axes);
timerData.n = timerData.n + 1;
set(timerObj, 'UserData', timerData);
end

Related

PyQt5 UI stuck at long operation

I'm creating a game with some AI that may take some time. The problem is even if I call relevant methods to update the UI before running the AI function, the UI is not visually updated.
Some example code looks like this
def onClickBoard(self, e):
x, y = toBoardGrid(e.x(), e.y())
self.game.move(x, y)
self.update_board()
print("before AI")
# This line takes a few seconds
ai_move = self.ai.get_best_move(self.game)
print("after AI")
self.game.move(ai_move[0], ai_move[1])
self.update_board()
Where self.update_board is a method that updates a QWidget and it's very fast. This onClickBoard method is assigned to the widget's mouseReleaseEvent.
self.board.mouseReleaseEvent = self.onClickBoard
When running the game, I can see before AI printed to the terminal but the visual window doesn't change. I see the window updates only once, after the AI commits its move.
Is there a way to make the board update once before the slow function call and another once after it?
Yes, you can force Qt to process all pending events, and thus update the GUI, with the QApplication::processEvents() method. Add the following line just before the slow function call:
QtWidgets.QApplication.instance().processEvents()

Cannot get QWindow::fromWinId to work properly

My Qt 5.9 program (on X11 Linux) launches other applications, using QProcess.
I would like to have control over windows these applications spawn, so I obtain their winId value and use QWindow::fromWinId to get a QWindow instance.
The problem is these instances are invalid and do not represent the window they are supposed to.
If I check the winId values using xwininfo, the correct information is returned, so I know they are good.
What am I doing wrong?
Edit: An example won't help much, but here goes:
QProcess *process=new QProcess(this);
...
process.open()
... // wait until window appears
WId winId=PidToWid(process->processId()); // this function returns the Window ID in decimal format. I test this with xwininfo, it's always correct
...
QWindow *appWindow=QWindow::fromWinId(winId);
... And that's basically it. appWindow is a valid QWindow instance, but it does not relate to the actual window in any way. For example, if I close() it, it returns true but the window does not close.
Even if I provide a wrong WId on purpose, the end result is the same.
This is not proper solution with explanation why it should work, however it may be helpful for somebody...
I had the same issue with my application when I switched from Qt4 QX11EmebeddedContainer to Qt5 implementation using QWindow. What I did to resolve / fix this issue was following:
Client application:
widget->show(); //Widget had to be shown
widget->createWinId();
sendWinId(widget->winId()); //Post window handle to master app where is constructed container
Master application:
QWindow* window = QWindow::fromWinId(clientWinId);
window->show(); //This show/hide toggle did trick in combination with show in client app
window->hide();
QWidget* container = QWidget::createWindowContainer(window, parentWindowWidget);
After this I was able to control window properly through QWidget container.

NAudio - Does a new instance of OffsetSampleProvider have to be created for each playback

As explained here, OffsetSampleProvider can be used in order to play a specific portion of an audio file. Like this:
AudioFileReader AudioReader = new AudioFileReader("x.wav");
OffsetSampleProvider OffsetProvider = New OffsetSampleProvider(AudioReader);
OffsetProvider.SkipOver = TimeSpan.FromSeconds(5);
OffsetProvider.Take = TimeSpan.FromSeconds(8);
myWaveOut.Init(OffsetProvider);
myWaveOut.Play();
The above example will play an audio for 8 seconds, starting at second 5. However, if I want to play it again, it will not play, unless I set the Position property of the AudioFileReader to 0, and re-create a new instance of OffsetSampleProvider from it. So I would like to know if I'm missing something, or this is the way that OffsetSampleProvider should be used (and if it does, do I have to free any resources related to it).
You could copy the code for OffsetSampleProvider and add a Reset method to it. I'd also avoid using SkipOver for performance reasons and just set the CurrentTime of the AudioFileReader to 5 seconds directly before you play.

COMException^ on FilePicker PickSingleFileAsync() call

I'm trying to make a game (Universal DX11 application) and at some point I need access to image library to allow user to select avatar. But for some reason call of PickSingleFileAsync on picker rises an exception.
Windows::Storage::Pickers::FileOpenPicker^ openPicker = ref new Windows::Storage::Pickers::FileOpenPicker();
openPicker->SuggestedStartLocation = Windows::Storage::Pickers::PickerLocationId::PicturesLibrary;
openPicker->ViewMode = Windows::Storage::Pickers::PickerViewMode::Thumbnail;
// Filter to include a sample subset of file types.
auto filters = openPicker->FileTypeFilter;
filters->Clear();
filters->Append(".png");
openPicker->PickSingleFileAsync();// same exception with create_task(...);
Seems like the sample works only if I put it into UI thread. How can I use picker from my own thread?
UPD: HRESULT:0x80004005
Ok, I just decided to call dipatcher's RunAsync to execute this code. But I still have no idea why I cannot open picker inside non-UI thread.

Actionscript - Flex mobile thread while loading data?

I am using Flash builder actionscript 3 Flex mobile.
I have a very heavy function that loads data from the local device and creates many graphic elements. While this function runs, the device freezes for 6 seconds or so.
I want to show a progress bar and let the device continue working, is there any way I can use threading to do this ? Other ideas are also welcome.
Thanks, Koby.
You know that at which function application getting freeze. Before that function call a progress bar. Create a progress bar in a pop up mode & call it. After 6 seconds(Not recommended) or getting the data just call removeallpopups() method. So now you can set the label in progress bar as "Loding..."
Sample code
<mx:ProgressBar id="sampleProgressBar" styleName="Calib16Blue"
indeterminate="true" labelPlacement="left"
label="{theMessage}"/>
Call this mxml by creating a pop up.
To do 'proper' muiltithreading you need to use the Worker Class (Documentation here), however the SQLConnection class and FileStream class have asynchronous methods that fit into the normal Actionscript event listener cycle and operate in "the background". Allowing the rest of the app to load when they're still pending.

Resources