Stopwatch implementing python - python

I got this code for an assignment:
from stop_watch import StopWatch
size = 1000000
stopWatch = StopWatch()
sum = 0
for i in range(1, size + 1):
sum += i
stopWatch.stop()
print("The loop time is", stopWatch.get_elapsed_time(), "milliseconds")
I have to create a class which generates a stopwatch and this is my code:
import time
class StopWatch:
def __init__(self):
pass
def start(self):
self.start = time.time()
return self.start
def stop(self):
self.stop = time.time()
return self.stop
def get_elapsed_time(self):
print(str(self.stop-self.start))
I get this error:
File "week33.py", line 10, in <module>
print("The loop time is", stopWatch.get_elapsed_time(), "milliseconds")
File "/Users/Marinkton/Desktop/stop_watch.py", line 16, in get_elapsed_time
print(str(self.stop-self.start))
TypeError: unsupported operand type(s) for -: 'float' and 'method'
What am I doing wrong? I could not discover a mistake.

You can't name your functions and your properties the same thing. When you do self.stop = time.time(), you overwrite the function stop.
You need to change the name of the internal fields.
import time
class StopWatch:
def __init__(self):
self.start_time = 0
self.stop_time = 0
def start(self):
self.start_time = time.time()
return self.start_time
def stop(self):
self.stop_time = time.time()
return self.stop_time
def get_elapsed_time(self):
print(str(self.stop_time - self.start_time))
PS: You're never calling start in your code.

Related

How to get args from a decorator that uses class

I was trying to make a loop function that uses class, and to make it easier i think i will make it as decorator, but there are a few problem when i tried my code,
When i tried this code, it says that I'm missing 1 required argument and it's "self"
I tried doing this to my code, but realized that it used __call__, which i don't want to because it will executed at the time the function is called. (I dont know if this true)
And this is how i used it, and https://hastebin.com/onozarogac.py (for the full code):
#looper(seconds=3) # this code is from other class
def print(self):
print(len(self.cache.get_available_guilds_view()))
self.print.start() # and by using this to trigger it
def looper(seconds):
def decorator(func):
return Looper(func, seconds * 1000)
return decorator
class Looper:
def __init__(self, fn, seconds):
self.fn = fn
self.interval_ms = seconds / 1000
self.time_last = time()
self.started = False
def loop(self):
time_now = time()
if time_now >= self.time_last + self.interval_ms:
self.fn()
self.time_last = time_now
return True
else:
return False
def set_interval_ms(self, interval_ms):
self.interval_ms = interval_ms / 1000
def set_interval_s(self, set_interval):
self.interval_ms = set_interval
def get_interval_ms(self):
return self.interval_ms
def get_interval_s(self):
return self.interval_ms * 1000
def start(self):
self.started = True
while True:
if self.started:
self.loop()
else:
break
def stop(self):
self.started = False
Its giving me the TypeError which:
TypeError: print() missing 1 required positional argument: 'self'
convert looper function to this
from functools import wraps
def looper(seconds):
def inner(func):
#wraps(func)
def wrapper(*args, **kwargs):
return Looper(func, seconds * 1000)
return wrapper
return inner

AttributeError: 'Float' object has no attribute 'time'

I am currently getting this error in my code
AttributeError: 'Float' object has no attribute 'time'
I have not seen an exact instance to mine I have seen some changes to dtype=object but I am unsure how to implement that and why I would need to. This is a pretty straight forward function.
import time
class lastCycle():
def __init__(self):
self.lastTime = time.time()
self.time = 0.0
def timer(self, time):
if (time.time() - self.lastTime) > self.time:
self.lastTime = time.time()
return True
else:
return False
statusUpdate = lastCycle().timer(1.0)
Don't use module name time as keyword here:
def timer(self, time):
if (time.time() - self.lastTime) > self.time:
self.lastTime = time.time()
return True
else:
return False
I guess this is the solution you are looking for:
def timer(self, timeVal):
if (timeVal - self.lastTime) > self.time:
self.lastTime = time.time()
return True
else:
return False
import time
class lastCycle():
def init(self):
self.lastTime = time.time()
self.time = 0.0
def timer(self, threshold):
if (time.time() - self.lastTime) > threshold:
self.lastTime = time.time()
return True
else:
return False

Implement datetime module in Python OOP

I am trying to implement datetime module to my Clock OOP, but the data is not being updated with the current hour, minute and second. Please have a look at the code. I can't see what I am doing wrong.
import datetime
import time
# Python class to emulate CLock
class ClockNow2:
def __init__(self):
self.theHour = 0
self.theMinute = 0
self.theSecond = 0
self.theLocale ="Unknow"
self.AM = True
#setters and getters (transformers and accessors)
#one setter and getter for each attribute
def setHour(self):
self.theHour =datetime.timezone
def getHour(self):
return self.theHour
def setMinute(self):
self.theMinute = now.minute
def getMinute(self):
return self.theMinute
def setSecond(self):
self.theSecond = now.second
def getSecond(self):
return self.theSecond
def setLocale(self,newval):
self.theLocale = newval
def getLocale(self):
return self.theLocale
def toString(self):
clockstring = "The time in " +self.theLocale + " is " +str(self.theHour) \
+ ":" +str(self.theMinute) + ":" + str(self.theSecond)
return clockstring

Countdown with Python and Gtk, problems with timeout_add

I'm trying to make a workout app, so I have to count each push-up or display a countdown for side plank. To do that I tried to use GObject.timeout_add but it appears it doesn't work like I thought it would.
In the current situation, all exercises of a session are run simultaneously, instead of one at a time, in the proper order.
I am certainly missing something, and through my web searching, I still haven't found it.
Here is my code :
#!/usr/bin/python
"""
Work out app to keep track of your progression through the session
"""
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GObject
from Programms import *
from time import sleep
def time_hours(t):
return t // 3600
def time_minutes(t):
return (t % 3600) // 60
def time_seconds(t):
return int((t % 3600) % 60)
def time_format(t):
hours = double_digit(time_hours(t))
minutes = double_digit(time_minutes(t))
seconds = double_digit(time_seconds(t))
return "{}:{}:{}".format(hours, minutes, seconds)
def double_digit(t):
if t == 0:
return "00"
elif t < 10:
return "0{}".format(t)
return t
class StartingLine:
"""
Gtk
"""
def __init__(self):
# main window
self.window = Gtk.Window()
self.window.set_title("Work out !")
self.window.set_size_request(200, 200)
self.window.connect('destroy', lambda x: Gtk.main_quit())
# start button
self.button = Gtk.Button("Start")
self.button.connect('clicked', self.start_work_out)
self.window.add(self.button)
self.window.show_all()
def start_work_out(self, widget):
self.window.hide()
work = Two
duration = work.duration
for exo in work.exercises:
Instructor(exo, duration)
class Instructor:
"""
Gtk
"""
def __init__(self, exo, duration):
# main window
self.window = Gtk.Window()
self.window.set_title("Work out !")
self.window.set_size_request(200, 200)
self.window.connect("destroy", lambda x: Gtk.main_quit())
# timer
self.current_time = 0
self.counter = 0
self.timer_label = Gtk.Label(time_format(self.counter))
# exercise
self.current_exercise = Gtk.Label(exo.name)
# overall progression
self.bar = Gtk.ProgressBar.new()
# hierarchy
grid = Gtk.Grid()
grid.attach(self.timer_label, 1, 0, 1, 1)
grid.attach(self.current_exercise, 1, 1, 1, 1)
grid.attach(self.bar, 1, 2, 1, 1)
self.window.add(grid)
# display
self.window.show_all()
if exo.type == ExoType.Reps:
print('exercise : ', exo.name)
self.counter = 0
self.timer_label.set_label(str(self.counter))
rep_id = GObject.timeout_add(1000*exo.in_between, self.display_rep, exo, duration)
print("rep ID : ", rep_id)
elif exo.type == ExoType.Timer:
self.counter = exo.number
self.timer_label.set_label(time_format(self.counter))
time_id = GObject.timeout_add(1000*exo.in_between, self.display_timer, exo, duration)
print("time ID : ", time_id)
def display_rep(self, exo, duration):
print("current time : ", self.current_time)
print("current exercise : ", exo.name)
print("rep : ", self.counter)
self.counter += 1
self.current_time += exo.in_between
self.timer_label.set_label(str(self.counter)) # update counter
self.current_exercise.set_label(exo.name) # update exercise name
self.bar.set_fraction(self.current_time/duration) # update progression bar
return self.counter < exo.number
def display_timer(self, exo, duration):
print("current time : ", self.current_time)
print("current exercise : ", exo.name)
print("timer : ", self.counter)
self.counter -= 1
self.current_time += exo.in_between
self.timer_label.set_label(time_format(self.counter)) # update counter
self.current_exercise.set_label(exo.name) # update name
self.bar.set_fraction(self.current_time/duration) # update progression bar
return self.counter > 0
if __name__ == "__main__":
StartingLine()
Gtk.main()
In this code I have used two types, which are :
#!/usr/bin/python
"""
define class exercise and class session
"""
class Exercise:
def __init__(self, name, typo, unilateral, number, preparation=0, in_between=1):
"""
:param name: name of the exercise
:param typo: either timer or reps
:param number: either a time in seconds or a a number of reps
:param preparation: time allocated to prepare the exercise, to put yourself in position
:param in_between: time between reps. 1s by default.
"""
self.name = name
self.type = typo
self.unilateral = unilateral
self.number = number
self.prep = preparation
self.in_between = in_between
class ExoType(enumerate):
Reps = 0
Timer = 1
class Session:
def __init__(self, name, exercises):
self.name = name
self.exercises = exercises
self.duration = time_length(exercises)
def time_length(exercises):
t = 0
for exo in exercises:
if exo.type == ExoType.Timer:
t += exo.number
elif exo.type == ExoType.Reps:
t += exo.number*exo.in_between
else:
print("Error : Session duration")
return t
First time I ask a question here, please tell me if I'm doing wrong.
rep_id = GObject.timeout_add(1000*exo.in_between, self.display_rep, exo, duration)
When you timeout_add you tell Mainloop to call function every n seconds.
for exo in work.exercises:
Instructor(exo, duration)
Here you add every exercise to mainloop, which leads to simultaneous run, because you create mainloop once.
There are several solutions and in my opinion none of them includes main_iteration_do.
Reorganise things so that 1 exercise runs it's own mainloop.
Emit a signal when one exercise is finished and in it's handler start another exercise.

Class and external method call

I am going through a data structures course and I am not understanding how a Class can call a method that's in another Class.
The code below has 2 classes: Printer and Task.
Notice that class Printer has a method called startNext, and this has a variable self.timeRemaining that gets assigned the result of newTask.getPages() * 60/self.pagerate.
How can newTaks reference the getPages() method from the Task class?
The code that passes this object to the Printer class never references the Task class.
The code works, since this is what the course gives out but, I just cannot understand how that method is accessed.
Code:
from pythonds.basic.queue import Queue
import random
class Printer:
def __init__(self, ppm):
self.pagerate = ppm
self.currentTask = None
self.timeRemaining = 0
def tick(self):
if self.currentTask != None:
self.timeRemaining = self.timeRemaining - 1
if self.timeRemaining <= 0:
self.currentTask = None
def busy(self):
if self.currentTask != None:
return True
else:
return False
def startNext(self, newTask):
self.currentTask = newTask
self.timeRemaining = newTask.getPages() * 60/self.pagerate
class Task:
def __init__(self, time):
self.timeStamp = time
self.pages = random.randrange(1, 21)
def getStamp(self):
return self.timeStamp
def getPages(self):
return self.pages
def waitTime(self, currentTime):
return currentTime - self.timeStamp
def simulation(numSeconds, pagesPerMinute):
labPrinter = Printer(pagesPerMinute)
printQueue = Queue()
waitingTimes = []
for currentSecond in range(numSeconds):
if newPrintTask():
task = Task(currentSecond)
printQueue.enqueue(task)
if (not labPrinter.busy()) and (not printQueue.isEmpty()):
nextTask = printQueue.dequeue()
waitingTimes.append(nextTask.waitTime(currentSecond))
labPrinter.startNext(nextTask)
labPrinter.tick()
averageWait = sum(waitingTimes)/len(waitingTimes)
print "Average Wait %6.2f secs %3d tasks remaining." % (averageWait, printQueue.size())
def newPrintTask():
num = random.randrange(1, 181)
if num == 180:
return True
else:
return False
for i in range(10):
simulation(3600, 5)
If I understand clearly your question, it is because you are adding task object to Queue list. Then when you are getting object (list item) back, you are getting again Task object:
#creating Task object and adding to Queque list
task = Task(currentSecond)
printQueue.enqueue(task)
class Queue:
def __init__(self):
#list of task objects
self.items = []
def enqueue(self, item):
#you are inserting Task object item to list
self.items.insert(0,item)
def dequeue(self):
#returns task object
return self.items.pop()
So then you can call startNext() method from Printer class, because the dequeue() method is returning Task object.
And because of the object in startNext() is type of Task, you can call getPages() method on that object.
Is it sufficient answer?

Categories

Resources