本文整理汇总了Python中scheduler.Scheduler.schedule方法的典型用法代码示例。如果您正苦于以下问题:Python Scheduler.schedule方法的具体用法?Python Scheduler.schedule怎么用?Python Scheduler.schedule使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scheduler.Scheduler
的用法示例。
在下文中一共展示了Scheduler.schedule方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save
# 需要导入模块: from scheduler import Scheduler [as 别名]
# 或者: from scheduler.Scheduler import schedule [as 别名]
def save(self, args):
if args["oldName"] == "":
key = args["name"]
av = Availability()
else:
key = args["oldName"]
av = Availability.find(self.env.get_db_cnx(), key)
av.name = args["name"]
av.validFrom = args["validFrom"]
av.validUntil = args["validUntil"]
av.resources = args["resources"]
av.weekdays = ""
self.appendWeekdays(av, args, "1")
self.appendWeekdays(av, args, "2")
self.appendWeekdays(av, args, "3")
self.appendWeekdays(av, args, "4")
self.appendWeekdays(av, args, "5")
self.appendWeekdays(av, args, "6")
self.appendWeekdays(av, args, "0")
av.workFrom = args["workFrom"]
av.workUntil = args["workUntil"]
av.save(self.env.get_db_cnx(), key)
scheduler = Scheduler()
scheduler.schedule(self.env, self.config);
return 'admin_availability.html', {"availabilities" : self.availabilities(), "view": "list"}
示例2: test_scheduler_insert_event
# 需要导入模块: from scheduler import Scheduler [as 别名]
# 或者: from scheduler.Scheduler import schedule [as 别名]
def test_scheduler_insert_event(self):
scheduler = Scheduler()
t = time()
while time() < t+1:
self.assertEqual(scheduler.schedule(),'idle')
sleep(0.05)
event = Event(time(), 'test_event')
self.assertEqual(scheduler.schedule([event]),event)
示例3: test_scheduler_listener
# 需要导入模块: from scheduler import Scheduler [as 别名]
# 或者: from scheduler.Scheduler import schedule [as 别名]
def test_scheduler_listener(self):
scheduler = Scheduler()
listener = SchedulerTestListener('test_event')
scheduler.add_listener(listener)
self.assertEqual(scheduler.schedule(),'idle')
event = Event(time(),'test_event')
self.assertEqual(scheduler.schedule([event]),event)
self.assertEqual(listener.count,1)
示例4: update
# 需要导入模块: from scheduler import Scheduler [as 别名]
# 或者: from scheduler.Scheduler import schedule [as 别名]
def update(self, nffg, delete = False):
session = Session().get_active_user_session_by_nf_fg_id(nffg.id, error_aware=True)
Session().updateStatus(session.id, 'updating')
# Get profile from session
graphs_ref = Graph().getGraphs(session.id)
if len(graphs_ref) > 1:
# If the graph has been split, the smart update is not supported
logging.warning("The graph has been split in various nffg, in this case the smart update is not supported.")
self.delete(nffg.id)
else:
old_nffg = Graph().get_nffg(graphs_ref[0].id)
logging.debug('NF-FG that has to be updated: '+old_nffg.getJSON())
nffg.db_id = old_nffg.db_id
# Get VNFs templates
self.prepareNFFG(nffg)
# Get the component adapter associated to the node where the nffg was instantiated
old_node = Node().getNode(Graph().getNodeID(graphs_ref[0].id))
scheduler = Scheduler(old_nffg.db_id, self.user_data)
orchestrator, new_node = scheduler.schedule(nffg)
# If the orchestrator have to connect two graphs in different nodes,
# the end-points must be characterized to allow a connection between nodes
remote_nffgs_dict = self.analizeRemoteConnection(nffg, new_node)
# If needed, update the remote graph
self.updateRemoteGraph(remote_nffgs_dict)
if new_node.id != old_node.id:
logging.warning("The graph will be instantiated in a different node, in this case the smart update is not supported.")
orchestrator.deinstantiateProfile(nffg, old_node)
Graph().delete_session(session.id)
Graph().addNFFG(nffg, session.id)
Graph().setNodeID(graphs_ref[0].id, Node().getNodeFromDomainID(new_node.domain_id).id)
try:
orchestrator.instantiateProfile(nffg, new_node)
except Exception as ex:
logging.exception(ex)
Session().set_error(session.id)
raise ex
else:
# Update the nffg
try:
orchestrator.updateProfile(nffg, old_nffg, new_node)
except Exception as ex:
logging.exception(ex)
Session().set_error(session.id)
raise ex
Session().updateStatus(session.id, 'complete')
Session().updateSessionNode(session.id, new_node.id, new_node.id)
return session.id
示例5: test_scheduler_timed_listener
# 需要导入模块: from scheduler import Scheduler [as 别名]
# 或者: from scheduler.Scheduler import schedule [as 别名]
def test_scheduler_timed_listener(self):
scheduler = Scheduler()
listener = SchedulerTestListener('test_event')
scheduler.add_listener(listener)
scheduler.add_timer(0.250,'test_event')
start = time()
count = 0
while time() < start+1.05:
event = scheduler.schedule()
if event!='idle' and event.label == 'test_event':
count = count + 1
sleep(0.05)
self.assertEqual(count,4)
self.assertEqual(listener.count,4)
示例6: updateRemoteGraph
# 需要导入模块: from scheduler import Scheduler [as 别名]
# 或者: from scheduler.Scheduler import schedule [as 别名]
def updateRemoteGraph(self, remote_nffgs_dict):
for remote_nffg in remote_nffgs_dict.itervalues():
try:
session = Session().get_active_user_session_by_nf_fg_id(remote_nffg.id, error_aware=True)
except sessionNotFound:
continue
remote_user_data = UserData()
remote_user_data.getUserData(session.user_id)
Session().updateStatus(session.id, 'updating')
self.prepareNFFG(remote_nffg)
scheduler = Scheduler(remote_nffg.db_id, remote_user_data)
orchestrator, node = scheduler.schedule(remote_nffg)
old_nf_fg = Graph().get_nffg(remote_nffg.db_id)
try:
orchestrator.updateProfile(remote_nffg, old_nf_fg, node)
except Exception as ex:
logging.exception(ex)
'''
Graph().delete_graph(nffg.db_id)
'''
Session().set_error(session.id)
raise ex
Session().updateStatus(session.id, 'complete')
示例7: SchedulerTest
# 需要导入模块: from scheduler import Scheduler [as 别名]
# 或者: from scheduler.Scheduler import schedule [as 别名]
class SchedulerTest(unittest.TestCase):
def test_scheduler_schedule(self):
self.scheduler = Scheduler()
self.assertEqual(self.scheduler.schedule(),'idle')
def test_scheduler_insert_event(self):
scheduler = Scheduler()
t = time()
while time() < t+1:
self.assertEqual(scheduler.schedule(),'idle')
sleep(0.05)
event = Event(time(), 'test_event')
self.assertEqual(scheduler.schedule([event]),event)
def test_scheduler_add_timer(self):
self.scheduler = Scheduler()
self.scheduler.add_timer(2, 'test_timer')
self.assertEqual(len(self.scheduler.timers),1);
self.assertTrue('test_timer' in self.scheduler.timers.keys())
self.assertEqual(self.scheduler.timers['test_timer'].getPeriod(),2)
def test_scheduler_timer(self):
self.scheduler = Scheduler()
error = 0.1
delay = 2
startTime = time()
self.scheduler.add_timer(delay,'test_timer')
while time() < startTime+delay-error:
self.assertEqual(self.scheduler.schedule(),'idle')
sleep(error/10)
event_count = 0
while time() < startTime+delay+error:
event = self.scheduler.schedule()
if event!='idle' and event.label=='test_timer':
event_count = event_count + 1
sleep(error/10)
self.assertEqual(event_count,1)
def test_scheduler_add_listener(self):
self.scheduler = Scheduler()
listener = SchedulerTestListener('foo')
self.scheduler.add_listener(listener)
self.assertEqual(len(self.scheduler.listeners),1)
self.assertEqual(self.scheduler.listeners['foo'],[listener])
def test_scheduler_add_bad_listener(self):
self.scheduler = Scheduler()
listener = SchedulerTestListener('foo')
listener.addEvent(None)
type_error = False
try:
self.scheduler.add_listener(listener)
except TypeError:
type_error = True
self.assertEqual(type_error,True)
def test_scheduler_listener(self):
scheduler = Scheduler()
listener = SchedulerTestListener('test_event')
scheduler.add_listener(listener)
self.assertEqual(scheduler.schedule(),'idle')
event = Event(time(),'test_event')
self.assertEqual(scheduler.schedule([event]),event)
self.assertEqual(listener.count,1)
def test_scheduler_timed_listener(self):
scheduler = Scheduler()
listener = SchedulerTestListener('test_event')
scheduler.add_listener(listener)
scheduler.add_timer(0.250,'test_event')
start = time()
#.........这里部分代码省略.........
示例8: Jailor
# 需要导入模块: from scheduler import Scheduler [as 别名]
# 或者: from scheduler.Scheduler import schedule [as 别名]
class Jailor(EIPCProcess):
"""
This class manages the communication between the execution environment
and the outside world.
"""
SERVICE_NAME_RE = re.compile('\w+\.\w+\.\w+')
def __init__(self, pipe, cores, debug = False):
"""
Constructor.
@type pipe: EIPC
@param address: The pipe used for IPC.
@type cores: int
@param cores: The number of cores/cpu to utilize when scheduling.
"""
# Initialize super class.
super(Jailor, self).__init__(pipe)
# Set up logging.
if debug:
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(levelname)s: %(message)s\n'\
'\t%(filename)s, %(funcName)s, %(lineno)s',
datefmt='%m/%d/%y %H:%M:%S')
else:
logging.basicConfig(level=logging.ERROR,
format='%(asctime)s - %(levelname)s: %(message)s',
datefmt='%m/%d/%y %H:%M:%S')
# Register a logger.
self.__logger = logging.getLogger('jailor')
# Create the scheduler and registry.
self.registry = ServiceRegistry()
self.scheduler = Scheduler(self, cores)
# Register functions for IPC.
self.register_function(self.perform_service)
self.register_function(self.service_exists)
self.register_function(self.install_service)
self.register_function(self.fetch_service_code)
self.__logger.info('Jailor initialized.')
@classmethod
def valid_service_name(cls, service_name):
return cls.SERVICE_NAME_RE.match(service_name) != None
def perform_service(self, service_name, service_input):
"""
Starts performing a named service on behalf of the client.
@type service_name: str
@param service_name: The service identifier.
@type service_input: dict (kwargs), tuple (pos args), or
any (single argument).
@param service_input: The input forthe given service.
"""
# Check the service name.
if not Jailor.valid_service_name(service_name):
self.__logger.info('Invalid service name %s used.'%service_name)
raise Exception('Invalid service name given.')
# Check that the service exists.
if not self.registry.has_service(service_name):
self.__logger.info('Call to non-existing service %s'%service_name)
raise Exception('The named service does not exist.')
# Now start performing the service.
execid = self.scheduler.schedule(service_name, service_input)
self.__logger.info('%s scheduled with execid=%i.'%(service_name, execid))
return execid
def service_exists(self, service_name):
"""
Checks whether a given service exists.
@type service_name: str
@param service_name: The service identifier.
"""
# Check the service name.
if not Jailor.valid_service_name(service_name):
self.__logger.info('Invalid service name %s used.'%service_name)
raise Exception('Invalid service name given.')
# Ask the registry whether or not the service is installed.
return self.registry.has_service(service_name)
def service_callback(self, execution_id, status, args):
"""
Entry point for service callbacks. This is called by services
upon completion or when an error occurs.
@type execution_id: int
@param execution_id: The id of the service execution. This is used on
the client side to identify the responding service.
@type status: str
@param status: The status of the execution. This is: 'DONE' if the service
has finished its execution, 'ERROR' if an error has occurred, and 'STATUS' if
the service is simply returning some status information about its execution.
@type args: dict
#.........这里部分代码省略.........
示例9: CrawlJob
# 需要导入模块: from scheduler import Scheduler [as 别名]
# 或者: from scheduler.Scheduler import schedule [as 别名]
class CrawlJob(object):
NWORKSETS_BITS = 8
def __init__(self, jobconfigs, jobname, crawlinfo, domaininfo):
self.jobconfigs = jobconfigs
self.jobname = jobname
self.mapper = CrawlMapper(self, self.NWORKSETS_BITS)
self.workset_state = [0 for i in range(self.mapper.nworksets)]
# seen-db initialization is delayed until it's actually needed
self.seen = None
#self.seen = Seen(dbdir=os.path.join(HQ_HOME, 'seen', self.jobname))
self.crawlinfodb = crawlinfo
self.domaininfo = domaininfo
self.scheduler = Scheduler(hqconfig.worksetdir(self.jobname),
self.mapper)
# self.inq = HashSplitIncomingQueue(
# qdir=hqconfig.inqdir(self.jobname),
# buffsize=500)
self.inq = PooledIncomingQueue(
qdir=hqconfig.inqdir(self.jobname),
buffsize=1000)
self.diverter = Diverter(self.jobname, self.mapper)
#self.discovered_executor = ThreadPoolExecutor(poolsize=1)
# currently disabled by default - too slow
self.use_crawlinfo = False
self.save_crawlinfo = False
PARAMS = [('use_crawlinfo', bool),
('save_crawlinfo', bool)]
def shutdown(self):
logging.info("shutting down scheduler")
self.scheduler.shutdown()
logging.info("shutting down diverter")
self.diverter.shutdown()
if self.seen:
logging.info("closing seen db")
self.seen.close()
logging.info("closing incoming queues")
self.inq.flush()
self.inq.close()
logging.info("shutting down crawlinfo")
self.crawlinfodb.shutdown()
logging.info("done.")
#self.discovered_executor.shutdown()
def get_status(self):
r = dict(job=self.jobname, oid=id(self))
r['seen'] = self.seen and self.seen.get_status()
r['sch'] = self.scheduler and self.scheduler.get_status()
r['inq'] = self.inq and self.inq.get_status()
return r
def get_workset_status(self):
r = dict(job=self.jobname, crawljob=id(self))
if self.scheduler:
r['sch'] = id(self.scheduler)
r['worksets'] = self.scheduler.get_workset_status()
return r
#def discovered_async(self, curis):
# return self.inq.add(curis)
def get_domaininfo(self, url):
uc = urlsplit(url)
host = uc.netloc
p = host.find(':')
if p > 0: host = host[:p]
di = self.domaininfo.get(host)
return di
def schedule(self, curis):
'''schedule curis bypassing seen-check. typically used for starting
new crawl cycle.'''
scheduled = 0
for curi in curis:
self.scheduler.schedule(curi)
scheduled += 1
return dict(processed=scheduled, scheduled=scheduled)
def discovered(self, curis):
return self.inq.add(curis)
def is_client_active(self, clid):
"""is client clid active?"""
# TODO: update ZooKeeper when active status changes
#t = self.client_last_active.get(str(clid))
return self.scheduler.is_active(clid)
def is_workset_active(self, wsid):
"""is workset wsid assigned to any active client?"""
clid = self.mapper.worksetclient[wsid]
return self.is_client_active(clid)
def workset_activating(self, wsid):
"""activates working set wsid; start sending CURIs to Scheduler
#.........这里部分代码省略.........
示例10: solution
# 需要导入模块: from scheduler import Scheduler [as 别名]
# 或者: from scheduler.Scheduler import schedule [as 别名]
def solution(toy_file, soln_file, num_elves, TARGET):
""" Creates a simple solution where the next available elf is assigned a toy. Elves do not start
work outside of sanctioned hours.
:param toy_file: filename for toys file (input)
:param soln_file: filename for solution file (output)
:param myelves: list of elves in a priority queue ordered by next available time
:return:
"""
hrs = Hours()
toy_loader = ToyLoader(toy_file)
solution_writer = SolutionWriter(soln_file)
busy_elves_heap = BusyElvesHeap(num_elves)
elves_ready = ElvesReady()
scheduler = Scheduler(TARGET, num_elves)
start = time.time()
current_time = 497340
print("Getting initial toys")
print('time taken = {0}, current_time = {1}'.format(time.time() - start, hrs.get_time_string(current_time)))
new_toy_orders = toy_loader.get_toys_up_to_minute(current_time)
print("Loading initial toys into backlog")
print('time taken = {0}, current_time = {1}'.format(time.time() - start, hrs.get_time_string(current_time)))
toy_backlog = ToyBacklogV2(new_toy_orders)
print("Finished initializing toys into backlog")
print('time taken = {0}, current_time = {1}'.format(time.time() - start, hrs.get_time_string(current_time)))
toys_finished = 0
toys_left_at_end = []
time_of_last_toy_assigned = current_time
while not (toy_loader.done() and toy_backlog.done() and len(toys_left_at_end) == 0):
# step 1 process newly arrived toys and fresh elves
new_elves = busy_elves_heap.get_elves_for_min(current_time)
elves_ready.add_elves(new_elves)
if (current_time % 120 == 60):
print('time taken = {0}, current_time = {1}'.format(time.time() - start, hrs.get_time_string(current_time)))
print('easy_toys:{0},\t constant_toys:{1},\t variable_toys:{2},\t hardest_toys:{3},\t toys_left_at_end:{4}'.format(
toy_backlog.easy_toy_list.size, len(toy_backlog.constant_rating_list),
len(toy_backlog.variable_toy_list), len(toy_backlog.hardest_toy_list), len(toys_left_at_end)))
print('elves ready:{0}, high-perf-elves:{1}'.format(len(elves_ready.training_elf_list),
len(elves_ready.high_performance_elf_list)))
print('toys finished = {0}'.format(toys_finished))
if (len(elves_ready.training_elf_list) + len(elves_ready.high_performance_elf_list)) == 0:
current_time = hrs.next_sanctioned_minute(current_time)
continue
if (toy_loader.done() and current_time - time_of_last_toy_assigned > 2880 and len(elves_ready.training_elf_list) == num_elves and len(toys_left_at_end) == 0):
print("starting cleanup")
for toy in toy_backlog.easy_toy_list.all_toys():
toys_left_at_end.append(toy)
toy_backlog.easy_toy_list.clear()
for toy in toy_backlog.constant_rating_list:
toys_left_at_end.append(toy)
toy_backlog.constant_rating_list = []
while len(toy_backlog.variable_toy_list) > 0:
toys_left_at_end.append(toy_backlog.pop_variable_toy())
while len(toy_backlog.hardest_toy_list) > 0:
toys_left_at_end.append(toy_backlog.pop_hardest_toy())
if (toy_loader.done() and len(toys_left_at_end) > 0):
# clean up last toys
toys_finished += scheduler.clean_up(toys_left_at_end, elves_ready, busy_elves_heap, current_time, solution_writer)
else:
# step 2 pair off as many elves and toys as possible
toys_newly_finished = scheduler.schedule(toy_backlog, elves_ready, busy_elves_heap, current_time,
solution_writer, toy_loader)
toys_finished += toys_newly_finished
if (toys_newly_finished > 0):
time_of_last_toy_assigned = current_time
current_time = hrs.next_sanctioned_minute(current_time)
toy_loader.close()
solution_writer.close()
示例11: print
# 需要导入模块: from scheduler import Scheduler [as 别名]
# 或者: from scheduler.Scheduler import schedule [as 别名]
if not argument:
print("* The dataset does not only contain digits")
return
print()
print("* The dataset only contains digits")
def hue(scheduler, mapper1, reducer1, mapper2, reducer2):
for i in range(100):
scheduler.add_operation("DS1", Priority.normal, mapper1, reducer1)
scheduler.add_operation("DS1", Priority.normal, mapper2, reducer2)
scheduler.add_operation("DS2", Priority.high, mapper1, reducer1)
scheduler.add_operation("DS2", Priority.low, mapper2, reducer2)
length_code = length.__code__
sum_code = sum.__code__
digit_code = digit.__code__
digits_code = digits.__code__
map1 = pickle.dumps(length_code)
rec1 = pickle.dumps(sum_code)
map2 = pickle.dumps(digit_code)
rec2 = pickle.dumps(digits_code)
lolle = Process(target=hue, args=(SCHEDULER, map1, rec1, map2, rec2))
lolle.start()
time.sleep(2)
print_section("Scheduling operations")
SCHEDULER.schedule()
示例12: __init__
# 需要导入模块: from scheduler import Scheduler [as 别名]
# 或者: from scheduler.Scheduler import schedule [as 别名]
class Sequencer:
def __init__(self, logger=None):
if logger is None:
logger = logging.getLogger("Sequencer")
self.logger = logger
self._params = {"tracks": {},
"buses": {},
"reference_colour": None,
"max_colour_distance": 1.0}
self._sounds = {}
self._tracks = collections.OrderedDict()
self._buses = collections.OrderedDict()
self._groups = []
self._scheduler = Scheduler()
self.control_panels = set()
self._setup_colour_receiver()
SynthController.kill_potential_engine_from_previous_process()
self._synth = SynthController()
self._synth.launch_engine()
self._synth.connect(self._synth.lang_port)
self._setup_websocket_server()
def _setup_colour_receiver(self):
self._current_colour = None
self._colour_receiver = ColourReceiver()
self._colour_receiver.received_colour = self.set_current_colour
self._colour_receiver.start()
def set_current_colour(self, rgb):
self._current_colour = rgb
if self._params["reference_colour"] is not None:
self._estimate_age()
self._set_age_dependent_rates()
for control_panel in self.control_panels:
control_panel.send_params()
def _estimate_age(self):
distance_to_reference = self._colour_distance(
self._current_colour, self._params["reference_colour"])
age = distance_to_reference / self._params["max_colour_distance"]
age = min(age, 1.0)
self._estimated_age = age
# self.log("estimated age: %.2f" % self._estimated_age)
def _set_age_dependent_rates(self):
for track in self._tracks.values():
params = self._params["tracks"][track["name"]]
if params["age_type"] is not None:
params["rate"] = self._age_dependent_rate(params["age_type"])
# self.log("rate %.1f for age_type=%s, track %s" % (
# params["rate"], params["age_type"], track["name"]))
self._on_track_params_changed(track)
def _age_dependent_rate(self, age_type):
if age_type == "decay":
return RATE_MIN + (RATE_MAX - RATE_MIN) * (1 - self._estimated_age)
else:
return RATE_MIN + (RATE_MAX - RATE_MIN) * self._estimated_age
def _colour_distance(self, colour1, colour2):
diffs = [colour1[n] - colour2[n]
for n in range(3)]
return math.sqrt(sum([diff*diff for diff in diffs]))
def calibrate_colour(self):
self.log("calibrate_colour %s" % self._current_colour)
if self._current_colour is not None:
self._params["reference_colour"] = self._current_colour
def get_tracks(self):
return self._tracks
def get_buses(self):
return self._buses
def get_params(self):
return self._params
def play(self, sound, looped=0):
track_name = self._sounds[sound]["track_name"]
track = self._tracks[track_name]
params = self._params["tracks"][track_name]
self._synth.play(
sound,
params["pan"],
params["fade"],
params["gain"] + params["gain_adjustment"],
params["rate"],
looped,
params["send"],
params["send_gain"] + params["gain_adjustment"],
params["comp_threshold"])
def schedule(self, action, delay):
self._scheduler.schedule(action, delay)
def is_playing(self, sound):
return self._synth.is_playing(sound)
def load_sounds(self, pattern):
#.........这里部分代码省略.........
示例13: Scheduler
# 需要导入模块: from scheduler import Scheduler [as 别名]
# 或者: from scheduler.Scheduler import schedule [as 别名]
[restart] restart the crawl
[stop] stop the crawl
[report] report on current crawl sent by <mail> OR stored in <file> OR printed out
[export] export the specified <collection> into a JSON file and then into a ZIP file
[run] directly run a project or every project in DB
-f --file Complete path of the sourcefile.
-o --o Outfile format for export
-k --key Bing API Key for SearchNY.
-e --email one or more emails separated by a coma
-u gmail adress account to send report
-p password of gmail account
-h --help Show usage and Options.
--version Show versions.
'''
__all__ = ['crawtext', 'manager','database', "scheduler", "dispatcher"]
import __future__
from docopt import docopt
from scheduler import Scheduler
import sys
CRAWTEXT = "crawtext"
if __name__ == "__main__":
'''sending job to be done'''
s = Scheduler(docopt(__doc__))
s.schedule()
sys.exit()
示例14: delete
# 需要导入模块: from scheduler import Scheduler [as 别名]
# 或者: from scheduler.Scheduler import schedule [as 别名]
def delete(self, name):
av = Availability.find(self.env.get_db_cnx(), name)
av.delete(self.env.get_db_cnx())
scheduler = Scheduler()
scheduler.schedule(self.env, self.config);
return 'admin_availability.html', {"availabilities" : self.availabilities(), "view": "list"}
示例15: Typist
# 需要导入模块: from scheduler import Scheduler [as 别名]
# 或者: from scheduler.Scheduler import schedule [as 别名]
class Typist(object):
TARGETS = { 'paper': {
'model': 'paper',
'textureRoot': 'Front',
'scale': Point3(0.85, 0.85, 1),
'hpr' : Point3(0, 0, 0),
}
}
def __init__(self, base, typewriterNP, underDeskClip, sounds):
self.base = base
self.sounds = sounds
self.underDeskClip = underDeskClip
self.typeIndex = 0
self.typewriterNP = typewriterNP
self.rollerAssemblyNP = typewriterNP.find("**/roller assembly")
assert self.rollerAssemblyNP
self.rollerNP = typewriterNP.find("**/roller")
assert self.rollerNP
self.carriageNP = typewriterNP.find("**/carriage")
assert self.carriageNP
self.baseCarriagePos = self.carriageNP.getPos()
self.carriageBounds = self.carriageNP.getTightBounds()
self.font = base.loader.loadFont('Harting.ttf', pointSize=32)
self.pnmFont = PNMTextMaker(self.font)
self.fontCharSize, _, _ = fonts.measureFont(self.pnmFont, 32)
print "font char size: ",self.fontCharSize
self.pixelsPerLine = int(round(self.pnmFont.getLineHeight()))
self.target = None
""" panda3d.core.NodePath """
self.targetRoot = None
""" panda3d.core.NodePath """
self.paperY = 0.0
""" range from 0 to 1 """
self.paperX = 0.0
""" range from 0 to 1 """
self.createRollerBase()
self.tex = None
self.texImage = None
self.setupTexture()
self.scheduler = Scheduler()
task = self.base.taskMgr.add(self.tick, 'timerTask')
task.setDelay(0.01)
def tick(self, task):
self.scheduler.tick(globalClock.getRealTime())
return task.cont
def setupTexture(self):
"""
This is the overlay/decal/etc. which contains the typed characters.
The texture size and the font size are currently tied together.
:return:
"""
self.texImage = PNMImage(1024, 1024)
self.texImage.addAlpha()
self.texImage.fill(1.0)
self.texImage.alphaFill(1.0)
self.tex = Texture('typing')
self.tex.setMagfilter(Texture.FTLinear)
self.tex.setMinfilter(Texture.FTLinear)
self.typingStage = TextureStage('typing')
self.typingStage.setMode(TextureStage.MModulate)
self.tex.load(self.texImage)
# ensure we can quickly update subimages
self.tex.setKeepRamImage(True)
# temp for drawing chars
self.chImage = PNMImage(*self.fontCharSize)
def drawCharacter(self, ch, px, py):
"""
Draw a character onto the texture
:param ch:
:param px: paperX
:param py: paperY
:return: the paper-relative size of the character
"""
h = self.fontCharSize[1]
if ch != ' ':
# position -> pixel, applying margins
x = int(self.tex.getXSize() * (px * 0.8 + 0.1))
y = int(self.tex.getYSize() * (py * 0.8 + 0.1))
#.........这里部分代码省略.........