I want to write an input in an value box and at the same time I want to verify that this value is bigger than another value saved in a Buffer.
Example:
2 Buffers are saved:
Buffer1 = 300
Buffer2 = 500
I want Buffer1 as Input in this value Box and at the same time I want to verify that:
Buffer1 > Buffer2
Do you have an idea how we could do that?
Verifying works like this
{B[buffer1]}<{B[buffer2]}
Related
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.
Experienced programmer playing around with Gamemaker2 Studio.
Trying to draw some random squares on the screen using a 2D array to store the "map"
Step 1 : declare a 2D array MyMap[25,25] this works
Step 2 : Set 100 random locations in Map[]=1 this works
I get a crash when I try to look up the values I have stored in the array.
Its crashing with:
**Execution Error - Variable Index [3,14] out of range [26,14] **
So it looks like it is trying to read 26 element, when you can see from my code the for next loop only goes to 20 and the array bound is 25.
Oddly enough it does the first two loops just fine?
Looking like a bug, I've spent so much time trying to work it out, anyone got an idea what is going on?
var tx=0;
var ty=0;
var t=0;
MyMap[25,25]=99; **// Works**
for( t=1; t<100; t+=1 ) **// Works**
{
MyMap[random(20),random(15)]=1
}
for( tx=1; tx<20; tx+=1 )
{
for( ty=1; ty<15; ty+=1 )
{
show_debug_message(string(tx) + ":" + string(ty))
t = MyMap[tx,ty]; /// **<---- Crashes Here**
if t=1 then {draw_rectangle(tx*32,ty*32,tx*32+32,ty*32+32,false) }
}
}
The line MyMap[random(20),random(15)]=1 does not initialize values in the entire array, creating a sparse array(where some elements do not exist).
The line MyMap[25,25]=99;
Should read:
for( tx=1; tx<20; tx+=1 )
{
for( ty=1; ty<15; ty+=1 )
{
MyMap[tx,ty]=99;
}
}
This will pre-initialize the all of the array values to 99. Filling out the array.
Then you can randomly assign the ones. (You will probably get less than 100 ones the due to duplicates in the random function and the random returning zeros.)
You should have the above code in the Create Event, or in another single fire or controlled fire event, and move the loops for the draw into the Draw Event.
All draw calls should be in the Draw Event. If the entire block were in Draw, it would randomize the blocks each step.
Using the built-in "Import Data..." functionality we can import a properly formatted text file (like CSV and/or tab-delimited) as an image. It is rather straight forward to write a script to do so. However, my scripting approach is not efficient - which requires me to loop through each raw (use the "StreamReadTextLine" function) so it takes a while to get a 512x512 image imported.
Is there a better way or an "undocumented" script function that I can tap in?
DigitalMicrograph offers an import functionality via the File/Import Data... menu entry, which will give you this dialog:
The functionality evoked by this dialog can also be accessed by script commands, with the command
BasicImage ImageImportTextData( String img_name, ScriptObject stream, Number data_type_enum, ScriptObject img_size, Boolean lines_are_rows, Boolean size_by_counting )
As with the dialog, one has to pre-specify a few things.
The data type of the image.
This is a number. You can find out which number belongs to which image data type by, f.e., creating an image outputting its data type:
image img := Realimage( "", 4, 100 )
Result("\n" + img.ImageGetDataType() )
The file stream object
This object describes where the data is stored. The F1 help-documention explains how one creates a file-stream from an existing file, but essentially you need to specify a path to the file, then open the file for reading (which gives you a handle), and then using the fileHandle to create the stream object.
string path = "C:\\test.txt"
number fRef = OpenFileForReading( path )
object fStream = NewStreamFromFileReference( fRef, 1 )
The image size object
This is a specific script object you need to allocate. It wraps image size information. In case of auto-detecting the size from the text, you don't need to specify the actual size, but you still need the object.
object imgSizeObj = Alloc("ImageData_ImageDataSize")
imgSizeObj.SetNumDimensions(2) // Not needed for counting!
imgSizeObj.SetDimensionSize(0,10) // Not used for counting
imgSizeObj.SetDimensionSize(1,10) // Not used for counting
Boolean checks
Like with the checkboxes in the UI, you spefic two conditions:
Lines are Rows
Get Size By Counting
Note, that the "counting" flag is only used if "Lines are Rows" is also true. Same as with the dialog.
The following script improrts a text file with couting:
image ImportTextByCounting( string path, number DataType )
{
number fRef = OpenFileForReading( path )
object fStream = NewStreamFromFileReference( fRef, 1 )
number bLinesAreRows = 1
number bSizeByCount = 1
bSizeByCount *= bLinesAreRows // Only valid together!
object imgSizeObj = Alloc("ImageData_ImageDataSize")
image img := ImageImportTextData( "Imag Name ", fStream, DataType, imgSizeObj, bLinesAreRows, bSizeByCount )
return img
}
string path = "C:\\test.txt"
number kREAL4_DATA = 2
image img := ImportTextByCounting( path, kREAL4_DATA )
img.ShowImage()
I've been trying to update a randomly selected row in my Sqlite database using Flask and the Flask-Sqlalchemy. I have just a few rows in the database with columns called "word", "yes", and "no", where word is a string and yes and no are integers. There are two buttons on the "vote" view, yes and no. When a button is pressed, the appropriate code executes, should increment the yes or no column, and the view is updated with a new random word from the Word table.
#app.route("/vote", methods=["GET", "POST"])
def vote():
#Get random row from database
query = db.session.query(Word)
rowCount = int(query.count())
row = query.offset(int(rowCount*random.random())).first()
#POST
# If "yes" button is pressed, increment yes column in database
if request.method == "POST":
if request.form.get("yes"):
row.yes += 1
db.session.commit()
return render_template("vote.html", row=row)
# otherwise increment no column
elif request.form.get("no"):
row.no += 1
db.session.commit()
return redirect(url_for("vote"))
#GET
# on get request, render vote.html
return render_template("vote.html", row=row)
This code is working, but the yes and no columns are only updated when the view comes back around to the random word the next time. If I close the browser right after clicking a button, the database is not incremented. I think this has something to do with db.session.commit(), or something about the session. It seems like:
row.yes += 1
is saved in the session object, but only committed when that database row is queried the next time. This code DID work when I replaced the query at the top of the method with:
row = Word.query.get(4)
which returns the row with id of 4. With this query, the yes or no column are updated immediately.
Any thoughts?
Thanks
Thanks all. I figured out the problem. The database incrementing was actually working fine, but I wasn't incrementing the correct rows. The problem was that I generated a random row from the database on each call of the vote() method, which meant that I got a random value for the GET request, and a different random value for the POST request, and ended up incrementing that different random value in the POST request.
I separated the logic out into two methods for the "/vote" route, getWord() and vote(), and created a randRow() method for the row generation. I needed to store the random row that gets generated when getWord() is called, so I used session variables so I could access the random row from the vote() method. It's a bit verbose, but seems to work.
Anyone have a better idea about how to achieve this?
#app.route('/vote', methods=["GET"])
def getWord():
wordObj = randRow()
session['word'] = wordObj.word
session['yesVotes'] = wordObj.yes
session['noVotes'] = wordObj.no
return render_template("vote.html", word=session['word'], yesVotes=session['yesVotes'], noVotes=session['noVotes'])
#app.route('/vote', methods=["POST"])
def vote():
# store session 'word' in word variable
# look up word in database and store object in wordObj
word = session['word']
wordObj = Word.query.filter_by(word=word).first()
# check button press on vote view, increment yes or no column
# depending on which button was pressed
if request.form.get("yes"):
wordObj.yes = wordObj.yes + 1
elif request.form.get("no"):
wordObj.no = wordObj.no + 1
db.session.commit()
return redirect(url_for("getWord"))
###### HELPERS ######
# returns a random row from the database
def randRow():
rowId = Word.query.order_by(func.random()).first().id
row = Word.query.get(rowId)
return row
I think you need to add the update into the session before the commit, using code like this:
[...]
row.yes += 1
db.session.add(row)
db.session.commit()
[...]
That's the pattern that I use for a basic update in Flask-SQLAlchemy.
I have a weired issue, I can't believe such a common feature could be broken (the error is certainely on my side), but I can't find how to make it work. I want to use the cursor from datastore to get paginated results, I keep getting all of them whatever i do
FetchOptions fetchOptions = FetchOptions.Builder.withChunkSize(5).prefetchSize(6);
String datastoreCursor = filter.getDatastoreCursor();
if (datastoreCursor != null) {
fetchOptions = fetchOptions.startCursor(Cursor.fromWebSafeString(datastoreCursor));
}
QueryResultList<Entity> result = preparedQuery.asQueryResultList(fetchOptions);
ArrayList<Product> productList = new ArrayList<Product>();
// int count = 0;
for (Entity entity : result) {
// if (++count == PRODUCTS_PER_PAGE)
// break;
Key key = entity.getKey();
productList.add(populateProduct(key.getId(), true, entity));
}
toReturn.setDatastoreCursor(result.getCursor());
Also if I don't read the rows (uncomment the lines with counter) and get the cursor the resulting cursor is the same. I thought it might bring me back to the last read element under the datastabase cursor (thinking result.getCursor() reflects the state of the db cursor)
I'm getting a cursor with this value E-ABAOsB8gEQbW9kaWZpY2F0aW9uRGF0ZfoBCQiIjsfAmKm_AuwBggIhagljaGF0YW1vamVyFAsSB1Byb2R1Y3QYgICAgICosgsMFA that points to no more elements (I have 23 elements for my test that I all receive from the first query)
When you use a QueryResultList, the requested cursor will always point to the end of the list. As specified by the javadoc of QueryResultList#getCursor:
Gets a Cursor that points to the result immediately after the last one in this list.
Even though you provide a prefetch and chunk size, The entire result list will still have all of your results since you have not specified a limit. Thus, the expected cursor is the cursor after the final element.
If you only want a specific number of entities per page, you should set a limit on the FetchOptions using the limit method. Then when you call getCursor(), you'll get a cursor at the end of your page, as opposed to the end of your dataset.
Instead, you could also use a QueryResultIterator. Unlike the QueryResultList, calling getCursor on a QueryResultIterator will result in the cursor that points after the last entity retrieved by calling .next() (javadoc).