Пример #1
0
    def add_data(self, x, y, axis_x_name, axis_y_name, record_unique_id_name,
                 record_unique_id_value):
        while self.uploading_data:
            # Log.logger.info("Not adding data to grid {} as it is uploading currently".format(self.grid_unique_name))
            threading._sleep(1)
        self.axis_x_name = axis_x_name
        # this column has the primary key - usually a datetime type (updated_on)
        if axis_x_name not in self.columns_cache:
            self.columns_cache[axis_x_name] = []
        if axis_y_name not in self.columns_cache:
            self.columns_cache[axis_y_name] = []
        if record_unique_id_name not in self.columns_cache:
            self.columns_cache[record_unique_id_name] = []

        self.columns_cache[axis_x_name].append(x)
        self.max_row_count = len(self.columns_cache[axis_x_name])
        # populate each columns with rows, keep no of rows identical in all columns
        for column_name in self.columns_cache.keys():
            if len(self.columns_cache[column_name]) < self.max_row_count:
                # fill in with empty rows to ensure each column has same no. of records
                while len(
                        self.columns_cache[column_name]) < self.max_row_count:
                    self.columns_cache[column_name].append(None)
            # replace last appended None value above with current y & unique record value
            if column_name == axis_y_name:
                self.columns_cache[column_name][self.max_row_count - 1] = y
            if column_name == record_unique_id_name:
                self.columns_cache[column_name][self.max_row_count -
                                                1] = record_unique_id_value
Пример #2
0
def try_reservation():
    r = Reservation(reservation_option)
    retry = True
    if r.login():
        #rogin cookie have
        waittime = datetime.datetime.now()
        wait = True
        # print curTime.hour
        while wait:
            waittime = datetime.datetime.now()
            # 6:00 start
            if waittime.hour == 6 and waittime.minute == 0:
                wait = False
            else:
                print "대기중", waittime
                threading._sleep(1)

        while retry:
            if r.get_available_time():
                if r.reserve():
                    return True
                else:
                    retry = reservation_option['try_less_time']
                    if not r.retry():
                        return True
    return False
Пример #3
0
 def run(self):
     """
         RUN is a magic name in the Threading Library
     """
     threading._sleep(self.sleeptime)
     self.funktion( *self.args)
     exit()
Пример #4
0
    def acquire(self,blocking=True,timeout=None):
        """Attempt to acquire this lock.

        If the optional argument "blocking" is True and "timeout" is None,
        this methods blocks until is successfully acquires the lock.  If
        "blocking" is False, it returns immediately if the lock could not
        be acquired.  Otherwise, it blocks for at most "timeout" seconds
        trying to acquire the lock.

        In all cases, this methods returns True if the lock was successfully
        acquired and False otherwise.
        """
        if timeout is None:
            return self.__lock.acquire(blocking)
        else:
            #  Simulated timeout using progressively longer sleeps.
            #  This is the same timeout scheme used in the stdlib Condition
            #  class.  If there's lots of contention on the lock then there's
            #  a good chance you won't get it; but then again, Python doesn't
            #  guarantee fairness anyway.  We hope that platform-specific
            #  extensions can provide a better mechanism.
            endtime = _time() + timeout
            delay = 0.0005
            while not self.__lock.acquire(False):
                remaining = endtime - _time()
                if remaining <= 0:
                    return False
                delay = min(delay*2,remaining,0.05)
                _sleep(delay)
            return True
Пример #5
0
    def proc1(self, time, plane_X, plane_Y, plane_Z, bufferA, bufferB, semA,
              semB, semC, semD, interval, itterations):

        semC.acquire()
        semD.acquire()
        i = time
        for i in range(0, itterations):
            threading._sleep(interval)

            if i % 2 == 0:
                semB.acquire()
                if not plane_X.getflag():
                    plane_X.move(bufferB)
                if not plane_Y.getflag():
                    plane_Y.move(bufferB)
                if not plane_Z.getflag():
                    plane_Z.move(bufferB)
                semB.release()
            else:
                semA.acquire()
                if not plane_X.getflag():
                    plane_X.move(bufferA)
                if not plane_Y.getflag():
                    plane_Y.move(bufferA)
                if not plane_Z.getflag():
                    plane_Z.move(bufferA)
                semA.release()

            plane_X.start()
            plane_Y.start()
            plane_Z.start()
            semC.release()
            semD.release()
Пример #6
0
 def check_buttons(self):
     while self.checking:
         pressed_buttons = filter(lambda b: self.lcd.buttonPressed(b),
                                  range(0, 5))
         if pressed_buttons:
             return pressed_buttons[0]
         threading._sleep(.1)
    def run(self, kismet_queue, sql_queue):

        d = dict()                                                      # Create dictionary (a.k.a Open hash-table (separate chaining))

        while not self.dh_quit:                                         # Loop while we want to process data

            timeout = time.time() + 60*2                                # 60*x min timeout
            d.clear()                                                   # Clear the dictionary for the next sql_queue put
            mac_array = []                                              # Clear the mac_array for the next sql_queue put

            while True:                                                 # nested while loop that runs for the timeout mins specified above.

                q_data = kismet_queue.get()                             # Get data from the queue. The data is 1 client. (mac, signal_dbm, conn_type, date, time, host_name)
                mac_key = q_data.split(' ')[1]                          # Split the mac address so we can use the mac address as a index address for the dictionary

                if mac_key not in d:                                    # if MAC Address is not in table. Add it
                    d[mac_key] = q_data                                 # Set the mac index address value equal to the queue data which contains the rest of the information on that client

                if(time.time() >= timeout):                             # if it has been X mins put the the mac_array on the SQL queue
                    for item in d:                                      # Lopp through each item in the dictionary. each item is 1 clients data.
                        split = d[item].split(' ')                      # Split the data for each client so we can append the data to the mac_array as a tuple.

                        if(split[3] == '2'):                            # if the conn_type = '2' then its a probe request. append to mac_array for the sql_queue.
                            mac_array.append((split[1], split[2], split[3], split[4], split[5], split[6]))      # append it.
                    break                                               # Break out of the nested while loop. This will allow the main while loop to put the data to the sql_queue
                else:
                    threading._sleep(0.02)                              # Slow down the execution of the thread so its not going crazy
                    ### Debigging - print q_data

            sql_queue.put(mac_array)                                    # Add the mac_array to the sql_queue


        print "DATA HANDLER: STOPPED"
        return
Пример #8
0
	def shutDown(self, restart=False):
		f = open(self.lang["shutdown"])
		shutText = f.read()
		f.close()

		self.text = ""
		self.updateText()

		height = self.height*3
		width = self.width*2
		cw = self.font.measure('A')
		ch = self.font.metrics("linespace")
		self.th = height/ch
		self.lw = width/cw
		self.config(foreground="white", height=self.th, width=self.lw)

		shutTime = self.shutTime #secs
		timepl = shutTime/len(shutText.split('\n'))

		for c in shutText.split('\n'):
			if len(c) > 1:
				if not c.endswith('.'):
					self.printOut(c + '\n')
				else:
					self.printOut(c)
			threading._sleep(timepl)

		if restart:
			self.state = const.states.restart
		else:
			self.state = const.states.shutdown
		self.event_generate("<<shut>>")
Пример #9
0
 def get_announcement(self):
     '''Connect to the announcing socket and get an analysis announcement
     
     returns an analysis_id / worker_request address pair
     
     raises a CancelledException if we detect cancellation.
     '''
     poller = zmq.Poller()
     poller.register(self.notify_socket, zmq.POLLIN)
     announce_socket = the_zmq_context.socket(zmq.SUB)
     announce_socket.setsockopt(zmq.SUBSCRIBE, "")
     announce_socket.connect(self.work_announce_address)
     try:
         poller.register(announce_socket, zmq.POLLIN)
         while True:
             for socket, state in poller.poll():
                 if socket == self.notify_socket and state == zmq.POLLIN:
                     msg = self.notify_socket.recv()
                     if msg == NOTIFY_STOP:
                         from cellprofiler.pipeline import CancelledException
                         self.cancelled = True
                         raise CancelledException()
                 elif socket == announce_socket and state == zmq.POLLIN:
                     announcement = dict(announce_socket.recv_json())
                     if len(announcement) == 0:
                         threading._sleep(0.25)
                         continue
                     if self.current_analysis_id in announcement:
                         analysis_id = self.current_analysis_id
                     else:
                         analysis_id = random.choice(announcement.keys())
                     return analysis_id, announcement[analysis_id]
     finally:
         announce_socket.close()
Пример #10
0
def age_timer(nme):
	"""
		age timer thread
	"""
	interval_time=2

	while nme.age_exit_flag is False:#thread not safe,but it does no matter
		threading._sleep(interval_time)
		nme.nme_lock.acquire()
		del_lst=set()
		#print "meeeow"
		#traverse the node table,fidn these expired node,and recollect them
		for nod in nme.node_tbl:
			if nme.node_tbl[nod].timer_cnt > nme.node_expiry_time:
				nme.node_tbl[nod].node_expiry_callback()
				del_lst.add(nod)
			else :
				nme.node_tbl[nod].timer_cnt+=interval_time
		for ele in del_lst:
			if ele in nme.node_tbl:
				#nme.node_id_pool.discard(ele)
				#nme.node_uuid_pool.discard(nme.node_tbl[ele].uuid)
				nme.node_delete(ele)
				#del nme.node_tbl[ele]
				#nme.node_delete(ele)
		#help(nme)
		nme.nme_lock.release()
Пример #11
0
def overHeatMsg(temp):
    message = message = (
        'telegram-cli -W -e "msg Jonathan_Carroll WARNING the current temp is '
        + temp + '."')
    os.system(message)
    # sleeping for 300 secs is 5 minutes
    threading._sleep(300)
    def run(self, data_queue):

        self.k_connect()                                                    # Connect to Kismet socket

        print "------------ KISMET INTRO ------------"
        self.k_sendCMD('!0 REMOVE TIME\r\n')                                # Deactivates the default timestamp Kismet sends
        self.k_sendCMD('!0 ENABLE CLIENT mac,signal_dbm,type,firsttime,lasttime\r\n')      # Tell Kismet we want to enable a socket client and receive the mac address, signal strength, connection type
        k_msg = self.k_recvData("*ACK: 0 OK \n")                          # Retrive the intro data kismet sends
        print k_msg                                                         # Display the intro message to the console

        while not self.k_close:                                             # Loop while we want the socket open

            k_msg = self.k_recvData('\n').strip(" \n")                      # Get 1 line of data from Kismet socket.

            if(k_msg.startswith('*CLIENT')):                                # Check if the received data is a client

                temp = k_msg.split(' ')

                k_msg = "{} {} {} {}".format(temp[0], temp[1], temp[2], temp[3])
                k_lastseen = datetime.datetime.fromtimestamp(int(temp[5]))
                curr_date = str(k_lastseen).split(' ')[0]                  # Get the current date
                curr_time = str(k_lastseen).split(' ')[1]                  # Get the current time

                ### DEBUGGING - #print "{} --- sub 1 ---> {}".format(str(datetime.datetime.fromtimestamp(int(temp[5]))), str(datetime.datetime.fromtimestamp(int(temp[5]))-datetime.timedelta(minutes=1)))
                ### DEBUGGING - #print datetime.datetime.now()

                if(k_lastseen >= datetime.datetime.now()-datetime.timedelta(minutes=2) ):
                    data_queue.put("{} {} {} {}".format(k_msg, curr_date, curr_time, self.hostname))      # Put the client, along with time/date info, in the queue

            threading._sleep(0.1)                                           # Slow down the execution of the thread so its not going crazy

        self.s.close()                                                      # Once loop is over close the kismet socket
        print "KISMET SOCKET: socket closed."
        return
Пример #13
0
    def display_current_message_in_thread(self):
        time_called = time.time()
        self.message_set_time = time_called
        rows = (len(self.message.message_text) / 16) + 1
        lines = []
        for i in xrange(rows):
            start = i * 16
            end = start + 16
            lines.append(self.message.message_text[start:end])
        if len(lines) == 1:
            lines.append("")
        size = len(lines)
        pairs = zip(lines[0 : size-1], lines[1:size])
        strings = ['\n'.join(p) for p in pairs]
        strings.append(strings[0])

        self.set_lcd_on_time(3 * len(strings))

        for s in strings:
            if self.message_set_time > time_called:
                return
            self.lcd.clear()
            self.logger.debug('displaying:\n%s' % s)
            self.lcd.message(s)
            threading._sleep(3)
Пример #14
0
    def acquire(self,blocking=True,timeout=None):
        """Attempt to acquire this lock.

        If the optional argument "blocking" is True and "timeout" is None,
        this methods blocks until is successfully acquires the lock.  If
        "blocking" is False, it returns immediately if the lock could not
        be acquired.  Otherwise, it blocks for at most "timeout" seconds
        trying to acquire the lock.

        In all cases, this methods returns True if the lock was successfully
        acquired and False otherwise.
        """
        if timeout is None:
            return self.__lock.acquire(blocking)
        else:
            #  Simulated timeout using progressively longer sleeps.
            #  This is the same timeout scheme used in the stdlib Condition
            #  class.  If there's lots of contention on the lock then there's
            #  a good chance you won't get it; but then again, Python doesn't
            #  guarantee fairness anyway.  We hope that platform-specific
            #  extensions can provide a better mechanism.
            endtime = _time() + timeout
            delay = 0.0005
            while not self.__lock.acquire(False):
                remaining = endtime - _time()
                if remaining <= 0:
                    return False
                delay = min(delay*2,remaining,0.05)
                _sleep(delay)
            return True
Пример #15
0
    def Update(self):
        assert (self.host_socket != None)

        self.iters += 1

        ## securely connect to server with existing or new account
        ##   c:LOGIN -> {s:LOGACCEPT,s:LOGDENIED}
        ##     if s:LOGACCEPT -> done
        ##     if s:LOGDENIED -> c:REGISTER
        ##     c:REGISTER -> {s:REGACCEPT,s:REGDENIED}
        ##       if s:REGACCEPT -> c:LOGIN -> s:AGREEMENT -> (c:CONFAGREE, c:LOGIN) -> s:LOGACCEPT
        ##       if s:REGDENIED -> exit
        if (self.client_acked_shared_key or (not self.want_secure_session)):
            if (not self.requested_authentication):
                self.out_LOGIN()

        ## periodically re-negotiate the session key (every
        ## 500*0.05=25.0s; models an ultra-paranoid client)
        if (self.client_acked_shared_key and self.want_secure_session
                and self.use_secure_session()):
            if ((self.iters % 50) == 0):
                self.reset_session_state()
                self.out_SETSHAREDKEY()

        if ((self.iters % 10) == 0):
            self.out_PING()

        threading._sleep(0.05)

        ## eat through received data
        self.Recv()
Пример #16
0
def start_sync():
    global global_config
    start_pos = global_config.pos()
    start_binlog = global_config.binlog()
    global_binlog_data_manage.set_filename(start_binlog)
    global_binlog_data_manage.set_position(start_pos)

    while True:
        mysql_channel = MYSQLChannel(global_config.host(),
                                     global_config.port(),
                                     global_config.username(),
                                     global_config.password(),
                                     global_config.database(),
                                     global_config.master_id())
        if mysql_channel.initChannel() == False:
            return False
        recv_data = mysql_channel.dump_binlog(start_pos, start_binlog)
        print 'dump...'
        if recv_data != '':
            (packet_list, count) = global_packet_manage.parse(recv_data)
            start_pos = global_binlog_data_manage.position()
            start_binlog = global_binlog_data_manage.filename()
            global_signal.set()
            mysql_channel.close()
        threading._sleep(3)
Пример #17
0
def wait(threads, startFirst=False, poll=0.5):
    if startFirst:
        for thread in threads:
            thread.start()

    while not __areAllComplete(threads):
        threading._sleep(poll)
Пример #18
0
 def run(self):
     """
         RUN is a magic name in the Threading Library
     """
     threading._sleep(self.sleeptime)
     self.funktion(*self.args)
     exit()
 def setUpClass(cls):
     prov = TestProvider()
     cls.stub = ServerStub(prov, serializers=[JsonSerializer()])
     cls.spinfo = prov.info()
     cls.t = threading.Thread(target=cls.stub.start)
     cls.t.start()
     threading._sleep(1)
Пример #20
0
    def display_current_message_in_thread(self):
        time_called = time.time()
        self.message_set_time = time_called
        rows = (len(self.message.message_text) / 16) + 1
        lines = []
        for i in xrange(rows):
            start = i * 16
            end = start + 16
            lines.append(self.message.message_text[start:end])
        if len(lines) == 1:
            lines.append("")
        size = len(lines)
        pairs = zip(lines[0:size - 1], lines[1:size])
        strings = ['\n'.join(p) for p in pairs]
        strings.append(strings[0])

        self.set_lcd_on_time(3 * len(strings))

        for s in strings:
            if self.message_set_time > time_called:
                return
            self.lcd.clear()
            self.logger.debug('displaying:\n%s' % s)
            self.lcd.message(s)
            threading._sleep(3)
Пример #21
0
    def get_announcement(self):
        '''Connect to the announcing socket and get an analysis announcement

        returns an analysis_id / worker_request address pair

        raises a CancelledException if we detect cancellation.
        '''
        poller = zmq.Poller()
        poller.register(self.notify_socket, zmq.POLLIN)
        announce_socket = the_zmq_context.socket(zmq.SUB)
        announce_socket.setsockopt(zmq.SUBSCRIBE, "")
        announce_socket.connect(self.work_announce_address)
        try:
            poller.register(announce_socket, zmq.POLLIN)
            while True:
                for socket, state in poller.poll():
                    if socket == self.notify_socket and state == zmq.POLLIN:
                        msg = self.notify_socket.recv()
                        if msg == NOTIFY_STOP:
                            from cellprofiler.pipeline import CancelledException
                            self.cancelled = True
                            raise CancelledException()
                    elif socket == announce_socket and state == zmq.POLLIN:
                        announcement = dict(announce_socket.recv_json())
                        if len(announcement) == 0:
                            threading._sleep(0.25)
                            continue
                        if self.current_analysis_id in announcement:
                            analysis_id = self.current_analysis_id
                        else:
                            analysis_id = random.choice(announcement.keys())
                        return analysis_id, announcement[analysis_id]
        finally:
            announce_socket.close()
    def start(self, subject_id, nao_ip_center, nao_ip_left, nao_ip_right,
              experimenter_ip):
        if self.gender == 'None' or self.left_robot_name == 'None' or self.center_robot_name == 'None' or self.right_robot_name == 'None':
            return

        self.nao_info = [(nao_ip_left, '0', self.left_robot_name),
                         (nao_ip_center, '1', self.center_robot_name),
                         (nao_ip_right, '2', self.right_robot_name),
                         (experimenter_ip, '3', 'experimenter')]
        self.cinfig_hist_data = {
            'nao_ip_experimenter': experimenter_ip,
            'nao_ip_left': nao_ip_left,
            'nao_ip_right': nao_ip_right,
            'nao_ip_center': nao_ip_center,
            'nao_name_left': self.left_robot_name,
            'nao_name_right': self.right_robot_name,
            'nao_name_center': self.center_robot_name
        }

        with open('cinfig_hist_data.json', 'w') as outfile:
            json.dump(self.cinfig_hist_data, outfile)

        t1 = threading.Thread(target=self.run_main,
                              args=(subject_id, self.nao_info))
        t1.start()

        rospy.Subscriber("correct_answer", String, self.update_score)

        threading._sleep(25)

        rospy.Subscriber('eye_tracking', String, self.update_pupil_work)

        print 'here-ui'

        self.sm.current = "flow"
Пример #23
0
    def Update(self):
        assert self.host_socket != None

        self.iters += 1

        ## securely connect to server with existing or new account
        ##   c:LOGIN -> {s:LOGACCEPT,s:LOGDENIED}
        ##     if s:LOGACCEPT -> done
        ##     if s:LOGDENIED -> c:REGISTER
        ##     c:REGISTER -> {s:REGACCEPT,s:REGDENIED}
        ##       if s:REGACCEPT -> c:LOGIN -> s:AGREEMENT -> (c:CONFAGREE, c:LOGIN) -> s:LOGACCEPT
        ##       if s:REGDENIED -> exit
        if self.client_acked_shared_key or (not self.want_secure_session):
            if not self.requested_authentication:
                self.out_LOGIN()

                ## periodically re-negotiate the session key (every
                ## 500*0.05=25.0s; models an ultra-paranoid client)
        if self.client_acked_shared_key and self.want_secure_session and self.use_secure_session():
            if (self.iters % 50) == 0:
                self.reset_session_state()
                self.out_SETSHAREDKEY()

        if (self.iters % 10) == 0:
            self.out_PING()

        threading._sleep(0.05)

        ## eat through received data
        self.Recv()
    def run_dynamics(self, step):
        self.reset_pupil_count()

        if step.text != "End":
            self.next_step = int(step.text)

        if self.next_step > self.number_of_steps:
            self.exit_experiment()
            return

        self.next_step += 1

        if self.next_step <= self.number_of_steps:
            self.flow.ids['next_button'].text = str(self.next_step)

        else:
            self.flow.ids['next_button'].text = str("End")

        if self.next_step - 1 == 1:
            self.flow_handler('alive')
            threading._sleep(1)
            self.flow_handler('next_step')

        else:
            self.flow_handler('next_step')
Пример #25
0
 def run(self):
     from random import random
     counter = 0
     while counter < self.quota:
         counter = counter + 1
         self.queue.put("%s.%d" % (self.getName(), counter))
         threading._sleep(random() * 0.00001)
Пример #26
0
 def getAllPageItems(self):
     allVotes = []
     for pageIndex in range(1, self.pageCount + 1):
         onePageVotes = self.getPageItems(pageIndex)
         allVotes += (onePageVotes)
         threading._sleep(0.1)
     return allVotes
Пример #27
0
 def run(self):
     from random import random
     counter = 0
     while counter < self.quota:
         counter = counter + 1
         self.queue.put("%s.%d" % (self.getName(), counter))
         threading._sleep(random() * 0.00001)
Пример #28
0
 def run(self):
     print "Starting Frame Processor"
     while(self.status == True):
         if self.queue.qsize() != 0:
             threading._sleep(.05)
         else:
             self.process_frame(self.queue.get())
Пример #29
0
def set_system_state(to_state, current_state):
    if to_state == state.UNKNOWN:
        LOG.error(
            'Trying to set system status UNKNOWN.... Uncool... bailing.  Current state: %s',
            state.print_state(current_state))
        return

    def _set_system_state(s):
        LOG.info('Setting system mode: %s', state.print_state(s))
        if s == state.HEAT:
            _heat_on()
        elif s == state.COOL:
            _cool_on()
        elif s == state.FAN_ONLY:
            _fan_only()
        elif s == state.OFF:
            _off()

        # Verify that the system state was set currently
        threading._sleep(1)
        cs, _ = get_system_state()
        if s != cs:
            LOG.error(
                'The system state was not set correctly!  Expected state: %s, Actual state: %s',
                state.print_state(s), state.print_state(cs))

    def _heat_on():
        LOG.debug('Setting system mode to HEAT')
        _set_outputs(green=True, white=True)

    def _cool_on():
        LOG.debug('Setting system mode to COOL')
        _set_outputs(green=True, white=True, yellow=True)

    def _fan_only():
        LOG.debug('Setting system mode to FAN ONLY')
        _set_outputs(green=True)

    def _off():
        LOG.debug('Setting system mode to OFF')
        _set_outputs()

    def _set_outputs(green=False, white=False, yellow=False):
        LOG.debug('Setting GREEN out pin to %s', 'ON' if green else 'OFF')
        GPIO.output(CONF.io.green_pin_out, green)

        LOG.debug('Setting WHITE out pin to %s', 'ON' if white else 'OFF')
        GPIO.output(CONF.io.white_pin_out, white)

        LOG.debug('Setting YELLOW out pin to %s', 'ON' if yellow else 'OFF')
        GPIO.output(CONF.io.yellow_pin_out, yellow)

    if current_state in [state.OFF, state.FAN_ONLY]:
        _set_system_state(to_state)
    else:
        # First set the system to fan only to let the system cool down for 2 minutes, then set the system state
        _set_system_state(state.FAN_ONLY)
        threading._sleep(CONF.hvac.on_mode_change_fan_interval)
        _set_system_state(to_state)
Пример #30
0
def Click():
    global clicks
    global click_speed
    global pos
    while(True):
        if clicks:
            clickSpot(pos)
            threading._sleep(click_speed)
Пример #31
0
 def set_range():
     start, end = 0, 1
     while end < 10e6:
         end *= 1.0001
         leg.unit = 'm'
         leg.range = (start, end)
         threading._sleep(0.0005)
     self.frame.Destroy()
Пример #32
0
def MoveActiveCars(cars, MainWindow):
    # Moves active cars every 300 ms
    while True:
        with dataframe(carlock) as df:
            acs = df.add(ActiveCar, cars)
            for car in acs:
                car.Move()
                _sleep(0.3)
Пример #33
0
    def run(self):
        global q

        for i in range(13) :
            f = self.food[random.randrange(len(self.food))]
            q.put(f)
            threading._sleep(1)
            print 'adding food to the queue'
Пример #34
0
def thread2_take_pictures():
    global image

    while (True):
        image2 = ImageGrab.grab()
        image = np.array(image2)
        image2.save('fixed.png')
        threading._sleep(0.5)
Пример #35
0
 def check_buttons(self):
     while self.checking:
         pressed_buttons = filter(
             lambda b: self.lcd.buttonPressed(b),
             range(0, 5)
         )
         if pressed_buttons:
             return pressed_buttons[0]
         threading._sleep(.1)
Пример #36
0
    def run(self):
        global q

        for i in range(13) :

            if not q.empty():
                f = q.get()
            threading._sleep(1)
            print 'removing food to the queue ' , f
Пример #37
0
def set_system_state(to_state, current_state):
    if to_state == state.UNKNOWN:
        LOG.error('Trying to set system status UNKNOWN.... Uncool... bailing.  Current state: %s',
                  state.print_state(current_state))
        return

    def _set_system_state(s):
        LOG.info('Setting system mode: %s', state.print_state(s))
        if s == state.HEAT:
            _heat_on()
        elif s == state.COOL:
            _cool_on()
        elif s == state.FAN_ONLY:
            _fan_only()
        elif s == state.OFF:
            _off()

        # Verify that the system state was set currently
        threading._sleep(1)
        cs, _ = get_system_state()
        if s != cs:
            LOG.error('The system state was not set correctly!  Expected state: %s, Actual state: %s',
                      state.print_state(s), state.print_state(cs))

    def _heat_on():
        LOG.debug('Setting system mode to HEAT')
        _set_outputs(green=True, white=True)

    def _cool_on():
        LOG.debug('Setting system mode to COOL')
        _set_outputs(green=True, white=True, yellow=True)

    def _fan_only():
        LOG.debug('Setting system mode to FAN ONLY')
        _set_outputs(green=True)

    def _off():
        LOG.debug('Setting system mode to OFF')
        _set_outputs()

    def _set_outputs(green=False, white=False, yellow=False):
        LOG.debug('Setting GREEN out pin to %s', 'ON' if green else 'OFF')
        GPIO.output(CONF.io.green_pin_out, green)

        LOG.debug('Setting WHITE out pin to %s', 'ON' if white else 'OFF')
        GPIO.output(CONF.io.white_pin_out, white)

        LOG.debug('Setting YELLOW out pin to %s', 'ON' if yellow else 'OFF')
        GPIO.output(CONF.io.yellow_pin_out, yellow)

    if current_state in [state.OFF, state.FAN_ONLY]:
        _set_system_state(to_state)
    else:
        # First set the system to fan only to let the system cool down for 2 minutes, then set the system state
        _set_system_state(state.FAN_ONLY)
        threading._sleep(CONF.hvac.on_mode_change_fan_interval)
        _set_system_state(to_state)
Пример #38
0
def StartPedestrian(peds, MainWindow):
    # Make a pedestrian walk every 3 secs.
    while True:
        with dataframe(pedlock) as df:
            for ped in df.add(StoppedPedestrian, peds):
                register(ped.ID, peds, MainWindow)
                ped.Move()
                break
        _sleep(3)
Пример #39
0
 def test_newest(self):
     import threading
     Project.objects.create(name="test1")
     threading._sleep(0.001)
     Project.objects.create(name="test2")
     threading._sleep(0.001)
     Project.objects.create(name="test3")
     newest = Project.objects.newest()[0]
     self.assertEquals('test3', newest.name)
Пример #40
0
def main():
    """
        -- the main procedure to generate the graphical tool
    """

    # the graphical tool
    app = QApplication(sys.argv)

    pixmap = QPixmap(":logo.png")
    splash = QSplashScreen(pixmap)
    splash.show()

    threading._sleep(1)

    app.setOrganizationName("AirBus")
    app.setApplicationName("AnemoClinoAnalyseur")
    app.setWindowIcon(QIcon(":/icon.png"))
    app.setStyle(
        "cleanlooks")  # important, if not, icon can't adapt the size of button

    username = os.environ['USERNAME']
    workspace_path = 'C:\Users\\' + username + '\Documents\Anemo_clino_analyser_workspace\\'
    calibrated_files_path = workspace_path + 'calibrated_files\\'
    global_context_path = workspace_path + 'global_context\\'

    if not os.path.exists(workspace_path):
        os.mkdir(workspace_path)
        os.mkdir(calibrated_files_path)
        os.mkdir(global_context_path)
        '''
        w = StartWindow()
        while not w.get_configuration_state():
            w.exec_()
        '''

    # Model
    global_context = GlobalContext()
    global_context.set_workspace_path(workspace_path)
    global_context.set_calibrated_files_path(calibrated_files_path)
    global_context.set_global_context_path(global_context_path)
    global_context.set_user_name(username)

    # Controller
    analyseur_mediator = AnalyserMediator()
    analyseur_mediator.set_global_context(global_context)

    # View
    anemo_clino_analyseur = AnalyserMainWindow()
    anemo_clino_analyseur.set_analyseur_mediator(analyseur_mediator)

    # execute the application
    anemo_clino_analyseur.show()

    splash.finish(anemo_clino_analyseur)

    app.exec_()
Пример #41
0
 def light_lcd_screen(self):
     while self.checking:
         self.lcd_backlight_semaphore.acquire()
         if self.lcd_time > 0:
             self.lcd_time -= 1
             self.lcd.backlight(self.lcd.TEAL)
         else:
             self.lcd.backlight(self.lcd.OFF)
         self.lcd_backlight_semaphore.release()
         threading._sleep(1)
 def test_lock_created_for_each_key(self):
     locks = []
     thread1 = LockCreatorThread(self.generic_lock_provider, locks)
     thread2 = LockCreatorThread(self.generic_lock_provider, locks)
     thread1.start()
     thread2.start()
     while len(locks) < 12:
         threading._sleep(0.001)
     self.assertEquals(len(locks), 12)
     self.assertEquals(len(list(set(locks))), 6)
Пример #43
0
 def light_lcd_screen(self):
     while self.checking:
         self.lcd_backlight_semaphore.acquire()
         if self.lcd_time > 0:
             self.lcd_time -= 1
             self.lcd.backlight(self.lcd.TEAL)
         else:
             self.lcd.backlight(self.lcd.OFF)
         self.lcd_backlight_semaphore.release()
         threading._sleep(1)
Пример #44
0
def generalTask():
    lastPageIndex = 0
    while True:
        if taskQueue.qsize()==0:
            print "current : "+str(lastPageIndex)
            for i in range(0,100):
                taskQueue.put(lastPageIndex)
                lastPageIndex+=1

        threading._sleep(1)
Пример #45
0
def generalTask():
    lastPageIndex = 0
    while True:
        if taskQueue.qsize() == 0:
            print "current : " + str(lastPageIndex)
            for i in range(0, 100):
                taskQueue.put(lastPageIndex)
                lastPageIndex += 1

        threading._sleep(1)
Пример #46
0
	def OpenSocket(self, server_addr):
		while (self.host_socket == None):
			try:
				## non-blocking so we do not have to wait on server
				self.host_socket = socket.create_connection(server_addr, 5)
				self.host_socket.setblocking(0)
			except socket.error as msg:
				print("[OpenSocket] %s" % msg)
				## print(traceback.format_exc())
				threading._sleep(0.5)
Пример #47
0
    def run(self, data_queue):

        self.db_connect()
        threading._sleep(1)

        while not self.db_close:
            threading._sleep(5)

        self.db.close()
        print 'SQL DB: CLOSED'
Пример #48
0
	def wait(self, timeout=None):
		waiter = _allocate_lock()
		waiter.acquire()				# get it the first time, no blocking
		self.append(waiter)
		
		
		try:
			# restore state no matter what (e.g., KeyboardInterrupt)
			# now we block, as we hold the lock already
			# in the momemnt we release our lock, someone else might actually resume
			self._lock.release()
			if timeout is None:
				waiter.acquire()
			else:
				# Balancing act:  We can't afford a pure busy loop, because of the 
				# GIL, so we have to sleep
				# We try to sleep only tiny amounts of time though to be very responsive
				# NOTE: this branch is not used by the async system anyway, but 
				# will be hit when the user reads with timeout 
				endtime = _time() + timeout
				delay = self.delay
				acquire = waiter.acquire
				while True:
					gotit = acquire(0)
					if gotit:
						break
					remaining = endtime - _time()
					if remaining <= 0:
						break
					# this makes 4 threads working as good as two, but of course
					# it causes more frequent micro-sleeping
					#delay = min(delay * 2, remaining, .05)
					_sleep(delay)
				# END endless loop
				if not gotit:
					try:
						self.remove(waiter)
					except AttributeError:
						# handle python 2.4 - actually this should be made thread-safe
						# but lets see ... 
						try:
							# lets hope we pop the right one - we don't loop over it
							# yet-we just keep minimal compatability with py 2.4
							item = self.pop()
							if item != waiter:
								self.append(item)
						except IndexError:
							pass
					except ValueError:
						pass
				# END didn't ever get it
		finally:
			# reacquire the lock 
			self._lock.acquire()
Пример #49
0
 def run(self):
     while True:
         try:
             url_name = urls_queue.get(block=False)
             download_image(*url_name)
         except Empty:
             if self.exit_event.is_set():
                 break
             pass
         except Exception, ex:
             print 'exception in UrlsConsumer:', ex
         threading._sleep(0.1)
    def run(self, data_queue):

        self.db_connect()
        threading._sleep(1)

        while not self.db_close:
            if not data_queue.empty():
                mac_data = data_queue.get()
                self.db_insert(mac_data)

        self.db.close()
        print 'SQL DB: CLOSED'
Пример #51
0
def RunClients(num_clients, num_updates):
	clients = [None] * num_clients

	for i in xrange(num_clients):
		clients[i] = LobbyClient(HOST_SERVER, (CLIENT_NAME % i), (CLIENT_PWRD % i))

	for j in xrange(num_updates):
		for i in xrange(num_clients):
			clients[i].Update()
		threading._sleep(0.05)

	for i in xrange(num_clients):
		clients[i].out_EXIT()
Пример #52
0
def set_system_state(to_state, current_state):
    if to_state == state.UNKNOWN:
        LOG.error('Trying to set system status UNKNOWN.... Uncool... bailing.  Current state: %s',
                  state.print_state(current_state))
        return

    def _set_system_state(s):
        LOG.info('Setting system mode: %s', state.print_state(s))
        if s == state.HEAT:
            _heat_on()
        elif s == state.COOL:
            _cool_on()
        elif s == state.FAN_ONLY:
            _fan_only()
        elif s == state.OFF:
            _off()

        # Verify that the system state was set currently
        threading._sleep(1)
        cs, _ = get_system_state()
        if s != cs:
            LOG.error('The system state was not set correctly!  Expected state: %s, Actual state: %s',
                      state.print_state(s), state.print_state(cs))

    def _heat_on():
        GPIO.output(CONF.io.green_pin_out, True)
        GPIO.output(CONF.io.white_pin_out, True)
        GPIO.output(CONF.io.yellow_pin_out, False)

    def _cool_on():
        GPIO.output(CONF.io.green_pin_out, True)
        GPIO.output(CONF.io.white_pin_out, True)
        GPIO.output(CONF.io.yellow_pin_out, True)

    def _fan_only():
        GPIO.output(CONF.io.green_pin_out, True)
        GPIO.output(CONF.io.white_pin_out, False)
        GPIO.output(CONF.io.yellow_pin_out, False)

    def _off():
        GPIO.output(CONF.io.green_pin_out, False)
        GPIO.output(CONF.io.white_pin_out, False)
        GPIO.output(CONF.io.yellow_pin_out, False)

    if current_state in [state.OFF, state.FAN_ONLY]:
        _set_system_state(to_state)
    else:
        # First set the system to fan only to let the system cool down for 2 minutes, then set the system state
        _set_system_state(state.FAN_ONLY)
        threading._sleep(CONF.hvac.on_mode_change_fan_interval)
        _set_system_state(to_state)
Пример #53
0
def fetchURL_request(query, testserver=False, debug=True):
	fetch_url = ''
	if testserver: fetch_url = '%s%s' % (crest_test_path, query)
	else: fetch_url = '%s%s' % (crest_path, query)
	if debug: thread_print( fetch_url )
	params = {
		'accept-encoding' : 'gzip',
		'user-agent'      : user_agent,
	}
	return_object = {}
	fatal_error = True
	for tries in range (0,retry_limit):
		time.sleep(sleep_timer*tries)
		try:
			request = requests.get( fetch_url,
									headers  = params,
									timeout = (default_timeout,default_readtimeout))
			return_object = request.json()
		except requests.exceptions.ConnectionError as e:
			#fatal_error = True
			fatal_error = False
			thread_print('connectionError:%s %s' % (e,fetch_url))
			continue
		except requests.exceptions.ConnectTimeout as e:
			fatal_error = True
			thread_print('connectionTimeout:%s %s' % (e,fetch_url))
			continue
		except requests.exceptions.ReadTimeout as e:
			fatal_error = True
			thread_print('readTimeout:%s %s' % (e,fetch_url))
			continue
		except ValueError:
			fatal_error = True
			thread_print('response not JSON')
			raise

		if request.status_code == requests.codes.ok:
			break
		else:
			fatal_error = False
			if request.status_code == 503:
				threading._sleep(random.random()/8.0)
			else:
				thread_print('HTTPError:%s %s' % (request.status_code,fetch_url))
			continue
	else:
		#thread_print( headers )
		if fatal_error: sys.exit(2)
		return {'items':[]}

	return return_object
Пример #54
0
 def send_payload(self):
     while 1:
         req = raw_input("Request: ").lower()
         while not self.valid_payload(req):
             req = raw_input("Request: ").lower()
         msg_to_send = {'request': req, 'content': None}
         # Add content to payload if required
         if req == "login" or req == "msg":
             content = raw_input("Content: ")
             msg_to_send['content'] = content
         # Json-dump the string for standard JSON-formatted string
         self.connection.send(json.dumps(msg_to_send))
         # Let the console have time to output response from server, find better solution?
         threading._sleep(0.5)
	def run(self):
		self.mtime1 = os.path.getmtime(init.savedir+init.savefile)
		while True:
			print '\nrunning...\n'
			threading._sleep(self.clock_pulse)
			self.time2 = time.time()
			self.mtime2 = os.path.getmtime(init.savedir+init.savefile)
			if self.mtime1 != self.mtime2: 
				self.file_state['CHANGED'] = True
				self.mtime1 = os.path.getmtime(init.savedir+init.savefile)
				self.mtime2 = os.path.getmtime(init.savedir+init.savefile)
			else: self.file_state['CHANGED'] = False
			if self.time2 - self.time1 >= 10 and self.mtime1 == self.mtime2:
				user.states['IDLE'] = True
				self.handle_idle_state()
			if len(user.ed.expenses_due(user)) > 0: self.handle_expenses_due_state()
			if self.file_state['CHANGED']: self.refresh_data_from_file()
Пример #56
0
    def _set_system_state(s):
        LOG.info('Setting system mode: %s', state.print_state(s))
        if s == state.HEAT:
            _heat_on()
        elif s == state.COOL:
            _cool_on()
        elif s == state.FAN_ONLY:
            _fan_only()
        elif s == state.OFF:
            _off()

        # Verify that the system state was set currently
        threading._sleep(1)
        cs, _ = get_system_state()
        if s != cs:
            LOG.error('The system state was not set correctly!  Expected state: %s, Actual state: %s',
                      state.print_state(s), state.print_state(cs))
Пример #57
0
 def run(self):
     global q
     while True:
         if q.qsize() < 1:
             threading._sleep(5)
             pass
         else:
             print '开始下载'
             print
             inageObj = q.get()
             print '正在下载', inageObj[1], inageObj[0] + str(q.qsize())
             print
             # print 'consumer' + ' ----- Queue Size:' + str(q.qsize())
             # print
             self.saveImg(inageObj[0], inageObj[1])
             print inageObj[1], inageObj[0] + '下载完成'
             print
Пример #58
0
def checkOnline():
	while True:
		currtime=time.time()
		userheartbeatlock.acquireR()
		hbs=userheartbeat.copy()
		userheartbeatlock.releaseR()
		print hbs
		for u in hbs.items():
			if currtime-u[1]>5:
				userheartbeatlock.acquireW()
				userheartbeat.pop(u[0])
				userheartbeatlock.releaseW()
				userlistlock.acquireW()
				userlist.pop(u[0])
				userlistlock.releaseW()
				print u[0]+" is offline"
		threading._sleep(5)