Haxe - Adding an event to process exit? - process

Haxe porgramming beginner here and I can't seem to find a solution for my problem.
I'm simply running another program on the computer via sys.io.Process.
import sys.io.Process;
import neko.Lib;
class Main
{
static function main()
{
var cProcess = new Process(pClient + sArgs);
}
}
I only want my Haxe program to be running as long as the "cProcess" exists.
So I need some kind of Eventhandler that calls a function when the cProcess is being closed.
Does anyone have an idea how to solve this problem?
Any suggestions welcome!
Thanks!

If all you want to do is wait for the process to complete it's execution
just call exitCode(), it will block until launched process exits.
var cProcess = new Process(pClient + sArgs);
cProcess.exitCode();
trace("Done!");

Mihail's solution is simple and should work.
If you need more on that, you can try asys, which is the asynchronous version of the sys package in Haxe standard library.
var process = new asys.io.Process('your command');
process.exitCode().handle(function(code) trace('process exited with code: $code'));
It also depends on the platform you are running on. If you are running on platforms with async io like nodejs, things should be simple. Otherwise you have to consider threads.

Related

How to set thread priority of a coroutine dispatcher in Kotlin Native

I'm using coroutines in my multiplatform (android + iOS) application. To be able to use multithreaded coroutines, I'm using native-mt builds. So now I need to create a CoroutineDispatcher which runs on a hight priority thread. On android I'm doing it like this
val thread = HandlerThread("myThread", -20).also {
it.start()
}
val highPriorityDispatcher = Handler(thread.looper).asCoroutineDispatcher()
Is there a way to create a similar hight-priority dispatcher on iOS?
First what I tried is to create a new dispatcher using newSingleThreadContext. In k/n the resulting dispatcher exposes its Worker, but I have not found any ways to set worker priority.
Also I tried to raise thread priority with the setThreadPriority method:
val highPriorityDispatcher = newSingleThreadContext("myThread").also {
scope.launch(it){
NSThread.setThreadPriority(1.0)
}
}
But it did not seem to have the proper effect.
I'm thinking about writing a custom dispatcher using dispatch_queue, but it seems to be a non-trivial task. So any help to find an easier way to solve this problem would be appreciated.
Ok, actually it seems I was wrong.
val highPriorityDispatcher = newSingleThreadContext("myThread").also {
scope.launch(it){
NSThread.setThreadPriority(1.0)
}
}
does the job and actually changes the priority, confirmed in the iOS profiler.
At the end I also added
pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0)
call to set the QoS. I used the pthread version, because here it says that
NSThread possesses a qualityOfService property, of type
NSQualityOfService. This class will not infer a QoS based on the
context of its execution, so the value of this property may only be
changed before the thread has started. Reading the qualityOfService of
a thread at any time provides its current value.

Repast - call simulation from java program without GUI

I am following the instruction to test calling my simulation model from another java program.
package test;
//import repast.simphony.runtime.RepastMain;
public class UserMain {
public UserMain(){};
public void start(){
String[] args = new String[]{"D:\\user\\Repast_java\\IntraCity_Simulator\\IntraCity_Simulator.rs"};
repast.simphony.runtime.RepastMain.main(args);
// repast.simphony.runtime.RepastBatchMain.main(args);
}
public static void main(String[] args) {
UserMain um = new UserMain();
um.start();
}
}
The java program will launch the GUI with the RepastMain configuration:
repast.simphony.runtime.RepastMain.main(args);
The java program will soon be terminated without running and returning nothing if I apply non-GUI configuration:
repast.simphony.runtime.RepastBatchMain.main(args);
How to enable the running of the simulation in headless mode?
SECONDLY, I need to deploy my simulation model on a remote server (Linux). What is the best way for the server to call my simulation model? if HTTP, how to perform the configuration subsequently? The running of the model is preferred to be batch run method (either a single run or multiple runs depending on the user choice). The batch run output needs to be transformed into JSON format to feedback to the server.
Parts of the batch run mechanism for Simphony can probably be used for this. For some context on headless command line batch runs, see:
https://repast.github.io/docs/RepastBatchRunsGettingStarted.pdf
That doesn't align exactly with what you are trying to do, given that you are embedding the simulation run in other java code, but should help as background.
Ultimately, though the batch run code calls an InstanceRunner:
https://github.com/Repast/repast.simphony/blob/master/repast.simphony.distributed.batch/src/repast/simphony/batch/InstanceRunner.java
The InstanceRunner either iterates over a list of parameters sets in a file or parameter set strings passed to it directly and then performs a simulation run for each of those parameter sets. If you passed it a single parameter set, it would run once which I think is what you want to do. So, I would suggest looking at the InstanceRunner code to get a sense of how it works, and mimic InstanceRunner.main() in your code that calls the simulation.
As for the remote execution, Simphony cancopy a simulation to a remote resource, run it and copy the results back. That's integrated with the Simphony GUI and so is not callable from other code without some work on your part. All the relevant code is in:
https://github.com/Repast/repast.simphony/tree/master/repast.simphony.distributed.batch/src/repast/simphony/batch
The SSHSession class has code for executing commands on a remote resource over SSH, methods for copying files and so on. So, perhaps that might be useful to you.

Error in starting second JVM when one is already started

I am developing a client-server software in which server is developed by python. I want to call a group of methods from a java program in python. All the java methods exists in one jar file. It means I do not need to load different jars.
For this purpose, I used jpype. For each request from client, I invoke a function of python which looks like this:
def test(self, userName, password):
Classpath = "/home/DataSource/DMP.jar"
jpype.startJVM(
"/usr/local/java/jdk1.7.0_60/jre/lib/amd64/server/libjvm.so",
"-ea",
"- Xmx512m",
"-Djava.class.path=%s" % Classpath)
NCh = jpype.JClass("Common.NChainInterface")
n = NCh(self._DB_ipAddress, self._DB_Port, self._XML_SCHEMA_PATH, self._DSTDir)
jpype.shutdownJVM()
For one function it works, but for the second call it cannot start jvm.
I saw a lot of complain about it but I could not find any solution for that. I appreciate it if any body can help.
If jpype has problem in multiple starting jvm, is there any way to start and stop jvm once? The server is deployed on a Ubuntu virtual machine but I do not have enough knowledge to write for example, a script for this purpose. Could you please provide a link, or an example?
Check isJVMStarted() before startJVM().
If JVM is running, it will return True, otherwise False.
def init_jvm(jvmpath=None):
if jpype.isJVMStarted():
return
jpype.startJVM(jpype.getDefaultJVMPath())
For a real example, see here.
I have solved it by adding these lines when defining the connection:
if not jpype.isJVMStarted():
jpype.startJVM(jvmPath, args)
This issue is not resolved by et9's answer above.
The problem is explained here.
Effectively you need to start/stop the JVM at the server/module level.
I have had success with multiple calls using this method in unit tests.

Another doGet() issue with Google Apps Script - "Unknown macro doGet" error

I'am obviously new to Google Apps Script, nevertheless I have some experience in coding in C, PHP and Java. Since we would like to create a small CRM in our company with Google Apps Script, we need to create an application with a form available on Google Sites. I've been searching an answer for this problem a long time, I haven't unfortunately found any answer. I have a code like this:
var klienci_id = new Array(100);
var klienci_nazwa = new Array(100);
var klienci_adres = new Array(100);
var klienci_osoba = new Array(100);
var klienci_telefon = new Array(100);
var klienci_email = new Array(100);
function doGet(e) {
var app = UiApp.createApplication();
// hello world label
var helloworldLabel = app.createLabel("I love Apps Script!").setStyleAttribute("fontSize","16px");
// add the label to the app container
app.add(helloworldLabel);
return app;
}
function main() {
var klienci = SpreadsheetApp.openById("0ArsOaWajjzv9dEdGTUZCWFc1NnFva05uWkxETVF6Q0E");
var kuchnia_polska = klienci.getSheetByName("Kuchnia polska");
var dane = kuchnia_polska.getRange("D7:F22");
doGet();
}
And everytime I try to publish it and enter the given link I get the error "Unknown macro doGet". I know this is a common problem when somebody doesn't use doGet() function but I do - and it still doesn't work. I also believe that Google should create a thorought documentation on Google Apps Script, which would work the way the Unix manual does, since I just cannot get through all these strange pages of goddamn help :) It's neither a Windows help, nor a good manual ;)
Regards,
Kamil
I have a suspicion that you made a "version" once, published the app, went to the "real" link and not the "development" link, and then added the doGet() function. When you make a version, it freezes the code at that time. The version that the app is published at is the version of the code that will run at the "real" link (what you give users), which allows you to keep editing the code without disturbing existing users of your app. There is a special "development" link given to you in the publish dialog that always refers to the most recent version of the code, but which will only work for you and no one else.
I'm affraid there is a little misunderstanding on your side concerning the use of the 'doGet()' function. When you want to run an application as a webapp, the doc says indeed that it must contain a doGet function but what it doesn't say explicitely is that this function is supposed to be the starting point of the whole app, ie the function that the url will call in the first place. So it doesn't make much sense to have the doGet function called from a so called "main" function since the "main" function is not the main function...
I cannot imagine right now a situation where some function calls the doGet function since every function in the script is called initially (directly or indirectly) from this doGet function.... in fact the 'end' of any other function in the script 'returns' to the doGet initial function. Well this is maybe not absolutely true in every case but it gives you the general idea about how it works.
I'm hoping this is clear enough and, to return to your code snippet, if you remove the doGet(e) call, it will ideed show a nice "I love Apps Script!" but it will never do anything else, certainly not see the "main" function.
I've copied your code here https://script.google.com/macros/d/MJ80AK8t7kbgDcC-NaLPYvH797_hv7HHb/edit?template=app&folder=0AKGkLMU9sHmLUk9PVA
and when deployed as a web app appears to work https://script.google.com/macros/s/AKfycbxOiaukLt7P4pIm7bms7aU16uEo6FuZ-MNOh0tSqUwr/dev
Only thing I can think of is there is something else in your code not copied into the snippet that is throwing the exception.
[Just before the GUI Builder was published I came up with Creating a framework for custom form interfaces using Google Apps Script which might help you with your project]
Thank you both for help. Serge, yes, it's really not obvious what the structure of Google Apps Scripts should be. They are based on JavaScript, however, due to lack of HTML in the code they have completely different flow - so naturally, there has to be a main function which is executed first. And of course in every programming environment it has to have a different name to make it more distinguishable ;-)
I created a new copy of my application, not changing the code completely - deployed it and it works beautifuly. Since I haven't changed anything in access options, it's quite strange that two applications with the same code and the same options don't give the same result. I think it may be a kind of the environment flaw, maybe someone from Google should look at this :)
Here's the link to the script, I've set access to "Anyone with the link".
https://script.google.com/a/macros/foodbroker.pl/s/AKfycbwk2IM-rIYLhQl6HOlbppwGOnw4Ik_kH7ixbaSNVxIE-QR7cq8/exec

NAnt, MbUnit, CruiseControl, Selenium - passing settings to the test assembly

I am putting together some ideas for our automated testing platform and have been looking at Selenium for the test runner.
I am wrapping the recorded Selenium C# scripts in an MbUnit test, which is being triggered via the MbUnit NAnt task. The Selenium test client is created as follows:
selenium = new DefaultSelenium("host", 4444, "*iexplore", "http://[url]/");
How can I pass the host, port and url settings into the test so their values can be controlled via the NAnt task?
For example, I may have multiple Selenium RC servers listening and I want to use the same test code passing in each server address instead of embedding the settings within the tests themselves.
I have an approach mocked up using a custom NAnt task I have written but it is not the most elegant solution at present and I wondered if there was an easier way to accomplish what I want to do.
Many thanks if anyone can help.
Thanks for the responses so far.
Environment variables could work, however, we could be running parallel tests via a single test assembly so I wouldn't want settings to be overwritten during execution, which could break another test. Interesting line of thought though, thanks, I reckon I could use that in other areas.
My current solution involves a custom NAnt task build on top of the MbUnit task, which allows me to specify the additional host, port, url settings as attributes. These are then saved as a config file within the build directory and then read in by the test assemblies. This feels a bit "clunky" to me as my tests need to inherit from a specific class. Not too bad but I'd like to have less dependencies and concentrate on the testing.
Maybe I am worrying too much!!
I have a base class for all test fixtures which has the following setup code:
[FixtureSetUp]
public virtual void TestFixtureSetup ()
{
BrowserType = (BrowserType) Enum.Parse (typeof (BrowserType),
System.Configuration.ConfigurationManager.AppSettings["BrowserType"],
true);
testMachine = System.Configuration.ConfigurationManager.AppSettings["TestMachine"];
seleniumPort = int.Parse (System.Configuration.ConfigurationManager.AppSettings["SeleniumPort"],
System.Globalization.CultureInfo.InvariantCulture);
seleniumSpeed = System.Configuration.ConfigurationManager.AppSettings["SeleniumSpeed"];
browserUrl = System.Configuration.ConfigurationManager.AppSettings["BrowserUrl"];
targetUrl = new Uri (System.Configuration.ConfigurationManager.AppSettings["TargetUrl"]);
string browserExe;
switch (BrowserType)
{
case BrowserType.InternetExplorer:
browserExe = "*iexplore";
break;
case BrowserType.Firefox:
browserExe = "*firefox";
break;
default:
throw new NotSupportedException ();
}
selenium = new DefaultSelenium (testMachine, seleniumPort, browserExe, browserUrl);
selenium.Start ();
System.Console.WriteLine ("Started Selenium session (browser type={0})",
browserType);
// sets the speed of execution of GUI commands
if (false == String.IsNullOrEmpty (seleniumSpeed))
selenium.SetSpeed (seleniumSpeed);
}
I then simply supply the test runner with a config. file:
For MSBuild I use environment variables, I create those in my CC.NET config then they would be available in the script. I think this would work for you too.
Anytime I need to integrate with an external entity using NAnt I either end up using the exec task or writing a custom task. Given the information you posted it would seem that writing your own would indeed be a good solution, However you state you're not happy with it. Can you elaborate a bit on why you don't think you current solution is an elegant one?
Update
Not knowing internal details it seems like you've solved it pretty well with a custom task. From what I've heard, that's how I would have done it.
Maybe a new solution will show itself in time, but for now be light on yourself!