def lambda_handler(event, context): stop_event = Event() def delay_actions(): """ Function that implements timeout """ while True: # ##### New York State ###### # # execute_scrape_counties_wikipedia() # scraped_county_table # Scraiping blocked from wikipedia # # time.sleep(10) # ################################################# # # execute_combine_counties_scraped_and_historical() # combined_county_table # # time.sleep(5) # execute_wrangle_nyc_percentage_daily_change() # nyc_percentage_daily_change_table # time.sleep(1) # execute_wrangle_counties_new_daily_cases() # counties_new_daily_cases_table # time.sleep(1) # execute_wrangle_counties_timeslider() # counties_timeslider_table ##### NYC ###### CONFIRMED # store_historical_nyc() #ONLY FOR RESET and pulling from historical # time.sleep(5) # execute_combine_nyc_scraped_and_historical() # time.sleep(1) # #### NYC ###### FOR PIE CHARTS # execute_update_age_nyc() # execute_update_sex_nyc() # time.sleep(1) # # ##### NYC ###### ZIPCODES # execute_update_zipcode_nyc() # time.sleep(15) # # ##### WORLD ##### execute_update_world() #works when everything commented out if stop_event.is_set(): break action_thread = Thread(target=delay_actions) action_thread.start() action_thread.join(timeout=5) stop_event.set() return 'Lambda function has been executed'
def __init__(self, file_location='/tmp/mycroft_in.wav', emitter=None): super(FileConsumer, self).__init__() self.path = file_location self.stop_event = Event() self.stt = None self.emitter = emitter
def __init__( self, bot: 'Bot', update_queue: Queue, workers: int = 4, exception_event: Event = None, job_queue: 'JobQueue' = None, persistence: BasePersistence = None, use_context: bool = True, context_types: ContextTypes[CCT, UD, CD, BD] = None, ): self.bot = bot self.update_queue = update_queue self.job_queue = job_queue self.workers = workers self.use_context = use_context self.context_types = cast(ContextTypes[CCT, UD, CD, BD], context_types or ContextTypes()) if not use_context: warnings.warn( 'Old Handler API is deprecated - see https://git.io/fxJuV for details', TelegramDeprecationWarning, stacklevel=3, ) if self.workers < 1: warnings.warn( 'Asynchronous callbacks can not be processed without at least one worker thread.' ) self.user_data: DefaultDict[int, UD] = defaultdict( self.context_types.user_data) self.chat_data: DefaultDict[int, CD] = defaultdict( self.context_types.chat_data) self.bot_data = self.context_types.bot_data() self.persistence: Optional[BasePersistence] = None self._update_persistence_lock = Lock() if persistence: if not isinstance(persistence, BasePersistence): raise TypeError( "persistence must be based on telegram.ext.BasePersistence" ) self.persistence = persistence self.persistence.set_bot(self.bot) if self.persistence.store_user_data: self.user_data = self.persistence.get_user_data() if not isinstance(self.user_data, defaultdict): raise ValueError("user_data must be of type defaultdict") if self.persistence.store_chat_data: self.chat_data = self.persistence.get_chat_data() if not isinstance(self.chat_data, defaultdict): raise ValueError("chat_data must be of type defaultdict") if self.persistence.store_bot_data: self.bot_data = self.persistence.get_bot_data() if not isinstance(self.bot_data, self.context_types.bot_data): raise ValueError( f"bot_data must be of type {self.context_types.bot_data.__name__}" ) if self.persistence.store_callback_data: self.bot = cast(telegram.ext.extbot.ExtBot, self.bot) persistent_data = self.persistence.get_callback_data() if persistent_data is not None: if not isinstance(persistent_data, tuple) and len(persistent_data) != 2: raise ValueError('callback_data must be a 2-tuple') self.bot.callback_data_cache = CallbackDataCache( self.bot, self.bot.callback_data_cache.maxsize, persistent_data=persistent_data, ) else: self.persistence = None self.handlers: Dict[int, List[Handler]] = {} """Dict[:obj:`int`, List[:class:`telegram.ext.Handler`]]: Holds the handlers per group.""" self.groups: List[int] = [] """List[:obj:`int`]: A list with all groups.""" self.error_handlers: Dict[Callable, Union[bool, DefaultValue]] = {} """Dict[:obj:`callable`, :obj:`bool`]: A dict, where the keys are error handlers and the values indicate whether they are to be run asynchronously.""" self.running = False """:obj:`bool`: Indicates if this dispatcher is running.""" self.__stop_event = Event() self.__exception_event = exception_event or Event() self.__async_queue: Queue = Queue() self.__async_threads: Set[Thread] = set() # For backward compatibility, we allow a "singleton" mode for the dispatcher. When there's # only one instance of Dispatcher, it will be possible to use the `run_async` decorator. with self.__singleton_lock: if self.__singleton_semaphore.acquire(blocking=False): # pylint: disable=R1732 self._set_singleton(self) else: self._set_singleton(None)
def __init__(self, decoder, function): Thread.__init__(self) self.decoder = decoder self.function = function self.stopped = Event()
0, winreg.KEY_ALL_ACCESS) except WindowsError: dpi_support = winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_96DPI_PIXEL", 0, winreg.KEY_ALL_ACCESS) mode = get_ie_mode() executable_name = sys.executable.split("\\")[-1] winreg.SetValueEx(browser_emulation, executable_name, 0, winreg.REG_DWORD, mode) winreg.CloseKey(browser_emulation) winreg.SetValueEx(dpi_support, executable_name, 0, winreg.REG_DWORD, 1) winreg.CloseKey(dpi_support) _main_window_created = Event() _main_window_created.clear() def create_window(window): def create(): browser = BrowserView.BrowserForm(window) BrowserView.instances[window.uid] = browser if not window.hidden: browser.Show() _main_window_created.set() if window.uid == 'master': app.Run()
for old_modbus_file in local_modbus_peripherals: # the leftover files are devices that have not been detected anymore, # and thus should be deleted r = requests.delete(api_endpoint + "/" + old_modbus_file) if __name__ == "__main__": init_logger() wait_for_bootstrap() gateway_ip = get_default_gateway_ip() # Runs the modbus discovery functions periodically e = Event() while True: xml_file = scan_open_ports(gateway_ip) with open(xml_file) as ox: namp_xml_output = ox.read() all_modbus_devices = parse_modbus_peripherals(namp_xml_output) manage_modbus_peripherals(all_modbus_devices) e.wait(timeout=90)
from threading import Thread, Event from time import sleep s = None # 全局变量用于通信 e = Event() # 事件对象 def 杨子荣(): print("杨子荣前来拜山头") global s s = "天王盖地虎" e.set() # 共享资源操作完毕 t = Thread(target=杨子荣) t.start() print("说对口令就是自己人") e.wait() # 阻塞等待 if s == "天王盖地虎": print("宝塔镇河妖") print("确认过眼神,你是对的人") else: print("打死他...") t.join()
def __init__(self, *args, **kwargs): super(FilteredHLSStreamReader, self).__init__(*args, **kwargs) self.filter_event = Event() self.filter_event.set()
def __init__(self): self.result = None self.status = None self.done_event = Event()
from threading import Thread, Event import time # Code to execute in an independent thread def countdown(n, started_evt): print('countdown starting') started_evt.set() #设置flag为ture,等待该事件的线程将开始run while n > 0: print('T-minus', n) n -= 1 time.sleep(0.5) # Create the event object that will be used to signal startup started_evt = Event() # Launch the thread and pass the startup event print('Launching countdown') t = Thread(target=countdown, args=(10,started_evt)) t.start() # Wait for the thread to start started_evt.wait() print('countdown is running')
from threading import Event, Thread from random import random from time import sleep from .. import socketio, faw from datetime import datetime from gevent import monkey monkey.patch_all() #random number Generator Thread thread = Thread() thread_stop_event = Event() class DataUpdateThread(Thread): def __init__(self): self.delay = 100 #seconds super(DataUpdateThread, self).__init__() def dataUpdate(self): """ update the data every 10 minutes and emit to a threads instance (broadcast) Ideally to be run in a separate thread? """ #infinite loop of data updates while not thread_stop_event.isSet(): print('Data written to the server at ' + datetime.today().strftime("%Y-%m-%d %H:%M:%S")) faw.write_matches_data() sleep(30) faw.write_standings_data()
from src.red_alert.ringer import Ringer from src.red_alert.speech import Speech from threading import Event ready = Event() r = Ringer(ready) r.run() ready.wait() print("done picked_up: " + str(r.picked_up)) #s = Speech() #s.request_polly("Achtung! Der Server Frontend, in der Region EU - Frankfurt, ist nicht erreichbar") #s.speak()
def main(args=None): # noqa args = args or make_argument_parser().parse_args() for path in args.path: sys.path.insert(0, path) if args.use_spawn: multiprocessing.set_start_method("spawn") try: if args.pid_file: setup_pidfile(args.pid_file) except RuntimeError as e: with file_or_stderr(args.log_file) as stream: logger = setup_parent_logging(args, stream=stream) logger.critical(e) return RET_PIDFILE canteen = multiprocessing.Value(Canteen) worker_pipes = [] worker_processes = [] worker_process_events = [] for worker_id in range(args.processes): read_pipe, write_pipe = multiprocessing.Pipe(duplex=False) event = multiprocessing.Event() proc = multiprocessing.Process( target=worker_process, args=(args, worker_id, StreamablePipe(write_pipe), canteen, event), daemon=False, ) proc.start() worker_pipes.append(read_pipe) worker_processes.append(proc) worker_process_events.append(event) # Wait for all worker processes to come online before starting the # fork processes. This is required to avoid race conditions like # in #297. for event in worker_process_events: if proc.is_alive(): if not event.wait(timeout=30): break fork_pipes = [] fork_processes = [] for fork_id, fork_path in enumerate(chain(args.forks, canteen_get(canteen))): read_pipe, write_pipe = multiprocessing.Pipe(duplex=False) proc = multiprocessing.Process( target=fork_process, args=(args, fork_id, fork_path, StreamablePipe(write_pipe)), daemon=True, ) proc.start() fork_pipes.append(read_pipe) fork_processes.append(proc) parent_read_pipe, parent_write_pipe = multiprocessing.Pipe(duplex=False) logger = setup_parent_logging(args, stream=StreamablePipe(parent_write_pipe)) logger.info("Dramatiq %r is booting up." % __version__) if args.pid_file: atexit.register(remove_pidfile, args.pid_file, logger) running, reload_process = True, False # To avoid issues with signal delivery to user threads on # platforms such as FreeBSD 10.3, we make the main thread block # the signals it expects to handle before spawning the file # watcher and log watcher threads so that those threads can # inherit the blocking behaviour. if hasattr(signal, "pthread_sigmask"): signal.pthread_sigmask( signal.SIG_BLOCK, {signal.SIGINT, signal.SIGTERM, signal.SIGHUP}, ) if HAS_WATCHDOG and args.watch: if not hasattr(signal, "SIGHUP"): raise RuntimeError( "Watching for source changes is not supported on %s." % sys.platform) file_watcher = setup_file_watcher(args.watch, args.watch_use_polling) log_watcher_stop_event = Event() log_watcher = Thread( target=watch_logs, args=(args.log_file, [parent_read_pipe, *worker_pipes, *fork_pipes], log_watcher_stop_event), daemon=False, ) log_watcher.start() def stop_subprocesses(signum): nonlocal running running = False for proc in chain(worker_processes, fork_processes): try: os.kill(proc.pid, signum) except OSError: # pragma: no cover if proc.exitcode is None: logger.warning("Failed to send %r to PID %d.", signum.name, proc.pid) def sighandler(signum, frame): nonlocal reload_process reload_process = signum == getattr(signal, "SIGHUP", None) if signum == signal.SIGINT: signum = signal.SIGTERM logger.info("Sending signal %r to subprocesses...", getattr(signum, "name", signum)) stop_subprocesses(signum) # Now that the watcher threads have been started, it should be # safe to unblock the signals that were previously blocked. if hasattr(signal, "pthread_sigmask"): signal.pthread_sigmask( signal.SIG_UNBLOCK, {signal.SIGINT, signal.SIGTERM, signal.SIGHUP}, ) retcode = RET_OK signal.signal(signal.SIGINT, sighandler) signal.signal(signal.SIGTERM, sighandler) if hasattr(signal, "SIGHUP"): signal.signal(signal.SIGHUP, sighandler) if hasattr(signal, "SIGBREAK"): signal.signal(signal.SIGBREAK, sighandler) # Wait for all workers to terminate. If any of the processes # terminates unexpectedly, then shut down the rest as well. The # use of `waited' here avoids a race condition where the processes # could potentially exit before we even get a chance to wait on # them. waited = False while not waited or any(p.exitcode is None for p in worker_processes): waited = True for proc in worker_processes: proc.join(timeout=1) if proc.exitcode is None: continue if running: # pragma: no cover logger.critical( "Worker with PID %r exited unexpectedly (code %r). Shutting down...", proc.pid, proc.exitcode) stop_subprocesses(signal.SIGTERM) retcode = proc.exitcode break else: retcode = retcode or proc.exitcode # The log watcher can't be a daemon in case we log to a file so we # have to wait for it to complete on exit. log_watcher_stop_event.set() log_watcher.join() if HAS_WATCHDOG and args.watch: file_watcher.stop() file_watcher.join() if reload_process: if sys.argv[0].endswith("/dramatiq/__main__.py"): return os.execvp(sys.executable, ["python", "-m", "dramatiq", *sys.argv[1:]]) return os.execvp(sys.argv[0], sys.argv) return RET_KILLED if retcode < 0 else retcode
def test_08_integration_test_with_messagebus(self): """ Full blown integration test listening for notifications on the bus, and checking which dir is up for a visit next. Needs a working local qpid broker. Test is skipped if qpid not available. """ try: broker = None connection = None import uuid from threading import Event from qpid.messaging import Connection, ConnectError from qpidtoollibs import BrokerAgent from lofar.messaging.messagebus import ToBus from lofar.messaging.messages import EventMessage from lofar.lta.ingest.common.config import DEFAULT_INGEST_NOTIFICATION_PREFIX # setup broker connection connection = Connection.establish('127.0.0.1') broker = BrokerAgent(connection) # add test service bus busname = 'test-LTASOIngestEventHandler-%s' % (uuid.uuid1()) broker.addExchange('topic', busname) sync_event = Event() class SyncedLTASOIngestEventHandler(LTASOIngestEventHandler): """This derived LTASOIngestEventHandler behaves exactly like the normal object under test LTASOIngestEventHandler, but it also sets a sync_event to sync between the listener thread and this main test thread""" def _handleMessage(self, msg): super(SyncedLTASOIngestEventHandler, self)._handleMessage(msg) sync_event.set() with SyncedLTASOIngestEventHandler(self.dbcreds, busname=busname): for site in self.db.sites(): for root_dir in self.db.rootDirectoriesForSite(site['id']): self._markAllDirectoriesRecentlyVisited() # create the subdir surl sub_dir_name = '/foo' sub_dir_path = root_dir['dir_name'] + sub_dir_name surl = site['url'] + sub_dir_path with ToBus(busname) as sender: msg = EventMessage( subject=DEFAULT_INGEST_NOTIFICATION_PREFIX + "TaskFinished", content={'srm_url': surl}) sender.send(msg) # wait for the handler to have processed the message self.assertTrue(sync_event.wait(2)) sync_event.clear() # surl should have been scheduled for a visit, all other dir's were marked as visited already... # so there should be a new dir for this surl, and it should be the least_recent_visited_dir site_visit_stats = self.db.visitStats( datetime.utcnow())[site['name']] least_recent_visited_dir_id = site_visit_stats.get( 'least_recent_visited_dir_id') self.assertIsNotNone(least_recent_visited_dir_id) least_recent_visited_dir = self.db.directory( least_recent_visited_dir_id) self.assertEqual(sub_dir_path, least_recent_visited_dir['dir_name']) except ImportError as e: logger.warning("skipping test due to: %s", e) except ConnectError as e: logger.warning("skipping test due to: %s", e) finally: # cleanup test bus and exit if broker: broker.delExchange(busname) if connection: connection.close()
def __init__(self, callback, tick): Thread.__init__(self) self.callback = callback self.stopFlag = Event() self.tick = tick self.iters = 0
saveOnServer = False serverImageDirectory = "/home/pi/server/" # The Time how long a picture will be show diashowTime = 5 captureButton = Button(27) reCaptureButton = Button(17) abortButton = Button(22) # in seconds screenSaverStartTime = 120 pictureLocationLock = Lock() capturedEvent = Event() # Subprocess preview picturePreviewSubProcess = None # LED initial ledCyclePin = board.D18 ORDER = neopixel.GRB def exit_handler(): print('My application is ending!') threads["Camera"].stop_preview() threads["ScreenSaver"].stop_screen_saver() #threads["LedRingControl"].stopLeds()
"My name is roboface! I am a friendly robot!", "Hello! It's a pleasure to meet you!", "I feel so lonely!" ] if __name__ == "__main__": #Roboface Constructor roboFace = face.Face(x_weight=0.8, y_weight=0.2) ################################################################# # Set up tracker tracker_type = 'MEDIANFLOW' tracker = cv2.Tracker_create(tracker_type) Tracking_Period = 5 # set tracking period before re-initialisation in seconds ################################################################# # Set Speed for smoother movement roboFace.setSpeedAll(100) roboFace.setSpeedHead(80) flag = Event() flag.clear() ################################################################# roboFace.neutral() # load the trained neural network model = load_model( '../face_detection/trained/pretrained_CelebA_normalised0203-05.h5') cv2.namedWindow("Webcam Preview") vc = cv2.VideoCapture(0) # 0 for built-in webcam, 1 for robot # Input from video file Only for debugging # vc = cv2.VideoCapture('/home/robotsnake/RoboFace18/vid/test.avi') if vc.isOpened(): # try to get the first frame rval, frame = vc.read() else: rval = False
class Camera(Thread): global threads global capturedEvent startPreviewEvent = Event() finishCaptureEvent = Event() def __init__(self): Thread.__init__(self) Thread.setName(self, "Camera") self.startCapturing = False subprocess.Popen('mkfifo fifo.mjpg', shell=True, stdout=False, stdin=subprocess.PIPE).wait() # Kill all gphoto2 processe subprocess.Popen('killall /usr/lib/gvfs/gvfs-gphoto2-volume-monitor', shell=True, stdout=False, stdin=False).wait() subprocess.Popen('killall /usr/lib/gvfs/gvfsd-gphoto2', shell=True, stdout=False, stdin=False).wait() def run(self): while True: self.startPreviewEvent.wait() # preview self.start_video_preview_process() # wait for subProcess Camera Stream closed self.videoPreviewSubProcess.wait() if (self.startCapturing): self.capture() # Das Event brauchen wir vllt nicht wenn wir die wait Funktion des Subprocess nutzen #self.finishCaptureEvent.wait() # wait for subProcess Picture Preview closed self.picturePreviewSubProcess.wait() def start_preview(self): self.startPreviewEvent.set() def stop_preview(self): self.startPreviewEvent.clear() try: self.stop_video_preview_process() except: pass #if(self.pucturePreviewSubProcess != None): try: self.stop_picture_preview_process() except: pass def start_capturing(self): self.startCapturing = True self.stop_video_preview_process() def is_set(self): return self.startPreviewEvent.is_set() def start_picture_preview_process(self): if (lastCapturedImage != noImageCapturedInfo): picturePreviewCommand = "feh -xFY " + imageDirectory + lastCapturedImage else: picturePreviewCommand = "feh -xFY " + lastCapturedImage # The os.setsid() is passed in the argument preexec_fn so # it's run after the fork() and before exec() to run the shell. self.picturePreviewSubProcess = subprocess.Popen(picturePreviewCommand, shell=True, preexec_fn=os.setsid) print("Start Picture preview") def stop_picture_preview_process(self): # Send the signal to all the process groups os.killpg(os.getpgid(self.picturePreviewSubProcess.pid), signal.SIGTERM) print("Stop Picture preview") # local function def start_video_preview_process(self): # Subprocess Preview Stream if (devModus): videoPreviewCommand = "feh '" + imageDirectory + "pre.jpg'" else: videoPreviewCommand = "gphoto2 --capture-movie --stdout > fifo.mjpg & omxplayer --layer 2 -b --live fifo.mjpg" # The os.setsid() is passed in the argument preexec_fn so # it's run after the fork() and before exec() to run the shell. self.videoPreviewSubProcess = subprocess.Popen(videoPreviewCommand, shell=True, preexec_fn=os.setsid) print("Start Camera preview") #Event().wait(0.3) # local function def stop_video_preview_process(self): # Stop Subprocess Preview Stream os.killpg(os.getpgid(self.videoPreviewSubProcess.pid), signal.SIGTERM) print("Stop Camera video preview") # local function def capture(self): global captured global lastCapturedImage global capturedEvent self.startCapturing = False Event().wait(1) threads["LedRingControl"].stop_led_countdown_event() threads["LedRingControl"].start_led_wait_event() # Subprocess Camera Capturing date = time.strftime("%Y-%m-%d-%H-%M-%S") # fileName = date + str(hashedName) + imageFileType lastCapturedImage = date + "." + imageFileType captureCommmand = "gphoto2 --keep --capture-image-and-download --stdout > " + imageDirectory + lastCapturedImage subprocess.Popen(captureCommmand, shell=True, stdout=False, stdin=False).wait() captured = True try: checkImg = Image.open(imageDirectory + lastCapturedImage) print("Image captured") except: print("Image cant captured") os.remove(imageDirectory + lastCapturedImage) lastCapturedImage = noImageCapturedInfo # start preview Subprocess self.start_picture_preview_process() capturedEvent.set()
def __init__(self, instance_data, plugin_manager): self.instance_data = instance_data self.plugin_manager = plugin_manager self.stopped = Event()
class ScreenSaver(Thread): global threads startScreenSaverEvent = Event() diashowDelayEvent = Event() def __init__(self): Thread.__init__(self) Thread.setName(self, "ScreenSaver") self.startScreenSaverEvent.set() self.lastInteraction = time.time() def run(self): while True: self.startScreenSaverEvent.wait(screenSaverStartTime - (time.time() - self.lastInteraction)) if (time.time() - self.lastInteraction > screenSaverStartTime): self.start_screen_saver() if (self.startScreenSaverEvent.is_set()): self.diashow() def start_screen_saver(self): global captured self.startScreenSaverEvent.set() self.diashowDelayEvent.clear() # Save Image saveImage() captured = False threads['Camera'].stop_preview() def stop_screen_saver(self): self.startScreenSaverEvent.clear() self.diashowDelayEvent.set() def is_set(self): return self.startScreenSaverEvent.is_set() def update_last_interaction(self): self.lastInteraction = time.time() def diashow(self): global diashowTime self.globalPictures = glob.glob(imageDirectory + '*.' + imageFileType) while not self.diashowDelayEvent.is_set(): if (len(self.globalPictures) == 0): imageViewCommand = 'feh -xFY ' + noImageFound else: #imageViewCommand = 'feh -xFY ' + tmpDisplayImage #imageViewCommand = 'raspidmx/pngview/pngview -b 0 -l 3 -t 10000 ' + tmpDisplayImage imageViewCommand = 'cd ' + imageDirectory + '; feh -xFYz -D ' + str( diashowTime) pro = subprocess.Popen(imageViewCommand, shell=True, preexec_fn=os.setsid) self.diashowDelayEvent.wait() os.killpg(os.getpgid(pro.pid), signal.SIGTERM) def stock_photos(self): pass
class WebsocketClientSubclass(WebsocketClient): running = Event() status = False def run(self): self.status = self.running.wait(4)
class LedRingControl(Thread): global threads ledEvents = Event() ledCountdownEvent = Event() ledWaitEvent = Event() ledRandomEvent = Event() # TODO add LED variables ledPixels = 24 pixels = neopixel.NeoPixel(ledCyclePin, ledPixels) startindex = 1 endindex = 23 def __init__(self): Thread.__init__(self) Thread.setName(self, "LedRingControl") self.pixels.fill((0, 0, 0)) def run(self): #self.led_ring_function_rainbow_cycle(0.001) #self.led_ring_function_countdown() while True: self.ledEvents.wait() if self.ledCountdownEvent.is_set(): self.led_ring_function_countdown(10, 0.5) self.stop_led_countdown_event() self.stop_led_events() if self.ledWaitEvent.is_set(): self.smile(0.3, 0.2) #self.led_ring_function_rainbow_cycle(0.01, 0.5) self.stop_led_wait_event() self.stop_led_events() if self.ledRandomEvent.is_set(): self.led_random_functions() self.stop_led_random_event() self.stop_led_events() # local def increase_led_ring(self): pass # local def reset_led_ring(self): pass def start_led_events(self): self.ledEvents.set() def stop_led_events(self): self.ledEvents.clear() def stop_all_led_events(self): self.ledEvents.clear() self.ledCountdownEvent.clear() self.ledWaitEvent.clear() self.ledRandomEvent.clear() def start_led_wait_event(self): self.start_led_events() self.ledWaitEvent.set() def stop_led_wait_event(self): self.ledWaitEvent.clear() def start_led_countdown_event(self): self.start_led_events() self.ledCountdownEvent.set() def stop_led_countdown_event(self): self.ledCountdownEvent.clear() def start_led_random_event(self): self.start_led_events() self.ledRandomEvent.set() def stop_led_random_event(self): self.ledRandomEvent.clear() def led_ring_function_countdown(self, countdown, brightness): startindex = self.startindex endindex = self.endindex #self.pixels.fill((50,0,0)) while countdown >= 0 and self.ledCountdownEvent.is_set(): if startindex != 6 and startindex != 12 and endindex != 18 and endindex != 24: self.pixels[startindex] = (255, 255, 255) self.pixels[endindex] = (255, 255, 255) self.pixels.brightness = brightness Event().wait(1) countdown -= 1 startindex += 1 endindex -= 1 #Event().wait(1) self.pixels.fill((0, 0, 0)) # TODO wait for: capture finished def led_ring_function_rainbow_cycle(self, wait, brightness): r = 0 g = 0 b = 0 steps = 20 reverse = False mini = 30 while self.ledWaitEvent.is_set(): for i in range(self.ledPixels): self.pixels[i] = (r, g, b) self.pixels.brightness = brightness if not reverse: if r < 255: r += steps if r > 255: r = 255 elif g < 255: g += steps if g > 255: g = 255 elif b < 255: b += steps if b > 255: b = 255 reverse = True else: if r > mini: r -= steps if r < mini: r = mini elif g > mini: g -= steps if g < mini: g = mini elif b > mini: b -= steps if b < mini: b = mini reverse = False time.sleep(wait) self.pixels.fill((0, 0, 0)) # created by Marius Petersen def sub(self, sys, val): if val > 2 * sys + 1: return val - (2 * sys + 1) elif val > sys: return val - sys elif val < 0: return val + sys + 1 else: return val # created by Marius Petersen def smile(self, wait, brightness): bright = int(255 * brightness) self.pixels.brightness = brightness self.pixels[3] = (0, 0, bright) self.pixels[21] = (0, 0, bright) tmp = 11 for j in range(4): for i in range(3 + 2 * j): self.pixels[i + tmp] = (bright, bright, bright) self.pixels.brightness = brightness time.sleep(wait) tmp = tmp - 1 time.sleep(wait) self.pixels[3] = (0, 0, 0) self.pixels[21] = (0, 0, 0) time.sleep(0.2) self.pixels[3] = (0, 0, bright) self.pixels[21] = (0, 0, bright) time.sleep(0.6) self.pixels[3] = (0, 0, 0) self.pixels[21] = (0, 0, 0) time.sleep(0.2) self.pixels[3] = (0, 0, bright) self.pixels[21] = (0, 0, bright) time.sleep(0.6) self.pixels.fill((0, 0, 0)) # created by Marius Petersen def wheelRed(self, wait, brightness): for i in range(23): if not self.ledRandomEvent.is_set(): break for j in range(23): if not self.ledRandomEvent.is_set(): break k = int(255 / (j**2 + 1)) self.pixels[sub(23, i - j)] = (k, 0, 0) self.pixels.brightness = brightness time.sleep(wait) # created by Marius Petersen def wheel3(self, wait, fade, brightness): bright = 255 # zwischen 0 und 255 # fade zwischen 1 und 3 for i in range(23): if not self.ledRandomEvent.is_set(): break for j in range(23): if not self.ledRandomEvent.is_set(): break k1 = int(bright / (j**fade + 1)) k2 = int(bright / ((j + 16)**fade + 1)) k3 = int(bright / ((j + 8)**fade + 1)) if j > 7: k2 = int(bright / ((j - 8)**fade + 1)) if j > 15: k3 = int(bright / ((j - 16)**fade + 1)) pixels[sub(23, i - j)] = (k1, k2, k3) self.pixels.brightness = brightness time.sleep(wait) # created by Marius Petersen def wheel4(self, wait, brightness): self.pixels.fill((0, 0, 0)) self.pixels.brightness = brightness for i in range(5): if not self.ledRandomEvent.is_set(): break k = int(255 / (i**2 + 1)) self.pixels[0 + i] = (255, 0, 0) for j in range(i): if not self.ledRandomEvent.is_set(): break self.pixels[0 + j] = ((j + 1) * k, 0, 0) self.pixels[6 + i] = (0, 255, 0) for j in range(i): if not self.ledRandomEvent.is_set(): break self.pixels[6 + j] = (0, (j + 1) * k, 0) self.pixels[12 + i] = (0, 0, 255) for j in range(i): if not self.ledRandomEvent.is_set(): break self.pixels[12 + j] = (0, 0, (j + 1) * k) self.pixels[18 + i] = (0, 0, 255) for j in range(i): if not self.ledRandomEvent.is_set(): break self.pixels[18 + j] = ((j + 1) * k, 0, (j + 1) * k) time.sleep(wait) def led_random_functions(self): while self.ledRandomEvent.is_set(): #rand = random.randrange(1, 3) rand = 1 if rand == 1: self.wheelRed(0.3, 0.6) elif rand == 2: self.wheel3(0.2, 1.2, 0.6) elif rand == 3: self.wheel4(0.6, 0.6) self.pixels.fill((0, 0, 0)) def set_led_color(self, ledNumber, rgb): self.pixels[ledNumber] = (rgb[0], rgb[1], rgb[2]) def set_led_on(self, ledNumber): pass def set_led_off(self, ledNumber): pass
str(client.bConnectedFlag) + ")") logging.debug(e) time.sleep(10) # } end while logging.info("Connected to broker.") my_publish_topic = 'measures/' + my_device my_subscription_topic = 'commands/' + my_device client.subscribe(my_subscription_topic, 0) client.loop_start() time.sleep(10) from threading import Event exit = Event() def main(): while client.continueLoop: exit.clear() while not exit.is_set(): logging.info('in main loop, sample duration set for ' + str(client.iSleepTime) + ' seconds\n') try: calculateOverride() getDhtReadings() time.sleep(
def __init__(self, parent, replay): QThread.__init__(self, parent) self.replay = replay self.stop = Event()
"unlabelled": [impaths] } """ data = json.loads(request.data) save_training_annotations(data) feed_training_data(data["labelled_data"], data["labels_list"]) if len(data["unlabelled"]) > 0: feed_query_data(data["unlabelled"]) return "" @app.route("/test_data", methods=["POST"]) def test_data(): '''Retrieve the test data and send them to the trainer thread data = {"test_data":, "labels_list":} ''' data = json.loads(request.data) save_test_data(data) feed_test_data(data["test_data"], data["labels_list"]) return "" ## Queue, events and thread def ## train_queue = queue.Queue() test_queue = queue.Queue() unlabelled_queue = queue.Queue() trainer = Trainer(train_queue, unlabelled_queue, test_queue) stopTrainer = Event() if __name__ == '__main__': app.run(host="localhost", port=3333)
def __init__(self, seconds, immediate=True): self.seconds = seconds self.event = Event() if immediate: self.sleep()
def __init__(self, cache): self.cache = cache self.__is_shutdown = Event() self.__is_stopped = Event() Thread.__init__(self)
def __init__(self): self.dir_path = os.path.dirname(os.path.realpath(__file__)) self.config_file_path = os.path.join(self.dir_path, "config.json") self.plugins = [] self.archivers = [] self.parsers = {} Runner.scaffold_initial_files() # get core configurations with open(self.config_file_path) as config_file: self.config = json.load(config_file) # load all the plugin directory paths into a list self.plugins_directory = os.path.join(os.getcwd(), PLUGINS) self.collectors_directory = os.path.join(self.plugins_directory, COLLECTORS) self.parser_directory = os.path.join(self.plugins_directory, PARSERS) # Grab the core's archiver default settings self.archiverDefaults = self.config.get("Archiving") # Build plugin objects found in plugin directory plugin_factory = PluginFactory() for found_plugin_dir in os.listdir(self.collectors_directory): if not "__init__" in found_plugin_dir: plugin_base_dir = os.path.join(self.collectors_directory, found_plugin_dir) plugin = plugin_factory.build_from(plugin_base_dir) self.plugins.append(plugin) # TODO Check Parser with new if "Parser" in plugin.config: parser_type = plugin.config["Parser"]["Value"] parser_type_tokens = parser_type.split(",") if len(parser_type_tokens) == 2: parser = getattr( __import__(parser_type_tokens[0], fromlist=[parser_type_tokens[1]]), parser_type_tokens[1]) self.parsers[plugin.name] = parser(plugin) # Create the plugin's archiver if plugin.config.get("archiver"): plugin_arch_configs = plugin.config["archiver"] archiver = Archive(plugin, plugin_arch_configs) else: # Plugin will use default core values archiver = Archive(plugin, self.archiverDefaults) self.archivers.append(archiver) # TODO: this for sure, is no way to implement async stuff need to look into this self.wait_event = Event() self.stop_event = Event() self.thread = Thread(target=self.__update, args=( self.wait_event, self.stop_event, )) self.thread.start()
] size_avail = os.statvfs(dc_path).f_frsize * os.statvfs( dc_path).f_bavail print(dc_resp) sleep(3) def serve(): dc = DataCenter() server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) file_transfer_pb2_grpc.add_DataTransferServiceServicer_to_server( dc, server) raft_pb2_grpc.add_raftImplemetationServicer_to_server(dc, server) server.add_insecure_port(my_id) server.start() # print("server started") try: while True: sleep(86400) except KeyboardInterrupt: sys.exit(1) if __name__ == '__main__': event = Event() event.set() t1 = Thread(target=serve) t3 = Thread(target=checkFiles) t1.start() t3.start()
def __init__(self, store=None): self.store = store self.event = Event() self.__id__ = [] self.__filter__ = [] self.proccess = None