本文整理匯總了Python中repeated_timer.RepeatedTimer.stop方法的典型用法代碼示例。如果您正苦於以下問題:Python RepeatedTimer.stop方法的具體用法?Python RepeatedTimer.stop怎麽用?Python RepeatedTimer.stop使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類repeated_timer.RepeatedTimer
的用法示例。
在下文中一共展示了RepeatedTimer.stop方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import stop [as 別名]
class DatDashSampler:
def __init__(self, app, interval):
self._app = app
self._timer = RepeatedTimer(interval, self._sample)
def stop(self):
self._timer.stop()
def name(self):
"""
Child class implements this function
"""
return "UnknownSampler"
def sample(self):
"""
Child class implements this function
"""
return {}
def _send_event(self, widget_id, body):
body["id"] = widget_id
body["updateAt"] = \
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S +0000")
formatted_json = "data: %s\n\n" % (json.dumps(body))
self._app.last_events[widget_id] = formatted_json
for event_queue in self._app.events_queue.values():
event_queue.put(formatted_json)
def _sample(self):
data = self.sample()
if data:
self._send_event(self.name(), data)
示例2: DashieSampler
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import stop [as 別名]
class DashieSampler(object):
def __init__(self, app, interval):
self._app = app
self._timer = RepeatedTimer(interval, self._sample)
def stop(self):
self._timer.stop()
def name(self):
'''
Child class implements this function
'''
return 'UnknownSampler'
def sample(self):
'''
Child class implements this function
'''
return {}
def _send_event(self, widget_id, body):
body['id'] = widget_id
body['updateAt'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S +0000')
formatted_json = 'data: %s\n\n' % (json.dumps(body))
self._app.last_events[widget_id] = formatted_json
for event_queue in self._app.events_queue.values():
event_queue.put(formatted_json)
def _sample(self):
data = self.sample()
if data:
self._send_event(self.name(), data)
示例3: __init__
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import stop [as 別名]
class MultiTouchInput:
current_state = 0
current_state_counter = [0]*12
touch_timer = None
def __init__(self, ipcon, key_queue):
if not config.UID_MULTI_TOUCH_BRICKLET:
print("Not Configured: Multi Touch")
return
self.key_queue = key_queue
self.ipcon = ipcon
self.mt = MultiTouch(config.UID_MULTI_TOUCH_BRICKLET, self.ipcon)
try:
self.mt.get_electrode_sensitivity()
print("Found: Multi Touch ({0})").format(config.UID_MULTI_TOUCH_BRICKLET)
except:
print("Not Found: Multi Touch ({0})").format(config.UID_MULTI_TOUCH_BRICKLET)
return
self.mt.set_electrode_sensitivity(100)
self.mt.register_callback(self.mt.CALLBACK_TOUCH_STATE, self.cb_touch_state)
self.touch_timer = RepeatedTimer(0.1, self.touch_tick)
def stop(self):
if self.touch_timer is not None:
self.touch_timer.stop()
def state_to_queue(self, state):
for item in config.KEYMAP_MULTI_TOUCH.items():
if state & (1 << item[0]):
self.key_queue.put(item[1])
def touch_tick(self):
state = 0
for i in range(12):
if self.current_state & (1 << i):
self.current_state_counter[i] += 1
else:
self.current_state_counter[i] = 0
if self.current_state_counter[i] > 5:
state |= (1 << i)
if state != 0:
self.state_to_queue(state)
def cb_touch_state(self, state):
changed_state = self.current_state ^ state
self.current_state = state
self.state_to_queue(changed_state & self.current_state)
示例4: updateNPMDependencies
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import stop [as 別名]
def updateNPMDependencies():
npm = NPM()
try :
npm.getCurrentNPMVersion(True)
except Exception as e:
print("Error: "+traceback.format_exc())
return
animation_loader = AnimationLoader(["[= ]", "[ = ]", "[ = ]", "[ = ]", "[ =]", "[ = ]", "[ = ]", "[ = ]"], 0.067, "Updating npm dependencies ")
interval_animation = RepeatedTimer(animation_loader.sec, animation_loader.animate)
try :
npm.update_all(False)
except Exception as e:
pass
animation_loader.on_complete()
interval_animation.stop()
示例5: updateNPMDependencies
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import stop [as 別名]
def updateNPMDependencies():
npm = NPM()
try :
npm.getCurrentNPMVersion(True)
except Exception as e:
if node_variables.NODE_JS_OS == "win" :
sublime.active_window().status_message("Can't use \"npm\"! To use features that requires \"npm\", you must install it! Download it from https://nodejs.org site")
print("Error: "+traceback.format_exc())
return
animation_loader = AnimationLoader(["[= ]", "[ = ]", "[ = ]", "[ = ]", "[ =]", "[ = ]", "[ = ]", "[ = ]"], 0.067, "Updating npm dependencies ")
interval_animation = RepeatedTimer(animation_loader.sec, animation_loader.animate)
try :
npm.update_all(False)
except Exception as e:
pass
animation_loader.on_complete()
interval_animation.stop()
示例6: BettingDisplay
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import stop [as 別名]
class BettingDisplay():
def __init__(self, parent, meeting):
self.parent = parent
self.display_type = 'odds'
self.date = datetime.date.today().strftime("%Y-%m-%d") #Currently will need to be restarted each day
self.meeting = meeting #PLACEHOLDER
self.schedule = Schedule(self.date, self.meeting)
self.races = self.schedule.meetings[0].races
self.next_race = None
self.set_next_race()
self.odds_var = StringVar()
self.title_var = StringVar()
self.dets_var = StringVar()
self.build_display()
self.start_timer()
print("STARTED SUCCESSFULLY")
def set_next_race(self):
next_race = None
found = False
for race in self.races:
cur_time = int(datetime.datetime.now().strftime("%H%M%S"))
race_time = int(re.sub('[:]', '', race.time))
if race_time > cur_time and not found:
next_race = race
found = True
if next_race is not self.next_race:
self.next_race = next_race
def start_timer(self):
self.threading_timer = RepeatedTimer(3, self.refresh)
self.threading_timer.start()
def refresh(self):
if self.display_type == 'odds':
self.set_next_race()
self.next_race.load_odds()
#---TEMP---#
horse_nums = ['']*20
for i in range(min(20, len(self.next_race.entries))):
horse_nums[i] = str(self.next_race.entries[i].number)
horse_names = ['']*20
for i in range(min(20, len(self.next_race.entries))):
horse_names[i] = str(self.next_race.entries[i].name)
win_odds = ['']*20
for i in range(min(20, len(self.next_race.entries))):
win_odds[i] = str(self.next_race.entries[i].odds_win)
lst = horse_nums + horse_names + win_odds
odds_str = TEST_TEMPLATE.format(lst)
title_str = TITLE_TEMPLATE.format(name=self.next_race.name)
dets_str = TIME_TEMPLATE.format(time=self.next_race.time, venue=self.next_race.meeting.venue, meet_no=self.next_race.meeting.number, country=self.next_race.meeting.country)
self.title_var.set(title_str)
self.dets_var.set(dets_str)
self.odds_var.set(odds_str)
#---TEMP END---#
elif self.display_type == 'test':
self.title_var.set('test')
self.dets_var.set('')
self.odds_var.set('')
def build_display(self):
#----TEMP----
self.cur_race_name = StringVar()
self.cur_race_time = StringVar()
self.title_text = Label(self.parent, fg="white", bg="black", font=("Courier", 40, "bold"), textvariable=self.title_var)
self.title_text.place(relx = 0.5, rely = 0, anchor=N, height = 80, width=1100)
self.dets_text = Label(self.parent, textvariable=self.dets_var, fg="white", bg="black", font=("Courier", 20, "bold"))
self.dets_text.place(relx = 0.5, y = 80, anchor=N, height = 30, width=1100)
self.odds_text = Label(self.parent, textvariable=self.odds_var, fg="white", bg="black", font=("Courier", 20, "bold"))
self.odds_text.place(relx = 0.5, y = 110, anchor=N, width=1100, height = 600)
self.quitbutton = Button(self.parent, text='quit', command=self.quitclick)
self.quitbutton.place(relx = 0.5, rely = 1, anchor=S)
#---TEMP END ---#
def quitclick(self):
self.threading_timer.stop()
self.parent.destroy()
示例7: DownloadNodeJS
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import stop [as 別名]
class DownloadNodeJS(object):
def __init__(self, node_version):
self.NODE_JS_VERSION = node_version
self.NODE_JS_TAR_EXTENSION = ".zip" if node_variables.NODE_JS_OS == "win" else ".tar.gz"
self.NODE_JS_BINARY_URL = "https://nodejs.org/dist/"+self.NODE_JS_VERSION+"/node-"+self.NODE_JS_VERSION+"-"+node_variables.NODE_JS_OS+"-"+node_variables.NODE_JS_ARCHITECTURE+self.NODE_JS_TAR_EXTENSION
self.NODE_JS_BINARY_TARFILE_NAME = self.NODE_JS_BINARY_URL.split('/')[-1]
self.NODE_JS_BINARY_TARFILE_FULL_PATH = os.path.join(node_variables.NODE_JS_BINARIES_FOLDER_PLATFORM, self.NODE_JS_BINARY_TARFILE_NAME)
self.animation_loader = AnimationLoader(["[= ]", "[ = ]", "[ = ]", "[ = ]", "[ =]", "[ = ]", "[ = ]", "[ = ]"], 0.067, "Downloading: "+self.NODE_JS_BINARY_URL+" ")
self.interval_animation = None
self.thread = None
def download(self):
try :
if os.path.exists(node_variables.NODE_JS_BINARIES_FOLDER_PLATFORM):
self.rmtree(node_variables.NODE_JS_BINARIES_FOLDER_PLATFORM)
os.makedirs(node_variables.NODE_JS_BINARIES_FOLDER_PLATFORM)
else :
os.makedirs(node_variables.NODE_JS_BINARIES_FOLDER_PLATFORM)
if os.path.exists(node_variables.NODE_MODULES_PATH):
self.rmtree(node_variables.NODE_MODULES_PATH)
request = urllib.request.Request(self.NODE_JS_BINARY_URL)
request.add_header('User-agent', r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1')
with urllib.request.urlopen(request) as response :
with open(self.NODE_JS_BINARY_TARFILE_FULL_PATH, 'wb') as out_file :
shutil.copyfileobj(response, out_file)
except Exception as err :
traceback.print_exc()
self.on_error(err)
return
self.extract()
self.on_complete()
def start(self):
self.thread = create_and_start_thread(self.download, "DownloadNodeJS")
if self.animation_loader :
self.interval_animation = RepeatedTimer(self.animation_loader.sec, self.animation_loader.animate)
def extract(self):
sep = os.sep
if self.NODE_JS_TAR_EXTENSION != ".zip" :
with tarfile.open(self.NODE_JS_BINARY_TARFILE_FULL_PATH, "r:gz") as tar :
for member in tar.getmembers() :
member.name = sep.join(member.name.split(sep)[1:])
tar.extract(member, node_variables.NODE_JS_BINARIES_FOLDER_PLATFORM)
else :
if node_variables.NODE_JS_OS == "win" :
import string
from ctypes import windll, c_int, c_wchar_p
UNUSUED_DRIVE_LETTER = ""
for letter in string.ascii_uppercase:
if not os.path.exists(letter+":") :
UNUSUED_DRIVE_LETTER = letter+":"
break
if not UNUSUED_DRIVE_LETTER :
sublime.message_dialog("Can't install node.js and npm! UNUSUED_DRIVE_LETTER not found.")
return
DefineDosDevice = windll.kernel32.DefineDosDeviceW
DefineDosDevice.argtypes = [ c_int, c_wchar_p, c_wchar_p ]
DefineDosDevice(0, UNUSUED_DRIVE_LETTER, node_variables.NODE_JS_BINARIES_FOLDER_PLATFORM)
try:
with zipfile.ZipFile(self.NODE_JS_BINARY_TARFILE_FULL_PATH, "r") as zip_file :
for member in zip_file.namelist() :
if not member.endswith("/") :
with zip_file.open(member) as node_file:
with open(UNUSUED_DRIVE_LETTER + "\\"+ member.replace("node-"+self.NODE_JS_VERSION+"-"+node_variables.NODE_JS_OS+"-"+node_variables.NODE_JS_ARCHITECTURE+"/", ""), "wb+") as target :
shutil.copyfileobj(node_file, target)
elif not member.endswith("node-"+self.NODE_JS_VERSION+"-"+node_variables.NODE_JS_OS+"-"+node_variables.NODE_JS_ARCHITECTURE+"/"):
os.mkdir(UNUSUED_DRIVE_LETTER + "\\"+ member.replace("node-"+self.NODE_JS_VERSION+"-"+node_variables.NODE_JS_OS+"-"+node_variables.NODE_JS_ARCHITECTURE+"/", ""))
except Exception as e:
print("Error: "+traceback.format_exc())
finally:
DefineDosDevice(2, UNUSUED_DRIVE_LETTER, node_variables.NODE_JS_BINARIES_FOLDER_PLATFORM)
def rmtree(self, path) :
if node_variables.NODE_JS_OS == "win" :
import string
from ctypes import windll, c_int, c_wchar_p
UNUSUED_DRIVE_LETTER = ""
for letter in string.ascii_uppercase:
if not os.path.exists(letter+":") :
UNUSUED_DRIVE_LETTER = letter+":"
break
if not UNUSUED_DRIVE_LETTER :
sublime.message_dialog("Can't remove node.js! UNUSUED_DRIVE_LETTER not found.")
return
DefineDosDevice = windll.kernel32.DefineDosDeviceW
DefineDosDevice.argtypes = [ c_int, c_wchar_p, c_wchar_p ]
DefineDosDevice(0, UNUSUED_DRIVE_LETTER, path)
try:
shutil.rmtree(UNUSUED_DRIVE_LETTER)
except Exception as e:
print("Error: "+traceback.format_exc())
finally:
DefineDosDevice(2, UNUSUED_DRIVE_LETTER, path)
else :
shutil.rmtree(path)
def on_error(self, err):
self.animation_loader.on_complete()
self.interval_animation.stop()
sublime.active_window().status_message("Can't install Node.js! Check your internet connection!")
def on_complete(self):
#.........這裏部分代碼省略.........
示例8: OpenSlides
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import stop [as 別名]
#.........這裏部分代碼省略.........
self.lbl_host = ttk.Label(lf, text=_("Host: {0}").format(self.host))
self.lbl_host.grid(row=0, column=0, sticky='W')
self.lbl_port = ttk.Label(lf, text=_("Port: {0}").format(self.port))
self.lbl_port.grid(row=0, column=1, sticky='W')
self.btn_settings = ttk.Button(lf, text="Settings", command=self.settings_dialog)
self.btn_settings.grid(row=0, column=4)
self.auto_start_svr = tk.BooleanVar()
self.auto_start_svr.set(True)
self.chb_auto_svr = ttk.Checkbutton(lf, text='Automatically open browser', variable=self.auto_start_svr, onvalue=True, offvalue=False)
self.chb_auto_svr.grid(row=1)
self.btn_server = ttk.Button(lf, text="Start Server", command=self.on_start_server)
self.btn_server.grid(row=2, columnspan=5, sticky='NSEW')
text_frame = ttk.Frame(self.root)
text_frame.grid(row=1, columnspan=2)
lft = ttk.LabelFrame(text_frame, text='Server Logs')
lft.pack()
xscrollbar = ttk.Scrollbar(lft, orient=tk.HORIZONTAL)
xscrollbar.grid(row=1, column=0, sticky=tk.N+tk.S+tk.E+tk.W)
yscrollbar = ttk.Scrollbar(lft)
yscrollbar.grid(row=0, column=1, sticky=tk.N+tk.S+tk.E+tk.W)
text = TextControl(lft, wrap=tk.NONE, state='disabled', xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set)
text.grid(row=0, column=0)
xscrollbar.config(command=text.xview)
yscrollbar.config(command=text.yview)
self.root.bind("<<EVT_CMD_START>>", self.on_cmd_start)
self.root.bind("<<EVT_CMD_STOP>>", self.on_cmd_stop)
self.cmd_runner = CommandRunner(text.append_message, self.root)
@property
def host(self):
return self._host
@host.setter
def host(self, host):
self._host = host
self.lbl_host.config(text=_("Host: {0}").format(host))
@property
def port(self):
return self._port
@port.setter
def port(self, port):
self._port = port
self.lbl_port.config(text=_("Port: {0}").format(port))
@property
def backup_interval_seconds(self):
factor = 0
if self.backupdb_interval_unit == "seconds":
factor = 1
elif self.backupdb_interval_unit == "minutes":
factor = 60
elif self.backupdb_interval_unit == "hours":
factor = 3600
return self.backupdb_interval * factor
示例9: msg_callback
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import stop [as 別名]
class Master:
def msg_callback(self, ch, method, properties, body):
callback_set = {'SUCCESS': self.success,
'FAIL': self.fail,
'AWAKE': self.update_slave_response_time,
'STOP': self.stop,
'ADD_SLAVE': self.add_slave,
'KILL_SLAVE': self.kill_slave,
'RESTART_SLAVE': self.restart_slave,
'STAT': self.stat,
'START': self.start,
'RECONFIGURE': self.configure,
'REFRESH': self.refresh
}
try:
command = body[:body.find(' ')]
info = body[body.find(' ')+1:]
if command in callback_set:
callback_set[command](ujson.loads(info))
else:
logging.debug(" [x] Unknown command %r" % (str(body),))
except KeyError as e:
if str(e) == "'Queue.DeclareOk'":
logging.debug("Queue.DelcareOk at %r" % (str(body),))
else:
logging.error("Unknown KeyError at %r:" % (str(body),))
except RuntimeError as e:
if 'recursion' in str(e):
logging.error('MAXIMUM RECURSION ERROR')
def __init__(self, conf_file):
self.config = ConfigParser.ConfigParser(allow_no_value=True)
self.clean_time_gap = None
self.wait_time_for_slave = None
self.master_queue_name = None
self.task_queue_name = None
self.task_queue_size_limit = None
self.task_file_name = None
self.task_counter_file = None
self.ssh_key = None
self.s3_bucket = None
self.s3_folder = None
self.slave_num_every_packup = None
self.slave_max_sec_each_task = None
self.slave_python_version = None
self.master_ip = None
self.slaves_ip = None
self.slave_awake_frequency = None
self.configure(conf_file)
self.last_wake_time = None
self.repeated_timer = None
self.is_started = False
self.pop_forever_handler = None
logging.info('Starting task manager...')
self.task_manager = TaskManager(self.task_file_name, self.task_counter_file)
logging.info('Starting slave manager...')
self.slave_manager = SlaveManager(master_ip=self.master_ip,
slaves_ip=self.slaves_ip,
ssh_key=self.ssh_key,
s3_bucket=self.s3_bucket,
s3_folder=self.s3_folder,
slave_num_every_packup=self.slave_num_every_packup,
slave_max_sec_each_task=self.slave_max_sec_each_task,
slave_python_version=self.slave_python_version,
slave_awake_frequency=self.slave_awake_frequency,
slave_buffer_size=1)
logging.info('Starting connection manager...')
self.message_connection = ConnectionManager(queue_name=self.master_queue_name,
durable=False,
callback=self.msg_callback,
no_ack=True)
def run(self):
logging.info(' [*] Waiting for messages. To exit press CTRL+C')
try:
self.message_connection.start_accepting_message()
except KeyboardInterrupt:
logging.info('Stopping master...')
master.stop(None)
except EOFError:
logging.info('Download finishes. Shutting down master.')
master.stop(None)
# except Exception as e:
# logging.info(str(e))
# logging.info('Stopping master...')
# TODO: write all configuration in one file
def configure(self, conf_file):
self.config.read(conf_file)
self.clean_time_gap = self.config.getint('main', 'clean_time_gap')
self.wait_time_for_slave = self.config.getint('main', 'wait_time_for_slave')
self.slave_awake_frequency = self.config.get('main', 'slave_awake_frequency')
self.master_ip = self.config.get('main', 'master_private_ip')
self.slaves_ip = self.config.get('main', 'slaves_private_ip')
self.master_queue_name = self.config.get('main', 'master_queue_name')
self.task_queue_name = self.config.get('main', 'task_queue_name')
#.........這裏部分代碼省略.........
示例10: main
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import stop [as 別名]
def main():
global _motion_timer
_motion_timer = RepeatedTimer(_motion_timer_period, _handle_motion_timer)
_motion_timer.start()
global _odom_timer
_odom_timer = RepeatedTimer(_odom_timer_period, _handle_odom_timer)
_odom_timer.start()
global _ctrl_timer
_ctrl_timer = RepeatedTimer(_ctrl_timer_period, _handle_ctrl_timer)
_ctrl_timer.start()
use_rcv3 = os.environ['USE_RCV3'] == 'true'
w.init(use_rcv3=use_rcv3)
# TODO: Okay, so Controller.init(None) will automagically load in some PID
# values for each of the x, y, theta position controllers. However, since
# `teleop` is run in real life on different robots, really it should read
# the correct YAML robot config file and load in the PID constants and
# pass them into Controller.init(gains) as in the controller_node.py.
# Two ways to do this: (1) do like os.environ['USE_RCV3'], where the odroid_setup.bash
# script loads up the PID constants as environment variables (this seems messy).
# (2) find a python YAML reading library and just read the file directly from here
# based on which robot this is (you can use os.environ['ROBOT'])
Controller.init()
print 'Started.'
global _velocities, _set_speed, _smooth, _odom_on, _previous_action, _ctrl_on
while(1):
action = get_action()
if action == 'UP':
_set_speed = True
_velocities = (0, _vy, 0)
elif action == 'DOWN':
_set_speed = True
_velocities = (0, -_vy, 0)
elif action == 'RIGHT':
_set_speed = True
_velocities = (_vx, 0, 0)
elif action == 'LEFT':
_set_speed = True
_velocities = (-_vx, 0, 0)
elif action == 'SPIN_CW':
_set_speed = True
_velocities = (0, 0, _w)
elif action == 'SPIN_CCW':
_set_speed = True
_velocities = (0, 0, -_w)
elif action == 'SET_HOME':
Odometry.init()
elif action == 'GO_HOME':
_motion_timer.stop()
motion.stop()
time.sleep(1)
_go_home()
time.sleep(1)
_set_speed = True
_velocities = (0, 0, 0)
_motion_timer.start()
elif action == 'GO_TO_POINT':
_toggle_timers(False)
motion.stop()
time.sleep(1)
_ask_for_point()
time.sleep(1)
_ctrl_on = True
_odom_on = True
_toggle_timers(True)
elif action == 'TOGGLE_CNTRL':
_ctrl_on = not _ctrl_on
print("Controller: {}".format(_ctrl_on))
elif action == 'TOGGLE_SMOOTH':
_smooth = not _smooth
print("Smooth: {}".format(_smooth))
elif action == 'TOGGLE_ODOM':
_odom_on = not _odom_on
print("Odom: {}".format(_odom_on))
elif action == 'BATTERY':
print("\n\r*** Battery: {} ***\n\r".format(get_battery()))
#.........這裏部分代碼省略.........
示例11: len
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import stop [as 別名]
#.........這裏部分代碼省略.........
b.append(self.COLORS[field[row][col]][2])
frame.append(self.COLORS[field[row][col]][0])
frame.append(self.COLORS[field[row][col]][1])
frame.append(self.COLORS[field[row][col]][2])
if not config.IS_LED_STRIP_V2:
# Make chunks of size 16
r_chunk = [r[i:i+16] for i in range(0, len(r), 16)]
g_chunk = [g[i:i+16] for i in range(0, len(g), 16)]
b_chunk = [b[i:i+16] for i in range(0, len(b), 16)]
for i in range(len(r_chunk)):
length = len(r_chunk[i])
# Fill up chunks with zeros
r_chunk[i].extend([0]*(16-len(r_chunk[i])))
g_chunk[i].extend([0]*(16-len(g_chunk[i])))
b_chunk[i].extend([0]*(16-len(b_chunk[i])))
try:
self.led_strip.set_rgb_values(i*16, length, r_chunk[i], g_chunk[i], b_chunk[i])
except:
break
else:
try:
self.led_strip.set_led_values(0, frame)
except:
return
def clear_lines(self, rows_to_clear):
if not self.okay:
return
self.drop_timer.stop()
rows_save = {}
for to_clear in rows_to_clear:
rows_save[to_clear] = self.playfield[to_clear]
self.display.increase_line_count(len(rows_to_clear))
self.speaker.beep_delete_line(len(rows_to_clear))
for i in range(6):
if i % 2 == 0:
for to_clear in rows_to_clear:
self.playfield[to_clear] = [255] + [0]*(self.FIELD_COLS-2) + [255]
else:
for to_clear in rows_to_clear:
self.playfield[to_clear] = rows_save[to_clear]
time.sleep(0.1)
for to_clear in rows_to_clear:
for row in reversed(range(1, to_clear+1)):
self.playfield[row] = self.playfield[row-1]
self.playfield[1] = [255] + [0]*(self.FIELD_COLS-2) + [255]
self.drop_timer.start()
def check_for_lines_to_clear(self):
rows_to_clear = []
for row_index, col in enumerate(self.playfield[1:-1]):
to_clear = True
示例12: __init__
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import stop [as 別名]
#.........這裏部分代碼省略.........
# if ix - 1 > 0:
# field[ix-1][iy] = PONG_COLOR_INDEX_BALL_LEFT
# if iy + 1 < config.LED_COLS:
# field[ix][iy+1] = PONG_COLOR_INDEX_BALL_TOP
# if iy - 1 > 0:
# field[ix][iy-1] = PONG_COLOR_INDEX_BALL_BOTTOM
#
# dx = x - int(x)
# dy = x - int(x)
# self.COLORS[PONG_COLOR_INDEX_BALL_RIGHT] = (0, 255*dx/64, 0)
# self.COLORS[PONG_COLOR_INDEX_BALL_LEFT] = (0, 255*(1-dx)/64, 0)
# self.COLORS[PONG_COLOR_INDEX_BALL_TOP] = (0, 255*dy/64, 0)
# self.COLORS[PONG_COLOR_INDEX_BALL_BOTTOM] = (0, 255*(1-dy)/64, 0)
def add_paddles_to_playfield(self, field):
for player in range(2):
for i in range(self.PADDLE_SIZE):
field[self.paddle_position_x[player]][self.paddle_position_y[player]+i] = config.PONG_COLOR_INDEX_PLAYER[player]
def move_paddle(self, player, change):
new_pos = self.paddle_position_y[player] + change
if new_pos >= 0 and new_pos <= config.LED_COLS - self.PADDLE_SIZE:
self.paddle_position_y[player] = new_pos
def new_ball(self):
self.ball_position = [(config.LED_ROWS - 1.0) / 2.0, (config.LED_COLS - 1.0) / 2.0]
self.ball_direction = [random.choice([-0.2, 0.2]), random.choice([random.randrange(1, 9)/10.0, random.randrange(-9, -1)/10.0])]
def tick(self):
# Move ball
for i in range(2):
self.ball_position[i] += self.ball_direction[i]
# Wall collision top/bottom
if self.ball_position[1] < 0 or self.ball_position[1] >= config.LED_COLS:
self.ball_direction[1] = -self.ball_direction[1]
# Wall collision left/right
def hit_left_right(player):
self.speaker.beep_sirene()
self.new_ball()
self.score[player] += 1
if self.score[player] > 9:
self.score[player] = 0
if self.ball_position[0] < 0:
hit_left_right(1)
if self.ball_position[0] >= config.LED_ROWS:
hit_left_right(0)
# Paddle collision
def hit_paddle(skew):
self.speaker.beep_paddle_hit()
self.ball_direction[0] = -self.ball_direction[0]
self.ball_direction[1] -= skew
for i in range(2):
self.ball_direction[i] *= 1.1 # Increase speed
if self.ball_direction[0] < 0:
if self.paddle_position_x[0] + 0.5 <= self.ball_position[0] <= self.paddle_position_x[0] + 1.5:
if self.paddle_position_y[0] - 0.5 <= self.ball_position[1] <= self.paddle_position_y[0] + self.PADDLE_SIZE + 0.5:
paddle_skew = (self.paddle_position_y[0] + self.PADDLE_SIZE/2.0 - self.ball_position[1])/10.0
hit_paddle(paddle_skew)
if self.ball_direction[0] > 0:
if self.paddle_position_x[1] - 0.5 <= self.ball_position[0] <= self.paddle_position_x[1] + 0.5:
if self.paddle_position_y[1] - 0.5 <= self.ball_position[1] <= self.paddle_position_y[1] + self.PADDLE_SIZE + 0.5:
paddle_skew = (self.paddle_position_y[1] + self.PADDLE_SIZE/2.0 - self.ball_position[1])/10.0
hit_paddle(paddle_skew)
def run_game_loop(self):
self.frame_rendered(0)
self.timer = RepeatedTimer(0.1, self.tick)
while self.loop:
key = self.kp.read_single_keypress().lower()
if key == 'a':
self.move_paddle(0, -1)
elif key == 's':
self.move_paddle(0, 1)
elif key == 'k':
self.move_paddle(1, -1)
elif key == 'l':
self.move_paddle(1, 1)
elif key == 'r':
self.init_game()
elif not config.HAS_GUI and key == 'q':
break
if not config.IS_LED_STRIP_V2:
self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_RENDERED, None)
else:
self.led_strip.register_callback(self.led_strip.CALLBACK_FRAME_STARTED, None)
self.timer.stop()
self.kp.stop()
示例13: DownloadNodeJS
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import stop [as 別名]
class DownloadNodeJS(object):
def __init__(self, node_version):
self.NODE_JS_VERSION = node_version
self.NODE_JS_TAR_EXTENSION = ".zip" if node_variables.NODE_JS_OS == "win" else ".tar.gz"
self.NODE_JS_BINARY_URL = "https://nodejs.org/dist/"+self.NODE_JS_VERSION+"/node-"+self.NODE_JS_VERSION+"-"+node_variables.NODE_JS_OS+"-"+node_variables.NODE_JS_ARCHITECTURE+self.NODE_JS_TAR_EXTENSION
self.NODE_JS_BINARY_TARFILE_NAME = self.NODE_JS_BINARY_URL.split('/')[-1]
self.NODE_JS_BINARY_TARFILE_FULL_PATH = os.path.join(node_variables.NODE_JS_BINARIES_FOLDER_PLATFORM, self.NODE_JS_BINARY_TARFILE_NAME)
self.animation_loader = AnimationLoader(["[= ]", "[ = ]", "[ = ]", "[ = ]", "[ =]", "[ = ]", "[ = ]", "[ = ]"], 0.067, "Downloading: "+self.NODE_JS_BINARY_URL+" ")
self.interval_animation = None
self.thread = None
def download(self):
try :
if os.path.exists(node_variables.NODE_JS_BINARIES_FOLDER_PLATFORM):
shutil.rmtree(node_variables.NODE_JS_BINARIES_FOLDER_PLATFORM)
os.makedirs(node_variables.NODE_JS_BINARIES_FOLDER_PLATFORM)
else :
os.makedirs(node_variables.NODE_JS_BINARIES_FOLDER_PLATFORM)
if os.path.exists(node_variables.NODE_MODULES_PATH):
shutil.rmtree(node_variables.NODE_MODULES_PATH)
request = urllib.request.Request(self.NODE_JS_BINARY_URL)
request.add_header('User-agent', r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1')
with urllib.request.urlopen(request) as response :
with open(self.NODE_JS_BINARY_TARFILE_FULL_PATH, 'wb') as out_file :
shutil.copyfileobj(response, out_file)
except Exception as err :
traceback.print_exc()
self.on_error(err)
return
self.extract()
self.on_complete()
def start(self):
self.thread = create_and_start_thread(self.download, "DownloadNodeJS")
if self.animation_loader :
self.interval_animation = RepeatedTimer(self.animation_loader.sec, self.animation_loader.animate)
def extract(self):
sep = os.sep
if self.NODE_JS_TAR_EXTENSION != ".zip" :
with tarfile.open(self.NODE_JS_BINARY_TARFILE_FULL_PATH, "r:gz") as tar :
for member in tar.getmembers() :
member.name = sep.join(member.name.split(sep)[1:])
tar.extract(member, node_variables.NODE_JS_BINARIES_FOLDER_PLATFORM)
else :
with zipfile.ZipFile(self.NODE_JS_BINARY_TARFILE_FULL_PATH, "r") as zip_file :
for member in zip_file.namelist() :
if member.endswith("/node.exe") :
with zip_file.open(member) as node_file:
with open(os.path.join(node_variables.NODE_JS_BINARIES_FOLDER_PLATFORM, "node.exe"), "wb") as target :
shutil.copyfileobj(node_file, target)
break
def on_error(self, err):
self.animation_loader.on_complete()
self.interval_animation.stop()
sublime.active_window().status_message("Can't install Node.js! Check your internet connection!")
def on_complete(self):
self.animation_loader.on_complete()
self.interval_animation.stop()
if os.path.isfile(self.NODE_JS_BINARY_TARFILE_FULL_PATH) :
os.remove(self.NODE_JS_BINARY_TARFILE_FULL_PATH)
node_js = NodeJS()
npm = NPM()
self.animation_loader = AnimationLoader(["[= ]", "[ = ]", "[ = ]", "[ = ]", "[ =]", "[ = ]", "[ = ]", "[ = ]"], 0.067, "Installing npm dependencies ")
self.interval_animation = RepeatedTimer(self.animation_loader.sec, self.animation_loader.animate)
try :
npm.getCurrentNPMVersion(True)
except Exception as e:
if node_variables.NODE_JS_OS == "win" :
sublime.error_message("Can't use \"npm\"! To use features that requires \"npm\", you must install it! Download it from https://nodejs.org site")
print("Error: "+traceback.format_exc())
try :
npm.install_all()
except Exception as e :
#print("Error: "+traceback.format_exc())
pass
self.animation_loader.on_complete()
self.interval_animation.stop()
if node_js.getCurrentNodeJSVersion(True) == self.NODE_JS_VERSION :
sublime.active_window().status_message("Node.js "+self.NODE_JS_VERSION+" installed correctly! NPM version: "+npm.getCurrentNPMVersion(True))
else :
sublime.active_window().status_message("Can't install Node.js! Something went wrong during installation.")
示例14: __init__
# 需要導入模塊: from repeated_timer import RepeatedTimer [as 別名]
# 或者: from repeated_timer.RepeatedTimer import stop [as 別名]
class CommandRunner:
UPDATE_INTERVAL = 5
def __init__(self, msg_func, master):
self.msg_func = msg_func
self.master = master
self.child_process = None
self.output_queue = queue.Queue()
self.output_read_thread = None
self.output_mutex = threading.RLock()
self.update_timer = RepeatedTimer(self.on_update_timer)
self._exitcode = None
def _read_output(self):
while True:
# NOTE: don't use iterator interface since it uses an
# internal buffer and we don't see output in a timely fashion
line = self.child_process.stdout.readline()
if not line:
break
self.output_queue.put(line)
def is_alive(self):
if self.child_process is None:
return False
return self.child_process.poll() is None
def run_command(self, *args):
if self.is_alive():
raise ValueError("already running a command")
cmd = [sys.executable, "-u", "-m", "openslides"]
cmd.extend(args)
creationflags = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
self._exitcode = None
self.child_process = subprocess.Popen(
cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, creationflags=creationflags)
self.child_process.stdin.close()
self.output_read_thread = threading.Thread(target=self._read_output)
self.output_read_thread.start()
self.update_timer.run(self.UPDATE_INTERVAL)
self.master.event_generate("<<EVT_CMD_START>>", when="tail")
def cancel_command(self):
if not self.is_alive():
return
self.msg_func("Stopping server...\n")
# hard-kill the spawned process tree
# TODO: offer the server the chance for a clean shutdown
proc = psutil.Process(self.child_process.pid)
kill_procs = [proc]
kill_procs.extend(proc.children(recursive=True))
for p in kill_procs:
p.kill()
def on_update_timer(self):
is_alive = self.is_alive()
if not is_alive:
# join thread to make sure everything was read
self.output_read_thread.join(5)
if self.output_read_thread.is_alive():
self.msg_func("Internal error: failed to join output reader thread")
self.output_read_thread = None
for line_no in itertools.count():
try:
data = self.output_queue.get(block=False)
except queue.Empty:
break
else:
# XXX: check whether django uses utf-8 or locale for
# it's cli output
text = data.decode("utf-8", errors="replace")
with self.output_mutex:
self.msg_func(text)
# avoid waiting too long here if child is still alive
if is_alive and line_no > 10:
break
if not is_alive:
self._exitcode = self.child_process.returncode
self.update_timer.stop()
self.child_process = None
self.master.event_generate("<<EVT_CMD_STOP>>", when="tail")
def append_message(self, text, newline="\n"):
with self.output_mutex:
self.msg_func(text + newline)
@property
def exitcode(self):
#.........這裏部分代碼省略.........