How do I run my syncronus search function wihout blocking my flutter app? - flutter

I am building a flutter application which searches a low level communication bus for devices and displays them in a table. Communication over the low level bus is slow, default speed is 4800 bits/s.
I want to run my search in the background so that the application is not halted for 10+ seconds every time the user performs a search. I also want to add the results to the table as the search function finds them (using the onFound argument to search).
SearchBar(
onSearch: (selection, parametersToDisplay) {
clearSearchResults();
communcationBus.search(selection, parametersToDisplay, onFound: (device) {addToSearchResults(device)})
},
onUpdateSearch: (display) {}, // TODO
)

You can achieve this using Isolates.
For a short conceptual intro, take a look at this Medium post by a Dart documentation writer.
The FlutterIsolate package (pub link) can help you to abstract out some of the complicated things.
You can use it to spawn a new isolate, which performs your slow operations. You can then store it in your app or use the SendPort/ReceivePort to send the result data to your main isolate.

Related

How to find which rule take long time to finish

We have around 15,000 rules running and it takes 2 hours to complete. I would like to figure out which rule takes long time. Its not possible for me to go to each rule and log it. So I implemented the AgendaEventListener and override afterMatchFired() method. I know which rules fired. But how do I know which rule took long time.
If you want the time to execute the match, update your listener to implement the beforeMatchFired method as well. When the beforeMatchFired method triggers, start the timer. When the same rule's afterMatchFired triggers, stop the timer and log it. You'll want to also track match cancelled to discard unnecessary timers.
Remember to track this on a per-rule basis -- you'll need to identify each rule uniquely (package + name should be specific enough). Note that this exercise will get a little complicated if you have rules that extend other rules.
Rather that doing your own profile, you should take a look at the new drools-metric module that solves exactly your problem.
From the manual
Use the drools-metric module to identify the obstruction in your rules
You can use the drools-metric module to identify slow rules especially
when you process many rules. The drools-metric module can also assist
in analyzing the Drools engine performance. Note that the
drools-metric module is not for production environment use. However,
you can perform the analysis in your test environment.
To analyze the Drools engine performance using drools-metric, add
drools-metric to your project dependencies and enable trace logging
for org.drools.metric.util.MetricLogUtils , as shown in the following
example:
Try RulesChronoAgendaEventListener and RulesChronoChartRecorder from da-utils
Both gives you real-time JMX monitoring, showing average and max execution time for each rule. Second gather jfreechart data to show you values in time, which gives you perfect sense of overall performance and 'problematic' cases.
Register session listener
AgendaEventListener rulesChrono = new RulesChronoChartRecorder().withMaxThreshold(500).schedule();
session.addEventListener(rulesChrono);
Print per rule statistic
StringBuilder sb = new StringBuilder();
rulesChrono.getPerfStat().values()
.forEach(s -> sb.append(format("%n%s - min: %.2f avg: %.2f max: %.2f activations: %d", s.getDomain(), s.getMinTimeMs(), s.getAvgTimeMs(), s.getMaxTimeMs(), s.getLeapsCount())));
System.out.println(sb.toString());
Draw charts
Map<String, TimeSeries> rulesMaxChart = rulesChrono.getRulesMaxChart();
Map<String, TimeSeries> rulesMinChart = rulesChrono.getRulesMinChart();
rulesChrono.getRulesAvgChart().entrySet()
.forEach(e -> ChartUtils.pngChart(format("charts/%s.png", e.getKey()), 1024, 500, e.getValue(), Color.black, rulesMaxChart.get(e.getKey()), Color.lightGray, rulesMinChart.get(e.getKey()), Color.lightGray));
For the second you'll need jfreechart dependency

Moving from file-based tracing session to real time session

I need to log trace events during boot so I configure an AutoLogger with all the required providers. But when my service/process starts I want to switch to real-time mode so that the file doesn't explode.
I'm using TraceEvent and I can't figure out how to do this move correctly and atomically.
The first thing I tried:
const int timeToWait = 5000;
using (var tes = new TraceEventSession("TEMPSESSIONNAME", #"c:\temp\TEMPSESSIONNAME.etl") { StopOnDispose = false })
{
tes.EnableProvider(ProviderExtensions.ProviderName<MicrosoftWindowsKernelProcess>());
Thread.Sleep(timeToWait);
}
using (var tes = new TraceEventSession("TEMPSESSIONNAME", TraceEventSessionOptions.Attach))
{
Thread.Sleep(timeToWait);
tes.SetFileName(null);
Thread.Sleep(timeToWait);
Console.WriteLine("Done");
}
Here I wanted to make that I can transfer the session to real-time mode. But instead, the file I got contained events from a 15s period instead of just 10s.
The same happens if I use new TraceEventSession("TEMPSESSIONNAME", #"c:\temp\TEMPSESSIONNAME.etl", TraceEventSessionOptions.Create) instead.
It seems that the following will cause the file to stop being written to:
using (var tes = new TraceEventSession("TEMPSESSIONNAME"))
{
tes.EnableProvider(ProviderExtensions.ProviderName<MicrosoftWindowsKernelProcess>());
Thread.Sleep(timeToWait);
}
But here I must reenable all the providers and according to the documentation "if the session already existed it is closed and reopened (thus orphans are cleaned up on next use)". I don't understand the last part about orphans. Obviously some events might occur in the time between closing, opening and subscribing on the events. Does this mean I will lose these events or will I get the later?
I also found the following in the documentation of the library:
In real time mode, events are buffered and there is at least a second or so delay (typically 3 sec) between the firing of the event and the reception by the session (to allow events to be delivered in efficient clumps of many events)
Does this make the above code alright (well, unless the improbable happens and for some reason my thread is delayed for more than a second between creating the real-time session and starting processing the events)?
I could close the session and create a new different one but then I think I'd miss some events. Or I could open a new session and then close the file-based one but then I might get duplicate events.
I couldn't find online any examples of moving from a file-based trace to a real-time trace.
I managed to contact the author of TraceEvent and this is the answer I got:
Re the exception of the 'auto-closing and restarting' feature, it is really questions about the OS (TraceEvent simply calls the underlying OS API). Just FYI, the deal about orphans is that it is EASY for your process to exit but leave a session going. This MAY be what you want, but often it is not, and so to make the common case 'just work' if you do Create (which is the default), it will close a session if it already existed (since you asked for a new one).
Experimentation of course is the touchstone of 'truth' but I would frankly expecting unusual combinations to just work is generally NOT true.
My recommendation is to keep it simple. You need to open a new session and close the original one. Yes, you will end up with duplicates, but you CAN filter them out (after all they are IDENTICAL timestamps).
The other possibility is use SetFileName in its intended way (from one file to another). This certainly solves your problem of file size growth, and often is a good way to deal with other scenarios (after all you can start up you processing and start deleting files even as new files are being generated).

Controlling light using midi inputs

I currently am using Max/MSP to create an interactive system between lights and sound.
I am using Philips hue lighting which I have hooked up to Max/MSP and now I am wanting to trigger an increase in brightness/saturation on the input of a note from a Midi instrument. Does anyone have any ideas how this might be accomplished?
I have built this.
I used the shell object. And then feed an array of parameters into it via a javascipt file with the HUE API. There is a lag time of 1/6 of a second between commands.
Javascript file:
inlets=1;
outlets=1;
var bridge="192.168.0.100";
var hash="newdeveloper";
var bulb= 1;
var brt= 200;
var satn= 250;
var hcolor= 10000;
var bulb=1;
function list(bulb,hcolor,brt,satn,tran) {
execute('PUT','http://'+bridge+'/api/'+hash+'/lights/'+bulb+'/state', '"{\\\"on\\\":true,\\\"hue\\\":'+hcolor+', \\\"bri\\\":'+brt+',\\\"sat\\\":'+satn+',\\\"transitiontime\\\":'+tran+'}"');
}
function execute($method,$url,$message){
outlet(0,"curl --request",$method,"--data",$message,$url);
}
To control Philips Hue you need to issue calls to a restful http based api, like so: http://www.developers.meethue.com/documentation/core-concepts, using the [jweb] or [maxweb] objects: https://cycling74.com/forums/topic/making-rest-call-from-max-6-and-saving-the-return/
Generally however, to control lights you use DMX, the standard protocol for professional lighting control. Here is a somewhat lengthy post on the topic: https://cycling74.com/forums/topic/controlling-video-and-lighting-with-max/, scroll down to my post from APRIL 11, 2014 | 3:42 AM.
To change the bri/sat of your lights is explained in the following link (Registration/Login required)
http://www.developers.meethue.com/documentation/lights-api#16_set_light_state
You will need to know the IP Address of your hue hue bridge which is explained here: http://www.developers.meethue.com/documentation/getting-started and a valid username.
Also bear in mind the performance limitations. As a general rule you can send up to 10 lightstate commands per second. I would recommend having a 100ms gap between each one, to prevent flooding the bridge (and losing commands).
Are you interested in finding out details of who to map this data from a MIDI input to the phillips HUE lights within max? or are you already familiar with Max.
Using Tommy b's javascript (which you could put into a js object), You could for example scale the MIDI messages you want to use using midiin and borax objects and map them to the outputs you want using the scale object. Karlheinz Essl's RTC library is a good place to start with algorithmic composition if you want to transform the data at all http://www.essl.at/software.html
+1 for DMX light control via Max. There are lots of good max-to-dmx tutorials and USB-DMX hardware is getting pretty cheap. However, as someone who previously believed in dragging a bunch of computer equipment on stage just to control a light or two with an instrument, I'd recommend researching and purchasing a simple one channel "color organ" circuit kit (e.g., Velleman MK 110). Controlling a 120/240V light bulb via audio is easier than you might think; a computer for this type of application is usually overkill. Keep it simple and good luck!

Is there any way to inter communicate with modules in boilerplatejs?

Regarding the BoilerplateJs example, how should we adjust those modules to be intercommunicate in such a way once the user done any change to one module, the other related modules should be updated with that change done.
For example, if there is a module to retrieve inputs from user as name and sales and another module to update those retrieved data in a table or a graph, can you explain with some example ,how those inter connection occurs considering event handling?
Thanks!!
In BoilerplateJS, each of your module will have it's own moduleContext object. This module context object contains two methods 'listen' and 'notify'. Have a look at the context class at '/src/core/context.js' for more details.
The component that need to 'listen' to the event, should register for the event by specifying the name of the event and callback handler. Component that raise the event should use 'notify' method to let others know something interesting happened (optionally passing a parameter).
Get an update of the latest BoilerplateJS code from GitHub. I just committed changes with making clickCounter a composite component where 'clickme component' raising an event and 'lottery component' listening to the event to respond.
Code for notifying the Event:
moduleContext.notify('LOTTERY_ACTIVITY', this.numberOfClicks());
Code for listening to the Event:
moduleContext.listen("LOTTERY_ACTIVITY", function(activityNumber) {
var randomNum = Math.floor(Math.random() * 3) + 1;
self.hasWon(randomNum === activityNumber);
});
I would look at using a Publish-Subscribe library, such as Amplify. Using this technique it is easy for one module to act as a publisher of events and others to register as subscribers, listening and responding to these events in a highly decoupled manner.
As you are already using Knockout you might be interested in first trying Ryan Niemeyer's knockout-postbox plugin first. More background on this library is available here including a demo fiddle. You can always switch to Amplify later if you require.

how to use "FindBarcodesInUIImage"?

I am developing Barcode scanner application for iPhone.
Library: RedLaser
Just I want to scan the barcode from the existing image, not from camera.
I didn't get any documentation to call FindBarcodesInUIImage method manually.
Can I get any sample code ?
Does this snippet from the documentation help?
This method analyses a given image and returns information on any barcodes discovered in the image. It is intended to be used in cases where the user already has a picture of a barcode (in their photos library, for example) that they want to decode. This method performs a thorough check for all barcode symbologies we support, and is not intended for real-time use.
When scanning barcodes using this method, you cannot (and need not) specify a scan orientation or active scan region; the entire image is scanned in all orientations. Nor can you restrict the scan to particular symbol types. If such a feature is absolutely necessary, you can implement it post-scan by filtering the result set.
FindBarcodesInUIImage operates synchronously, but can be placed in a thread. Depending on image size and processor speed, it can take several seconds to process an image.
void ScanImageForBarcodes(UIImage *inputImage)
{
NSSet *resultSet = FindBarcodesInUIImage(inputImage);
// Print the results
NSLog(#"%#", resultSet);
}
If the SDK did not find any barcodes in the image, the log message will be (null). Otherwise, it will be something like:
{(
(0x19e0660) Code 39: 73250110 -- (1 finds)
)}
This log message indicates a found set containing one item, a Code 39 barcode with the value "73250110".
Remember that the SDK is not guaranteed to find barcodes in an image. Even if an image contains a barcode, the SDK might not be able to read it, and you will receive no results.