I have a do: in Pharo that takes a long time to process. I'd like to show the progress of it to the user. How is that done in Pharo?
Here are two ways:
Collection borrows from UIManager and supports a displayingProgress: every: milliseconds variant of do::
(1 to: 60)
do: [ :e | (Delay forSeconds: 0.5) wait "simulate a delay" ]
displayingProgress: [ :e | 'waiting ' , e asString ] every: 1000
You can play with the every: on this example to see that if you set it to less than 1000ms, it will update more often (setting it to 100 will show you every value of the interval).
Also, you can simply use displayingProgress: 'Waiting...' to only show the same string the whole time, without a block.
Using the Job class. Here's a similar solution as above:
myColl := 1 to: 20.
[ :job |
myColl
do: [ :e |
job
progress: e / myColl size;
title: 'waiting ' , e asString.
(Delay forSeconds: 0.5) wait ] ] asJob run
Related
Hello I'm trying to make a countdown timer with exactly milliseconds and print it to terminal.
input : a float value like (9.200)
output : countdown time for 9 seconds 200 milliseconds
like below site tool
https://www.online-stopwatch.com/countdown-timer/
even i could try to print time in milliseconds format but the time is not exactly. Maybe it's a not good question but Is there any way to do it?. Thank you guys so much.
I tried to search about this case but can't match any
Below code is what i got from internet but time is not correct and i need a countdown timer a above site had. Thanks
from __future__ import print_function, division
import time , datetime
counter, timestr = 0, ''
print(time.asctime())
t0 = time.time()
try:
while True:
sectime, ff = divmod(counter,1000)
mintime, ss = divmod(sectime,60)
hh, mm = divmod(mintime, 60)
print(''.join('\b' for c in timestr), end='')
timestr='%02i:%02i:%02i.%2s' % (hh, mm, ss, ff)
print(timestr, end='')
time.sleep(.1)
counter += 1
except KeyboardInterrupt:
t0 = time.time() - t0
print('\nCounter seconds: %.1f, time.time seconds: %.1f'
% (counter/10.0, t0 ))
You haven't mentioned what exactly didn't work for you, but I'll attempt to give a general answer anyway. You could try something like this -
# Saved as timer.py
import sys, time
## Create the variable _TIME from sys.argv or wherever, make sure it is a valid float, > 0, etc etc
## Depends on how you expect input
_TIME = 5 # Just for example, remove this
while _TIME > 0:
m, s = divmod(_TIME, 60)
h, m = divmod(m, 60)
print(f"\r{int(h)}".rjust(3,'0'), f"{int(m)}".rjust(2,'0'),
f"{s:.3f}".rjust(5,'0'), sep=':', end='')
_TIME -= 0.001
time.sleep(0.001)
else:
print("\r Completed ! ")
Then use $ python3 timer.py 5 or something like that in your terminal.
Notes :
This may not be accurate, especially if your print statement is slow in the the terminal. See What is the best way to repeatedly execute a function every x seconds? for several better alternatives since accuracy may be important here.
In some terminals/GUIs, \r may not actually move the cursor back to the start of the line as expected. You might not be able to really do anything about this, that's a problem with the terminal app.
Edit:
Right after I posted this, I saw that you'd updated your question. The code vou've shared definitely has problems - its a lot for me to completely explain here. The most obvious is time.sleep(0.1) waits 100ms, not 1, so your timer won't ever update that often. Try reading other sources on how to accomplish what you want.
I am trying to simulate n-dimensional game of life for first t=6 time steps. My Nim code is a straightforward port from Python and it works correctly but instead of the expected speedup, for n=4, t=6 it takes 2 seconds to run, which is order of magnitude slower than my CPython version. Why is my code so slow? What can I do to speed it up? I am compiling with -d:release and --opt:speed
I represent each point in space with a single 64bit integer.
That is, I map (x_0, x_1, ..., x_{n-1}) to sum x_i * 32^i. I can do that since I know that after 6 time steps each coordinate -15<=x_i<=15 so I have no overflow.
The rules are:
alive - has 2 or 3 alive neigbours: stays alive
- different number of them: becomes alive
dead - has 3 alive neighbours: becomes alive
- else: stays dead
Below is my code. The critical part is the proc nxt which gets set of active cells and outputs set of active cells next time step. This proc is called 6 times. The only thing I'm interested in is the number of alive cells.
I run the code on the following input:
.##...#.
.#.###..
..##.#.#
##...#.#
#..#...#
#..###..
.##.####
..#####.
Code:
import sets, tables, intsets, times, os, math
const DIM = 4
const ROUNDS = 6
const REG_SIZE = 5
const MAX_VAL = 2^(REG_SIZE-1)
var grid = initIntSet()
# Inits neighbours
var neigbours: seq[int]
proc initNeigbours(base,depth: int) =
if depth == 0:
if base != 0:
neigbours.add(base)
else:
initNeigbours(base*2*MAX_VAL-1, depth-1)
initNeigbours(base*2*MAX_VAL+0, depth-1)
initNeigbours(base*2*MAX_VAL+1, depth-1)
initNeigbours(0,DIM)
echo neigbours
# Calculates next iteration:
proc nxt(grid: IntSet): IntSet =
var counting: CountTable[int]
for x in grid:
for dx in neigbours:
counting.inc(x+dx)
for x, count in counting.pairs:
if count == 3 or (count == 2 and x in grid):
result.incl(x)
# Loads input
var row = 0
while true:
var line = stdin.readLine
if line == "":
break
for col in 0..<line.len:
if line[col] == '#':
grid.incl((row-MAX_VAL)*2*MAX_VAL + col-MAX_VAL)
inc row
# Run computation
let time = cpuTime()
for i in 1..ROUNDS:
grid = nxt(grid)
echo "Time taken: ", cpuTime() - time
echo "Result: ", grid.len
discard stdin.readLine
Your code runs in my computer in about 0.02:
Time taken: 0.020875947
Result: 2276
Time taken: 0.01853268
Result: 2276
Time taken: 0.021355269
Result: 2276
I changed the part where the input is read to this:
# Loads input
var row = 0
let input = open("input.txt")
for line in input.lines:
for i, col in line:
if col == '#':
grid.incl((row-MAX_VAL)*2*MAX_VAL + i-MAX_VAL)
inc row
input.close()
But it shouldn't impact the performance, it just looks better to my eyes. I compiled with:
nim c -d:danger script.nim
Using Nim 1.4.2. -d:danger is the flag for maximum speed before entering deeper waters.
But even compiling in debug mode:
$ nim c -r script.nim
Time taken: 0.07699487199999999
Result: 2276
Way faster than 2 seconds. There has to be other problem in your end. Sorry for the non-answer.
I want to print out a sort of pyramid. User inputs an integer value 'i', and that is displayed i-times.
Like if input=5
1
22
333
4444
55555
I have tried this:
input=5
for i in range(input+1):
print("i"*i)
i=i+1
The result of which is
i
ii
iii
iiii
iiiii
The problem is that (as far as I know), only a string can be printed out 'n' times, but if I take out the inverted commas around "i", it becomes (i*i) and gives out squares:
0
1
4
9
16
25
Is there a simple way around this?
Thanks!
Just convert your int loop varaible to str before building the output string by multiplying:
input = 5
for i in range(1, input+1):
print(str(i) * i)
Try this:
a = 5
for i in range(a): # <-- this causes i to go from 0,1,2,3,...,a-1
print("{}".format(i+1)*(i+1)) # < -- this creates a new string in each iteration ; an alternative would be str(i+1)*(i+1)
i=i+1 # <-- this is unnecessary, i already goes from 0 to a-1 and will be re-created in the next iteration of the loop.
This creates a new string in each iteration of the loop.
Note that for i in range(a) will go through the range by itself. There is no need to additionally increment i at the end. In general it is considered bad practise to change indices you loop over.
This is a matlab code that uses guide to run a timer. The timer function counts 10 numbers starting from the number provided in the text field. I would like to know how to enter two numbers successively and make matlab counts 10 numbers for both values in parallel.
let's say I entered 0 then I pressed the start button, then I immediately entered 10 and pressed the start button again. what happens now is that it counts only from 0 to 10. I would appreciate if you can share a way to make my code count from 0 to 10 and from 10 to 20 simultaneously in parallel.
guide code :
function startbutton_Callback(hObject, eventdata, handles)
t=timer;
t.TimerFcn = #counter;
t.Period = 15;
t.ExecutionMode = 'fixedRate';
t.TasksToExecute = 1;
start(t);
stop (t);
delete (t);
timer callback function:
function counter(~,~)
handles = guidata(counterFig);
num = str2double(get(handles.edit1,'String'));
for i = 0:10
disp (num);
num = num+1;
pause (1);
end
you can use parrallel toolbox for real parallel computation.
but if you dont have that , you can create another timer object that count from 10 to 20
and run it
Setup
I have a column of durations stored as a strings in a dataframe. I want to convert them to an appropriate time object, probably POSIXlt. Most of the strings are easy to parse using this method:
> data <- data.frame(time.string = c(
+ "1 d 2 h 3 m 4 s",
+ "10 d 20 h 30 m 40 s",
+ "--"))
> data$time.span <- strptime(data$time.string, "%j d %H h %M m %S s")
> data$time.span
[1] "2012-01-01 02:03:04" "2012-01-10 20:30:40" NA
Missing durations are coded "--" and need to be converted to NA - this already happens but should be preserved.
The challenge is that the string drops zero-valued elements. Thus the desired value 2012-01-01 02:00:14 would be the string "1 d 2 h 14 s". However this string parses to NA with the simple parser:
> data2 <- data.frame(time.string = c(
+ "1 d 2 h 14 s",
+ "10 d 20 h 30 m 40 s",
+ "--"))
> data2$time.span <- strptime(data2$time.string, "%j d %H h %M m %S s")
> data2$time.span
[1] NA "2012-01-10 20:30:40" NA
Questions
What is the "R Way" to handle all the possible string formats? Perhaps test for and extract each element individually, then recombine?
Is POSIXlt the right target class? I need duration free from any specific start time, so the addition of false year and month data (2012-01-) is troubling.
Solution
#mplourde definitely had the right idea w/ dynamic creation of a formatting string based on testing various conditions in the date format. The addition of cut(Sys.Date(), breaks='years') as the baseline for the datediff was also good, but failed to account for a critical quirk in as.POSIXct() Note: I'm using R2.11 base, this may have been fixed in later versions.
The output of as.POSIXct() changes dramatically depending on whether or not a date component is included:
> x <- "1 d 1 h 14 m 1 s"
> y <- "1 h 14 m 1 s" # Same string, no date component
> format (x) # as specified below
[1] "%j d %H h %M m %S s"
> format (y)
[1] "% H h % M %S s"
> as.POSIXct(x,format=format) # Including the date baselines at year start
[1] "2012-01-01 01:14:01 EST"
> as.POSIXct(y,format=format) # Excluding the date baselines at today start
[1] "2012-06-26 01:14:01 EDT"
Thus the second argument for the difftime function should be:
The start of the first day of the current year if the input string has a day component
The start of the current day if the input string does not have a day component
This can be accomplished by changing the unit parameter on the cut function:
parse.time <- function (x) {
x <- as.character (x)
break.unit <- ifelse(grepl("d",x),"years","days") # chooses cut() unit
format <- paste(c(if (grepl("d", x)) "%j d",
if (grepl("h", x)) "%H h",
if (grepl("m", x)) "%M m",
if (grepl("s", x)) "%S s"), collapse=" ")
if (nchar(format) > 0) {
difftime(as.POSIXct(x, format=format),
cut(Sys.Date(), breaks=break.unit),
units="hours")
} else {NA}
}
difftime objects are time duration objects that can be added to either POSIXct or POSIXlt objects. Maybe you want to use this instead of POSIXlt?
Regarding the conversion from strings to time objects, you could do something like this:
data <- data.frame(time.string = c(
"1 d 1 h",
"30 m 10 s",
"1 d 2 h 3 m 4 s",
"2 h 3 m 4 s",
"10 d 20 h 30 m 40 s",
"--"))
f <- function(x) {
x <- as.character(x)
format <- paste(c(if (grepl('d', x)) '%j d',
if (grepl('h', x)) '%H h',
if (grepl('m', x)) '%M m',
if (grepl('s', x)) '%S s'), collapse=' ')
if (nchar(format) > 0) {
if (grepl('%j d', format)) {
# '%j 1' is day 0. We add a day so that x = '1 d' means 24hrs.
difftime(as.POSIXct(x, format=format) + as.difftime(1, units='days'),
cut(Sys.Date(), breaks='years'),
units='hours')
} else {
as.difftime(x, format, units='hours')
}
} else { NA }
}
data$time.span <- sapply(data$time.string, FUN=f)
I think you will have better luck with lubridate:
From Dates and Times Made Easy with lubridate:
5.3. Durations
...
The length of a duration is invariant to leap years, leap seconds, and daylight savings time
because durations are measured in seconds. Hence, durations have consistent lengths and
can be easily compared to other durations. Durations are the appropriate object to use when
comparing time based attributes, such as speeds, rates, and lifetimes.
lubridate uses the difftime class from base R for durations. Additional difftime methods
have been created to facilitate this.
lubridate uses the difftime class from base R for durations. Additional difftime methods
have been created to facilitate this.
...
Duration objects can be easily created with the helper functions dyears(), dweeks(), ddays(), dhours(), dminutes(), and dseconds(). The d in the title stands for duration and distinguishes these objects from period objects, which are discussed in Section 5.4. Each object creates a duration in seconds using the estimated relationships given above.
That said, I haven't (yet) found a function to parse a string into a duration.
You might also take a look at Ruby's Chronic to see how elegant time parsing can be. I haven't found a library like this for R.