Curses.getstr cleans windows on the first call - ruby

The first Curses.getstr call clears another window. On later calls it doesn't happen.
require "curses"
Curses.init_screen
window = Curses::Window.new(10, 10, 5, 0)
window.scrollok true
Thread.new do
loop do
window.addstr rand(1000000).to_s
window.refresh
sleep 0.1
end
end
Curses.setpos 20, 0
sleep 1
# now several lines of numbers suddenly disappear
loop{ Curses.getstr }
How can I fight this behaviour?

What you're seeing is an implicit refresh() of the stdscr window -- because getstr() is really wgetstr(stdscr). Your options include:
Manually refreshing stdscr before drawing anything
Using your new window for input, rather than stdscr, and/or
Using stdscr for output.
At least, that's the answer I'd give for curses' native C -- I'm not sure how it translates to Ruby.

Related

Effect of print("") in a while loop in julia

I encountered a strange bug in julia. Essentially, adding a print("") statement somewhere sensibly changes the behavior of the following code (in a positive way). I am quite puzzled. Why?
xs = [1,2,3,4,5,6,7,8]
cmds = [`sleep $x` for x in xs]
f = open("results.txt", "w")
i = 1
nb_cmds = length(cmds)
max_running_ps = 3
nb_running_ps = 0
ps = Dict()
while true
# launching new processes if possible
if nb_running_ps < max_running_ps
if i <= nb_cmds && !(i in keys(ps))
print("spawn:")
println(i)
p = spawn(cmds[i], Base.DevNull, f, f)
setindex!(ps,p,i)
nb_running_ps = nb_running_ps + 1
i = i+1
end
end
# detecting finished processes to be able to launch new ones
for j in keys(ps)
if process_exited(ps[j])
print("endof:")
println(j)
delete!(ps,j)
nb_running_ps = nb_running_ps - 1
else
print("")
# why do I need that ????
end
end
# nothing runs and there is nothing to run
if nb_running_ps <= 0 && i > nb_cmds
break
end
end
close(f)
println("finished")
(Indeed, the commands are in fact more useful than sleep.)
If the print("") is removed or commented, the content of the conditional "if process_exited(ps[j])" seems to never run, and the program runs into an infinite while loop even though the first max_running_ps processes have finished.
Some background: I need to run a piece of code which takes quite a long time to run (and uses a lot of memory), for different values of a set of parameters (represented here by x). As they take a long time, I want to run them in parallel. On the other hand, there is nearly nothing to share between the different runs, so the usual parallel tools are not really relevant. Finally, I want to avoid a simple pmap, first in order to avoid loosing everything if there is a failure, and second because it may be useful to have partial results during the run. Hence this code (written in julia because the main code doing actual computations is in julia).
This is not a bug, though it might be surprising if you are not used to this kind of asynchronous programming.
Julia is single-threaded by default and only one task will run at once. And for a task to finish, Julia needs to switch to it. Tasks are switched whenever the current task yields.
print is also an asynchronous operation and so it will yield for you, but a simpler way to do it is yield(), which achieves the same result. For more information on asynchronous programming, see the documentation.

Make byebug stay in scope/function after running last line

Say I'm debugging a function like this
def foo {
byebug
x = 1+1
}
Running this, we hit the breakpoint. If I now hit "n", it runs the next line and exits the function. How can I instead remain in the function and inspect x?
Try finish 0.
The finish command should step out the number of frames you specify as an argument. If you specify 0, it has special behavior and just finishes the current frame without stepping out of it.

Terminal-based snake game: input thread manipulates output

I'm writing a snake game for the terminal, i.e. output via print.
The following works just fine:
while status[snake_monad] do
print to_string draw canvas, compose_all([
frame,
specs,
snake_to_hash(snake[snake_monad])
])
turn! snake_monad, get_dir
move! snake_monad, specs
sleep 0.25
end
But I don't want the turn!ing to block, of course. So I put it into a new Thread and let it loop:
Thread.new do
loop do
turn! snake_monad, get_dir
end
end
while status[snake_monad] do
...
# no turn! here
...
end
Which also works logically (the snake is turning), but the output is somehow interspersed with newlines. As soon as I kill the input thread (^C) it looks normal again.
So why and how does the thread have any effect on my output?
And how do I work around this issue? (I don't know much about threads, even less about them in ruby. Input and output concurrently on the same terminal make the matter worse, I guess...)
Also (not really important): Wanting my program as pure as possible, would it be somewhat easily possible to get the input non-blockingly while passing everything around?
Thank you!
You don't want non-blocking IO - you want unbuffered IO.
There's no need for threads, here - you just need to put your terminal into the right mode and then wait for the keypress on the main event loop.
Here's a completely ridiculous example.
require 'io/wait'
def ping
term = `stty -g`
`stty raw -echo cbreak`
loop do
if STDIN.ready?
#command thy snake!
ret = STDIN.getc
end
if ret
#process the snake command if there was one
STDOUT.write("you told the snake to #{ret}\n")
else
#slither around bitin' fools and hustling apples.
end
end
ensure
`stty #{term}`
end
I found a dirty solution:
I just had to add a carriage return (\r) after each newline in the to_string function, so everything that gets printed after it will be overwritten. Since it was a newline, it loses its effect. Everything seems fine now.
But I'd much rather know why this happens and fix it (if possible) cleanly.

how to kill orphaned winword.exe in matlab

Running matlab R2010B on Windows 7 Enterprise
In matlab scripts, I save a bunch of results to a word file and then at the end, close and quit word. The code I use is:
WordFname = ['BatInfoDoc' sprintf('%0.3f',now) '.doc']; % serialnumbered filenames
WordFile = fullfile(pwd,WordFname);
WordApp = actxserver('Word.Application');
WordDoc = WordApp.Documents.Add;
WordDoc.SaveAs2(WordFile);
....
WordApp.Selection.TypeText([title2 title3 title4 title5 title6]);
WordApp.Selection.TypeParagraph;
then finally at the end of the script
WordDoc.Close;
WordApp.Quit;
The problem I have is that through my development process, I often crash the matlab script and wind up leaving orphaned WINWORD.EXE processes, each one of which keeps a lock on the file it had been writing.
Up until now I have been using TaskManager to kill these processes one at a time by hand. Having been developing all morning, I find myself with around 20 files I can't delete because they are locked by about 11 orphaned WINWORD.EXE processes!
My question(s):
1) Is there an elegant way to handle the file writing and saving and closing and so on so I don't lock up files and processes when my script crashes out before I get to the part where I close the file and quit word?
2) Is there an elegant way to determine the bad processes from within matlab script and go through and delete them from within a matlab script? That is, can I code my matlab so it cleans up after itself?
ADDED A FEW MINUTES LATER:
By the way, I would prefer NOT to enclose all my code in a big try-catch and then close the windows after I've caught my error. The problem with this is I do like to go to debug mode on error, and caught errors don't bring me to debug mode.
Straight after you create Wordapp, use c = onCleanup(#()Wordapp.Quit). When your function exits, either naturally or with a crash, c will be deleted and its function will execute, quitting Word. If this is part of a script rather than a function, you can manually delete c to quit.
Also - while developing/debugging, I would set Wordapp.Visible to true so you can manually close word if necessary. Set back to false for production.
Use a handle class to delete them automatically.
classdef SafeWord < handle
properties(Access=public)
WordApp;
end
methods(Access=public)
function this = SafeWord(WordApp)
this.WordApp= WordApp;
end
function delete(this)
this.WordDoc.Close;
this.WordApp.Quit;
end
end
end
And the use case:
sw = SafeWord(Word.Application());
WordApplication = sw.WordApp;
% Do something here
% When sw ends its lifecycle, it calls delete.
Here is a related question.

Threading Around a Blocking Read

I'm doing some joystick programming in Ruby on Linux using a Ruby extension which wraps the basic functionality of joystick.h. Getting a joystick event is a blocking read by default, but I don't want that to interrupt the game loop.
Currently I'm hacking around it by making non-blocking calls to the joystick and running that in a really fast loop. That works, but it also makes the script use 100% CPU because I want the joystick events as close to real time as possible.
I'm trying to do something like
input = Thread.new do
while e = joystick.event
#event = e
end
end
main = Thread.new do
while true
sleep 0.1
puts #event
end
end
But even then, the joystick.event call blocks the main thread. Am I totally misunderstanding how Ruby threads work, or how joysticks work on Linux? Or is there a totally different way of approaching this that is better?
I needed to make the read call in the C extension using rb_thread_blocking_region. Works perfectly now!

Resources