本文整理汇总了Python中timer.Timer.stop方法的典型用法代码示例。如果您正苦于以下问题:Python Timer.stop方法的具体用法?Python Timer.stop怎么用?Python Timer.stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类timer.Timer
的用法示例。
在下文中一共展示了Timer.stop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import stop [as 别名]
class PhysicsManager:
def __init__(self):
self.timer = Timer(PHYSICS_TIMER_INTERVAL, "physics_timer")
self.started = False
self.tasks = []
def __del__(self):
self.timer.stop()
def update(self):
if len(self.tasks) == 0:
self.started = False
self.timer.stop()
return
for task in self.tasks:
vy = task.velocity[1]
for i in [0, 1, -1]:
v0 = task.velocity[i]
task.velocity[i] += task.accel[i] * PHYSICS_TIMER_INTERVAL
task.position[i] += (v0 + task.velocity[i]) / 2.0 * PHYSICS_TIMER_INTERVAL
task.falling_time += PHYSICS_TIMER_INTERVAL
task.falling_height += abs(task.velocity[1] + vy) / 2.0 * PHYSICS_TIMER_INTERVAL
task.obj.update_position(task.position)
self.timer.add_task(PHYSICS_TICK, self.update)
# do physics to an object which has:
# * method update_position(position) to update its position
def do_physics(self, position, accel, obj):
self.tasks.append(PhysicsTask(position, accel, obj))
if not self.started:
self.started = True
self.timer.add_task(PHYSICS_TICK, self.update)
self.timer.start()
示例2: run
# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import stop [as 别名]
def run(self):
timer = Timer()
timer.start()
# Create list of search urls
search_urls = []
filter = Filter(self.filter, self.startpage, self.maxpages)
for page in range(self.startpage, self.startpage + self.maxpages):
search_urls.append(filter.create_filter_url((page - 1) * 10))
# Create pool of worker threads
pool = ThreadPool(4)
# Open the urls in their own threads
organisaties = pool.map(unwrap_self_process_search, zip([self] * len(search_urls), search_urls))
pool.close()
pool.join()
results = {}
results["organisaties"] = self.consolidate(organisaties)
timer.stop()
results["stats"] = { "exectime": timer.exectime(), "matches": { "total": str(self.search_results["results"]), "pages": str(self.search_results["pages"]) }, "read": { "page_from": str(self.startpage), "page_to": str(self.maxpages) } }
return results
示例3: stopall
# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import stop [as 别名]
def stopall(self, timeout=10):
"""
Stops all known child processes by calling
"""
all = InProgressAll(*[process.stop() for process in self.processes.keys()])
# Normally we yield InProgressAll objects and they get implicitly connected
# by the coroutine code. We're not doing that here, so we connect a dummy
# handler so the underlying IPs (the processes) get connected to the IPAll.
all.connect(lambda *args: None)
# XXX: I've observed SIGCHLD either not be signaled or be missed
# with stopall() (but not so far any other time). So this kludge
# tries to reap all processes every 0.1s while we're killing child
# processes.
poll_timer = Timer(lambda: [process._check_dead() for process in self.processes.keys()])
poll_timer.start(0.1)
while not all.finished:
main.step()
poll_timer.stop()
# Handle and log any unhandled exceptions from stop() (i.e. child
# failed to die)
for process in self.processes:
try:
inprogress(process).result
except SystemError, e:
log.error(e.message)
示例4: compress
# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import stop [as 别名]
def compress():
"""
compress temp docstring
"""
hb_nice = int(read_value('nice'))
hb_cli = read_value('com')
hb_out = read_value('temp_output')
hb_api = HandBrake()
if not hb_api.findProcess():
if hb_api.loadMovie():
print "Encoding and compressing %s" % hb_api.getMovieTitle()
stopwatch = Timer()
if hb_api.convert(args=hb_cli, nice=hb_nice, output=hb_out):
print "Movie was compressed and encoded successfully"
stopwatch.stop()
print ("It took %s minutes to compress %s"
%
(stopwatch.getTime(), hb_api.getMovieTitle()))
else:
stopwatch.stop()
print "HandBrake did not complete successfully"
else:
print "Queue does not exist or is empty"
else:
print "Process already running skipper"
示例5: test_stop
# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import stop [as 别名]
def test_stop(self):
timer = Timer()
time.sleep(5)
timer.stop()
time.sleep(3)
timer.start()
time.sleep(5)
self.assertEqual(timer.get_counter(),10)
示例6: add_location
# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import stop [as 别名]
def add_location(self, pos = None):
if pos is None:
pos = helpers.parse_coords(self.location_str.get())
pos = tuple(pos)
styles = ["b", "g", "r", "c", "m", "y", "k"]
threshold = 1e-4
if len(pos) == 2:
pos = pos[0], pos[1], 0.0
if PROJECTIONS[self.opts.projection.get()] != '3d':
pos = pos[0], pos[1], 0.0
self.location_str.set("%0.4g, %0.4g" % (pos[0], pos[1]))
else:
self.location_str.set("%0.4g, %0.4g, %0.4g" % pos)
#Search for a fixed point
## fp = self.system.find_fp(pos, threshold = 1e-4)
## if fp is not None:
## fp_clean = tuple(np.round(fp, 3))
## if not fp_clean in self.fixed_points:
## self.fixed_points.add(fp_clean)
## self.fig.draw_fp(fp_clean)
## self.update_fig()
## vel = self.system(fp_clean)
## logging.info("Found a fixed point: %s %s\n" % (str(fp_clean), str(vel)))
if pos in self.trajectories:
logging.warning("Trajectory already exists.")
self.status.info("Trajectory already exists.")
return
self.status.info("Computing trajectory...")
try:
t = Timer()
t.start()
traj = self.system.trajectory(pos, self.opts.tmax.get(), threshold = threshold,
bidirectional = self.opts.reverse.get(), nsteps = 5 * (self.opts.tmax.get()/self.opts.dt.get()),
max_step = self.opts.dt.get(), use_ode = True)
t.stop()
logging.debug("Computing trajectory (%d points) took %g seconds" % (len(traj.x), t.seconds()))
except:
pos_str = ", ".join(map(str, pos))
logging.warning("Could not compute trajectory from: %s" % pos_str)
logging.debug(traceback.format_exc())
return
#if traj.dist[-1] < 10*threshold:
# return
self.trajectories[pos] = traj
if traj.t[-1] > self.anim_tmax:
self.anim_tmax = traj.t[-1]
style = (len(self.trajectories) - 1) % len(styles)
traj.style = styles[style]
self.status.info("Drawing trajectory...")
self.fig.add_trajectory(traj)
self.status.clear()
#self.fig.draw_trajectory(traj)
self.fig.draw()
self.last_loc = pos
示例7: rip
# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import stop [as 别名]
def rip():
"""
Main function for ripping
Does everything
Returns nothing
"""
log = Logger("rip", read_value("debug"))
mkv_save_path = read_value("save_path")
mkv_tmp_output = read_value("temp_output")
mkv_api = makeMKV(read_value("min_length"), read_value("cache_MB"), read_value("handbrake"), read_value("debug"))
log.debug("Autoripper started successfully")
log.debug("Checking for DVDs")
dvds = mkv_api.findDisc(mkv_tmp_output)
log.debug("%d DVDs found" % len(dvds))
if len(dvds) > 0:
# Best naming convention ever
for dvd in dvds:
mkv_api.setTitle(dvd["discTitle"])
mkv_api.setIndex(dvd["discIndex"])
movie_title = mkv_api.getTitle()
if not os.path.exists("%s/%s" % (mkv_save_path, movie_title)):
os.makedirs("%s/%s" % (mkv_save_path, movie_title))
mkv_api.getDiscInfo()
stopwatch = Timer()
if mkv_api.ripDisc(mkv_save_path, mkv_tmp_output):
stopwatch.stop()
log.info("It took %s minutes to complete the ripping of %s" % (stopwatch.getTime(), movie_title))
else:
stopwatch.stop()
log.info("MakeMKV did not did not complete successfully")
log.info("See log for more details")
log.debug("Movie title: %s" % movie_title)
else:
log.info("Movie folder %s already exists" % movie_title)
else:
log.info("Could not find any DVDs in drive list")
示例8: api_organisations
# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import stop [as 别名]
def api_organisations():
timer = Timer()
timer.start()
app.logger.debug(request.args)
filter = {}
filter["handelsnaam"] = check_args("handelsnaam")
filter["kvknummer"] = check_args("kvknummer")
filter["straat"] = check_args("straat")
filter["huisnummer"] = check_args("huisnummer")
filter["postcode"] = check_args("postcode")
filter["plaats"] = check_args("plaats")
filter["hoofdvestiging"] = check_args_boolean("hoofdvestiging", True, False)
filter["nevenvestiging"] = check_args_boolean("nevenvestiging", True, False)
filter["rechtspersoon"] = check_args_boolean("rechtspersoon", True, False)
filter["vervallen"] = check_args_boolean("vervallen", False, True)
filter["uitgeschreven"] = check_args_boolean("uitgeschreven", False, True)
app.logger.debug(filter)
if filter["handelsnaam"] == "" and filter["kvknummer"] == "" and filter["straat"] == "" and filter["huisnummer"] == "" and filter["postcode"] == "" and filter["plaats"] == "":
return unprocessable_entity()
else:
if 'startpage' in request.args:
startpage = int(request.args['startpage'])
else:
startpage = 1
if 'maxpages' in request.args:
maxpages = int(request.args['maxpages'])
else:
maxpages = 1
try:
search = Search(filter, startpage, maxpages)
except NoResultsError:
return not_found()
else:
results = search.run()
timer.stop();
results["total_exectime"] = timer.exectime()
results["api_version"] = "v1"
results["release"] = release
resp = jsonify(results)
resp.status_code = 200
return resp
示例9: rip
# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import stop [as 别名]
def rip():
"""
rip temp docstring
"""
mkv_save_path = read_value('save_path')
mkv_min_length = int(read_value('min_length'))
mkv_cache_size = int(read_value('cache_MB'))
mkv_tmp_output = read_value('temp_output')
use_handbrake = bool(read_value('handbrake'))
mkv_api = makeMKV()
dvds = mkv_api.findDisc(mkv_tmp_output)
if (len(dvds) > 0):
# Best naming convention ever
for dvd in dvds:
mkv_api.setTitle(dvd["discTitle"])
mkv_api.setIndex(dvd["discIndex"])
movie_title = mkv_api.getTitle()
if not os.path.exists('%s/%s' % (mkv_save_path, movie_title)):
os.makedirs('%s/%s' % (mkv_save_path, movie_title))
stopwatch = Timer()
if mkv_api.ripDisc(path=mkv_save_path,
length=mkv_min_length,
cache=mkv_cache_size,
queue=use_handbrake,
output=mkv_tmp_output):
stopwatch.stop()
print ("It took %s minutes to complete the ripping of %s"
%
(stopwatch.getTime(), movie_title))
else:
stopwatch.stop()
print "MakeMKV did not did not complete successfully"
print "Movie title: %s" % movie_title
else:
print "Movie folder %s already exists" % movie_title
else:
print "Could not find any DVDs in drive list"
示例10: getSummariesSingleKeyword
# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import stop [as 别名]
def getSummariesSingleKeyword(keywords, max_entries=4, lang='en', pics_folder='pics/'):
timer = Timer(verbose=True)
timer.start()
wikipedia.set_lang(lang)
articles = []
summary_box_info = {}
num_results = 0
for keyword,score in keywords:
if num_results >= max_entries:
break
#check cache first
if keyword in keyword_cache:
articles.append(keyword_cache[keyword])
num_results += 1
else:
try:
result = wikipedia.search(keyword)
except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError, requests.exceptions.ConnectTimeout, requests.exceptions.RetryError, requests.exceptions.InvalidURL, requests.exceptions.SSLError) as e:
print 'WARNING! Connection error in wiki_search!'
result = []
pass
if len(result) > 0:
try:
article = result[0]
#exclude number articles
if not "(number)" in article and not "Unk"==article:
summary = filterBrackets(wikipedia.summary(article, sentences=1))
articles.append((article,summary,score))
num_results += 1
keyword_cache[keyword] = (article,summary,score)
except Exception as e: #TODO: we should jut ignore DisambiguationError and report the rest
pass
else:
keyword_cache[keyword] = ("","",0.0)
for article,summary,score in articles:
if article != '':
if article in wiki_cache:
wiki_article = wiki_cache[article]
else:
wiki_article = wikipedia.page(article)
summary_box_info[wiki_article.title] = {'title':wiki_article.title,'text':summary,'url':'https://'+lang+'.wikipedia.org/w/index.php?title='+wiki_article.title.replace(' ','_'),'categories':wiki_article.categories,'score':score}
timer.stop()
return summary_box_info
示例11: kruskal_wallis
# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import stop [as 别名]
def kruskal_wallis(genotype, phenVals, useTieCorrection=True):
t = Timer()
num_accessions=len(genotype.accessions)
num_snps = genotype.num_snps
assert num_accessions== len(phenVals), "SNPs and phenotypes are not equal length."
ranks, group_counts = _kw_get_ranks_(phenVals)
assert len(group_counts) == len(set(ranks)), 'Somethings wrong..'
tieCorrection = 1.0
if useTieCorrection:
n_total = len(ranks)
ones_array = np.repeat(1.0, len(group_counts))
s = np.sum(group_counts * (group_counts * group_counts - ones_array))
s = s / (n_total * (n_total * n_total - 1.0))
tieCorrection = 1.0 / (1 - s)
n = len(phenVals)
ds = np.zeros(num_snps)
c = 12.0 / (n * (n + 1))
snps = genotype.get_snps_iterator()
for i, snp in enumerate(snps):
ns = np.bincount(snp)
rs = np.array([0.0, np.sum(snp * ranks)])
rs[0] = np.sum(ranks) - rs[1]
nominator = 0.0
mean_r = (n + 1) / 2.0
for j in range(2):
v = (rs[j] / ns[j]) - mean_r
nominator += ns[j] * v * v
ds[i] = (c * nominator) * tieCorrection
ps = sp.stats.chi2.sf(ds, 1)
log.info('Took %s' % t.stop(True))
return {"ps":ps, "ds":ds}
示例12: __init__
# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import stop [as 别名]
class PowerSupply:
def __init__(self, path, onChange, args=[], kwargs={}):
self.timer = Timer(10, self.__update, False, args, kwargs)
self.uevent = UEvent(path, self.__update, args, kwargs)
self.onChange = onChange
self.path = path
self.info = {}
def __update(self, *args, **kwargs):
if callable(self.onChange):
self.onChange(*args, **kwargs)
def __read_sysfs(self, filename):
try:
with open(self.path + "/" + filename, "r") as f:
s = f.read()
except:
s = False
if s[-1] == "\n":
s = s[:-1]
return s
def getInfo(self):
uevent = self.__read_sysfs("uevent")
if not uevent:
return {}
uevent = uevent.splitlines()
index1 = len("POWER_SUPPLY_")
for i in range(0, len(uevent)):
index2 = uevent[i].rfind("=")
self.info[uevent[i][index1:index2].lower()] = uevent[i][index2+1:]
self.info["type"] = self.__read_sysfs("type")
return self.info
def getValue(self, attr):
return self.__read_sysfs(attr)
def start_monitor(self):
self.timer.start()
self.uevent.start()
def stop_monitor(self):
self.timer.stop(True)
self.uevent.stop()
示例13: linear_model
# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import stop [as 别名]
def linear_model(snps, phenotypes, cofactors=None):
lm = LinearModel(phenotypes)
if cofactors:
for cofactor in cofactors:
lm.add_factor(cofactor)
log.info("Running a standard linear model")
t = Timer()
res = lm.fast_f_test(snps)
log.info('Took: %s' % t.stop(True))
return res
示例14: anova
# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import stop [as 别名]
def anova(snps, phenotypes):
"""
Run EMMAX
"""
lmm = LinearModel(phenotypes)
log.info("Running ANOVA")
t = Timer()
res = lmm.anova_f_test(snps)
log.info('Took: %s' % t.stop(True))
return res
示例15: emmax_anova
# 需要导入模块: from timer import Timer [as 别名]
# 或者: from timer.Timer import stop [as 别名]
def emmax_anova(snps, phenotypes, K):
"""
Run EMMAX
"""
lmm = LinearMixedModel(phenotypes)
lmm.add_random_effect(K)
log.info("Running EMMAX-ANOVA")
t = Timer()
res = lmm.emmax_anova_f_test(snps)
log.info('Took:%s' % t.stop(True))
return res