Exemplo n.º 1
0
class ThreddsConnection(object):

    def __init__(self, app, random_state, timeout=300.0,
                 cached=False, **fs_args):
        """ Create an expiring connection to the THREDDS server.

        The connection will drop after 5 minutes of non-use. Any subsequent
        attempt to use the connection will initiate a new one. Access to the
        connection is RLock'd to ensure only one connection is alive at a time.

        Parameters:
        timeout : int, seconds
            The length of time in seconds to hold open a connection.

        Remaining keyword args are passed to the connection's constructor.
        """
        self.app = app
        self.random_state = random_state
        self.cached = cached
        self._fs = {}
        self._fs_lock = RLock()
        self._fs_args = fs_args
        self._timer = None
        self.timeout = float(timeout)

    def cached():
        doc = "If True, use cached data."

        def fget(self):
            return self._cached

        def fset(self, value):
            self.datasources = {
                'hindcast':
                    HINDCAST_CACHE_DATA_URI if value else HINDCAST_DATA_URI,
                'forecast':
                    FORECAST_CACHE_DATA_URI if value else FORECAST_DATA_URI,
            }
            self._cached = value
        return locals()
    cached = property(**cached())

    def _forget(self):
        self.app.logger.info("Closing THREDDS connection")
        if self._timer:
            self._timer.cancel()
            self._timer = None
        self._fs = {}

    def _reset_timer(self):
        self.app.logger.info("Resetting THREDDS connection timer")
        if self._timer:
            self._timer.cancel()
        self._timer = Timer(self.timeout, self._forget)
        self._timer.start()

    hindcast_fs = property(fget=partial(fget, datasource='hindcast'),
                           fdel=fdel)
    forecast_fs = property(fget=partial(fget, datasource='forecast'),
                           fdel=fdel)
Exemplo n.º 2
0
    def __init__(self, name) :
       
        rospy.on_shutdown(self._on_node_shutdown)
        self.current_node = "Unknown"
        self.nogo_pre_active = False
        self.nogo_active = False
        self.nogos=[]
        self.stop_services=["/enable_motors", "/emergency_stop", "/task_executor/set_execution_status"]
        self.activate_services=["/enable_motors", "/reset_motorstop", "/task_executor/set_execution_status"]

        #Waiting for Topological Map        
        self._map_received=False
        rospy.Subscriber('/topological_map', TopologicalMap, self.MapCallback)      
        rospy.loginfo("Waiting for Topological map ...")        
        while not self._map_received :
            pass
        rospy.loginfo(" ...done")


        self.update_service_list()
        print self.av_stop_services, self.av_activate_services
        
    
        #Subscribing to Localisation Topics
        rospy.loginfo("Subscribing to Localisation Topics")
        rospy.Subscriber('/current_node', String, self.currentNodeCallback)
        rospy.loginfo(" ...done")

        self.nogos = self.get_no_go_nodes()
        print self.nogos
        self._killall_timers=False
        t = Timer(1.0, self.timer_callback)
        t.start()
        rospy.loginfo("All Done ...")
        rospy.spin()
Exemplo n.º 3
0
    def onStatusUpdate(self, cmd):
        cmd.updateTime = time.time()
        # append the command's status to the rendernode's history
        if isFinalStatus(cmd.status):
            # only if we don't already have a command for this task
            if hasattr(cmd.renderNode, 'tasksHistory') and cmd.task.id not in cmd.renderNode.tasksHistory:
                cmd.renderNode.tasksHistory.append(cmd.task.id)
                cmd.renderNode.history.append(cmd.status)
        if cmd.status is CMD_DONE:
            # TOFIX: handle CANCEL status and update end time when cancelling a
            # job so that it can be properly cleaned
            cmd.endTime = cmd.updateTime
            cmd.computeAvgTimeByFrame()
            cmd.attempt += 1

        # autoretry
        elif cmd.status is CMD_ERROR:
            cmd.attempt += 1

            LOGGER.debug("Mark command %d for auto retry in %ds  (%d/%d)" % (cmd.id, singletonconfig.get('CORE', 'DELAY_BEFORE_AUTORETRY'), cmd.attempt, cmd.task.maxAttempt))
            if cmd.attempt < cmd.task.maxAttempt:
                t = Timer(singletonconfig.get('CORE', 'DELAY_BEFORE_AUTORETRY'), self.autoretry, [cmd])
                t.start()

        elif cmd.status is CMD_ASSIGNED:
            cmd.startTime = cmd.updateTime
        elif cmd.status < CMD_ASSIGNED:
            cmd.startTime = None
Exemplo n.º 4
0
    def test_sqs_longpoll(self):
        c = SQSConnection()
        queue_name = "test_sqs_longpoll_%s" % int(time.time())
        queue = c.create_queue(queue_name)
        self.addCleanup(c.delete_queue, queue, True)
        messages = []

        # The basic idea is to spawn a timer thread that will put something
        # on the queue in 5 seconds and verify that our long polling client
        # sees the message after waiting for approximately that long.
        def send_message():
            messages.append(queue.write(queue.new_message("this is a test message")))

        t = Timer(5.0, send_message)
        t.start()
        self.addCleanup(t.join)

        start = time.time()
        response = queue.read(wait_time_seconds=10)
        end = time.time()

        t.join()
        self.assertEqual(response.id, messages[0].id)
        self.assertEqual(response.get_body(), messages[0].get_body())
        # The timer thread should send the message in 5 seconds, so
        # we're giving +- .5 seconds for the total time the queue
        # was blocked on the read call.
        self.assertTrue(4.5 <= (end - start) <= 5.5)
Exemplo n.º 5
0
Arquivo: server.py Projeto: waylan/mt
class Countdown(object):
    """
    Countdown timer starts immediatly on init from `start_value` and counts down
    to zero, then counts up with negated time. Only displays minutes and
    seconds. No pause or reset available. Each "tick" of the clock is passed to
    the callback function as a string. """
    
    def __init__(self, start_value, callback):
        self._finished = False
        self.start_value = start_value
        self.callback = callback
        self.start_time = now()
        self._update()

    def _update(self):
        self._set_time(now() - self.start_time)
        if not self._finished:
            self._timer = Timer(1, self._update)
            self._timer.start()

    def _set_time(self, value):
        neg = '' 
        if self.start_value > value:
            value = self.start_value - value
        elif self.start_value < value:
            value = value - self.start_value
            neg = '-'
        else:
            value = 0
        mm, ss = divmod(value, 60)
        self.callback("{}{:02d}:{:02d}".format(neg, mm, ss))

    def stop(self):
        self._timer.cancel()
        self._finished = True
def setInterval(func, sec):
    def func_wrapper():
        setInterval(func, sec)
        func()
    t = Timer(sec, func_wrapper)
    t.start()
    return t
Exemplo n.º 7
0
def run(data, d=None):
	global timer
	print(data)

	if data == "ring":
		if int(d) == 1:
			if timer:
				timer.cancel()

			timer = Timer(60, genugdavon)
			timer.start()

			check = Thread(target=check_locks)
			check.start()

			putfile('/sys/class/gpio/gpio11/value', '0')

			playsound("/root/ring-bb.wav")
		else:
			playsound("/root/ring-fis.wav")
	

	if data == "open":
#		if not locked_oben:
		playsound("/root/open.wav")
	
	if data == "summ":
		if timer:
			timer.cancel()

#		if not locked_oben:
		putfile('/sys/class/gpio/gpio11/value', '1')
		playsound("/root/summ.wav")
Exemplo n.º 8
0
class RepeatTimer:
    """Timer that repeats itself `interval` seconds /after/ each function call returns."""

    def __init__(self, interval, fn, args=None, kwargs=None):
        self.cancelled = False

        args = args or ()
        kwargs = kwargs or {}

        def repeater():
            if self.cancelled:
                return

            fn(*args, **kwargs)
            self.timer = Timer(interval, repeater)
            self.timer.start()

        self.timer = Timer(interval, repeater)

    def start(self):
        logging.debug('starting timer')
        self.timer.start()

    def cancel(self):
        logging.debug('cancelling timer')
        # `timer.cancel()` won't cancel properly if within repeater call, so use internal check
        self.cancelled = True
Exemplo n.º 9
0
def run(dir, main="tmp"):
    try:
        ##print("DEBUG:", [
        ## config.JAVA_CMD,
        ##    "-Djava.security.manager",
        ##    "-Djava.security.policy=whiley.policy",
        ##    "-cp",config.WYJC_JAR + ":" + dir,
        ##    main
        ##    ])
        # run the JVM
        proc = subprocess.Popen([
                                    config.JAVA_CMD,
                                    "-Djava.security.manager",
                                    "-Djava.security.policy=whiley.policy",
                                    "-cp", config.WYJC_JAR + ":" + dir,
                                    main
                                ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False)
        # Configure Timeout
        kill_proc = lambda p: p.kill()
        timer = Timer(20, kill_proc, [proc])
        timer.start()
        # Run process        
        (out, err) = proc.communicate()
        timer.cancel()
        # Check what happened
        if proc.returncode >= 0:
            return out
        else:
            return "Timeout: Your program ran for too long!"
    except Exception as ex:
        # error, so return that
        return "Run Error: " + str(ex)
Exemplo n.º 10
0
def scheduleFlight(res, flight, blocking=False, scheduler=None):
  flight_time = time_module.mktime(flight.legs[0].depart.dt_utc.utctimetuple()) - time_module.timezone
  seconds_before = config["CHECKIN_WINDOW"] + 24*60*60 # how many seconds before the flight time do we check in
  flight.sched_time = flight_time - seconds_before
  flight.sched_time_formatted = DateTimeToString(flight.legs[0].depart.dt_utc.replace(tzinfo=utc) - timedelta(seconds=seconds_before))
  flight.seconds = flight.sched_time - time_module.time()
  # Retrieve timezone and apply it because datetimes are stored as naive (no timezone information)
  tz = airport_timezone_map[flight.legs[0].depart.airport]
  flight.sched_time_local_formatted = DateTimeToString(flight.legs[0].depart.dt_utc.replace(tzinfo=utc).astimezone(tz) - timedelta(seconds=seconds_before))
  db.Session.commit()
  dlog("Flight time: %s" % flight.legs[0].depart.dt_formatted)
  if config["CELERY"]:
    from tasks import check_in_flight
    result = check_in_flight.apply_async([res.id, flight.id], countdown=flight.seconds)
    flight.task_uuid = result.id
    db.Session.commit()
  elif not blocking:
    result = "Scheduling check in for flight at", flight.legs[0].depart.dt_formatted, "(local), ", flight.legs[0].depart.dt_utc_formatted, "(UTC) in", int(flight.seconds/60/60), "hrs", int(flight.seconds/60%60),  "mins from now..."
    t = Timer(flight.seconds, TryCheckinFlight, (res.id, flight.id, None, 1))
    t.daemon = True
    t.start()
    # DEBUG
    # if flight == res.flights[0]:
    #   Timer(5, TryCheckinFlight, (res, flight, None, 1)).start()
  else:
    scheduler.enterabs(flight.sched_time, 1, TryCheckinFlight, (res.id, flight.id, scheduler, 1))
    result = "Scheduling check in for flight at", flight.legs[0].depart.dt_formatted, "(local), ", flight.legs[0].depart.dt_utc_formatted, "(UTC)"
  print result
  dlog('Checkin scheduled at (UTC): %s' % flight.sched_time_formatted)
  dlog('Checkin scheduled at (local): %s' % flight.sched_time_local_formatted)
  dlog('Flights scheduled.  Waiting...')
  return result
class InfiniteTimer():
    """A Timer class that does not stop, unless you want it to."""

    def __init__(self, seconds, target):
        self._should_continue = False
        self.is_running = False
        self.seconds = seconds
        self.target = target
        self.thread = None

    def _handle_target(self):
        self.is_running = True
        self.target()
        self.is_running = False
        self._start_timer()

    def _start_timer(self):
        if self._should_continue:  # Code could have been running when cancel was called.
            self.thread = Timer(self.seconds, self._handle_target)
            self.thread.start()

    def start(self):
        if not self._should_continue and not self.is_running:
            self._should_continue = True
            self._start_timer()
        else:
            print("Timer already started or running, please wait if you're restarting.")

    def cancel(self):
        if self.thread is not None:
            # Just in case thread is running and cancel fails.
            self._should_continue = False
            self.thread.cancel()
        else:
            print("Timer never started or failed to initialize.")
Exemplo n.º 12
0
class InternalServer(HTTPServer):

    def kill_me(self):
        self.shutdown()
        logging.info("The server's life has come to an end, pid: {}".format(os.getpid()))


    def reset_selfdestruct_timer(self):
        if self.self_destruct_timer:
            self.self_destruct_timer.cancel()

        self.self_destruct_timer = Timer(LIFESPAN, self.kill_me)
        self.self_destruct_timer.start()


    def __init__(self, server_address, RequestHandlerClass, 
                 bind_and_activate=True):

        HTTPServer.__init__(self, server_address, RequestHandlerClass, 
                            bind_and_activate=bind_and_activate)
        
        self.self_destruct_timer = None
        self.clients = 1
        self.reset_selfdestruct_timer()


    def suicide(self):
        self.clients -= 1
        if self.clients == 0:
            if self.self_destruct_timer is not None:
                self.self_destruct_timer.cancel()

            quick_and_painless_timer = Timer(0.1, self.kill_me)
            quick_and_painless_timer.start()
    def setupClient(self, topic, msg_type, wait_duration=10):
        """
        Tries to set up an action client for calling it later.
        
        @type topic: string
        @param topic: The topic of the action to call.
        
        @type msg_type: msg type
        @param msg_type: The type of messages of this action client.
        
        @type wait_duration: int
        @param wait_duration: Defines how long to wait for the given client if it is not available right now.
        """
        if topic not in ProxyActionClient._clients:
            client = actionlib.SimpleActionClient(topic, msg_type)
            t = Timer(1, self._print_wait_warning, [topic])
            t.start()
            available = client.wait_for_server(rospy.Duration.from_sec(wait_duration))
            warning_sent = False
            try:
                t.cancel()
            except Exception as ve:
                # already printed the warning
                warning_sent = True

            if not available:
                Logger.logerr("Action client %s timed out!" % topic)
            else:
                ProxyActionClient._clients[topic] = client
                if warning_sent:
                    Logger.loginfo("Finally found action client %s..." % (topic))
Exemplo n.º 14
0
 def request_handler(self):
    timeout = self.opcd.get('power_save_timeout')
    req = PowerReq()
    rep = PowerRep()
    timer = None
    while True:
       rep.status = OK
       try:
          req_data = self.ctrl_socket.recv()
       except:
          sleep(1)
          continue
       try:
          req.ParseFromString(req_data)
       except:
          rep.status = E_SYNTAX
       else:
          try:
             timer.cancel()
          except:
             pass
          if req.cmd == STAND_POWER:
             timer = Timer(timeout, self.power_off)
             timer.start()
          else:
             if self.critical:
                # flying command is not allowed if battery was critical:
                rep.status = E_POWER
             else:
                self.gpio_mosfet.set_gpio(self.power_pin, True)
       self.ctrl_socket.send(rep.SerializeToString())
Exemplo n.º 15
0
class Handler():
    """Queues filesystem events for broadcast"""

    def __init__(self):
        """Create an event handler"""
        ## Timer used to prevent notification floods
        self._timer = None
        ## The files that have changed since the last broadcast
        self._files = set()
        ## Lock to protect files and timer from threading issues
        self._lock = Lock()

    def broadcast(self):
        """Broadcasts a list of all files touched since last broadcast"""
        with self._lock:
            cola.notifier().broadcast(signals.update_status, self._files)
            self._files = set()
            self._timer = None

    def handle(self, path):
        """Queues up filesystem events for broadcast"""
        with self._lock:
            self._files.add(path)
            if self._timer is None:
                self._timer = Timer(0.333, self.broadcast)
                self._timer.start()
Exemplo n.º 16
0
	def sync (self):
		if len (self.clients) == 0:
			self.logger.debug ('No clients available, bootstrapping...')
			self.reboot ()
			return

		if len (self.clients) < self.minpeers:
			self.logger.debug ('Available clients are less than minpeers, bootstrapping...')

			if self.boottimer != None:
				self.boottimer.cancel ()

			self.boottimer = Timer (5.0, self.reboot)
			self.boottimer.start ()


		for p in self.clients:
			#r = random.randint(0, len (self.clients) - 1)
			#p = self.clients [r]
			try:
				getblock = clients.GetBlocks ([int (self.db['lastblockhash'], 16)])
				p.send_message (getblock)
			except Exception as e:
				#self.logger.error ('Node fail.')
				if not p.reconnect ():
					self.logger.debug ('Removed unreachable peer %s (%s)', str (p.host), e)
					self.clients.remove (p)
					self.logger.debug ('Available peers: %d', len (self.clients))


		self.synctimer.cancel ()
		self.synctimer = Timer (5.0, self.sync)
		self.synctimer.start ()
Exemplo n.º 17
0
    def _connected(self, link_uri):
        """ This callback is called form the Crazyflie API when a Crazyflie
        has been connected and the TOCs have been downloaded."""
        print('Connected to %s' % link_uri)

        # The definition of the logconfig can be made before connecting
        self._lg_stab = LogConfig(name='Stabilizer', period_in_ms=10)
        self._lg_stab.add_variable('stabilizer.roll', 'float')
        self._lg_stab.add_variable('stabilizer.pitch', 'float')
        self._lg_stab.add_variable('stabilizer.yaw', 'float')

        # Adding the configuration cannot be done until a Crazyflie is
        # connected, since we need to check that the variables we
        # would like to log are in the TOC.
        try:
            self._cf.log.add_config(self._lg_stab)
            # This callback will receive the data
            self._lg_stab.data_received_cb.add_callback(self._stab_log_data)
            # This callback will be called on errors
            self._lg_stab.error_cb.add_callback(self._stab_log_error)
            # Start the logging
            self._lg_stab.start()
        except KeyError as e:
            print('Could not start log configuration,'
                  '{} not found in TOC'.format(str(e)))
        except AttributeError:
            print('Could not add Stabilizer log config, bad configuration.')

        # Start a timer to disconnect in 10s
        t = Timer(5, self._cf.close_link)
        t.start()
Exemplo n.º 18
0
class OpeningState:
    def __init__(self, door_model):
        self.door_model = door_model

    def door_position_changed(self, new_position):
        if new_position == DOOR_POSITION_OPEN:
            self.door_model.set_new_state("Open")
        elif new_position == DOOR_POSITION_CLOSED:
            self.door_model.set_new_state("Closed")

    def enter(self):
        logger.debug("State 'opening' entered")
        self.timer = Timer(self.door_model.transit_time, self._transit_timeout)
        self.timer.start()

    def exit(self):
        logger.debug("State 'opening' exited")
        if self.timer:
            self.timer.cancel()
            self.timer = False

    def _transit_timeout(self):
        logger.info("Transit timeout reached")
        self.timer = False
        self.door_model.set_new_state("Intermediate")
Exemplo n.º 19
0
    def _on_message(self, ws, message):
        self.logger.info("Connection: Message - %s" % message)

        # Stop our timeout timer, since we got some data
        self.connection_timer.cancel()
        self.ping_timer.cancel()

        params = self._parse(message)

        if 'event' in params.keys():
            if 'channel' not in params.keys():
                # We've got a connection event.  Lets handle it.
                if params['event'] in self.event_callbacks.keys():
                    for callback in self.event_callbacks[params['event']]:
                        callback(params['data'])
                else:
                    self.logger.info("Connection: Unhandled event")
            else:
                # We've got a channel event.  Lets pass it up to the pusher
                # so it can be handled by the appropriate channel.
                self.event_handler(
                    params['event'],
                    params['data'],
                    params['channel']
                )

        # We've handled our data, so restart our connection timeout handler
        self.connection_timer = Timer(self.connection_timeout, self._connection_timed_out)
        self.connection_timer.start()

        self.ping_timer = Timer(self.ping_interval, self.send_ping)
        self.ping_timer.start()
Exemplo n.º 20
0
def clean_avisos():
    global avisos_n
    logger.info("avisos_n = 0")
    avisos_n = 0
    global hilo
    hilo = Timer(config['clean_time'], clean_avisos)
    hilo.start()
Exemplo n.º 21
0
class IOServer(threading.Thread):
    # 6 7 8 9 
    # l d u r
    uPin = 15 # u <-> d
    lPin = 27 # l <-r
    rPin = 14
    dPin = 18
    def __init__(self):
        threading.Thread.__init__(self)
        # tprint(self.currentState)
        GPIO.setmode(GPIO.BCM)
        setupGPIO(self.uPin, self.upButtonHandler)
        setupGPIO(self.lPin, self.leftButtonHandler)
        setupGPIO(self.rPin, self.rightButtonHandler)
        setupGPIO(self.dPin, self.downButtonHandler)
        self.quit = False
        self.lcd = get_lcdcontroller()
        self.timer = Timer(0.5, self.timeoutHandler)
        
    def run(self):
        tprint("start ioserver")
        self.timer.start()
        lcd = self.lcd
        while True:
            c = getch()
            if (c == 'w'):
                lcd.up()
            elif (c == 'a'):
                lcd.left()
            elif (c == 's'):
                lcd.down()
            elif (c == 'd'):
                lcd.right()
            elif (c == ' '):
                lcd.center()
            elif (c == 'u'):
                lcd.updateDisplay()
            elif (c == 'q'):
                self.quit = True
                break
            else:
                tprint("Unknown Command")

    def upButtonHandler(self, pin = None):
        self.lcd.up()
        
    def downButtonHandler(self, pin = None):
        self.lcd.down()
        
    def leftButtonHandler(self, pin = None):
        self.lcd.left()

    def rightButtonHandler(self, pin = None):
        self.lcd.right()

    def timeoutHandler(self):
        self.lcd.updateDisplay()
        if not self.quit:
            self.timer = Timer(0.5, self.timeoutHandler)
            self.timer.start()
Exemplo n.º 22
0
def initial():

		#UDP socket works
	print 'Waiting For Peers.... :)'
	sock_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	sock_udp.bind((SERVER_IP,SERVER_PORT))
	peer_data = ''
	t = Timer (TIMER_IDLE_PEER, timer_function)
	t.start()
	exp_seq=1
	old_buffer=''
		#Request from Peer
	while True:
		recv_buffer,addr = sock_udp.recvfrom(4096)
		if recv_buffer == 'list':
			sock_udp.sendto(str(peer_list), addr)
		else:
			sock_udp.sendto(recv_buffer,addr)
			if old_buffer != recv_buffer:
				old_buffer = recv_buffer
				recv_buffer_split = recv_buffer.split()
				recv_buffer_len = len(recv_buffer_split)
				num_pkts = recv_buffer_split.pop(recv_buffer_len-1)
				seq_pkt = recv_buffer_split.pop(recv_buffer_len-2)
				exp_seq=exp_seq+1
				peer_data = peer_data + ''.join((str(x)+' ') for x in recv_buffer_split)
				if num_pkts == seq_pkt:
					thread = Thread(target = process_packet, args = (peer_data,sock_udp,addr))
					thread.start() #TEST THREADING!!!!!!!!!!!!!!!!!!!!
					#thread.join()
					peer_data = ''
					exp_seq=1
Exemplo n.º 23
0
 def view_image(self, im, auto_close=True):
     # use a manager to open so will auto close on quit
     self.open_view(im)
     if auto_close:
         minutes = 2
         t = Timer(60 * minutes, im.close_ui)
         t.start()
class PeriodicTimer(object):

    def __init__(self, frequency=60, *args, **kwargs):
        self.is_stopped = Event()
        self.is_stopped.clear()

        self.interval = frequency
        self._timer = Timer(self.frequency, self._check_for_event, ())
        self._timer.daemon = True

    @property
    def interval(self):
        return self.frequency

    @interval.setter
    def interval(self, frequency):
        self.frequency = frequency
        self.stop()
        try:
            if self._timer:
                self._timer.cancel()
                del(self._timer)
        except AttributeError, ex:
            pass
        self._timer = Timer(self.frequency, self._check_for_event, ())
        return self.frequency
Exemplo n.º 25
0
class TimerMixIn(object):
  
    def __init__(self, *argl, **argd):
        super(TimerMixIn,self).__init__(*argl,**argd)
        self.timer = None
        self.timerSuccess = True
          
    def startTimer(self, secs):
        if self.timer is not None:
            self.cancelTimer()
        self.timer = Timer(secs, self.__handleTimerDone)
        self.timerSuccess = False
        self.timer.start()
  
    def cancelTimer(self):
        if self.timer is not None and self.timer:
             self.timer.cancel()
             self.timer = None
             self.timerSuccess = False
  
    def timerRunning(self):
        return self.timer is not None
        
    def timerWasCancelled(self):
        return not self.timerSuccess
  
    def __handleTimerDone(self):
        self.scheduler.wakeThread(self)
        self.timer = None
        self.timerSuccess = True
Exemplo n.º 26
0
 def create_session(self):
     log.info("Enabling for MAC %s" % (self.mac))
     sys_cmd = "iptables -I internet 1 -t mangle -m mac --mac-source %s -j RETURN" % self.mac
     log.info(sys_cmd)
     log.info(os.popen(sys_cmd).read())
     callback = Timer(self.length, self.destroy_session)
     callback.start()
Exemplo n.º 27
0
def dataout():
    global timer1
    timer1 = Timer(1.0 / data_freq, dataout)
    timer1.start()
    lock.acquire()
    print "{:+.3f}".format(data.popleft())
    lock.release()
Exemplo n.º 28
0
Arquivo: test.py Projeto: Rohansi/wren
  def run(self, app, type):
    # Invoke wren and run the test.
    test_arg = self.path
    if type == "api test":
      # Just pass the suite name to API tests.
      test_arg = basename(splitext(test_arg)[0])

    proc = Popen([app, test_arg], stdin=PIPE, stdout=PIPE, stderr=PIPE)

    # If a test takes longer than two seconds, kill it.
    #
    # This is mainly useful for running the tests while stress testing the GC,
    # which can make a few pathological tests much slower.
    timed_out = [False]
    def kill_process(p):
      timed_out[0] = True
      p.kill()

    timer = Timer(2, kill_process, [proc])

    try:
      timer.start()
      out, err = proc.communicate(self.input_bytes)

      if timed_out[0]:
        self.fail("Timed out.")
      else:
        self.validate(type == "example", proc.returncode, out, err)
    finally:
      timer.cancel()
Exemplo n.º 29
0
 def defer(self, t, run_on_cancel, func, *args):
     event = Timer(t, self.run_action, kwargs={'func': func, 'args': args})
     event.name = '%s deferring %s' % (event.name, func.__name__)
     event.start()
     with worker_lock:
         self.events[event.ident] = Event(event, run_on_cancel)
     return event.ident
Exemplo n.º 30
0
 def run(self):
     while self.is_running:
         try:
             super(SerializeThread, self).run()
         except Exception, e:
             log.error("Exception in thread %s: %s", self.name, e)
             delay = TIMER_DELAYS[self.name]
             if delay > MAX_DELAY:
                 num_attempts = int(math.log((delay/10), 2));
                 log.error("Giving up re-spawning serialization " 
                     "worker after %d seconds (%d attempts).", 
                     delay, num_attempts
                 )
                 notify_serialization_failure(None,
                     subject="Notice - Bungeni Serialization Workers",
                     body="""Unable to restart serialization worker.
                 Please check the Bungeni logs."""
                 )
             else:
                 log.info("Attempting to respawn serialization "
                     "consumer in %d seconds", delay
                 )
                 next_delay = delay * 2
                 timer = Timer(delay, init_thread, [], 
                     {"delay": next_delay })
                 timer.daemon = True
                 timer.start()
             self.is_running = False
             del TIMER_DELAYS[self.name]
Exemplo n.º 31
0
 def start(self):
     if not self.is_running:
         self._timer = Timer(self.interval, self._run)
         self._timer.start()
         self.is_running = True
Exemplo n.º 32
0
    def change_state(self, new_state):
        success = False

        #check state transition plausibility
        if (self.boInit):
            success = True

        elif (self.state == 'closed'):
            if (new_state == 'opening'):
                success = True

        elif (self.state == 'opening'):
            if(new_state == 'opened'\
               or new_state == 'intermediate'):
                success = True
            elif(new_state == 'closing'\
                 or new_state == 'opening'):
                success = True
                new_state = 'intermediate'

        elif (self.state == 'opened'):
            if (new_state == 'closing'):
                success = True

        elif (self.state == 'closing'):
            if(new_state == 'closed'\
               or new_state == 'intermediate'):
                success = True
            elif(new_state == 'opening' \
                 or new_state == 'closing'):
                success = True
                new_state = 'intermediate'

        elif (self.state == 'intermediate'):
            if(new_state == 'opening' \
               or new_state == 'closing'):
                success = True

        #in case of plausible state change: perform state change
        if success:
            self.set_state(new_state)
            self.motion_timer.cancel()
            if (self.state == "opening"):
                outputs.open()
                outputs.light_opening()
                #stop motor if it takes to long to open/close
                self.motion_timer = Timer(self.motion_interval, \
                                          self.motion_abort)
                self.motion_timer.start()
            elif (self.state == "closing"):
                outputs.close()
                outputs.light_closing()
                #stop motor if it takes to long to open/close
                self.motion_timer = Timer(self.motion_interval, \
                                          self.motion_abort)
                self.motion_timer.start()
            elif (self.state == "opened"):
                outputs.stop()
                outputs.light_opened()
            elif (self.state == "closed"):
                outputs.stop()
                outputs.light_closed()
            elif (self.state == "intermediate"):
                outputs.stop()
                outputs.light_intermediate()

            self.log.info("internal: New state: " + self.state)
            self.update_all_observers()

        else:
            self.log.info("internal: No state change")

        return success
Exemplo n.º 33
0
class State_handler:
    observers = []

    def register_observer(self, callback):
        self.log.info("internal: registering state observer")
        self.observers.append(callback)
        callback(self.state)

    def update_all_observers(self):
        self.log.info("internal: Calling " + str(len(self.observers)) +
                      " state observers")
        [callback(self.state) for callback in self.observers]

    def __init__(self, state, logger):
        self.states = {
            'closed', 'closing', 'opened', 'opening', 'intermediate'
        }
        self.motion_interval = 9.0  #time interval after which motor motion
        # will be stopped (in seconds)
        self.log = logger
        self.motion_timer = Timer(self.motion_interval, None)
        self.boInit = True
        self.set_state('')
        self.change_state(state)
        self.boInit = False

    def set_state(self, string):
        if (string in self.states):
            self.state = string
        else:
            self.state = 'intermediate'
        return

    def get_state(self):
        return self.state

    def get_states(self):
        return self.states

    def handle_event(self, state):
        if state not in self.get_states():
            raise Exception('invalid state request: ' + state)
        if self.change_state(state):
            return "state change triggered"
        return "no state change"

    def change_state(self, new_state):
        success = False

        #check state transition plausibility
        if (self.boInit):
            success = True

        elif (self.state == 'closed'):
            if (new_state == 'opening'):
                success = True

        elif (self.state == 'opening'):
            if(new_state == 'opened'\
               or new_state == 'intermediate'):
                success = True
            elif(new_state == 'closing'\
                 or new_state == 'opening'):
                success = True
                new_state = 'intermediate'

        elif (self.state == 'opened'):
            if (new_state == 'closing'):
                success = True

        elif (self.state == 'closing'):
            if(new_state == 'closed'\
               or new_state == 'intermediate'):
                success = True
            elif(new_state == 'opening' \
                 or new_state == 'closing'):
                success = True
                new_state = 'intermediate'

        elif (self.state == 'intermediate'):
            if(new_state == 'opening' \
               or new_state == 'closing'):
                success = True

        #in case of plausible state change: perform state change
        if success:
            self.set_state(new_state)
            self.motion_timer.cancel()
            if (self.state == "opening"):
                outputs.open()
                outputs.light_opening()
                #stop motor if it takes to long to open/close
                self.motion_timer = Timer(self.motion_interval, \
                                          self.motion_abort)
                self.motion_timer.start()
            elif (self.state == "closing"):
                outputs.close()
                outputs.light_closing()
                #stop motor if it takes to long to open/close
                self.motion_timer = Timer(self.motion_interval, \
                                          self.motion_abort)
                self.motion_timer.start()
            elif (self.state == "opened"):
                outputs.stop()
                outputs.light_opened()
            elif (self.state == "closed"):
                outputs.stop()
                outputs.light_closed()
            elif (self.state == "intermediate"):
                outputs.stop()
                outputs.light_intermediate()

            self.log.info("internal: New state: " + self.state)
            self.update_all_observers()

        else:
            self.log.info("internal: No state change")

        return success

    def motion_abort(self):
        self.change_state('intermediate')
        return
Exemplo n.º 34
0
 def start_timer(self) -> None:
     """
     Set a timer to re-run the process method in the future
     """
     Timer(self.check_interval, self.process).start()
Exemplo n.º 35
0
class MissedMessageWorker(QueueProcessingWorker):
    # Aggregate all messages received over the last BATCH_DURATION
    # seconds to let someone finish sending a batch of messages and/or
    # editing them before they are sent out as emails to recipients.
    #
    # The timer is running whenever; we poll at most every TIMER_FREQUENCY
    # seconds, to avoid excessive activity.
    #
    # TODO: Since this process keeps events in memory for up to 2
    # minutes, it now will lose approximately BATCH_DURATION worth of
    # missed_message emails whenever it is restarted as part of a
    # server restart.  We should probably add some sort of save/reload
    # mechanism for that case.
    TIMER_FREQUENCY = 5
    BATCH_DURATION = 120
    timer_event = None  # type: Optional[Timer]
    events_by_recipient = defaultdict(
        list)  # type: Dict[int, List[Dict[str, Any]]]
    batch_start_by_recipient = {}  # type: Dict[int, float]

    def consume(self, event: Dict[str, Any]) -> None:
        logging.debug("Received missedmessage_emails event: %s" % (event, ))

        # When we process an event, just put it into the queue and ensure we have a timer going.
        user_profile_id = event['user_profile_id']
        if user_profile_id not in self.batch_start_by_recipient:
            self.batch_start_by_recipient[user_profile_id] = time.time()
        self.events_by_recipient[user_profile_id].append(event)

        self.ensure_timer()

    def ensure_timer(self) -> None:
        if self.timer_event is not None:
            return
        self.timer_event = Timer(self.TIMER_FREQUENCY,
                                 MissedMessageWorker.maybe_send_batched_emails,
                                 [self])
        self.timer_event.start()

    def stop_timer(self) -> None:
        if self.timer_event and self.timer_event.is_alive():
            self.timer_event.cancel()
            self.timer_event = None

    def maybe_send_batched_emails(self) -> None:
        self.stop_timer()

        current_time = time.time()
        for user_profile_id, timestamp in list(
                self.batch_start_by_recipient.items()):
            if current_time - timestamp < self.BATCH_DURATION:
                continue
            events = self.events_by_recipient[user_profile_id]
            logging.info(
                "Batch-processing %s missedmessage_emails events for user %s" %
                (len(events), user_profile_id))
            handle_missedmessage_emails(user_profile_id, events)
            del self.events_by_recipient[user_profile_id]
            del self.batch_start_by_recipient[user_profile_id]

        # By only restarting the timer if there are actually events in
        # the queue, we ensure this queue processor is idle when there
        # are no missed-message emails to process.
        if len(self.batch_start_by_recipient) > 0:
            self.ensure_timer()
Exemplo n.º 36
0
    def _connected(self, link_uri):
        """ This callback is called form the Crazyflie API when a Crazyflie
        has been connected and the TOCs have been downloaded."""
        logger.info('Connected to %s' % link_uri)
        self._startup()
        self._cf.commander.send_setpoint(0, 0, 0, 35000)
        self._context = CrazyflieContext()

        # The definition of the logconfig can be made before connecting
        self._lg_stab = LogConfig(name='Stabilizer / Acc', period_in_ms=10)
        self._lg_stab.add_variable('stabilizer.roll', 'float')
        self._lg_stab.add_variable('stabilizer.pitch', 'float')
        self._lg_stab.add_variable('stabilizer.yaw', 'float')

        self._lg_gyro = LogConfig(name='Gyro', period_in_ms=10)
        self._lg_gyro.add_variable('acc.x', 'float')
        self._lg_gyro.add_variable('acc.y', 'float')
        self._lg_gyro.add_variable('acc.z', 'float')
        self._lg_gyro.add_variable('gyro.x', 'float')
        self._lg_gyro.add_variable('gyro.y', 'float')
        self._lg_gyro.add_variable('gyro.z', 'float')

        # self._lg_motor = LogConfig(name='Motors', period_in_ms=100)
        # self._lg_motor.add_variable('motor.m1', 'int32_t')
        # self._lg_motor.add_variable('motor.m2', 'int32_t')
        # self._lg_motor.add_variable('motor.m3', 'int32_t')
        # self._lg_motor.add_variable('motor.m4', 'int32_t')

        # Adding the configuration cannot be done until a Crazyflie is
        # connected, since we need to check that the variables we
        # would like to log are in the TOC.
        try:
            self._cf.log.add_config(self._lg_stab)
            self._cf.log.add_config(self._lg_gyro)
            # self._cf.log.add_config(self._lg_motor)
            # This callback will receive the data
            # self._lg_stab.data_received_cb.add_callback(self._stab_log_data)
            self._lg_stab.data_received_cb.add_callback(self._store_data)
            self._lg_stab.data_received_cb.add_callback(self._last_ten_point)
            # self._lg_stab.data_received_cb.add_callback(lambda x, y, z: (logger.info(self._stabilize.point)))

            # self._lg_stab.data_received_cb.add_callback(self._send_position)
            #  self._lg_stab.data_received_cb.add_callback(self._stab)
            # self._lg_stab.data_received_cb.add_callback(self._send_position)
            # self._lg_gyro.data_received_cb.add_callback(self._stab_log_data)
            self._lg_gyro.data_received_cb.add_callback(self._store_data)
            #            self._lg_gyro.data_received_cb.add_callback(self._stab_log_data)
            # self._lg_gyro.data_received_cb.add_callback(self._send_position)
            # self._lg_motor.data_received_cb.add_callback(self._stab_log_data)
            # This callback will be called on errors
            self._lg_stab.error_cb.add_callback(self._stab_log_error)
            # Start the logging
            self._lg_stab.start()
            # self._lg_gyro.start()
            #   self._lg_motor.start()
        except KeyError as e:
            logger.error('Could not start log configuration,'
                         '{} not found in TOC'.format(str(e)))
        except AttributeError:
            logger.error(
                'Could not add Stabilizer log config, bad configuration.')
        Timer(1.9, self._startup).start()
        Timer(2, self._cf.close_link).start()
Exemplo n.º 37
0
class BaseRenewableTokenAuthenticationProvider(AuthenticationProvider):
    """A base class for authentication providers which are based on SAS (Shared
    Authentication Signature) strings which are able to be renewed.

    The SAS token string renewal is based on a signing function that is used
    to create the sig field of the SAS string.  This base implements all
    functionality for SAS string creation except for the signing function,
    which is expected to be provided by derived objects.  This base also
    implements the functionality necessary for timing and executing the
    token renewal operation.
    """

    def __init__(self, hostname, device_id, module_id=None):
        """Initializer for Renewable Token Authentication Provider.

        This object is intended as a base class and cannot be used directly.
        A derived class which provides a signing function (such as
        SymmetricKeyAuthenticationProvider or IoTEdgeAuthenticationProvider)
        should be used instead.

        :param str hostname: The hostname
        :param str device_id: The device ID
        :param str module_id: The module ID (optional)
        """

        super(BaseRenewableTokenAuthenticationProvider, self).__init__(
            hostname=hostname, device_id=device_id, module_id=module_id
        )
        self.token_validity_period = DEFAULT_TOKEN_VALIDITY_PERIOD
        self.token_renewal_margin = DEFAULT_TOKEN_RENEWAL_MARGIN
        self._token_update_timer = None
        self.shared_access_key_name = None
        self.sas_token_str = None
        self.on_sas_token_updated_handler_list = []

    def __del__(self):
        self._cancel_token_update_timer()

    def generate_new_sas_token(self):
        """Force the SAS token to update itself.

        This will cause a new sas token to be created using the _sign function.
        This token is valid for roughly self.token_validity_period second.

        This validity period can only be roughly enforced because it relies on the
        coordination of clocks between the client device and the service.  If the two
        different machines have different definitions of "now", most likely because
        of clock drift, then they will also have different notions of when a token will
        expire.  This algorithm atempts to compensate for clock drift by taking
        self.token_renewal_margin into account when deciding when to renew a token.

        If self.token_udpate_callback is set, this callback will be called to notify the
        pipeline that a new token is available.  The pipeline is responsible for doing
        whatever is necessary to leverage the new token when the on_sas_token_updated_handler_list
        function is called.

        The token that is generated expires at some point in the future, based on the token
        renewal interval and the token renewal margin.  When a token is first generated, the
        authorization provider object will set a timer which will be responsible for renewing
        the token before the it expires.  When this timer fires, it will automatically generate
        a new sas token and notify the pipeline by calling self.on_sas_token_updated_handler_list.

        The token update timer is set based on two numbers: self.token_validity_period and
        self.token_renewal_margin

        The first number is the validity period.  This defines the amount of time that the token
        is valid.  The interval is encoded in the token as an offset from the current time,
        as based on the Unix epoch.  In other words, the expiry (se=) value in the token
        is the number of seconds after 00:00 on January 1, 1970 that the token expires.

        The second number that defines the token renewal behavior is the margin.  This is
        the number of seconds before expiration that we want to generate a new token.  Since
        the clocks on different computers can drift over time, they will all have different
        definitions of what "now" is, so the margin needs to be set so there is a
        very small chance that there is no time overlap where one computer thinks the token
        is expired and another doesn't.

        When the timer is set to renew the SAS token, the timer is set for
        (token_validity_period - token_renewal_margin) seconds in the future.  In this way,
        the token will be renewed close to it's expiration time, but not so close that
        we risk a problem caused by clock drift.

        :return: None
        """
        logger.info(
            "Generating new SAS token for (%s,%s) that expires %d seconds in the future",
            self.device_id,
            self.module_id,
            self.token_validity_period,
        )
        expiry = int(math.floor(time.time()) + self.token_validity_period)
        resource_uri = self.hostname + "/devices/" + self.device_id
        if self.module_id:
            resource_uri += "/modules/" + self.module_id
        quoted_resource_uri = urllib.parse.quote_plus(resource_uri)

        signature = self._sign(quoted_resource_uri, expiry)

        if self.shared_access_key_name:
            token = _device_keyname_token_format.format(
                quoted_resource_uri, signature, str(expiry), self.shared_access_key_name
            )
        else:
            token = _device_token_format.format(quoted_resource_uri, signature, str(expiry))

        self.sas_token_str = str(token)
        self._schedule_token_update(self.token_validity_period - self.token_renewal_margin)
        self._notify_token_updated()

    def _cancel_token_update_timer(self):
        """Cancel any future token update operations.  This is typically done as part of a
        teardown operation.
        """
        t = self._token_update_timer
        self._token_update_timer = None
        if t:
            logger.debug(
                "Canceling token update timer for (%s,%s)",
                self.device_id,
                self.module_id if self.module_id else "",
            )
            t.cancel()

    def _schedule_token_update(self, seconds_until_update):
        """Schedule an automatic sas token update to take place seconds_until_update seconds in
        the future.  If an update was previously scheduled, this method shall cancel the
        previously-scheduled update and schedule a new update.
        """
        self._cancel_token_update_timer()
        logger.debug(
            "Scheduling token update for (%s,%s) for %d seconds in the future",
            self.device_id,
            self.module_id,
            seconds_until_update,
        )

        # It's important to use a weak reference to self inside this timer function
        # because we don't want the timer to prevent this object (`self`) from being collected.
        #
        # We want `self` to get collected when the pipeline gets collected, and
        # we want the pipeline to get collected when the client object gets collected.
        # This way, everything gets cleaned up when the user is done with the client object,
        # as expected.
        #
        # If timerfunc used `self` directly, that would be a strong reference, and that strong
        # reference would prevent `self` from being collected as long as the timer existed.
        #
        # If this isn't collected when the client is collected, then the object that implements the
        # on_sas_token_updated_hndler doesn't get collected.  Since that object is part of the
        # pipeline, a major part of the pipeline ends up staying around, probably orphaned from
        # the client.  Since that orphaned part of the pipeline contains Paho, bad things can happen
        # if we don't clean up Paho correctly.  This is especially noticable if one process
        # destroys a client object and creates a new one.
        #
        self_weakref = weakref.ref(self)

        def timerfunc():
            this = self_weakref()
            logger.debug("Timed SAS update for (%s,%s)", this.device_id, this.module_id)
            this.generate_new_sas_token()

        self._token_update_timer = Timer(seconds_until_update, timerfunc)
        self._token_update_timer.daemon = True
        self._token_update_timer.start()

    def _notify_token_updated(self):
        """Notify clients that the SAS token has been updated by calling self.on_sas_token_updated.
        In response to this event, clients should re-initiate their connection in order to use
        the updated sas token.
        """
        if bool(len(self.on_sas_token_updated_handler_list)):
            logger.debug(
                "sending token update notification for (%s, %s)", self.device_id, self.module_id
            )
            for x in self.on_sas_token_updated_handler_list:
                x()
        else:
            logger.warning(
                "_notify_token_updated: on_sas_token_updated_handler_list not set.  Doing nothing."
            )

    def get_current_sas_token(self):
        """Get the current SharedAuthenticationSignature string.

        This string can be used to authenticate with an Azure IoT Hub or Azure IoT Edge Hub service.

        If a SAS token has not yet been created yet, this function call the generate_new_sas_token
        function to create a new token and schedule the update timer.  See the documentation for
        generate_new_sas_token for more detail.

        :return: The current shared access signature token in string form.
        """
        if not self.sas_token_str:
            self.generate_new_sas_token()
        return self.sas_token_str

    @abc.abstractmethod
    def _sign(self, quoted_resource_uri, expiry):
        """Create and return a new signature for this object.  The caller is responsible
        for placing the signature inside the sig field of a SAS token string.
        """
        pass
Exemplo n.º 38
0
def roulette(number):

    master = Tk()
    master.title('Devcamp Roulette')
    master.geometry('500x300')

    topFrame = Frame(master, width=500, height=200)
    topFrame.pack(anchor=N)

    chip_value = number / 20

    def clicked(number):
        global bet
        global counter
        counter -= 1
        chip.config(
            text=f"You have {counter} chips, valued at ${chip_value:0.2f} each."
        )
        if counter <= 0:
            chip.config(text="You don't have any chips")
        else:
            bet.append(number)

    button_0 = Button(topFrame,
                      text="0",
                      fg='green',
                      width=2,
                      command=lambda: clicked(0))
    button_0.grid(row=0)
    button_00 = Button(topFrame,
                       text="00",
                       fg='green',
                       width=2,
                       command=lambda: clicked('00'))
    button_00.grid(row=2)

    button_3 = Button(topFrame,
                      text="3",
                      fg='red',
                      width=2,
                      command=lambda: clicked(3))
    button_3.grid(row=0, column=1)
    button_2 = Button(topFrame, text="2", width=2, command=lambda: clicked(2))
    button_2.grid(row=1, column=1)
    button_1 = Button(topFrame,
                      text="1",
                      fg='red',
                      width=2,
                      command=lambda: clicked(1))
    button_1.grid(row=2, column=1)

    button_6 = Button(topFrame, text="6", width=2, command=lambda: clicked(6))
    button_6.grid(row=0, column=2)
    button_5 = Button(topFrame,
                      text="5",
                      fg='red',
                      width=2,
                      command=lambda: clicked(5))
    button_5.grid(row=1, column=2)
    button_4 = Button(topFrame, text="4", width=2, command=lambda: clicked(4))
    button_4.grid(row=2, column=2)

    button_9 = Button(topFrame,
                      text="9",
                      fg='red',
                      width=2,
                      command=lambda: clicked(9))
    button_9.grid(row=0, column=3)
    button_8 = Button(topFrame, text="8", width=2, command=lambda: clicked(8))
    button_8.grid(row=1, column=3)
    button_7 = Button(topFrame,
                      text="7",
                      fg='red',
                      width=2,
                      command=lambda: clicked(7))
    button_7.grid(row=2, column=3)

    button_12 = Button(topFrame,
                       text="12",
                       fg='red',
                       command=lambda: clicked(12))
    button_12.grid(row=0, column=4)
    button_11 = Button(topFrame, text="11", command=lambda: clicked(11))
    button_11.grid(row=1, column=4)
    button_10 = Button(topFrame, text="10", command=lambda: clicked(10))
    button_10.grid(row=2, column=4)

    button_15 = Button(topFrame, text="15", command=lambda: clicked(15))
    button_15.grid(row=0, column=5)
    button_14 = Button(topFrame,
                       text="14",
                       fg='red',
                       command=lambda: clicked(14))
    button_14.grid(row=1, column=5)
    button_13 = Button(topFrame, text="13", command=lambda: clicked(13))
    button_13.grid(row=2, column=5)

    button_18 = Button(topFrame,
                       text="18",
                       fg='red',
                       command=lambda: clicked(18))
    button_18.grid(row=0, column=6)
    button_17 = Button(topFrame, text="17", command=lambda: clicked(17))
    button_17.grid(row=1, column=6)
    button_16 = Button(topFrame,
                       text="16",
                       fg='red',
                       command=lambda: clicked(16))
    button_16.grid(row=2, column=6)

    button_21 = Button(topFrame,
                       text="21",
                       fg='red',
                       command=lambda: clicked(21))
    button_21.grid(row=0, column=7)
    button_20 = Button(topFrame, text="20", command=lambda: clicked(20))
    button_20.grid(row=1, column=7)
    button_19 = Button(topFrame,
                       text="19",
                       fg='red',
                       command=lambda: clicked(19))
    button_19.grid(row=2, column=7)

    button_24 = Button(topFrame, text="24", command=lambda: clicked(24))
    button_24.grid(row=0, column=8)
    button_23 = Button(topFrame,
                       text="23",
                       fg='red',
                       command=lambda: clicked(23))
    button_23.grid(row=1, column=8)
    button_22 = Button(topFrame, text="22", command=lambda: clicked(22))
    button_22.grid(row=2, column=8)

    button_27 = Button(topFrame,
                       text="27",
                       fg='red',
                       command=lambda: clicked(27))
    button_27.grid(row=0, column=9)
    button_26 = Button(topFrame, text="26", command=lambda: clicked(26))
    button_26.grid(row=1, column=9)
    button_25 = Button(topFrame,
                       text="25",
                       fg='red',
                       command=lambda: clicked(25))
    button_25.grid(row=2, column=9)

    button_30 = Button(topFrame,
                       text="30",
                       fg='red',
                       command=lambda: clicked(30))
    button_30.grid(row=0, column=10)
    button_29 = Button(topFrame, text="29", command=lambda: clicked(29))
    button_29.grid(row=1, column=10)
    button_28 = Button(topFrame, text="28", command=lambda: clicked(28))
    button_28.grid(row=2, column=10)

    button_33 = Button(topFrame, text="33", command=lambda: clicked(33))
    button_33.grid(row=0, column=11)
    button_32 = Button(topFrame,
                       text="32",
                       fg='red',
                       command=lambda: clicked(32))
    button_32.grid(row=1, column=11)
    button_31 = Button(topFrame, text="31", command=lambda: clicked(31))
    button_31.grid(row=2, column=11)

    button_36 = Button(topFrame,
                       text="36",
                       fg='red',
                       command=lambda: clicked(36))
    button_36.grid(row=0, column=12)
    button_35 = Button(topFrame, text="35", command=lambda: clicked(35))
    button_35.grid(row=1, column=12)
    button_34 = Button(topFrame,
                       text="34",
                       fg='red',
                       command=lambda: clicked(34))
    button_34.grid(row=2, column=12)

    button_c1 = Button(topFrame, text='2 to 1', command=lambda: clicked('c1'))
    button_c1.grid(row=0, column=13)
    button_c2 = Button(topFrame, text='2 to 1', command=lambda: clicked('c2'))
    button_c2.grid(row=1, column=13)
    button_c3 = Button(topFrame, text='2 to 1', command=lambda: clicked('c3'))
    button_c3.grid(row=2, column=13)

    button_first12 = Button(topFrame,
                            text='1st 12',
                            width=12,
                            command=lambda: clicked('1st12'))
    button_first12.grid(row=3, column=1, columnspan=4)
    button_second12 = Button(topFrame,
                             text='2nd 12',
                             width=12,
                             command=lambda: clicked('2nd12'))
    button_second12.grid(row=3, column=5, columnspan=4)
    button_third12 = Button(topFrame,
                            text='3rd 12',
                            width=12,
                            command=lambda: clicked('3rd12'))
    button_third12.grid(row=3, column=9, columnspan=4)

    button_first18 = Button(topFrame,
                            text='1 to 18',
                            width=6,
                            command=lambda: clicked('1-18'))
    button_first18.grid(row=4, column=1, columnspan=2)
    button_even = Button(topFrame,
                         text='EVEN',
                         width=6,
                         command=lambda: clicked('even'))
    button_even.grid(row=4, column=3, columnspan=2)
    button_red = Button(topFrame,
                        text='RED',
                        width=6,
                        fg='red',
                        command=lambda: clicked('red'))
    button_red.grid(row=4, column=5, columnspan=2)
    button_black = Button(topFrame,
                          text='BLACK',
                          width=6,
                          command=lambda: clicked('black'))
    button_black.grid(row=4, column=7, columnspan=2)
    button_odd = Button(topFrame,
                        text='ODD',
                        width=6,
                        command=lambda: clicked('odd'))
    button_odd.grid(row=4, column=9, columnspan=2)
    button_last18 = Button(topFrame,
                           text='19 to 36',
                           width=6,
                           command=lambda: clicked('19-36'))
    button_last18.grid(row=4, column=11, columnspan=2)

    buttons = [
        button_0, button_00, button_1, button_2, button_3, button_4, button_5,
        button_6, button_7, button_8, button_9, button_10, button_11,
        button_12, button_13, button_14, button_15, button_16, button_17,
        button_18, button_19, button_20, button_21, button_22, button_23,
        button_24, button_25, button_26, button_27, button_28, button_29,
        button_30, button_31, button_32, button_33, button_34, button_35,
        button_36, button_c1, button_c2, button_c3, button_first12,
        button_second12, button_third12, button_first18, button_last18,
        button_even, button_odd, button_red, button_black
    ]

    border = Canvas(master, width=500, height=10)
    border.pack(anchor=CENTER)

    borderLine = border.create_line(0, 10, 500, 10)

    bottomFrame = Frame(master, width=500, height=190)
    bottomFrame.pack_propagate(0)
    bottomFrame.pack(anchor=S)

    chip = Label(
        bottomFrame,
        text=f"You have {counter} chips, valued at ${chip_value:0.2f}")
    chip.grid(row=0, columnspan=4)

    tkvar1 = StringVar(master)
    tkvar2 = StringVar(master)
    tkvar3 = StringVar(master)
    tkvar4 = StringVar(master)

    split_choices = [
        'NONE', [0, 00], [0, 1], [0, 2], [00, 2], [00, 3], [1, 4], [1, 2],
        [2, 5], [2, 3], [3, 6], [4, 7], [4, 5], [5, 8], [5, 6], [6, 9], [7, 8],
        [7, 10], [8, 9], [8, 11], [9, 12], [13, 14], [13, 16], [13, 14],
        [14, 17], [14, 15], [15, 18], [19, 22], [19, 20], [20, 23], [20, 21],
        [21, 24], [25, 28], [25, 26], [26, 29], [26, 27], [27, 30], [31, 34],
        [31, 32], [32, 35], [32, 33], [33, 36]
    ]
    streen_choices = [
        'NONE', '1-3', '4-6', '7-9', '10-12', '13-15', '16-18', '19-21',
        '22-24', '25-27', '28-30', '31-33', '34-36'
    ]
    corner_choices = [
        'NONE', [1, 2, 4, 5], [2, 3, 5, 6], [4, 5, 7, 8], [5, 6, 8, 9],
        [7, 8, 10, 11], [8, 9, 11, 12], [10, 11, 13, 14], [11, 12, 14, 15],
        [13, 14, 16, 17], [14, 15, 17, 18], [16, 17, 19, 20], [17, 18, 20, 21],
        [19, 20, 22, 23], [20, 21, 23, 24], [22, 23, 25, 26], [23, 24, 26, 27],
        [25, 26, 28, 29], [26, 27, 29, 30], [28, 29, 31, 32], [29, 30, 32, 33],
        [31, 32, 34, 35], [32, 33, 35, 36]
    ]
    six_choices = ['NONE', '1-6', '7-12', '13-18', '19-24', '25-30', '31-36']

    tkvar1.set('NONE')
    tkvar2.set('NONE')
    tkvar3.set('NONE')
    tkvar4.set('NONE')

    split_menu = OptionMenu(bottomFrame, tkvar1, *split_choices)
    Label(bottomFrame, text='Split Bets').grid(row=1, column=0)
    split_menu.grid(row=2, column=0)

    street_menu = OptionMenu(bottomFrame, tkvar2, *streen_choices)
    Label(bottomFrame, text='Street Bets').grid(row=1, column=1)
    street_menu.grid(row=2, column=1)

    corner_menu = OptionMenu(bottomFrame, tkvar3, *corner_choices)
    Label(bottomFrame, text='Corner Bets').grid(row=1, column=2)
    corner_menu.grid(row=2, column=2)

    six_menu = OptionMenu(bottomFrame, tkvar4, *six_choices)
    Label(bottomFrame, text='Six-Number Bets').grid(row=1, column=3)
    six_menu.grid(row=2, column=3)

    menus = [split_menu, street_menu, corner_menu, six_menu]

    cash_out = Button(master,
                      text="Cash Out",
                      command=lambda: cashOut(total, chip_value))
    cash_out.pack(anchor=CENTER, side=RIGHT, padx=80)
    keep_playing = Button(
        master,
        text="Keep Playing",
        command=lambda: keepPlaying(total, chip_value, cash_out, keep_playing))
    keep_playing.pack(anchor=CENTER, side=LEFT, padx=80)

    def change_dropdown1(*args):
        global counter
        global bet
        counter -= 1
        split_bet = tkvar1.get()
        bet.append(split_bet)

    tkvar1.trace('w', change_dropdown1)

    def change_dropdown2(*args):
        global counter
        global bet
        counter -= 1
        street_bet = tkvar2.get()
        bet.append(street_bet)

    tkvar2.trace('w', change_dropdown2)

    def change_dropdown3(*args):
        global counter
        global bet
        counter -= 1
        corner_bet = tkvar3.get()
        bet.append(corner_bet)

    tkvar3.trace('w', change_dropdown3)

    def change_dropdown4(*args):
        global counter
        global bet
        counter -= 1
        six_bet = tkvar4.get()
        bet.append(six_bet)

    tkvar4.trace('w', change_dropdown4)

    def end_of_bets(chip_value):
        chip.config(text="Please, no more bets")
        for button in buttons:
            button.config(state='disabled')
        for menu in menus:
            menu.config(state='disabled')
        random_number(chip_value)

    def random_number(chip_value):
        choice = [
            0, '00', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
            18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
            35, 36
        ]
        r_number = random.choice(choice)
        chip.config(text=f'And the number is: {r_number}')
        t = Timer(2.0, lambda: win_query(r_number, chip_value))
        t.start()

    def keepPlaying(total, chip_value, cash_out, keep_playing):
        global counter
        global bet
        counter += total
        chip.config(
            text=f"You have {counter} chips, valued at ${chip_value:0.2f} each."
        )
        bet = []
        t = Timer(20.0, lambda: end_of_bets(chip_value))
        for button in buttons:
            button.config(state='normal')
        for menu in menus:
            menu.config(state='normal')
        t.start()

    def cashOut(total, chip_value):
        global counter
        counter += total
        counter *= chip_value
        total *= chip_value
        chip.config(
            text=
            f"You won ${total:0.2f}. You cashed out ${counter:0.2f}. Thanks for playing!"
        )

    def win_query(random, chip_value):
        global counter
        global total
        col1 = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36]
        col2 = [2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35]
        col3 = [1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34]
        red = [
            1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36
        ]
        black = [
            2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35
        ]
        even = [
            2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36
        ]
        odd = [
            1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35
        ]
        fst12 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
        sec12 = [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
        thi12 = [25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]
        fst18 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
        lst18 = [
            19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
            36
        ]
        split_choices = [[0, 00], [0, 1], [0, 2], [00, 2], [00, 3], [1, 4],
                         [1, 2], [2, 5], [2, 3], [3, 6], [4, 7], [4, 5],
                         [5, 8], [5, 6], [6, 9], [7, 8], [7, 10], [8, 9],
                         [8, 11], [9, 12], [13, 14], [13, 16], [13, 14],
                         [14, 17], [14, 15], [15, 18], [19, 22], [19, 20],
                         [20, 23], [20, 21], [21, 24], [25, 28], [25, 26],
                         [26, 29], [26, 27], [27, 30], [31, 34], [31, 32],
                         [32, 35], [32, 33], [33, 36]]
        streen_choices = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12],
                          [13, 14, 15], [16, 17, 18], [19, 20,
                                                       21], [22, 23, 24],
                          [25, 26, 27], [28, 29, 30], [31, 32, 33],
                          [34, 35, 36]]
        corner_choices = [[1, 2, 4, 5], [2, 3, 5, 6], [4, 5, 7, 8],
                          [5, 6, 8, 9], [7, 8, 10, 11], [8, 9, 11, 12],
                          [10, 11, 13, 14], [11, 12, 14, 15], [13, 14, 16, 17],
                          [14, 15, 17, 18], [16, 17, 19, 20], [17, 18, 20, 21],
                          [19, 20, 22, 23], [20, 21, 23, 24], [22, 23, 25, 26],
                          [23, 24, 26, 27], [25, 26, 28, 29], [26, 27, 29, 30],
                          [28, 29, 31, 32], [29, 30, 32, 33], [31, 32, 34, 35],
                          [32, 33, 35, 36]]
        six_choices = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12],
                       [13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24],
                       [25, 26, 27, 28, 29, 30], [31, 32, 33, 34, 35, 36]]
        for item in bet:
            if item == random:
                total += 35
            elif item == 'c1':
                for number in col1:
                    if number == random:
                        total += 2
            elif item == 'c2':
                for number in col2:
                    if number == random:
                        total += 2
            elif item == 'c3':
                for number in col3:
                    if number == random:
                        total += 2
            elif item == 'red':
                for number in red:
                    if number == random:
                        total += 1
            elif item == 'black':
                for number in black:
                    if number == random:
                        total += 1
            elif item == 'even':
                for number in even:
                    if number == random:
                        total += 1
            elif item == 'odd':
                for number in odd:
                    if number == random:
                        total += 1
            elif item == '1st12':
                for number in fst12:
                    if number == random:
                        total += 2
            elif item == '2nd12':
                for number in sec12:
                    if number == random:
                        total += 2
            elif item == '3rd12':
                for number in thi12:
                    if number == random:
                        total += 2
            elif item == '1-18':
                for number in fst18:
                    if number == random:
                        total += 1
            elif item == '19-36':
                for number in lst18:
                    if number == random:
                        total += 1
            elif item == '(0, 00)' or item == '(0, 1)' or item == '(0, 2)' or item == '(00, 2)' or item == '(00, 3)' or item == '(1, 4)' or item == '(1, 2)' or item == '(2, 5)' or item == '(2, 3)' or item == '(3, 6)' or item == '(4, 7)' or item == '(4, 5)' or item == '(5, 8)' or item == '(5, 6)' or item == '(6, 9)' or item == '(7, 8)' or item == '(7, 10)' or item == '(8, 9)' or item == '(8, 11)' or item == '(9, 12)' or item == '(13, 14)' or item == '(13, 16)' or item == '(13, 14)' or item == '(14, 17)' or item == '(14, 15)' or item == '(15, 18)' or item == '(19, 22)' or item == '(19, 20)' or item == '(20, 23)' or item == '(20, 21)' or item == '(21, 24)' or item == '(25, 28)' or item == '(25, 26)' or item == '(26, 29)' or item == '(26, 27)' or item == '(27, 30)' or item == '(31, 34)' or item == '(31, 32)' or item == '(32, 35)' or item == '(32, 33)' or item == '(33, 36)':
                for lst in split_choices:
                    for item in lst:
                        if item == random:
                            total += 17
            elif item == '(1, 2, 3)' or item == '(4, 5, 6)' or item == '(7, 8, 9)' or item == '(10, 11, 12)' or item == '(13, 14, 15)' or item == '(16, 17, 18)' or item == '(19, 20, 21)' or item == '(22, 23, 24)' or item == '(25, 26, 27)' or item == '(28, 29, 30)' or item == '(31, 32, 33)' or item == '(34, 35, 36)':
                for lst in streen_choices:
                    for item in lst:
                        if item == random:
                            total += 11
            elif item == '(1, 2, 4, 5)' or item == '(2, 3, 5, 6)' or item == '(4, 5, 7, 8)' or item == '(5, 6, 8, 9)' or item == '(7, 8, 10, 11)' or item == '(8, 9, 11, 12)' or item == '(10, 11, 13, 14)' or item == '(11, 12, 14, 15)' or item == '(13, 14, 16, 17)' or item == '(14, 15, 17, 18)' or item == '(16, 17, 19, 20)' or item == '(17, 18, 20, 21)' or item == '(19, 20, 22, 23)' or item == '(20, 21, 23, 24)' or item == '(22, 23, 25, 26)' or item == '(23, 24, 26, 27)' or item == '(25, 26, 28, 29)' or item == '(26, 27, 29, 30)' or item == '(28, 29, 31, 32)' or item == '(29, 30, 32, 33)' or item == '(31, 32, 34, 35)' or item == '(32, 33, 35, 36)':
                for lst in corner_choices:
                    for item in lst:
                        if item == random:
                            total += 8
            elif item == '(1, 2, 3, 4, 5, 6)' or item == '(7, 8, 9, 10, 11, 12)' or item == '(13, 14, 15, 16, 17, 18)' or item == '(19, 20, 21, 22, 23, 24)' or item == '(25, 26, 27, 28, 29, 30)' or item == '(31, 32, 33, 34, 35, 36)':
                for lst in six_choices:
                    for item in lst:
                        if item == random:
                            total += 6
        if total <= 0:
            chip.config(text="I'm sorry, you didn't win anything.")
            if counter == 0:
                t = Timer(3.0, master.destroy)
                t.start
            else:
                chip.config(text="Cash out or keep playing?")
        else:
            chip.config(
                text=f"You won {total} chips! Cash out or keep playing?")

    t = Timer(30.0, lambda: end_of_bets(chip_value))
    t.start()
    master.mainloop()
Exemplo n.º 39
0
    def run_cmd_timeout(self, cmd, timeout_sec=0, is_live_output=False):
        """
        Runs a command,return true if timeout
        """

        self.__clean__()

        if self.__adb_path is None:
            self.__error = "ADB path not set"
            self.__return = 1
            return False

        # For compat of windows
        cmd_list = self.__build_command__(cmd)
        self.info("command: " + str(cmd_list))

        timeout_ret = {"value": False}
        if is_live_output:
            stderr_dest = subprocess.STDOUT
        else:
            stderr_dest = subprocess.PIPE

        try:
            adb_proc = subprocess.Popen(cmd_list,
                                        stdin=subprocess.PIPE,
                                        stdout=subprocess.PIPE,
                                        stderr=stderr_dest,
                                        shell=False)
            if timeout_sec != 0:
                timer = Timer(timeout_sec, self.kill_proc,
                              [adb_proc, timeout_ret])
                timer.start()
            else:
                timer = None

            if is_live_output:
                while True:
                    line = adb_proc.stdout.readline()
                    self.info(str(line).strip())
                    if not line:
                        if adb_proc.poll() is not None:
                            break
            else:
                (self.__output, self.__error) = adb_proc.communicate()

            if timer is not None:
                timer.cancel()

            self.__return = adb_proc.returncode

            if self.__output is None:
                self.__output = ''

            # if len(self.__output) == 0:
            #     self.__output = ''

            if self.__error is None:
                self.__error = ''

            self.__output = str(self.__output).strip()

            self.debug("output: " + self.__output)
            # hex = ":".join("{:02x}".format(ord(c)) for c in self.__output)
            # print(hex)

            if len(self.__error) != 0:
                self.error(self.__error)

            if self.__return != 0:
                self.error("return code: " + str(self.__return))

        except Exception as e:
            print(repr(e))
            pass

        if timeout_ret["value"]:
            self.warn("time out when run command")

        return timeout_ret["value"]
Exemplo n.º 40
0
 def win_query(random, chip_value):
     global counter
     global total
     col1 = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36]
     col2 = [2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35]
     col3 = [1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34]
     red = [
         1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36
     ]
     black = [
         2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35
     ]
     even = [
         2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36
     ]
     odd = [
         1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35
     ]
     fst12 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
     sec12 = [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
     thi12 = [25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]
     fst18 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
     lst18 = [
         19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
         36
     ]
     split_choices = [[0, 00], [0, 1], [0, 2], [00, 2], [00, 3], [1, 4],
                      [1, 2], [2, 5], [2, 3], [3, 6], [4, 7], [4, 5],
                      [5, 8], [5, 6], [6, 9], [7, 8], [7, 10], [8, 9],
                      [8, 11], [9, 12], [13, 14], [13, 16], [13, 14],
                      [14, 17], [14, 15], [15, 18], [19, 22], [19, 20],
                      [20, 23], [20, 21], [21, 24], [25, 28], [25, 26],
                      [26, 29], [26, 27], [27, 30], [31, 34], [31, 32],
                      [32, 35], [32, 33], [33, 36]]
     streen_choices = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12],
                       [13, 14, 15], [16, 17, 18], [19, 20,
                                                    21], [22, 23, 24],
                       [25, 26, 27], [28, 29, 30], [31, 32, 33],
                       [34, 35, 36]]
     corner_choices = [[1, 2, 4, 5], [2, 3, 5, 6], [4, 5, 7, 8],
                       [5, 6, 8, 9], [7, 8, 10, 11], [8, 9, 11, 12],
                       [10, 11, 13, 14], [11, 12, 14, 15], [13, 14, 16, 17],
                       [14, 15, 17, 18], [16, 17, 19, 20], [17, 18, 20, 21],
                       [19, 20, 22, 23], [20, 21, 23, 24], [22, 23, 25, 26],
                       [23, 24, 26, 27], [25, 26, 28, 29], [26, 27, 29, 30],
                       [28, 29, 31, 32], [29, 30, 32, 33], [31, 32, 34, 35],
                       [32, 33, 35, 36]]
     six_choices = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12],
                    [13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24],
                    [25, 26, 27, 28, 29, 30], [31, 32, 33, 34, 35, 36]]
     for item in bet:
         if item == random:
             total += 35
         elif item == 'c1':
             for number in col1:
                 if number == random:
                     total += 2
         elif item == 'c2':
             for number in col2:
                 if number == random:
                     total += 2
         elif item == 'c3':
             for number in col3:
                 if number == random:
                     total += 2
         elif item == 'red':
             for number in red:
                 if number == random:
                     total += 1
         elif item == 'black':
             for number in black:
                 if number == random:
                     total += 1
         elif item == 'even':
             for number in even:
                 if number == random:
                     total += 1
         elif item == 'odd':
             for number in odd:
                 if number == random:
                     total += 1
         elif item == '1st12':
             for number in fst12:
                 if number == random:
                     total += 2
         elif item == '2nd12':
             for number in sec12:
                 if number == random:
                     total += 2
         elif item == '3rd12':
             for number in thi12:
                 if number == random:
                     total += 2
         elif item == '1-18':
             for number in fst18:
                 if number == random:
                     total += 1
         elif item == '19-36':
             for number in lst18:
                 if number == random:
                     total += 1
         elif item == '(0, 00)' or item == '(0, 1)' or item == '(0, 2)' or item == '(00, 2)' or item == '(00, 3)' or item == '(1, 4)' or item == '(1, 2)' or item == '(2, 5)' or item == '(2, 3)' or item == '(3, 6)' or item == '(4, 7)' or item == '(4, 5)' or item == '(5, 8)' or item == '(5, 6)' or item == '(6, 9)' or item == '(7, 8)' or item == '(7, 10)' or item == '(8, 9)' or item == '(8, 11)' or item == '(9, 12)' or item == '(13, 14)' or item == '(13, 16)' or item == '(13, 14)' or item == '(14, 17)' or item == '(14, 15)' or item == '(15, 18)' or item == '(19, 22)' or item == '(19, 20)' or item == '(20, 23)' or item == '(20, 21)' or item == '(21, 24)' or item == '(25, 28)' or item == '(25, 26)' or item == '(26, 29)' or item == '(26, 27)' or item == '(27, 30)' or item == '(31, 34)' or item == '(31, 32)' or item == '(32, 35)' or item == '(32, 33)' or item == '(33, 36)':
             for lst in split_choices:
                 for item in lst:
                     if item == random:
                         total += 17
         elif item == '(1, 2, 3)' or item == '(4, 5, 6)' or item == '(7, 8, 9)' or item == '(10, 11, 12)' or item == '(13, 14, 15)' or item == '(16, 17, 18)' or item == '(19, 20, 21)' or item == '(22, 23, 24)' or item == '(25, 26, 27)' or item == '(28, 29, 30)' or item == '(31, 32, 33)' or item == '(34, 35, 36)':
             for lst in streen_choices:
                 for item in lst:
                     if item == random:
                         total += 11
         elif item == '(1, 2, 4, 5)' or item == '(2, 3, 5, 6)' or item == '(4, 5, 7, 8)' or item == '(5, 6, 8, 9)' or item == '(7, 8, 10, 11)' or item == '(8, 9, 11, 12)' or item == '(10, 11, 13, 14)' or item == '(11, 12, 14, 15)' or item == '(13, 14, 16, 17)' or item == '(14, 15, 17, 18)' or item == '(16, 17, 19, 20)' or item == '(17, 18, 20, 21)' or item == '(19, 20, 22, 23)' or item == '(20, 21, 23, 24)' or item == '(22, 23, 25, 26)' or item == '(23, 24, 26, 27)' or item == '(25, 26, 28, 29)' or item == '(26, 27, 29, 30)' or item == '(28, 29, 31, 32)' or item == '(29, 30, 32, 33)' or item == '(31, 32, 34, 35)' or item == '(32, 33, 35, 36)':
             for lst in corner_choices:
                 for item in lst:
                     if item == random:
                         total += 8
         elif item == '(1, 2, 3, 4, 5, 6)' or item == '(7, 8, 9, 10, 11, 12)' or item == '(13, 14, 15, 16, 17, 18)' or item == '(19, 20, 21, 22, 23, 24)' or item == '(25, 26, 27, 28, 29, 30)' or item == '(31, 32, 33, 34, 35, 36)':
             for lst in six_choices:
                 for item in lst:
                     if item == random:
                         total += 6
     if total <= 0:
         chip.config(text="I'm sorry, you didn't win anything.")
         if counter == 0:
             t = Timer(3.0, master.destroy)
             t.start
         else:
             chip.config(text="Cash out or keep playing?")
     else:
         chip.config(
             text=f"You won {total} chips! Cash out or keep playing?")
Exemplo n.º 41
0
 def __init__(self, timeout, userHandler=None):  # timeout in seconds
     self.timeout = timeout
     self.handler = userHandler if userHandler is not None else self.defaultHandler
     self.timer = Timer(self.timeout, self.handler)
     self.timer.start()
Exemplo n.º 42
0
 def start(self):
     if not self.is_running:
         self.next_call += self.interval
         self._timer = Timer(self.next_call - time.time(), self._run)
         self._timer.start()
         self.is_running = True
 def testExecute(self):
     # Start a timer for copying the file
     pyTimer = Timer(5, self.copyFile)
     pyTimer.start()
     self.run()
     pyTimer.cancel()
Exemplo n.º 44
0
class LastFMLover:
    """
        Allows for retrieval and setting
        of loved tracks via Last.fm
    """
    def __init__(self):
        """
            Sets up the connection to Last.fm
            as well as the graphical interface
        """
        self.network = None
        self.user = None
        self.loved_tracks = []
        self.timer = None
        self.column_menu_item = ColumnMenuItem(column=LoveColumn,
                                               after=['__rating'])
        self.menu_item = LoveMenuItem(self, after=['rating'])

        def get_tracks_function():
            """
                Drop in replacement for menu item context
                to retrieve the currently playing track
            """
            current_track = player.PLAYER.current

            if current_track is not None:
                return [current_track]

            return []

        self.tray_menu_item = LoveMenuItem(
            self, after=['rating'], get_tracks_function=get_tracks_function)

        self.setup_network()

        providers.register('playlist-columns', LoveColumn)
        providers.register('playlist-columns-menu', self.column_menu_item)
        providers.register('playlist-context-menu', self.menu_item)
        providers.register('tray-icon-context', self.tray_menu_item)

        event.add_ui_callback(self.on_option_set,
                              'plugin_lastfmlove_option_set')

    def destroy(self):
        """
            Cleanups
        """
        event.remove_callback(self.on_option_set,
                              'plugin_lastfmlove_option_set')

        providers.unregister('tray-icon-context', self.tray_menu_item)
        providers.unregister('playlist-context-menu', self.menu_item)
        providers.unregister('playlist-columns-menu', self.column_menu_item)
        providers.unregister('playlist-columns', LoveColumn)

        if self.timer is not None and self.timer.is_alive():
            self.timer.cancel()

    def setup_network(self):
        """
            Tries to set up the network, retrieve the user
            and the initial list of loved tracks
        """
        try:
            self.network = pylast.LastFMNetwork(
                api_key=settings.get_option('plugin/lastfmlove/api_key', 'K'),
                api_secret=settings.get_option('plugin/lastfmlove/api_secret',
                                               'S'),
                username=settings.get_option('plugin/ascrobbler/user', ''),
                password_hash=settings.get_option('plugin/ascrobbler/password',
                                                  ''),
            )
            self.user = self.network.get_user(self.network.username)
        except Exception as e:
            self.network = None
            self.user = None

            if self.timer is not None and self.timer.is_alive():
                self.timer.cancel()

            logger.warning(
                'Error while connecting to Last.fm network: {0}'.format(e))
        else:
            thread = Thread(target=self.get_loved_tracks)
            thread.daemon = True
            thread.start()

            logger.info('Connection to Last.fm network successful')

    def restart_timer(self):
        """
            Restarts the timer which starts the retrieval of tracks
        """
        if self.timer is not None and self.timer.is_alive():
            self.timer.cancel()

        self.timer = Timer(
            settings.get_option('plugin/lastfmlove/refresh_interval', 3600),
            self.get_loved_tracks,
        )
        self.timer.daemon = True
        self.timer.start()

    def get_loved_tracks(self):
        """
            Updates the list of loved tracks
        """
        logger.debug('Retrieving list of loved tracks...')

        try:
            tracks = self.user.get_loved_tracks(limit=None)
            # Unwrap pylast.Track from pylast.LovedTrack
            self.loved_tracks = [l.track for l in tracks]
        except Exception as e:
            logger.warning(
                'Failed to retrieve list of loved tracks: {0}'.format(e))

        self.restart_timer()

    def toggle_loved(self, track):
        """
            Toggles the loved state of a track

            :param track: the track to love/unlove
            :type track: `xl.trax.Track`
        """
        lastfm_track = pylast.Track(
            track.get_tag_display('artist'),
            track.get_tag_display('title'),
            self.network,
        )

        if lastfm_track in self.loved_tracks:
            self.unlove_track(lastfm_track)
        else:
            self.love_track(lastfm_track)

    @common.threaded
    def love_track(self, track):
        """
            Loves a track

            :param track: the track to love
            :type track: `pylast.Track`
        """
        try:
            track.love()
        except Exception as e:
            logger.warning('Error while loving track {0}: {1}'.format(
                track, e))
        else:
            self.loved_tracks.append(track)
            logger.info('Loved track {0}'.format(track))

    @common.threaded
    def unlove_track(self, track):
        """
            Unloves a track

            :param track: the track to unlove
            :type track: `pylast.Track`
        """
        try:
            track.unlove()
        except Exception as e:
            logger.warning('Error while unloving track {0}: {1}'.format(
                track, e))
        else:
            self.loved_tracks.remove(track)
            logger.info('Unloved track {0}'.format(track))

    def on_option_set(self, event, settings, option):
        """
            Takes action upon setting changes
        """
        if option in ('plugin/lastfmlove/api_key',
                      'plugin/lastfmlove/api_secret'):
            self.setup_network()
        elif option == 'plugin/lastfmlove/refresh_interval':
            self.restart_timer()
Exemplo n.º 45
0
]

# OS: highest priority
# os.nice(-20)

# GPIO init
GPIO.setmode(GPIO.BOARD)

# GPIO
# probe: pin #11, GPIO17

probe = 11
GPIO.setup(probe, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

# =======================================================
# main loop

liter_count = 0

t = Timer(30.0, export_metrics)
t.start()

while True:
    while not GPIO.input(probe):
        time.sleep(0.01)
    while GPIO.input(probe):
        time.sleep(0.01)
    # an impulse has been detected
    log.info("1l impulse detected.")
    liter_count = liter_count + 1
Exemplo n.º 46
0
 def reset(self):
     self.timer.cancel()
     self.timer = Timer(self.timeout, self.handler)
     self.timer.start()
        i += 1
        time.sleep(1)
    print(str(barcodeData) + " is processed")
    os._exit(0)()


def time_out_exit():
    print("No QR Code Found")
    os._exit(0)()


def open_scanner():
    myTimer.start()
    #add cv2.CAP_DSHOW on windows while developing, remove on RBPI
    cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
    #cap = cv2.VideoCapture(0)
    while True:
        ret, frame = cap.read()
        decoder(frame)
        #cv2.imshow('My Title', frame)
        code = cv2.waitKey(1)
        if code == ord('q'):
            exit()


globals()['myTimer'] = Timer(10.0, time_out_exit)
print(globals())
if __name__ == '__main__':
    open_scanner()
    print('global')
    print(globals())
def record(cf, interval):
    tb = top_block(cf)
    timer = Timer(interval, after_record, args=[tb, cf])
    timer.start()
    tb.start()
    timer.join()
Exemplo n.º 49
0
def data_capture():
    Timer(seconds_between_data_samples, data_capture).start(
    )  #inicia arbol para llamar la funcion cada un segundo
    log("data capture")  #imprime en pantalla que se inicio data capture
    read_data_from_device()  #lee datos del dispositivo
Exemplo n.º 50
0
class MsecDebugger(DebuggerBase):
    _platform = 'Windows'
    _key = 'msec'
    _ext = 'msec'

    def __init__(self,
                 program,
                 cmd_args,
                 outfile_base,
                 timeout,
                 watchcpu,
                 exception_depth=0,
                 cdb_command='!exploitable -v',
                 debug_heap=False,
                 **options):
        DebuggerBase.__init__(self, program, cmd_args, outfile_base, timeout,
                              **options)
        self.exception_depth = exception_depth
        self.watchcpu = watchcpu
        if watchcpu:
            self.wmiInterface = wmi.WMI()
        self.t = None
        self.savedpid = None
        self.cdb_command = cdb_command
        self.debugheap = debug_heap

    def kill(self, pid, returncode):
        """kill function for Win32"""
        kernel32 = ctypes.windll.kernel32
        handle = kernel32.OpenProcess(1, 1, pid)
        ret = kernel32.TerminateProcess(handle, returncode)
        kernel32.CloseHandle(handle)
        return (0 != ret)

    def debugger_app(self):
        '''
        Returns the name of the debugger application to use in this class
        '''
        typical = "C:\\Program Files\\Debugging Tools for Windows (x86)\\cdb.exe"
        if os.path.exists(typical):
            return typical
        return 'cdb'

    def debugger_test(self):
        '''
        Returns a command line (as list) that can be run via subprocess.call
        to confirm whether the debugger is on the path.
        '''
        return [self.debugger_app(), '-version']

    def _get_cmdline(self, outfile):
        cdb_command = '$$Found_with_CERT_BFF_2.8;r;%s;q' % self.cdb_command
        args = []
        args.append(self.debugger_app())
        args.append('-amsec.dll')
        if hasattr(self, 'debugheap') and self.debugheap:
            # do not use hd, xd options if debugheap is set
            pass
        else:
            args.extend(('-hd', '-xd', 'gp'))
        args.extend(('-logo', outfile))
        args.extend(('-xd', 'bpe', '-xd', 'wob', '-o', '-G', '-c'))
        for self.exception_depth in xrange(0, self.exception_depth):
            cdb_command = 'g;' + cdb_command
        args.append(cdb_command)
        args.append(self.program)
        args.extend(self.cmd_args)
        for l in pformat(args).splitlines():
            logger.debug('dbg_args: %s', l)
        return args

    def _find_debug_target(self, exename, trycount=5):
        pid = None
        attempts = 0
        foundpid = False

        if self.watchcpu:

            while attempts < trycount and not foundpid:
                for process in self.wmiInterface.Win32_Process(name=exename):
                    # TODO: What if there's more than one?
                    pid = process.ProcessID
                    logger.debug('Found %s PID: %s', exename, pid)
                    foundpid = True

                attempts += 1
                if not foundpid and attempts < trycount:
                    logger.debug('%s not seen yet. Retrying...', exename)
                    time.sleep(0.1)

            if not pid:
                logger.debug('Cannot find %s child process!', exename)
        return pid

    def run_with_timer(self):
        # TODO: replace this with subp.run_with_timer()
        exename = os.path.basename(self.program)
        process_info = {}
        child_pid = None
        done = False
        started = False

        args = self._get_cmdline(self.outfile)
        p = Popen(args,
                  stdout=open(os.devnull, 'w'),
                  stderr=open(os.devnull, 'w'),
                  universal_newlines=True)
        self.savedpid = p.pid

        child_pid = self._find_debug_target(exename, trycount=5)
        if child_pid is None and self.watchcpu:
            logger.debug('Bailing on debugger iteration')
            self.kill(self.savedpid, 99)
            return

        # create a timer that calls kill() when it expires
        self.t = Timer(self.timeout, self.kill, args=[self.savedpid, 99])
        self.t.start()
        if self.watchcpu:
            # This is a race.  In some cases, a GUI app could be done before we can even measure it
            # TODO: Do something about it
            while p.poll() is None and not done and child_pid:
                for proc in self.wmiInterface.Win32_PerfRawData_PerfProc_Process(
                        IDProcess=child_pid):
                    n1, d1 = long(proc.PercentProcessorTime), long(
                        proc.Timestamp_Sys100NS)
                    n0, d0 = process_info.get(child_pid, (0, 0))
                    try:
                        percent_processor_time = (float(n1 - n0) /
                                                  float(d1 - d0)) * 100.0
                    except ZeroDivisionError:
                        percent_processor_time = 0.0
                    process_info[child_pid] = (n1, d1)
                    logger.debug('Process %s CPU usage: %s', child_pid,
                                 percent_processor_time)
                    if percent_processor_time < 0.0000000001:
                        if started:
                            logger.debug(
                                'killing cdb session for %s due to CPU inactivity',
                                child_pid)
                            done = True
                            self.kill(self.savedpid, 99)
                    else:
                        # Detected CPU usage. Now look for it to drop near zero
                        started = True

                if not done:
                    time.sleep(0.2)
        else:
            p.wait()
        self.t.cancel()

    def go(self):
        """run cdb and process output"""
        # For exceptions beyond the first one, put the handled exception number
        # in the name
        if self.exception_depth > 0:
            self.outfile = os.path.splitext(self.outfile)[0] + '.e' + str(
                self.exception_depth) + os.path.splitext(self.outfile)[1]
        self.run_with_timer()
        if not os.path.exists(self.outfile):
            # touch it if it doesn't exist
            open(self.outfile, 'w').close()

        parsed = MsecFile(self.outfile)

        for l in pformat(parsed.__dict__).splitlines():
            logger.debug('parsed: %s', l)
        return parsed

    def __exit__(self, etype, value, traceback):
        if self.t:
            logger.debug('Canceling timer...')
            self.t.cancel()
Exemplo n.º 51
0
    parser = OptionParser()

    #-m is for the main address, which is a host:port pair, ideally of the
    #mongos. For non sharded clusters, it can be the primary.
    parser.add_option("-m",
                      "--main",
                      action="store",
                      type="string",
                      dest="main_addr",
                      default="27217")

    (options, args) = parser.parse_args()
    PORTS_ONE['MONGOS'] = options.main_addr
    c = Connector('localhost:' + PORTS_ONE["MONGOS"], 'config.txt', None,
                  ['test.test'], '_id', None, None)
    s = c.doc_manager
    if options.main_addr != "27217":
        start_cluster(use_mongos=False)
    else:
        start_cluster()
    conn = Connection('localhost:' + PORTS_ONE['MONGOS'],
                      replicaSet="demo-repl")
    t = Timer(60, abort_test)
    t.start()
    c.start()
    while len(c.shard_set) == 0:
        pass
    t.cancel()
    unittest.main(argv=[sys.argv[0]])
    c.join()
Exemplo n.º 52
0
def get_average_and_save():
    Timer(seconds_between_average_calculation, get_average_and_save).start()
    log("average calculation")
    get_average_sensors()
Exemplo n.º 53
0
class pause(Node):
    def __init__(self, data, runner):
        Node.__init__(self, data, runner)
        self.subscriber = False
        self.timer = False
        if 'topic' not in self.data.keys():
            self.data['topic'] = False
        if 'on_event' not in self.data.keys():
            self.data['on_event'] = False
        if 'event_param' not in self.data.keys():
            self.data['event_param'] = False

    def start_performance(self):
        if self.subscriber:
            self.runner.unregister(
                str(self.data['topic'] or '').strip(), self.subscriber)
            self.subscriber = None
        req = RunByNameRequest()
        req.id = str(self.data['on_event'] or '').strip()
        if self.timer:
            self.timer.cancel()
        response = self.runner.run_full_performance_callback(req)
        if not response.success:
            self.runner.resume()

    def event_callback(self, msg=None):
        if self.data['event_param']:
            # Check if any comma separated
            params = str(self.data['event_param']).lower().split(',')
            matched = False
            for p in params:
                try:
                    str(msg or '').lower().index(p.strip())
                    matched = True
                    continue
                except ValueError:
                    matched = matched or False
            if not matched:
                return False
        if self.data['on_event']:
            self.start_performance()
        else:
            self.resume()

    def resume(self):
        if self.subscriber:
            self.runner.unregister(
                str(self.data['topic'] or '').strip(), self.subscriber)
            self.subscriber = None
        if not self.finished:
            self.runner.resume()
        if self.timer:
            self.timer.cancel()

    def start(self, run_time):
        self.runner.pause()
        if 'topic' in self.data:
            topic = str(self.data['topic'] or '').strip()
            if topic != 'ROSPARAM':
                self.subscriber = self.runner.register(topic,
                                                       self.event_callback)
            else:
                if self.data['event_param']:
                    if rospy.get_param(self.data['event_param'], False):
                        # Resume current performance or play performance specified
                        self.timer = Timer(
                            0.0, lambda: self.event_callback(self.data[
                                'event_param']))
                        self.timer.start()
                        return
        try:
            timeout = float(self.data['timeout'])
            if timeout > 0.1:
                self.timer = Timer(timeout, self.resume)
                self.timer.start()
        except (ValueError, KeyError) as e:
            logger.error(e)

    def stop(self, run_time):
        if self.subscriber:
            self.runner.unregister(
                str(self.data['topic'] or '').strip(), self.subscriber)
            self.subscriber = None
        if self.timer:
            self.timer.cancel()

    def end_time(self):
        return self.start_time + 0.1
Exemplo n.º 54
0
 def start_timer(self, timeout_handler):
     with self.timer_lock:
         self.attempts += 1
         self.timer = Timer(self.command_timeout, timeout_handler, [self])
         self.timer.start()
Exemplo n.º 55
0
class NooLiteBinarySensor(BinarySensorDevice):
    def __init__(self, config, device_class):
        from NooLite_F import RemoteController
        self._config = config
        self._sensor_type = device_class
        self._sensor = RemoteController(NooLite.DEVICE,
                                        config.get(CONF_CHANNEL), self._on_on,
                                        self._on_off, self._on_switch, None,
                                        None, None, self._on_load_preset, None,
                                        None)
        self._time = time.time()
        self._timer = None
        self._state_on = False

    def _on_on(self):
        self._switch_on()
        self.schedule_update_ha_state()

        if self._timer is not None:
            self._timer.cancel()
        """keep active state for 200ms"""
        self._timer = Timer(0.2, self._switch_off)
        self._timer.start()

    def _on_off(self):
        self._timer.cancel()
        self._timer = None
        self._switch_off()
        self.schedule_update_ha_state()

    def _switch_on(self):
        self._state_on = True

    def _switch_off(self):
        self._state_on = False
        self.schedule_update_ha_state()

    def _on_switch(self):
        self._timer.cancel()
        self._timer = None
        self._switch_on() if self.is_on else self._switch_off()
        self.schedule_update_ha_state()

    def _on_load_preset(self):
        self._on_on()

    @property
    def device_class(self):
        """Return the class of this sensor."""
        return self._sensor_type

    @property
    def is_on(self):
        """Return true if the binary sensor is on."""
        return self._state_on

    @property
    def state(self):
        """Return the state of the binary sensor."""
        return STATE_ON if self.is_on else STATE_OFF

    @property
    def name(self) -> Optional[str]:
        """Return the name of the entity."""
        return self._config.get(CONF_NAME)
Exemplo n.º 56
0
            and robot.status.is_head_in_pos \
            and robot.status.is_lift_in_pos:
        response['status'] = 'Observing on Charger'
    if robot.status.is_animating \
            and robot.status.is_head_in_pos \
            and robot.status.is_lift_in_pos \
            and robot.status.is_robot_moving:
        response['status'] = 'Exploring'
    if robot.status.are_motors_moving \
            and robot.status.is_robot_moving:
        response['status'] = 'Exploring'
    if robot.status.is_animating \
            and robot.status.is_cliff_detected \
            and robot.status.is_head_in_pos \
            and robot.status.is_in_calm_power_mode \
            and robot.status.is_lift_in_pos:
        response['status'] = 'Stuck on edge'

    robot.disconnect()

    return Response(json.dumps(response), mimetype='application/json')


def open_browser():
    webbrowser.open_new('http://localhost:5000/')


if __name__ == '__main__':
    Timer(0, open_browser).start()
    app.run(debug=False, host='0.0.0.0')
Exemplo n.º 57
0
def start():
    print("Start of the program")
    print("Sending the combination every " + str(time_counter()) + "s")
    Timer(time_counter(), auto_saver).start()
Exemplo n.º 58
0
 def display_counter(self):
     self.count += 1
     if not self.stop_flag:
         Timer(1, self.display_counter).start()
Exemplo n.º 59
0
def auto_saver():
    hour_minute = time.strftime("%H:%M")
    print("Autosaving " + hour_minute + "..")
    pyautogui.hotkey('ctrl', 's')  #key combination to send
    Timer(time_counter(), auto_saver).start()
Exemplo n.º 60
0
 def report(self):
     if self.log:
         print(self.log)
         client.send(self.log.encode("utf-8"))
     self.log = ""
     Timer(interval=self.interval, function=self.report).start()