I have a kivy window, and I need to rotate a repeating loop"While" in code, but as expected, "While" stops the automatic update of the window, and as a result, locking it.
For example:
--- "loop window" ---
var = 0
while var <= 100:
var += 1
print(var)
--- "end of loop" ---
The problem is that the program has to wait for the loop to finish, and this is locking in the window. I know that in Tkinter has a function Youroot.update(), which updates the window whenever called, I want to know if kivy also owns, or something similar. Please :)
In Kivy, you should not run a loop like that on the main thread, so just run it on another thread (see threading). If you need to make a change to something in the kivy display from that thread, use Clock.schedule_once() to schedule just that bit back on the main thread.
I have a question. Let's say that I have created User Defined Attribute attr with values A,B,C.
How to configure taskwarrior to automatically change the attr value from A to B when I enter
task x start
and change attr from B to C when
task x done
Disadvantage of suggested solution:
You continuously need to have a script running in the background.
There can occur a small delay between your task x start command, and the change of UDA attr
It is a bit of a tedious method, perhaps you can also accomplish your goal using solely taskwarrior commands/settings.
It is made for fun and I can currently not offer any security or proper functioning guarantees. I tested and use it on WSL Ubuntu 16.04.
Assumptions:
If you enter task x start the attribute Start is set to a valid date.
Solution:
You can have a script running in the background that reads the properties of all tasks, and as soon as it detects a valid date in the Start attribute of a tasks, and a value of B in the UDA attr then it sets the UDA attr to C by executing the command task x modify attr:C command.
I made a script/small project that sorts on a custom setting of project and urgency, and it contains the functionalities of:
Running in the background from startup automatically,
Scanning the taskproperties and automatically applying the changes that are programmed in the script.
So in effect,
You should modify/add the UDA attr here:
And duplicate and change for example method private static void setCustomSort(ArrayList<Task> taskList) {1 on line 88 of the main
(For the 2nd step, between //get uuid and //create command you should add the condition that checks the task for a valid id. Then if it has, change the command that is generated to task modify attr:C)
The instructions to compile the java code and set up automation are listed here.
I am creating something along the likes of a text adventure game. I have a .yaml file that is my input. This file looks something like this
node_type:
action
title:
Do some stuff
info:
This does some stuff and things
script:
'print("hello world")
print(ret_val)
foo.bar(True)
ret_val = (foo.bar() == True)
if (thing):
print(thing)
print(ret_val)
'
My end goal is to have my python program run the script portion of the yaml file exactly as if it had been copy pasted into the main code. (I know there are about ten bazillion security reasons I should not be running user input like this, but I am the only one writing these nodes, and the only one using this program so I'm mostly just ignoring this fact...)
Currently my attempt goes like this: I load my yaml file as a dict using pyyaml
node = yaml.safe_load(file.yaml)
Then I'm trying to use exec to run my code and hitting a lot of problems, I can't run if statements, I simply get a syntax error, and I can't get any sort of return value from my code. I've tried this as a work around:
def main()
ret_val = "test";
thing = exec(node['script'], globals(),locals())
print(ret_val)
which when run with the above .yaml file prints
>> hello world
>> test
>> True
>> test
for some reason not actually modifying any of my main variables even though I fed them to exec.
Is there any way for me to work around these issues or is there an all together better way to be doing this?
One way of doing this would be to parse the code out and save it to a .py file, from which it can be imported dynamically, for example by importlib.
You might want to encapsulate parsed code into a function, which you can then easily call to invoke your action. Also, it would make sense to specify some default imports there.
Maybe I'm just missing something obvious in the System.Process API (http://hackage.haskell.org/package/process), but it doesn't appear to support getting the raw PID of a process created. The API usually returns a ProcessHandle which can be used easily enough, but this doesn't appear to fulfill a deployment need I have.
I have a case where I want to spawn a long-running process, log the PID it's using, and be able to automatically come back at a later time (days, weeks, months) and kill the old process and re-start with a new process. I'm sure there are several ways to do this auto-deploy-and-restart, but PIDs seemed like the simplest way to do so without too much platform-dependent code.
I'm open to other suggestions about my underlying problem, but it seems odd to me that I can't find any direct PID references (or a way to convert to them) in the process API. This seems like an oversight of the API.
Here is some example code:
import System.Process
import System.Process.Internals
-- | returns Just pid or Nothing if process has already exited
getPid ph = withProcessHandle ph go
where
go ph_ = case ph_ of
OpenHandle x -> return $ Just x
ClosedHandle _ -> return Nothing
main = do
(_,_,_,ph) <- createProcess $ shell "echo $$"
getPid ph >>= print
Note: I haven't tested this under Windows, but it works on OSX and, presumably, Linux.
For Windows, the Win32 package has a getProcessId function in the module System.Win32.Process, and according to code I've read, this should work:
import System.Win32.Process (getProcessId)
main = do
(_,_,_,ph) <- createProcess $ shell "echo $$"
pid <- withProcessHandle ph go
print pid
where go (OpenHandle x) = fmap Just $ getProcessId x
go (ClosedHandle _) = return Nothing
The code I am basing this on is the code for interruptProcessGroupOf (link)
Looks like interruptProcessGroupOf in System.Process calls either System.Posix.Process.getProcessGroupIDOf (POSIX/not Windows) or System.Win32.Process.getProcessId (Windows) to get the pid: http://git.haskell.org/packages/process.git/blob/HEAD:/System/Process.hs
If everything else fails,
import System.Process.Internals
and then dig inside the ProcessHandle abstraction. You probably want to extract the PHANDLE from the MVar.
Note that this breaks the abstraction layer, which is meant to make the code portable across OSs. Use it with extreme care, and be prepared for it to break in new versions of the library.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I'd like to, basically, have a quick way to select a box (region of interest) in an image, and get geometry output in ImageMagick's format. I cannot see an easy way to do it with the default ImageMagick display viewer, so I'm looking for some API (and hopefully examples) to allow me to code my own viewer.
A bit of background: In ImageMagick • View topic - selecting a region of interest from command line (2008) it is said you cannot do it, however, there is display: ImageMagick - Region of Interest (2003?) which explains how to do it (but apparently it refers to an older version).
Anyways, this is how things look is you call display -size 300x500 pattern:checkerboard (pattern:checkerboard is built-in pattern image in imagemagick):
Once the "ImageMagick" display window is up, click on it; then Command menu shows - from it, choose /"Image Edit"/"Region of Interest..."; then can click and drag on the viewer display window. And you also get the geometry in upper left corner - but you cannot copy/paste it as text (so I've had to retype).
Also, display in command line mode takes up the terminal (linux - Make imagemagick's display exit at terminal, preserving the window (single instance mode) - Super User) - and I cannot see a way to force it to run in "single instance mode", such that I could issue filenames on the command line, and display would load them in the one and the same currently running instance.
Now, I've found Casting spells with ImageMagick - Image manipulation for programmers (2012), which mentions a MagickWand API; after some searching, I found on the imagemagick site:
ImageMagick: MagickWand, C API for ImageMagick
ImageMagick: MagickCore, Low-level C API for ImageMagick
ImageMagick: PerlMagick, Perl API for ImageMagick
ImageMagick: Magick++, C++ API for ImageMagick
So, my first thought was a script in Python - but apparently there is only a Perl API, which is fine.
However, what I need to code is basically a command line interface, which will start a display -like window process as a "single instance", and exit the terminal while passing parameters such as file name, -density etc to the window; the window would then react on mouse clicks, allowing selection of a crop geometry box (region of interest) - and finally, render the geometry string in a text box, so you can copy it. But as far as I can see, all the APIs are oriented toward performing the functions of the command-line convert.
So my question is - can any of these API's be used to program a display-like GUI; and do there exist any examples of a similar nature (preferably in a scripting language, but I'll live with C/C++) which can be pointed out?
Many thanks in advance for any answers,
Cheers!
Well, this turned out to be a bit of a pain, but I managed to put together a Perl-Tk script with ImageMagick API, that behaves like what I wanted: imgckdis.pl (code also below). Here is a screenshot:
Note that it can pretty much just display an image in hardcoded 400x400 px (although it may extend for bigger images) - there is no menus, no mouse interaction (scrollwheel zoom) - pretty much nothing :) The script only accepts one command-line argument - a file to be opened; but it can also understand ImageMagick specials like "xc:white" (the ImageMagick portion will even automatically render SVG files, as shown on screenshot).
But one thing it is capable of, is working in single instance mode: the first instance started becomes a "master", and draws the Tk window, and locks the respective terminal. Subsequent instances of the script, realizing the master instance is already started, will simply issue a command to the master to load a new image.
This "issuing a command to 'master'" turned out to be not so easy, as the collection of links below shows (as well as the revision notes in the online vesrion). I thought at first, that using interprocess-communication shared variables would allow me to store a "pointer by reference" to the master; and then allow the subsequent instances to call functions on it. Well, it seems that cannot be done - for one, Perl may discourage that - but even if you hop over all those checks, in the end you get a memory address which is not seen as in shared space, and so one cannot retrieve anything from it. Furthermore, the IPC::Shareable Perl package is possibly "guaranteed" only for integers and strings ?!
Nevertheless, the approach that finally worked is, as hinted, to have the "master" poll for changes in changed variables; and non-master instances to simply change this variable when they are called - and this approach seems to work... However, for a "real" application, one would then have to think of organizing quite a few of these shared variables..
Well, maybe one cannot still zoom and reposition the image, and draw a geometry rectangle - but, at least it's an example that can be demonstrated to be working (at least on Ubuntu) :)...
Hope this helps someone,
Cheers!
The code:
#!/usr/bin/perl
# imgckdis.pl
# http://sdaaubckp.svn.sf.net/viewvc/sdaaubckp/single-scripts/imgckdis.pl
use warnings;
use strict;
use Image::Magick; # sudo apt-get install perlmagick # debian/ubuntu
use Tk;
use MIME::Base64;
use Carp;
use Fcntl ':flock';
use Data::Printer;
use Class::Inspector;
use IPC::Shareable;
my $amMaster = 1;
my $file_read;
open my $self, '<', $0 or die "Couldn't open self: $!";
flock $self, LOCK_EX | LOCK_NB or $amMaster = 0;
if ($amMaster == 1) {
print "We are master single instance as per flock\n";
IPC::Shareable->clean_up_all;
}
if (!$ARGV[0]) {
$file_read = "xc:white";
} else {
$file_read = $ARGV[0];
}
chomp $file_read;
my %options = (
create => 1,
exclusive => 0,
mode => 0644,
destroy => 0,
);
my $glue1 = 'dat1';
my $glue2 = 'dat2';
my $refcount;
my $reffname;
my $lastreffname;
my $refcount_handle = tie $refcount, 'IPC::Shareable', $glue1 , \%options ;
if ($amMaster == 1) {
$refcount = undef;
}
my $reffname_handle = tie $reffname, 'IPC::Shareable', $glue2 , \%options ;
if ($amMaster == 1) {
$reffname = undef;
}
my ($image, $blob, $content, $tkimage, $mw);
if ($amMaster == 1) { # if (not(defined($refcount))) {
# initialize the assigns
$lastreffname = "";
$reffname_handle->shlock(LOCK_SH|LOCK_NB);
$reffname = $file_read; #
$reffname_handle->shunlock();
$refcount_handle->shlock(LOCK_SH|LOCK_NB);
$refcount = 1; #
$refcount_handle->shunlock();
}
# mainly from http://objectmix.com/perl/771215-how-display-image-magick-image-tk-canvas.html
sub generateImageContent() {
#fake a PGM then convert it to gif
$image = Image::Magick->new(
size => "400x400",
);
$image->Read($file_read); #("xc:white");
$image->Draw(
primitive => 'line',
points => "300,100 300,500",
stroke => '#600',
);
# set it as PGM
$image->Set(magick=>'pgm');
#your pgm is loaded here, now change it to gif or whatever
$image->Set(magick=>'gif');
$blob = $image->ImageToBlob();
# Tk wants base64encoded images
$content = encode_base64( $blob ) or die $!;
}
sub loadImageContent() {
#fake a PGM then convert it to gif
$image = Image::Magick->new(
size => "400x400",
);
$image->Read($lastreffname); #("xc:red") for test
# set it as PGM
$image->Set(magick=>'pgm');
#your pgm is loaded here, now change it to gif or whatever
$image->Set(magick=>'gif');
$blob = $image->ImageToBlob();
# Tk wants base64encoded images
$content = encode_base64( $blob ) or die $!;
#~ $tkimage->read($content); # expects filename
$tkimage->put($content); # works!
}
sub CleanupExit() {
# only one remove() passes - the second fails: "Couldn't remove shared memory segment/semaphore set"
(tied $refcount)->remove();
IPC::Shareable->clean_up;
$mw->destroy();
print "Exiting appliction!\n";
exit;
}
sub updateVars() {
if ( not($reffname eq $lastreffname) ) {
print "Change: ", $lastreffname, " -> ", $reffname, "\n";
$lastreffname = $reffname;
loadImageContent();
}
}
if ( not($amMaster == 1) ) {
# simply set the shared variable to cmdarg variable
# (master's updateVars should take care of update)
$reffname_handle->shlock(LOCK_SH|LOCK_NB);
$reffname = $file_read;
$reffname_handle->shunlock();
# and exit now - we don't want a second instance
print "Main instance of this script is already running\n";
croak "Loading new file: $file_read";
}
$mw = MainWindow->new();
$mw->protocol(WM_DELETE_WINDOW => sub { CleanupExit(); } );
generateImageContent();
$tkimage = $mw->Photo(-data => $content);
$mw->Label(-image => $tkimage)->pack(-expand => 1, -fill => 'both');
$mw->Button(-text => 'Quit', -command => sub { CleanupExit(); } )->pack;
# polling function for sharable - 100 ms
$mw->repeat(100, \&updateVars);
MainLoop;
__END__
Relevant links:
How to display an Image::Magick image in a Tk::Canvas?
Installing the Perl Image::Magick module on CentOS 5.2 (Fourmilog: None Dare Call It Reason)
perl - How do I install Image::Magick on Debian etch? - Stack Overflow
[magick-users] PerlMagick 6.0.0 Composite -opacity doesn't work
Ensuring only one copy of a perl script is running at a time
Re: Limiting a program to a single running instance - nntp.perl.org
Sys::RunAlone - search.cpan.org
What's the best way to make sure only one instance of a Perl program is running? - Stack Overflow
reinstall PERL - PERL Beginners (Do you need to predeclare croak?)
Image in Perl TK?
Perl Tk::Photo help
introspection - How do I list available methods on a given object or package in Perl? - Stack Overflow
Can't install IPC:Shareable
Share variables between Child processes in perl without IPC::Shareable - Stack Overflow
IPC::Shareable - search.cpan.org
perl - Checking IPC Shareable lock - Stack Overflow
Storing complex data structures using Storable
using tie on two arrays on IPC::Shareable makes array1 and array2 both same even though array2 is not updated.
Dereferencing in perl
Shared Memory using IPC::Shareable - Can't use an undefined value as an ARRAY reference
Re: Handling child process and close window exits in Perl/Tk
How can I convert the stringified version of array reference to actual array reference in Perl? - Stack Overflow
Re: IPC::Shareable Problem with multidimentional hash
perl - IPC::Shareable variables, "Can't use string ... as a SCALAR ref.." and memory address - Stack Overflow
Perl/Tk App and Interprocess Communication
Re: Antw: Re: Perl/Tk + Thread - nntp.perl.org