Trouble binding print screen in XMonad - xorg

I'm trying to bind the print screen key in Xmonad, but it doesn't seem to work.
I have the following code in my xmonad.hs:
myKeys conf#(XConfig {XMonad.modMask = modm}) = M.fromList $
[
...
, ((0, xK_Print), spawn "scrot -q 1 $HOME/pictures/screenshots/%Y-%m-%d-%H:%M:%S.png")
...
]
However, if I press print screen nothing happens (the file isn't there). Replacing xK_Print with xK_F12 works.
Using xev, I found the keysym of print screen:
KeyPress event, serial 32, synthetic NO, window 0x1a00001,
root 0x90, subw 0x0, time 8532454, (593,435), root:(594,454),
state 0x10, keycode 218 (keysym 0xff61, Print), same_screen YES,
XKeysymToKeycode returns keycode: 107
XLookupString gives 0 bytes:
XmbLookupString gives 0 bytes:
XFilterEvent returns: False
KeyRelease event, serial 32, synthetic NO, window 0x1a00001,
root 0x90, subw 0x0, time 8532501, (593,435), root:(594,454),
state 0x10, keycode 218 (keysym 0xff61, Print), same_screen YES,
XKeysymToKeycode returns keycode: 107
XLookupString gives 0 bytes:
XFilterEvent returns: False
which seems to be 0xff61. But using this instead of xK_Print doesn't work as well (I checked with ghci and xK_Print is just an alias for 0xff61).
How can I bind the print screen key to something?
Of course I can use another key for the job, but it feels silly not using print screen to take a screenshot.

Try changing the $HOME to a full, hardcoded path. I think that when xmonad.hs runs, it doesn't have access to all the environment variables.
To debug this, do the following:
Map that key to something that you know works (i.e., duplicate the key binding that you used for another, working key).
If that works, then you know that Xmonad can "see" the key.
Now map that key to what you want, but send any errors to a file. E.g.,
.... spawn "scrot -q 1 $HOME/pictures/screenshots/%Y-%m-%d-%H:%M:%S.png > /home/me/errors.log 2>&1")
See what errors you get, and deal with them.

Related

Progress4gl how to lock yourself?

In an unit test, I need to verify that the program skip locked records when processing a table.
I have been unable to setup a locked records because the test can't lock itself which make a lot of sense.
Here is a sample of what I'm trying to achieve.
DEV VAR v_isCommitted AS LOGI NO-UNDO.
DEF VAR hl AS HANDLE NO-UNDO.
DEF BUFFER bufl FOR tablename.
hl = BUFFER bufl:HANDLE.
LOCKED_RECORDS:
DO TRANSACTION ON ERROR UNDO, LEAVE LOCKED_RECORDS:
/*Setup : Create record not committed yet*/
CREATE tablename.
ASSIGN tablename.fields = fieldsvalue.
/*ACT : Code I'm trying to test*/
/*...some code...*/
v_isCommitted = hl:FIND-BY-ROWID(ROWID(tablename), EXCLUSIVE-LOCK, NO-WAIT)
AND AVAILABLE(bufl)
AND NOT LOCKED(bufl).
/*...some code touching the record if it is commited...*/
/*ASSERT : program left new record tablename AS IS.*/
END.
The problem is that the record is available and not locked to the test because it was created by it.
Is there a way I could have the test lock a record from itself so the act part can actually skip the record like it was created by someone else?
Progress: 11.7.1
A session can not lock itself. So you will need to start a second session. For example:
/* code to set things up ... */
/* spawn a sub process to try to lock the record */
os-command silent value( substitute( '_progres -b -db &1 -p lockit.p -param "&2" && > logfile 2>&&1', dbname, "key" )).
In lockit.p use session:parameter to get the key for the record to test (or hard code it I suppose).
Or, as mentioned in the comments below:
/* locktest.p
*/
define variable lockStatus as character no-undo format "x(20)".
find first customer exclusive-lock.
input through value( "_progres /data/sports120/sports120 -b -p ./lockit.p" ).
repeat:
import unformatted lockStatus.
end.
display lockStatus.
and:
/* lockit.p
*/
find first customer exclusive-lock no-wait no-error.
if locked( customer ) then
put "locked".
else
put "not locked".
quit.

R: How to write a command that if no respond within certain time, execute certain function [duplicate]

How to break a loop after a certain elapsed time? I have a function that collects observational data from a user. The user should have a pre-defined time limit, when the data are recorded (30 sec in the example). At the moment, the function breaks, if the user-input arrives later than the end of the time limit.
record.events <- function(duration = 30, first.event = "a"){
# Initial settings
time.start <- proc.time()[3]
events <- c(first.event, 0)
# Timed data collection
while(proc.time()[3] - time.start < duration){
temp <- readline("record events...")
events <- c(events, temp, proc.time()[3] - time.start)
}
# Format recorded data for post-processing
events <- as.data.frame(matrix(events, byrow=T, ncol=2,
dimnames=list(NULL, c("events","stroke.time"))))
events[,2] <- round(as.numeric(as.character(events[,2])),3)
return(events)
}
Gives for example this result:
events stroke.time
1 a 0.000
2 f 2.618
3 a 23.791
4 f 24.781
5 a 33.488
The last event (a) arrived after the time limit. SO has a solution for this in matlab. Is there a way in R, how to stop waiting for the user input as soon as the time is up?
Edit:
While functions setTimeLimit() and R.utils::withTimeout() can terminate execution of a function that takes too long (thanks to Kodl, Carl Witthoft and Colombo, together with this answer), neither can interrupt readline(). Documentation to withTimeout specifies:
Furthermore, it is not possible to interrupt/break out of a "readline" prompt (e.g. readline() and readLines()) using timeouts; the timeout exception will not be thrown until after the user completes the prompt (i.e. after pressing ENTER).
The user input after the time limit is thus the only way, how to stop waiting for readline. The check can be executed with the while loop as in my code, or with setTimeLimit or withTimeout in a combination with tryCatch. I therefore accept Kodl's answer.
I've also been looking for a solution to this, ended up writing my own function below, but it only works in some setups/platforms.
The main problem is that readline suspends execution until input is provided, so it may hang indefinitely, without ever returning.
My workaround is to open(file('stdin'), blocking=FALSE), and then use readLines(n=1). Problem with that is that it only accepts file('stdin'), which is not always connected. It fails in RGui for windows and MacOS, and for RStudio (at least for MacOS). But it seems to work for R when run from terminal under MacOS.
readline_time <- function(prompt, timeout = 3600, precision=.1) {
stopifnot(length(prompt)<=1, is.numeric(timeout), length(timeout)==1, !is.na(timeout), timeout>=0, is.numeric(precision), length(precision)==1, !is.na(precision), precision>0)
if(!interactive()) return(NULL)
if(timeout==0) return(readline(prompt))
my_in <- file('stdin')
open(my_in, blocking=FALSE)
cat(prompt)
ans <- readLines(my_in, n=1)
while(timeout>0 && !length(ans)) {
Sys.sleep(precision)
timeout <- timeout-precision
ans <- readLines(my_in, n=1)
}
close(my_in)
return(ans)
}
Or if you want to import (along with some other functions):
devtools::install_github('EmilBode/EmilMisc')
i think you can use fucntion "setTimeLimit" from library base. so...
record.events <- function(duration = 30, first.event = "a"){
# Initial settings
time.start <- proc.time()[3]
events<-first.event
stroke.time<-c(0)
# Timed data collection
while(proc.time()[3] - time.start < duration){
temp <- tryCatch({setTimeLimit(elapsed=(time.start + duration - proc.time()[3]),
transient = TRUE);readline("record events...")},
error = function(e) { return("NULL")})
#you need to set up back this function... (but why i dont know????)
setTimeLimit(elapsed = Inf, transient = TRUE)
events[length(events)+1] <- temp
stroke.time[length(stroke.time)+1]<-round(proc.time()[3],3)
}
# Format recorded data for post-processing
events<-data.frame(events, stroke.time)
return(events)
}
But setTimeLimit inst great for use in user functions.. My results is:
events stroke.time
1 a 0.00
2 s 1539.12
3 s 1539.52
4 ass 1539.96
5 s 1540.49
6 asd 1540.94
7 fed 1541.27
8 NULL 1541.55
For more info see:
https://stackoverflow.com/a/7891479
https://stat.ethz.ch/R-manual/R-devel/library/base/html/setTimeLimit.html
How does setTimeLimit work in R?
setTimeLimit fails to terminate idle call in R
I was curious to see if anyone had a real Rland solution to this problem, but it looks like not.
One possible solution is to shell out with system() and run a command that allows reading input with a time limit. This is inherently platform-specific. The Unix bash shell provides a read builtin that is perfect for this purpose, and this will also work on the Cygwin emulation layer on Windows. Unfortunately, I haven't ever come across a command available on the vanilla native Windows platform that provides sufficient functionality for this. set /p can read arbitrary string input but does not provide a timeout, while choice.exe provides a timeout (accurate to the second) but only supports selection of an item from a finite list of (single-character!) items, as opposed to arbitrary string input. Fun fact: choice.exe has its own Wikipedia article.
Here's how you can use read to do this:
LIMIT <- 10; ## conceptual constant
end <- Sys.time()+(left <- LIMIT); ## precompute end of input window and init left
repeat {
input <- suppressWarnings(system(intern=T,sprintf(
'read -r -t %.2f; rc=$?; echo "$REPLY"; exit $rc;',
left
))); ## suppress warnings on non-zero return codes
left <- difftime(end,Sys.time(),units='secs');
cat(sprintf('got input: \"%s\" [%d] with %.2fs left\n',
input,
if ('status'%in%names(attributes(input))) attr(input,'status') else 0L,
left
));
if (left<=0) break;
};
## asdf
## got input: "asdf" [0] with 9.04s left
## xcv
## got input: "xcv" [0] with 8.15s left
## a
## got input: "a" [0] with 6.89s left
## b
## got input: "b" [0] with 6.68s left
## c
## got input: "c" [0] with 6.44s left
##
## got input: "" [0] with 5.88s left
##
## got input: "" [1] with 4.59s left
## got input: "" [1] with 3.70s left
##
## got input: "" [0] with 0.86s left
##
## got input: "" [0] with 0.15s left
## got input: "" [142] with -0.03s left
The sample output I've shown above was me playing around during the input window. I mostly typed some random lines and pressed enter to submit them, giving a return code of 0. The two lines of output that show a return code of 1 were me pressing ^d, which causes read to return 1 immediately, leaving whatever input that was in the buffer in $REPLY (nothing, in those two cases). The final line of output was read terminating immediately upon hitting the timeout, which I believe is the functionality you're looking for. You can use the return code of 142 to distinguish the timeout event from other input events. I'm not completely certain that the return code of 142 is consistent and reliable on all Unix systems, but there's also another way to detect the timeout event: check the current time against end (i.e. the left calculation), as I do in the code. Although I suppose that approach introduces a race condition between a possible last-moment submission and the time check in Rland, but you probably don't need that level of design criticality.

watchkit: sleep -- can the isIdleTimer be changed/disabled?

I'm looking for an equivalent to the following iOS option: UIApplication.shared.isIdleTimerDisabled = true
That is, I'd like my Watch application to stay alive longer than the quick "sleep"/idle time that gets triggered when you don't move your wrist.
Its not perfect -- the watch will still sleep with inactvity, but this extension does slow it down by tricking the watch do ignore a 'wrist-down' or 'wrist-move' motion: Add the WKExtension inside one of your #IBActions:
#IBAction func mySlidefunction(){
// ... etc ...
WKExtension.shared().isAutorotating = true;
// ... etc ...
}

QDialog closing crash

I have problem in ensuring the dialog is closed/released with the following Qt codes.
//Segment 1: To open a 'wait' dialog for some long-running tasks
void MainWindow::ui_showProgressDialog(QString title) {
dlgProgress = new QProgressDialog(title, tr("Cancel"), 0, 0, this);
dlgProgress->setAttribute(Qt::WA_DeleteOnClose); // line 1
dlgProgress->setModal(true);
dlgProgress->show();
connect(voidWatcher, SIGNAL(finished()),
this, SLOT(onPopulationFile()));
}
//Segment 2: Attempts to close the 'wait' dialog
void MainWindow::onPopulationFile() {
qDebug((dlgProgress == NULL) ? "true" : "false");
if (dlgProgress) //
{
qDebug("0");
dlgProgress->close(); // line 2
qDebug("1");
}
qDebug((dlgProgress == NULL) ? "true" : "false");
}
Issue: When I trigger the call 'ui_showProgressDialog' twice, the second call always crash my program. Originally, my code has no line 1 of segment 1, and from the QtCreator, it always crashes on line 2 of segment 2. Debug message shows as follow
// first call to onPopulationFile
false
0
1
false
// second call to onPopulationFile
false
0
*** CRASH ***
I read the documentation that NEVER delete objects from different threads, I'm doubt that the call 'onPopulationFile' is invoked from a non-main thread. So I added the line 1 to segment to let the program decide when the delete the object. But it seems not work. Any suggestion to the problem?
Experiment done: If I replace QProgressDialog with QDialog, the program goes without crashes, and the debug message show
// first call to onPopulationFile
false
0
1
false
// second call to onPopulationFile
false
0
1
false
So,
Why the second null test in segment 2 always fail? [Edit: I have to explicitly set the variable to NULL]
Is there any better way to close the 'wait' dialog?
I try to close/release the dialog as I want release memory as soon as possible. Do I really need to manually delete the dialog?
Platform: Qt Opensource 4.8 (x64), Windows 7 (x64), MinGW (rubenvb 4.7.2)
dlgProgress->setAttribute(Qt::WA_DeleteOnClose); deletes the widget when it is closed. As you are calling dlgProgress->close();, after this line the object it points to has been freed, and dlgProgress is now a invalid pointer.
You need to set dlgProgress to null after any call to close, or event better, use the signal Qobject::destroyed().
EDIT:
Qt::WA_DeleteOnClose specify that the object will be deleted if a close event happens. Not exactly how much time it will take. For instance if they are using QObject::deleteLater(), then the object is not deleted right away. Even if it is not the case , pieces of code like
A* a = new A;
a->dosomething();
delete a;
a->dosomething();
are undefined behavior. The second call to a->dosomething(); may crash (if you are lucky) or may not crash.

Sticky key activation (shift 5 times) doesn't work by hotkey ::Send {LShift 5}

I would like to activate sticky keys by pressing 1 button, instead of pressing shift 5 times, which is the default way.
If I were to do
F9::Send {LShift 5}
pressing F9 will yield nothing.
I also tried
F9::
Send {LShift}
sleep 50
Send {LShift}
sleep 50
Send {LShift}
sleep 50
Send {LShift}
sleep 50
Send {LShift}
sleep 50
return
Are there any reasons as to why it's not working?
While there is most likely a way to do a dll call or something complicated, it is also possibly to program similar functionality using AutoHotkey. This would also avoid the sticky keys prompt, and you can do a traytip instead.
stickykeys = 0
F9::
stickykeys:=!stickykeys
Traytip, Sticky Keys, % (stickykeys) ? "On" : "Off"
return
#If stickykeys
*$Shift::
key = 0
Input, key, L1 M
SendInput {Shift Down}{%key%}{Shift Up}
return
*$Ctrl::
key = 0
Input, key, L1 M
SendInput {Ctrl Down}{%key%}{Ctrl Up}
Return
*$Alt::
key = 0
Input, key, L1 M
SendInput {Alt Down}{%key%}{Alt Up}
Return
#If
F9 simply toggles sticky keys on and off.
Note: This is using AHK_L which supports #If
SPI_GETSTICKYKEYS:=0x003A
SPI_SETSTICKYKEYS:=0x003B
SKF_STICKYKEYSON:=0x1
VarSetCapacity(STICKYKEYS,8) ; DWORD cbSize;DWORD dwFlags;
NumPut(8,&STICKYKEYS,"UInt")
F9::
DllCall("SystemParametersInfo","UInt",SPI_GETSTICKYKEYS,"UInt",8,"PTR",&STICKYKEYS,"UInt",0)
dwFlags:=NumGet(&STICKYKEYS,4,"Uint")
If (dwFlags & SKF_STICKYKEYSON)
dwFlags-=SKF_STICKYKEYSON
else dwFlags|=SKF_STICKYKEYSON
ToolTip % "STICKYKEYS are " (dwFlags & SKF_STICKYKEYSON ? "ON" : "OFF")
SetTimer,ToolTipOff,-1000
NumPut(dwFlags,&STICKYKEYS,4,"UInt")
DllCall("SystemParametersInfo","UInt",SPI_SETSTICKYKEYS,"UInt",8,"PTR",&STICKYKEYS,"UInt",0)
Return
ToolTipOff:
The code is from the Autohotkey forums at http://www.autohotkey.com/community/viewtopic.php?f=1&t=93650
A note for anyone wanting to use the code: I think you have to put it at the top of your script for it to work. In my script of hotkeys, placing it in the middle, and pressing F9 to activate sticky keys caused some weird things to happen: The cursor jumped around, some folders were launched, the script exited, etc. I'm guessing that it activated other hotkeys nearby?

Resources