I'm trying to establish an interactive session with another process using Mathematicas' StartProcess. It is basically the same scenario as in this question, only that I'm calling a D program instead of a Fortran one.
Take for instance a minimal D program that reads from Standard Input and writes to Standard Output interactively (notice the infinite loop):
// D
void main(string[] argv) {
while(true) {
auto name = readln().chomp;
writefln("Hello %s!", name);
}
}
When I run this program from the command prompt, it behaves as expected. If I would want to run it from Mathematica, this is supposed to work:
(* Mathematica *)
dhello = StartProcess["dhello.exe"];
WriteLine[dhello, "Wulfrick"];
ReadLine[dhello]
but it doesn't. The call to ReadLine[] blocks, as if waiting for the Process to finish. I initially thought it may be a problem in Mathematica, but I tried calling a C# program instead and it worked! Take for instance:
// C#
static void Main(string[] args) {
while (true) {
var name = Console.ReadLine();
Console.WriteLine($"Hello {name}!");
}
}
Now on the Mathematica side, doing:
(* Mathematica *)
cshello = StartProcess["cshello.exe"];
WriteLine[cshello, "Wulfrick"];
ReadLine[cshello]
Works as expected, printing the output as soon as I call ReadLine[] and maintaining interactivity. So it looks like the problem is in the D side really. Also that's why I decided to post here and not on mathematica.stackexchange.
I would really like to make this work with the D program. Any input is much appreciated.
System:
Windows 10 x64
Mathematica 11.2
DMD v2.078.2
Standard output may not have been flushed.
Try:
import std.stdio : stdout;
stdout.flush();
At the end of your while loop.
Related
I am currently working on a Ruby script which is supposed to perform different tasks on a pretty long list of hosts. I am using the net-ssh gem for connectivity with those hosts. The thing is, there seem to exist some conditions under which net-ssh times out without throwing an exception. As of know, the script was only once able to finish a run. Most of the time, the scripts just hangs at some point without ever throwing an exception or doing anything.
I thought about running all tasks that may timeout in different threads, passing them a pointer to some variable they can change when the tasks finished successfully, and then check that variable for a given amount of time. If the task has not finished by then, throw an exception in the main thread that I can catch somewhere.
This is the first time I am writing something in Ruby. To give a clear demonstration of what I want to accomplish, this is what I'd do in C++:
void perform_long_running_task(bool* finished);
void start_task_and_throw_on_timeout(int secs, std::function<void(bool*)> func);
int seconds_to_wait {5};
int seconds_task_takes{6};
int main() {
start_task_and_throw_on_timeout(seconds_to_wait, &perform_long_running_task);
// do other stuff
return 0;
}
void perform_long_running_task(bool* finished){
// Do something that may possible timeout..
std::this_thread::sleep_for(std::chrono::seconds(seconds_task_takes));
// Finished..
*finished = true;
}
void start_task_and_throw_on_timeout(int secs, std::function<void(bool*)> func){
bool finished {false};
std::thread task(func, &finished);
while (secs > 0){
std::this_thread::sleep_for(std::chrono::seconds(1));
secs--;
if (finished){
task.join();
return;
}
}
throw std::exception();
}
Here, when 'seconds_task_takes' is bigger than 'seconds_to_wait', an exception is thrown in the main thread. If the task finishes in time, everything goes on smoothly.
However, I need to write my piece of software in a dynamic scripting language that can run anywhere and needs not to be compiled. I would be super glad for any advice about how I could write something like the code above in Ruby.
Thanks alot in advance :)
edit: in the example ,I added a std::function parameter to start_task_and_throw_timeout so it's reusable for all similar functions
I think module timeout has everything you need to do. It allows you to run the block for a while and raise an exception if it was not fast enough.
Here is a code example:
require "timeout"
def run(name)
puts "Running the job #{name}"
sleep(10)
end
begin
Timeout::timeout(5) { run("hard") }
rescue Timeout::Error
puts "Failed!"
end
You can play with it here: https://repl.it/repls/CraftyUnluckyCore. The documentation for the module lives here: https://ruby-doc.org/stdlib-2.5.1/libdoc/timeout/rdoc/Timeout.html. Notice that you can customize not only the timeout, but also error class and message, so different jobs may have different kinds of errors.
I need to get user input (y/n) keypress in console.
How I can do it? I know that I can use readln, but is there any other way? I am trying to use getc()
import std.stdio;
import std.string;
import std.stream;
void main()
{
while (getc() != 'y')
{
writeln("try again");
}
}
but I am getting error:
source\app.d(6): Error: function core.stdc.stdio.getc (shared(_iobuf)* stream) is not callable using argument types (File)
next attempt:
char [] checkYesNo() #property
{
char [] key;
while(readln(key) != 'y')
{
}
return key;
}
This code compile, but failure at execution time with strange error "Error executing command run"
One library that does the single press is my terminal.d
https://github.com/adamdruppe/arsd/blob/master/terminal.d
It looks more complex than it is. Here's an example to get a single key:
import terminal;
void main() {
auto terminal = Terminal(ConsoleOutputType.linear);
auto input = RealTimeConsoleInput(&terminal, ConsoleInputFlags.raw);
terminal.writeln("Press any key to exit");
auto ch = input.getch();
terminal.writeln("Bye!");
}
To build, put terminal.d in your folder and then compile them together: dmd yourfile.d terminal.d.
First, you construct a terminal. The two types are linear or cellular. Linear outputs one line at a time, cellular goes "full screen" in the console.
Then, you make an input struct based on that terminal. The ConsoleInputFlags says what you want: do you want echo? Mouse input? etc. raw is the simplest one: it will send you plain keyboard input as they happen with relatively little else.
Then you can write to the terminal and get characters from the input. The input.getch() line fetches a single character, returning immediately when something is available without buffering. Other functions available on input include kbhit, which returns true if a key was hit so input is available, false if it isn't - useful for a real time game, being checked on a timer, or nextEvent, which gives full input support, including mouse events. The Demo in the terminal.d source code shows something with full support:
https://github.com/adamdruppe/arsd/blob/master/terminal.d#L2265
Another useful convenience function on terminal itself btw is getline, which grabs a full line at a time, but also lets the user edit it and offers history and autocomplete. terminal also offers a function called color to do colored output, and moveTo, useful in cellular mode, to move the cursor around the screen. Browse the code to learn more, if you're interested.
The error is because phobos is conflicting with the runtime.
std.stdio publicly imports core.stdc.stdio, and they both define stdin, but as different types. getc() really just calls fgetc( stdin ), so when the runtime tries calling getc(), it passes in the stdin from std.stdio instead of the correct one from core.stdc.stdio, resulting in the error.
The best way to get around the conflict is just to alias core.stdc.stdio as something else and then use the fully qualified name.
import std.stdio;
void main()
{
while (getc() != 'y')
{
writeln("try again");
}
}
auto getc()
{
import stdc = core.stdc.stdio;
return stdc.getc( stdc.stdin );
}
But beware that getc() uses a buffer internally, and won't return until the user presses the enter key, at which point it reads the first char from the buffer and returns that, and will continue to read the next char from the buffer for subsequent calls until it reaches the end. So entering nnn<enter> in the terminal window results in try again being printed 3 times. If you want a method that returns a single char without the need for the enter key, you'll need to look for a library solution, no standard functions for that exist in either C or D.
If you're not concerned with a cross-platform solution, there's a Windows-specific header that defines a getch() function which doesn't use a buffer and returns on every keystroke, rather than on enter. Just add this to your code and replace the call to getc() with a call to getch().
extern( C ) int getch();
How about:
import std.stdio;
void main(){
writefln("Enter something: ");
char entered;
do{
readf(" %c\n", &entered);
writefln("Entered: %s", entered);
}while(entered != 'y');
}
The important bit is the " %c\n".
%c tells readf to match a char rather than a string.
I have the following UnitTest:
[TestMethod]
public void NewGamesHaveDifferentSecretCodesTothePreviousGame()
{
var theGame = new BullsAndCows();
List<int> firstCode = new List<int>(theGame.SecretCode);
theGame.NewGame();
List<int> secondCode = new List<int>(theGame.SecretCode);
theGame.NewGame();
List<int> thirdCode = new List<int>(theGame.SecretCode);
CollectionAssert.AreNotEqual(firstCode, secondCode);
CollectionAssert.AreNotEqual(secondCode, thirdCode);
}
When I run it in Debug mode, my code passes the test, but when I run the test as normal (run mode) it does not pass. The exception thrown is:
CollectionAssert.AreNotEqual failed. (Both collection contain same elements).
Here is my code:
// constructor
public BullsAndCows()
{
Gueses = new List<Guess>();
SecretCode = generateRequiredSecretCode();
previousCodes = new Dictionary<int, List<int>>();
}
public void NewGame()
{
var theCode = generateRequiredSecretCode();
if (previousCodes.Count != 0)
{
if(!isPreviouslySeen(theCode))
{
SecretCode = theCode;
previousCodes.Add(previousCodes.Last().Key + 1, SecretCode);
}
}
else
{
SecretCode = theCode;
previousCodes.Add(0, theCode);
}
}
previousCodes is a property on the class, and its Data type is Dictionary key integer, value List of integers. SecretCode is also a property on the class, and its Data type is a List of integers
If I were to make a guess, I would say the reason is the NewGame() method is called again, whilst the first call hasn't really finished what it needs to do. As you can see, there are other methods being called from within the NewGame() method (e.g. generateRequiredSecretCode()).
When running in Debug mode, the slow pace of my pressing F10 gives sufficient time for processes to end.
But I am not really sure how to fix that, assuming I am right in my identification of the cause.
What happens to SecretCode when generateRequiredSecretCode generates a duplicate? It appears to be unhandled.
One possibility is that you are getting a duplicate, so SecretCode remain the same as its previous value. How does the generator work?
Also, you didn't show how the BullsAndCows constructor is initializing SecretCode? Is it calling NewGame?
I doubt the speed of keypresses has anything to do with it, since your test method calls the functions in turn without waiting for input. And unless generateReq... is spawning a thread, it will complete whatever it is doing before it returns.
--after update--
I see 2 bugs.
1) The very first SecretCode generated in the constructor is not added to the list of previousCodes. So the duplicate checking won't catch if the 2nd game has the same code.
2) after previousCodes is populated, you don't handle the case where you generate a duplicate. a duplicate is previouslySeen, so you don't add it to the previousCodes list, but you don't update SecretCode either, so it keeps the old value.
I'm not exactly sure why this is only showing up in release mode - but it could be a difference in the way debug mode handles the random number generator. See How to randomize in WPF. Release mode is faster, so it uses the same timestamp as seed, so it does in fact generate exactly the same sequence of digits.
If that's the case, you can fix it by making random a class property instead of creating a new one for each call to generator.
As you know TCL has some mathematical functions such as sin, cos, and hypot that are called in expr command with () braces as follows:
puts [expr sin(1.57)]
Now how can I add a function using TCL library functions so that it was called exactly the same way, and was doing something that a certain proc defines.
I would like to clarify my question. Say there is a proc (string) as follows:
proc add { a b } { return [expr $a+$b] } ;# string of a proc
Also I have a TCL interpreter in my C++ code. Now I want get the string of a proc and runtime register a function called add into the tcl::mathfunc namespace (I guess I should use Tcl_CreateObjCommand) so that I could call the following:
puts [expr add(1.57, 1.43)]
How this can be done. Could you please write a simple example. I could not find any example in TCL documentation and in books as well which describe the usage of this command.
Creating a function from C isn't too hard. To do it, you've got to write an implementation of a command that will perform the operation, and register that implementation as a command in the correct namespace. (In 8.4 and before, functions were done with a separate interface that was quite a bit nastier to use; the mechanism was wholly overhauled in 8.5.)
Command Implementation
Note that the signature is defined, and the ignored parameter is not used here. (It's really a void * — great when you're wanting to do things like binding a command to an object — but it simply isn't needed for doing an addition.)
static int AddCmd(ClientData ignored, Tcl_Interp *interp, int objc,
Tcl_Obj *const objv[]) {
double x, y, sum;
/* First, check number of arguments: command name is objv[0] always */
if (objc != 3) {
Tcl_WrongNumArgs(interp, 1, objv, "x y");
return TCL_ERROR;
}
/* Get our arguments as doubles */
if ( Tcl_GetDoubleFromObj(interp, objv[1], &x) != TCL_OK ||
Tcl_GetDoubleFromObj(interp, objv[2], &y) != TCL_OK) {
return TCL_ERROR;
}
/* Do the real operation */
sum = x + y;
/* Pass the result out */
Tcl_SetObjResult(interp, Tcl_NewDoubleObj(sum));
return TCL_OK;
}
Don't worry about the fact that it's allocating a value here; Tcl's got a very high performance custom memory manager that makes that a cheap operation.
Command Registration
This is done usually inside an initialization function that is registered as part of a Tcl package definition or which is called as part of initialization of the overall application. You can also do it directly if you are calling Tcl_CreateInterp manually. Which you do depends on how exactly how you are integrating with Tcl, and that's quite a large topic of its own. So I'll show how to create an initialization function; that's usually a good start in all scenarios.
int Add_Init(Tcl_Interp *interp) {
/* Use the fully-qualified name */
Tcl_CreateObjCommand(interp, "::tcl::mathfunc::add", AddCmd, NULL, NULL);
return TCL_OK;
}
The first NULL is the value that gets passed through as the first (ClientData) parameter to the implementation. The second is a callback to dispose of the ClientData (or NULL if it needs no action, as here).
Doing all this from C++ is also quite practical, but remember that Tcl is a C library, so they have to be functions (not methods, not without an adapter) and they need C linkage.
To get the body of a procedure from C (or C++), by far the easiest mechanism is to use Tcl_Eval to run a simple script to run info body theCmdName. Procedure implementations are very complex indeed, so the interface to them is purely at the script level (unless you actually entangle yourself far more with Tcl than is really wise).
Hi people i am currently working at my second visual studio made project :) . I am a delphi coder so please excuse my ignorance.
I want to write a simple routine to list some files and i wanted to write a simple function like Delphi's
IncludeTrailingPathDelimiter()
It's a simple function witch adds a \ to a file path if is not there...
So i came up with this
void listfiles(wchar_t * root)
{
if (root[wcslen(root) - 1] != L'\\')
wcscat_s(root,wcslen(root)+2,L"\\");
printf("%S",root);
}
It works but after exiting the function i get an (Stack Corruption) over this line
wcscat_s(root,wcslen(root)+2,L"\\");
What am i doing wrong do i need to allocate memory to the new created buffer or what?
Using the safe string functions is fine, but you do need to use them properly. The 2nd argument to wcscat_s() is the size of the buffer. You don't know the size of the buffer in this code, it most certainly isn't wcslen(root)+2. Rewrite the function like this:
void listfiles(wchar_t * root, size_t rootSize)
{
if (root[wcslen(root) - 1] != L'\\')
wcscat_s(root, rootSize, L"\\");
printf("%S",root);
}
...
wchar_t buffer[666];
...
listfile(buffer, sizeof(buffer) / sizeof(buffer[0]));
And now the debugger will step in when your buffer is too small. It is.