Ejemplo n.º 1
7
def main(channel = 'Z'):
    ##channel = 'X' # This can be 'X' or 'Y' or 'Z' channels
    min_position = -4 # mm
    max_position = 12.2 # m
    rate = 0.5 # number of points written per second to the stage
    density = 2 # number of points across the full scale range
    wait =  6 # Wait time before sweeping back in seconds

    x_mm_array_f = numpy.linspace(min_position,max_position,density)
    x_mm_array_b = numpy.linspace(max_position,min_position,density)
    xps = qt.instruments['xps']

    while 1:
        if (msvcrt.kbhit() and (msvcrt.getch() == 'q')): break
        print 'Sweeping %s forward...' % channel
        for i in x_mm_array_f:
            xps.set('abs_position%s' % channel, i)
            time.sleep(1.0/rate)
        time.sleep(wait)
        if (msvcrt.kbhit() and (msvcrt.getch() == 'q')): break
        print 'Sweeping %s backward...' % channel
        for i in x_mm_array_b:
            xps.set('abs_position%s' % channel, i)
            time.sleep(1.0/rate)
        time.sleep(wait)


    f_string = 'set_abs_position' + channel
    # Create function that corresponds to the abs_position set function of
    # the correct channel, then call it to reset the voltage to 0.
    reset_channel = getattr(xps, f_string)
    reset_channel(0.0)
    return
Ejemplo n.º 2
1
    def anykey(message=""):
        if message:
            print(message)

        from msvcrt import getch

        # getch returns b'[character]', so we turn it into a string
        # and strip out the b' and ' parts
        while msvcrt.kbhit():
            char = getch()
        # some inputs need to be compared using their number, for some reason
        if ord(char) == 224:
            # aha! an arrow key!
            char = ord(getch())
            if char == 72:
                char = movementButtons[0]  # up
            elif char == 80:
                char = movementButtons[1]  # down
            elif char == 75:
                char = movementButtons[2]  # left
            elif char == 77:
                char = movementButtons[3]  # right
        elif ord(char) == 3:
            char = "q"  # KeyboardInterrupt
        elif ord(char) == 27:
            char = "p"  # Esc
        elif ord(char) == 8:
            char = "\x7F"  # backspace
        elif ord(char) == 18:
            char = "\x12"  # ctrl-R
        else:
            char = str(char)[2:-1]
        if char == "q":
            quit(True)
        return char.lower()
Ejemplo n.º 3
0
def main():
    """
        Main Function.
    """
    maze = GameMaze()
    try:
        maze.load()
    except IOError:
        pass
    position = [10, 10]
    place_tile = '.'
    while True:
        print (maze)
        print ("Bomb Density : %d" % (maze.count_attribute('B')))
        print ("Place Tile : %s" % (place_tile))
        print ("Position : (%d, %d)" % tuple(position))
        character = getch()
        while character not in ['q', 'w', 'a', 's', 'd', 'B', 'G', '.']:
            character = getch()
        if character == 'q':
            maze.dump()
            exit(0)
        if character in ['B', 'G', '.']:
            place_tile = character
        if character == 'w':
            position[1] = position[1] - 1
        if character == 'a':
            position[0] = position[0] - 1
        if character == 's':
            position[1] = position[1] + 1
        if character == 'd':
            position[0] = position[0] + 1
        maze.set_attribute(position, place_tile)
Ejemplo n.º 4
0
def getch():
    """getch() for Windows and Linux.
       This won't work unless run from a terminal.
    """
    # this must be executed from a terminal
    if not is_executed_from_console():
        system_exit("libastyle.getch() must be run from the console")
    # WINDOWS uses msvcrt
    if os.name == "nt":
        # clear buffer
        while msvcrt.kbhit():
            msvcrt.getch()
        # read char
        ch_in = msvcrt.getch()
    # LINUX uses termios and tty
    else:
        # clear buffer
        sys.stdin.flush()
        # read char
        fd_in = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd_in)
        try:
            tty.setraw(sys.stdin.fileno())
            ch_in = sys.stdin.read(1)
            if ch_in == '\x1b':			# alt key (27)
                ch_in = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd_in, termios.TCSADRAIN, old_settings)
    # convert to unicode for Python 3
    return ch_in.decode('utf-8')
Ejemplo n.º 5
0
def wait():
    try:
        import msvcrt
        print("Press any key to continue")
        msvcrt.getch()
    except Exception:
        pass
Ejemplo n.º 6
0
def maps(summ):
    count = 0
    os.system(clear_fn)
    quit = ''
    for x in full:
        if summ == x['summoner']:
            count += 1
            print 'Champion: %s' % (x['champion'])
            print 'Date: %s - Won: %s - Length: %s' % (x['datetime'], x['won'], x['length'])
            try:
                print 'Kills: %s - Deaths: %s - Assists: %s - KDR: %.2f' % (x['kills'], x['deaths'], x['assists'], x['kills'] / x['deaths'])
            except ZeroDivisionError:
                print 'Kills: %s - Deaths: %s - Assists: %s - KDR: 0' % (x['kills'], x['deaths'], x['assists'])

            print 'Dealt: Phyiscal: %s - Magical: %s - Total: %s' % (com(x['physicalDamageDealt']), com(x['magicDamageDealt']), com(x['physicalDamageDealt'] + x['magicDamageDealt']))
            print 'Received: Phyiscal: %s - Magical: %s - Total: %s' % (com(x['physicalDamageTaken']), com(x['magicDamageTaken']), com(x['physicalDamageTaken'] + x['magicDamageTaken']))
            print 'Gold: %s - Healing: %s - CreepScore: %s ' % (com(x['gold']), com(x['healed']), com(x['neutralMinionsKilled'] + x['minions']))
            length = getsec(x['length'])
            print 'Gold/Min: %s - CS/Min: %.2f\n' % (com((x['gold'] / length) * 60), ((x['neutralMinionsKilled'] + x['minions']) / length) * 60)

            if quit == 'q' or quit == 'Q':
                break

            if count >= 2:
                print 'Press a key to view more or Q to quit\n'
                quit = msvcrt.getch()
                count = 0
                os.system(clear_fn)
    print '\nPress a Key to continue'
    msvcrt.getch()
Ejemplo n.º 7
0
def champs(summ):
    defloop = True
    while defloop:
        l = []
        o = []
        os.system(clear_fn)
        for x in full:
            if summ == x['summoner']:
                if x['champion'] in o:
                    continue
                o.append(x['champion'])
                l.append(x['champion'])

                if len(l) == 2:
                    print '\t   '.join(l)
                    l = []
        if len(l) == 1:
            print '    '.join(l)
        usrinput = raw_input('\nEnter a Champion name to view more info on it, or type Q to quit:\n')

        if usrinput == 'q' or usrinput == 'Q':
            break

        if usrinput in o:
            champinfo(usrinput, summ)
            break

        else:
            print 'Not a valid champion selection. Press a key to try again.'
            msvcrt.getch()
Ejemplo n.º 8
0
def main():
    grid = [[0]*4 for i in range(4)]
    x, y = random.randrange(4), random.randrange(4)
    grid[y][x] = 2 if random.random() < .9 else 4
    while True:
        print('\n' * H)
        print(grid_fmt.format(*[i or '' for r in grid for i in r]))
        gridcp = [r[:] for r in grid]
        if not (move_up(gridcp) or move_down(gridcp) or
                move_left(gridcp) or move_right(gridcp)):
            print('Game over!')
            break
        moved = False
        k = msvcrt.getch()
        if msvcrt.kbhit():
            k += msvcrt.getch()
        if k == b'\xe0H':
            moved = move_up(grid)
        elif k == b'\xe0P':
            moved = move_down(grid)
        elif k == b'\xe0K':
            moved = move_left(grid)
        elif k == b'\xe0M':
            moved = move_right(grid)
        elif k in (b'\x1b', b'q'):
            break
        if moved:
            x, y = random.randrange(4), random.randrange(4)
            while grid[y][x]:
                x, y = random.randrange(4), random.randrange(4)
            grid[y][x] = 2 if random.random() < .9 else 4
Ejemplo n.º 9
0
def get_ui_to(prompt, toSec=None, tSleepSec=None):
  # import sys
  from time import time, sleep
  from msvcrt import getch, getche, kbhit

  if toSec==None: # wait forever
    userKey = raw_input(prompt)
    return userKey

  tElapsed = 0
  t0 = time()
  if tSleepSec == None:
    tSleep = 0.1*toSec
  else:
    tSleep = tSleepSec
  while True:
    if tElapsed > toSec:
      print "Timeout after tElapsed secs...%.3f"%tElapsed
      userKey = ''
      break
    print "\n", prompt,
    if kbhit():
      userKey = getche()
      while kbhit(): # flush input
        getch() # sys.stdin.flush()
      # userKey = raw_input(prompt)
      break
    # print "sleep tSleep secs...%.3f"%tSleep
    sleep(tSleep)
    tNow = time()
    tElapsed = tNow - t0

  return userKey
Ejemplo n.º 10
0
def wait():
    try:
        import msvcrt
        print("Slappah hoe")
        msvcrt.getch()
    except Exception:
        pass
Ejemplo n.º 11
0
def alarm(hours, minutes, seconds):
    time.sleep(abs(hours * 3600 + minutes * 60 + seconds))
    while msvcrt.kbhit():
        msvcrt.getch()
    while not msvcrt.kbhit():
        winsound.Beep(440, 250)
        time.sleep(0.25)
Ejemplo n.º 12
0
def lister():
    quit = ''
    count = 0
    global setting
    os.system(clear_fn)
    print 'List all Players (list), or type in a name'
    usrinput = raw_input('Enter: ')
    if usrinput == 'list':
        os.system(clear_fn)
        count = 0
        players = defaultdict(int)  # dict for counting how many times a player has been played with.
        l = []  # Temp list for displaying players and times played with.
        print 'Player Name - Times played with\n'
        for f in full:
            players[f['summoner']] += 1

        for key, value in sorted(players.iteritems(), reverse=True, key=lambda (v, k): (k, v)):
            if setting[1] == '0':
                if value == 1:
                    continue
            a = '%s - %s' % (key.ljust(19), value)
            l.append(a)
            if len(l) == 2:
                print '    '.join(l)
                l = []
            count += 1

            if count >= 30:
                print '\nPress a key to view more or Q to enter a profile name or quit.\n'
                quit = msvcrt.getch()
                count = 0
            if quit == 'q' or quit == 'Q':
                break
        if len(l) == 1:
            print ''.join(l)

        usrinput = raw_input('Enter a profile name or hit enter to continue: ')
        select = False
        for x in full:
            if usrinput == x['summoner']:
                select = True

        if select:
            selection(usrinput)
        else:
            print '\nNo summoner by that name, try again. Remember search is case sensitive.\n'
            print 'Press a key to continue'
            msvcrt.getch()
    else:
        select = False
        for x in full:
            if usrinput == x['summoner']:
                select = True

        if select:
            selection(usrinput)
        else:
            print '\nNo summoner by that name, try again. Remember search is case sensitive.\n'
            print 'Press a key to continue'
            msvcrt.getch()
Ejemplo n.º 13
0
def get_key(timeout=0.0):
    """Non-blocking version of getch"""
    
    if timeout < 0:
        # Revert to blocking version
        return getch()
        
    char = None
    if os.name == 'nt':
        import msvcrt
        start = time.time()
        while True:
            if msvcrt.kbhit():
                char = msvcrt.getch()
                if char in b'\x00\xe0':
                    # special key, two bytes
                    char += msvcrt.getch()
                break
            if time.time() > (start + timeout):
                break
            else:
                # poll at most every 50 ms
                time.sleep(0.05)
    
    elif os.name == 'posix':
        from select import select
        rlist, wlist, xlist = select([sys.stdin], [], [], timeout)
        if sys.stdin in rlist:
            char = sys.stdin.read()
    
    return char
Ejemplo n.º 14
0
def do_action():
	action = ord(getch())
	while action not in list(ALL_ACTION.values()):
		action = ord(getch())
	if action == ALL_ACTION['KEY_ONE']:
		clear(), add_new_donor()
	if action == ALL_ACTION['KEY_TWO']:
		clear(), add_new_event()
	if action == ALL_ACTION['KEY_THREE']:
		clear(), delete_donor()
	if action == ALL_ACTION['KEY_FOUR']:
		clear(), delete_event()
	if action == ALL_ACTION['KEY_FIVE']:
		clear(), submenu(LIST)
	if action == ALL_ACTION['KEY_SIX']:
		clear(), submenu(SEARCH)
	if action == ALL_ACTION['KEY_SEVEN']:
		clear(), submenu(MODIFY)
	if action == ALL_ACTION['KEY_EIGHT']:
		line = random.choice(open('web.txt').read().splitlines())
		webbrowser.open(line)  # or http://www.randomwebsite.com/cgi-bin/random.pl
	if action == ALL_ACTION['KEY_NINE']:
		location = (os.path.dirname(os.path.realpath('matrix.bat')))
		system(location + '\\matrix.bat')
	if action == ALL_ACTION['KEY_PLUS']:
		change_text_color()
	if action == ALL_ACTION['KEY_MINUS']:
		change_background_color()
	if action == ALL_ACTION['KEY_ASTERISK']:
		change_random_color()
	if action == ALL_ACTION['KEY_M']:
		create_music()
	if action == ALL_ACTION['KEY_ESC']:
		print("Bye!"), system('COLOR 07'), exit()
Ejemplo n.º 15
0
def load_text(file_location, progress_file):
	text = np.genfromtxt(file_location,dtype='str')
	text_temp = []
	start_index = 0
	progress_text = []
	if progress_file:
		progress_text = np.genfromtxt(progress_file,dtype=str)
		if len(progress_text) > 0:
			index = np.where(text == progress_text[len(progress_text)-1])
			start_index = index[0]
	print 'start:'+str(start_index)
	key = ''
	prev_word = []
	for word in text[start_index+1:]:
		print word
		key = msvcrt.getch()
		if key == 'k': 
			progress_text = np.append(progress_text, word)
		elif key == 'b':
			progress_text = np.append(progress_text, prev_word)
			print prev_word + ' added. add:'+ word+'?'
			key = msvcrt.getch()
			if key == 'k': 
				progress_text = np.append(progress_text, word)
			else:
				print '--'
		elif key == 'q':
			break
		else:
			print '--'
		prev_word = word
		
	np.savetxt('KeptWords.txt',progress_text,delimiter='\n', fmt="%s")
Ejemplo n.º 16
0
def KBcode():
    """
    prints the keyboard code for each key typed (except backspace (ord 8) which breaks out of the function)
    """
    a = 0
    while a != 8:
        char = msvcrt.getch()
        a = ord(char)
        if a in [000, 224]:
            char2 = msvcrt.getch()
            b = ord(char2)
            print str(a) + ":" + str(b)
        else:
            print str(a)

# horz = chr(205) # horizontal
# vert = chr(186) # vertical
# topl = chr(201) # top-left corner
# topr = chr(187) # top-right corner
# botl = chr(200) # bottom-left corner
# botr = chr(188) # bottom-right corner
# nort = chr(202) # North T-intersection
# sout = chr(203) # South T-intersection
# east = chr(204) # East T-intersection
# west = chr(185) # West T-intersection
# cros = chr(206) # Cross intersection
# empt = " "      # Space
# newl = "\n"     # New-line
Ejemplo n.º 17
0
def submenu(string_name_of_submenu):
	print(
		"{} (press 1, 2 or ESC):\n\t1. Donor\n\t2. Event\n\tEsc. Back to the Main menu".format(string_name_of_submenu))
	action = ord(getch())
	while action not in list(ALL_ACTION.values()):
		action = ord(getch())
	if action == ALL_ACTION['KEY_ONE']:
		if not file_is_empty(DONOR_PATH):
			loading()
			if LIST == string_name_of_submenu:
				list_donor()
			if SEARCH == string_name_of_submenu:
				search_donor()
			if MODIFY == string_name_of_submenu:
				modofy_donor()
	if action == ALL_ACTION['KEY_TWO']:
		if not file_is_empty(EVENT_PATH):
			loading()
			if LIST == string_name_of_submenu:
				list_events()
			if SEARCH == string_name_of_submenu:
				search_event()
			if MODIFY == string_name_of_submenu:
				modify_event()
	if action == ALL_ACTION['KEY_ESC']:
		menu()
Ejemplo n.º 18
0
     def get_char(self):
       ch = msvcrt.getch()      
       if len(ch) == 1:
         if ch in string.printable:
           return ch
         elif ch == '\x08':
           self.delchar() 		 
   	 elif ch == '\xe0':
          ch = msvcrt.getch()
          if ch == self.CODE_LEFT: 
            if self.cursor > 0:
	      self.print_text(self.MOVE_LEFT)	
	      self.cursor -= 1	
          elif ch == self.MOVE_RIGHT:
            if self.cursor < len(self.line):
	      pad = len(self.line) - self.cursor
	      self.print_text(self.line[self.cursor:] + (pad - 1) * self.MOVE_LEFT)
	      self.cursor += 1
          elif ch == self.MOVE_UP:
	      self.clear_line()
	      cmd = self.history.getnext()
	      if cmd:
                self.insert_text(cmd)	
          elif ch == self.MOVE_DOWN:
	      self.clear_line()
              cmd = self.history.getprev()
	      if cmd:
	        self.insert_text(cmd)
          return None
Ejemplo n.º 19
0
 def __call__(self):
     import msvcrt
     k=ord(msvcrt.getch())
     if k == 0 or k == 224:                    #Special keys
         return 1000+ord(msvcrt.getch())   #return 1000+ 2nd code
     else:
         return k
Ejemplo n.º 20
0
Archivo: term.py Proyecto: eblot/pyftdi
def getkey(fullterm=False):
    """Return a key from the current console, in a platform independent way"""
    # there's probably a better way to initialize the module without
    # relying onto a singleton pattern. To be fixed
    global _INIT
    if not _INIT:
        _INIT = _init_term(fullterm)
    if os.name == 'nt':
        # w/ py2exe, it seems the importation fails to define the global
        # symbol 'msvcrt', to be fixed
        import msvcrt
        while 1:
            z = msvcrt.getch()
            if z == '\3':
                raise KeyboardInterrupt('Ctrl-C break')
            if z == '\0':
                msvcrt.getch()
            else:
                if z == '\r':
                    return '\n'
                return z
    elif os.name == 'posix':
        c = os.read(sys.stdin.fileno(), 1)
        return c
    else:
        import time
        time.sleep(1)
        return None
Ejemplo n.º 21
0
 def get_command():
     """Uses the msvcrt module to get key codes from buttons pressed to navigate through the game. The arrows,
     enter, tab, Page Down, and escape keys are used so far."""
     cmd = ""
     while 1:
         key = ord(getch())
         if key == 224:
             key = ord(getch())
             cmd = arrow_keys.get(key, "")
             return cmd
         elif key == 13:
             putch("\n")
             break
         elif key == 8:
             cmd = cmd[:-1]
             putch(chr(8))
             putch(" ")
             putch(chr(8))
         elif key == 27:
             cmd = 'q'
             return cmd
         elif key == 9:
             cmd = 'tab'
             return cmd
         else:
             putch(chr(key))
             cmd += chr(key)
     return cmd
Ejemplo n.º 22
0
	def getch():
		ch = msvcrt.getch()
		if ord(ch) == 224:
			ch += msvcrt.getch()
		elif ord(ch) == 3:
			raise KeyboardInterrupt
		return ch
Ejemplo n.º 23
0
    def get_user_command(self):
        """Get a command from the user.

        This method displays a prompt to the user and returns when one of
        the command keys is pressed.
        """
        self.cmd_line.display_command()
        cmd_string = ''
        cmd_key = None
        self.tab_count = 0
        while not cmd_key in ['ENTER_POSIX', 'ENTER_WIN']:
            key = getch()
            # If a special key, act on it
            if key in _COMMAND_KEY:
                cmd_key = _COMMAND_KEY[key]
                # Windows does things oddly for some keys
                if not os.name == 'posix' and cmd_key == 'SPECIAL_WIN':
                    key = getch()
                    cmd_key = _WIN_COMMAND_KEY.get(key)
                    if cmd_key is None:
                        continue
                self._process_command_keys(cmd_key)
                cmd_string = self.cmd_line.get_command()
            # else add key to command buffer
            else:
                cmd_string = self.cmd_line.get_command()
                self.cmd_line.add(key)
                cmd_string = self.cmd_line.get_command()
            sys.stdout.flush()

        self.position = 0
        return cmd_string
Ejemplo n.º 24
0
 def p_opts_screen(self, def_num, min_op, max_op, menu):
     enter_not_pressed = True
     while enter_not_pressed:
         cls()
         print()
         print()
         print()
         print(menu[def_num])
         key = ord(getch())
         if key == 224:
             key = ord(getch())
             if key == 72:  # -UP-
                 if def_num == min_op:
                     pass
                 else:
                     def_num -= 1
             if key == 80:  # -DOWN-
                 if def_num == max_op:
                     pass
                 else:
                     def_num += 1
         elif key == 13:
             enter_not_pressed = False
             return def_num
         elif key == 27:
             return False
	def keypress(self):
		
		while True:
			
			key = msvcrt.getch()
			key1 = ""
			if key == u'\xe0'.encode('latin-1'):
				key1 = msvcrt.getch()
			
			
			print "Key:" + key + key1
			
			key = key + key1
			
			if key == u'\xe0M'.encode('latin-1'):
				print 'Right'
				self.tts.next()
			if key == u'\xe0K'.encode('latin-1'):
				print 'Left'
				self.tts.previous()
			if key == 'h':
				print 'Hello'
			if key == 'e':
				self.tts.stopSpeak()
				break;
Ejemplo n.º 26
0
 def __call__(self):
     msvcrt = self.msvcrt
     
     c = msvcrt.getch()
     if c == '\x00' or c == '\xE0':    #functions keys
         msvcrt.getch()
     return c
 def handle_exception(exctype, value, tb):  # pylint: disable=invalid-name
     """Print an exception and wait for a key"""
     traceback.print_exception(exctype, value, tb)
     sys.stderr.flush()
     sys.stdout.write('\n[Press any key]\n')
     sys.stdout.flush()
     msvcrt.getch()
Ejemplo n.º 28
0
 def exit_script(self, error):
     #exit script when an error occured
     print error
     print 'Configuration script stoped.\n'
     print 'Press any key to continue...'
     msvcrt.getch()
     sys.exit(1)
Ejemplo n.º 29
0
def main():
    print("""Please use the Spacebar to tap,
press any other key to finish or r to restart""")
    data = []
    msvcrt.getch()
    lasttime = time.time()
    while True:
        if msvcrt.kbhit():
            key = ord(msvcrt.getch())
            if key == 32:
                data.append(time.time() - lasttime)
                lasttime = time.time()
            elif key == 114:
                main()
                break
            else:
                invData = [60 / x for x in data]
                for d in invData:
                    print(d)
                break
            avg = sum(data) / float(len(data))
            os.system('cls')
            print("""Please use the Spacebar to tap,
press any other key to finish or r to restart""")
            print('Average BPM:', 60 // avg)
Ejemplo n.º 30
0
import socket
import msvcrt

from qlibs.net.asyncsocket import AsyncSocket

sock = AsyncSocket(socket.create_connection(("localhost", 51235)))

while True:
    while msvcrt.kbhit():
        sock.send(msvcrt.getch())
    for c in sock.recv(1):
        msvcrt.putch(bytes([c]))
Ejemplo n.º 31
0
def GetKeydown():
    if msvcrt.kbhit():
        key = msvcrt.getch().decode('UTF-8')
        return key
    return None
Ejemplo n.º 32
0
    def read_input():
        nonlocal timestamp_en
        nonlocal timestamp_input_en
        if os.name == 'nt':
            from msvcrt import getch
        else:
            import tty
            import termios
            stdin_fd = sys.stdin.fileno()
            tty_attr = termios.tcgetattr(stdin_fd)
            tty.setraw(stdin_fd)
            getch = lambda: sys.stdin.read(1).encode()

        while device.is_open:
            ch = getch()
            # print(ch)
            if ch == b'\x1d':  # 'ctrl + ]' to quit
                break
            if ch == b'\x0c':
                screen_clear()  # 'ctrl + l' to clear screen
            if ch == b'\x14':  # 'ctrl + t' to change timestamp status
                timestamp_en = bool(1 - timestamp_en)
            if ch == b'\x00' or ch == b'\xe0':  # arrow keys' escape sequences for windows
                ch2 = getch()
                esc_dict = {
                    b'H': b'A',
                    b'P': b'B',
                    b'M': b'C',
                    b'K': b'D',
                    b'G': b'H',
                    b'O': b'F'
                }
                if ch2 in esc_dict:
                    queue.append(b'\x1b[' + esc_dict[ch2])
                else:
                    queue.append(ch + ch2)
                timestamp_input_en = False
            else:
                queue.append(ch)
                if ch == b' ' or ch == b'\n' or ch == b'\r':
                    timestamp_input_en = False
                elif ch == b'\x1b':  # arrow keys' escape sequences for linux
                    ch2 = getch()
                    if ch2 == b'[':
                        ch2 = getch()
                        esc_dict = {
                            b'A': b'A',
                            b'B': b'B',
                            b'C': b'C',
                            b'D': b'D',
                            b'H': b'H',
                            b'F': b'F'
                        }
                        if ch2 in esc_dict:
                            queue.append(b'[' + esc_dict[ch2])
                        else:
                            queue.append(b'[' + ch2)
                    else:
                        queue.append(ch2)
                    timestamp_input_en = False
                else:
                    timestamp_input_en = True
                # print(queue)

        if os.name != 'nt':
            termios.tcsetattr(stdin_fd, termios.TCSADRAIN, tty_attr)
Ejemplo n.º 33
0
def get_key(key):
    """Read key input."""
    while True:
        vk = ord(msvcrt.getch())
        if vk in (VK_W, VK_A, VK_S, VK_D):
            key.value = vk
Ejemplo n.º 34
0
import sys, msvcrt, time, serial  # pip install pyserial

# serial port uzerinden 'com3' ardunio cihaza baglaniyoruz.
gsmkit = serial.Serial("COM3", 9600, timeout=5)
# 4 saniye bekletiyoruz.
time.sleep(4)
while True:
    # microsoft runtime ile Console I/O islemleri icin ekrana basilan tuslari takip ediyoruz.
    if msvcrt.kbhit():
        # consolda basilan tus varsa ve esc(keykodu 27) ise sistemden cikis yap diyoruz
        if ord(msvcrt.getch()) == 27:
            # cikis
            sys.exit()
        # consolda basilan tus varsa ve tab(keykodu 9) ise input ile komut al
        if ord(msvcrt.getch()) == 9:
            gidecekkomut = input("Cihaza komut yolla:")
            # kullanicidan gelen komutu encode ederek ardunio'ya yolla
            gsmkit.write(
                str(gidecekkomut.replace('\n', '').replace('\r', '') +
                    "\r\n").encode('utf-8'))

    # ardunio uzerinden while ile veri okumak istiyoruz. gelen veriyi decode ediyoruz.
    # errors = kismi cihazdan UTF-8 disinda bir veri gelirse hata vermemesi icin.
    gelen = str(gsmkit.readline().decode('UTF-8', errors='replace'))
    # gelen veri iceriginde yeni satirlari siliyoruz
    gelen = gelen.replace('\r', '').replace('\n', '')
    # gelen veri bir karakterden fazla ise ekrana yansitiyoruz.
    if len(gelen) > 0:
        print(gelen)
Ejemplo n.º 35
0
def check_q():
    if msvcrt.kbhit():
        c = msvcrt.getch()
        if c == b'q':
            return True
    return False
Ejemplo n.º 36
0
def update_db():
    _break = 0
    try:
        while 1:
            if _break:
                break

            paths = []
            try:
                jdb = open(DB_NAME, 'r').read()
            except:
                jdb = json.dumps([])
                main()
            if jdb and json.loads(jdb):
                db = json.loads(jdb)
            else:
                db = []

            for root, directories, filenames in os.walk('C:/Users'):

                filenames = [f for f in filenames if not f[0] == '.']
                directories[:] = [
                    d for d in directories
                    if not d[0] == '.' and "AppData" not in d
                ]

                if "AppData" in directories:
                    directories.remove("AppData")

                if kbhit() and getch() == chr(27).encode():
                    time.sleep(0.1)
                    _break = 1
                    os.remove(DB_NAME)
                    os.remove(SEMAPHORE_NAME)
                    break

                if _break:
                    break

                for filename in filenames:
                    if _break:
                        break

                    path = os.path.join(root, filename)
                    paths.append(path)

                    if path in db:
                        continue

                    db.append(path)
                    jdb = json.dumps(db)
                    open(DB_NAME, 'w').write(jdb)

            while len(db) != len(paths):
                if kbhit() and getch() == chr(27).encode():
                    time.sleep(0.1)
                    _break = 1
                    os.remove(DB_NAME)
                    os.remove(SEMAPHORE_NAME)
                    break

                if _break:
                    break

                for path in db:
                    if _break:
                        break

                    if path not in paths:
                        db.remove(path)
                        jdb = json.dumps(db)
                        open(DB_NAME, 'w').write(jdb)

    except PermissionError:
        update_db()
Ejemplo n.º 37
0
def getPackageData():
    curfile = os.path.dirname(os.path.realpath(__file__))
    names = getPath()
    # make dir
    mkdir(curfile + '\\result')
    shutil.rmtree(curfile + '\\result')
    mkdir(curfile + '\\result')

    log = open(curfile + '\\log.txt', 'wb')
    log.write('result path: ' + curfile + '\\result' + '\n')
    for name in names:
        try:
            getAllData2(curfile + '\\result', curfile + '\\source\\' + name,
                        name)
            print('analysis id = ' + name + ',success')
            log.write('analysis id = ' + name + ',success' + '\n')
        except Exception, e:
            print('analysis id = ' + name + ',fail')
            log.write('analysis id = ' + name + ',fail')
            log.write('message: ' + e.message)
    log.close()
    print('analysis finish')
    print("Press 'd' to exit...")
    while True:
        if ord(msvcrt.getch()) in [68, 100]:
            break


if __name__ == '__main__':
    getPackageData()
Ejemplo n.º 38
0
 def getch():
     return msvcrt.getch().decode()
Ejemplo n.º 39
0
def wait():
    m.getch()
Ejemplo n.º 40
0
def press():
    inp = msvcrt.getch().decode()
    return inp
Ejemplo n.º 41
0
    u_f0p = []
    Bx_field_measured = []
    Bz_field_measured = []
    f_centre_list = []
    f_diff_list = []
    positions = []
    timestamps = []
    pos = 0

    for k in range(len(steps)):

        print '-----------------------------------'
        print 'press q to stop measurement cleanly'
        print '-----------------------------------'
        qt.msleep(5)
        if (msvcrt.kbhit() and (msvcrt.getch() == 'q')):
            break

        GreenAOM.set_power(laser_power)
        optimiz0r.optimize(dims=['x', 'y', 'z', 'x', 'y'], int_time=100)

        step = steps[k]
        pos += step
        positions.append(pos)
        print 'stepping by ' + str(step) + 'to_pos = ' + str(pos)
        if step == 0:
            print 'step = 0, made no steps'
        else:
            if abs(step) / magnet_step_size == 0:
                print 'check your magnet stepsize!'
                break
Ejemplo n.º 42
0
    try:
        cursor.execute(query)
    except (psycopg2.DataError, psycopg2.ProgrammingError) as err:
        print("[EE] PostgreSQL Exception :: {}".format(err), flush=True)
        conn.rollback()
        cursor.close()
        return None
    except Exception as err:
        print("[!!] Exception :: {}\n{}".format(
            err, "".join(traceback.format_exc())),
              flush=True)
        return None
    else:
        conn.commit()
    # __________________________________________________________________________
    return cursor  # <class 'psycopg2.extensions.cursor'>


# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if __name__ == '__main__':
    rc = main()
    # __________________________________________________________________________
    if os.name == 'nt':
        # noinspection PyUnresolvedReferences
        import msvcrt

        print("[..] Press any key to exit", flush=True)
        msvcrt.getch()
    # __________________________________________________________________________
    sys.exit(not rc)  # Compatible return code
Ejemplo n.º 43
0
 def __call__(self):
     import msvcrt
     return msvcrt.getch()
Ejemplo n.º 44
0
def unos():
    global default_smer, zmija, BRZINA_IGRE

    while True:
        if msvcrt.kbhit():

            unos = ord(msvcrt.getch())

            if unos == 27:
                print("Game paused.")
                while True:
                    resume = ord(msvcrt.getch())
                    if resume == 27:
                        print("Game resuming...")
                        time.sleep(1)
                        if msvcrt.kbhit():
                            unos = ord(msvcrt.getch())
                            if unos == 224:
                                default_smer = 224
                                break
                        break
                break

            if unos == 224:
                default_smer = 224
                break
        break

    if default_smer == 224:
        default_smer = ord(msvcrt.getch())

    if default_smer == 77:  # desno

        glava = zmija[-1]
        glava = [glava[0], glava[1] + 1]
        for i in range(len(zmija) - 1):
            zmija[i] = zmija[i + 1]
        zmija[len(zmija) - 1] = glava

    if default_smer == 75:  # levo

        glava = zmija[-1]
        glava = [glava[0], glava[1] - 1]
        for i in range(len(zmija) - 1):
            zmija[i] = zmija[i + 1]
        zmija[len(zmija) - 1] = glava

    if default_smer == 72:  # gore

        glava = zmija[-1]
        glava = [glava[0] - 1, glava[1]]
        for i in range(len(zmija) - 1):
            zmija[i] = zmija[i + 1]
        zmija[len(zmija) - 1] = glava

    if default_smer == 80:  # dole

        glava = zmija[-1]
        glava = [glava[0] + 1, glava[1]]
        for i in range(len(zmija) - 1):
            zmija[i] = zmija[i + 1]
        zmija[len(zmija) - 1] = glava
Ejemplo n.º 45
0
def spin_control(name, data, par):
    par['green_repump_voltage'] = ins_green_aom.power_to_voltage(par['green_repump_amplitude'])
    par['green_off_voltage'] = 0.01#ins_green_aom.power_to_voltage(par['green_off_amplitude'])
    par['Ex_CR_voltage'] = ins_E_aom.power_to_voltage(par['Ex_CR_amplitude'])
    par['A_CR_voltage'] = ins_A_aom.power_to_voltage(par['A_CR_amplitude'])
    par['Ex_SP_voltage'] = ins_E_aom.power_to_voltage(par['Ex_SP_amplitude'])
    par['A_SP_voltage'] = ins_A_aom.power_to_voltage(par['A_SP_amplitude'])
    par['Ex_RO_voltage'] = ins_E_aom.power_to_voltage(par['Ex_RO_amplitude'])
    par['A_RO_voltage'] = ins_A_aom.power_to_voltage(par['A_RO_amplitude'])

    if  (par['SP_duration'] > max_SP_bins) or \
        (par['sweep_length']*par['RO_duration'] > max_RO_dim):
            print ('Error: maximum dimensions exceeded')
            return(-1)

    #print 'SP E amplitude: %s'%par['Ex_SP_voltage']
    #print 'SP A amplitude: %s'%par['A_SP_voltage']

    adwin.start_spincontrol(
        counter_channel = par['counter_channel'],
        green_laser_DAC_channel = par['green_laser_DAC_channel'],
        Ex_laser_DAC_channel = par['Ex_laser_DAC_channel'],
        A_laser_DAC_channel = par['A_laser_DAC_channel'],
        AWG_start_DO_channel = par['AWG_start_DO_channel'],
        AWG_done_DI_channel = par['AWG_done_DI_channel'],
        send_AWG_start = par['send_AWG_start'],
        wait_for_AWG_done = par['wait_for_AWG_done'],
        green_repump_duration = par['green_repump_duration'],
        CR_duration = par['CR_duration'],
        SP_duration = par['SP_duration'],
        SP_filter_duration = par['SP_filter_duration'],
        sequence_wait_time = par['sequence_wait_time'],
        wait_after_pulse_duration = par['wait_after_pulse_duration'],
        CR_preselect = par['CR_preselect'],
        RO_repetitions = par['RO_repetitions'],
        RO_duration = par['RO_duration'],
        sweep_length = par['sweep_length'],
        cycle_duration = par['cycle_duration'],
        green_repump_voltage = par['green_repump_voltage'],
        green_off_voltage = par['green_off_voltage'],
        Ex_CR_voltage = par['Ex_CR_voltage'],
        A_CR_voltage = par['A_CR_voltage'],
        Ex_SP_voltage = par['Ex_SP_voltage'],
        A_SP_voltage = par['A_SP_voltage'],
        Ex_RO_voltage = par['Ex_RO_voltage'],
        A_RO_voltage = par['A_RO_voltage'])
        
    if lt1:
        adwin_lt2.start_check_trigger_from_lt1()

    CR_counts = 0
    while (physical_adwin.Process_Status(9) == 1):
        reps_completed = physical_adwin.Get_Par(73)
        CR_counts = physical_adwin.Get_Par(70) - CR_counts
        cts = physical_adwin.Get_Par(26)
        trh = physical_adwin.Get_Par(25)
        print('completed %s / %s readout repetitions, %s CR counts/s'%(reps_completed,par['RO_repetitions'], CR_counts))
        print('threshold: %s cts, last CR check: %s cts'%(trh,cts))
        if (msvcrt.kbhit() and (msvcrt.getch() == 'q')): 
            break

        qt.msleep(2.5)
    physical_adwin.Stop_Process(9)
    
    if lt1:
        adwin_lt2.stop_check_trigger_from_lt1()

    reps_completed  = physical_adwin.Get_Par(73)
    print('completed %s / %s readout repetitions'%(reps_completed,par['RO_repetitions']))

    sweep_length = par['sweep_length']
    par_long   = physical_adwin.Get_Data_Long(20,1,25)
    par_float  = physical_adwin.Get_Data_Float(20,1,10)
    CR_before = physical_adwin.Get_Data_Long(22,1,1)
    CR_after  = physical_adwin.Get_Data_Long(23,1,1)
    SP_hist   = physical_adwin.Get_Data_Long(24,1,par['SP_duration'])
    RO_data   = physical_adwin.Get_Data_Long(25,1,
                    sweep_length * par['RO_duration'])
    RO_data = reshape(RO_data,(sweep_length,par['RO_duration']))
    SSRO_data   = physical_adwin.Get_Data_Long(27,1,
                    sweep_length * par['RO_duration'])
    SSRO_data = reshape(SSRO_data,(sweep_length,par['RO_duration']))
    statistics = physical_adwin.Get_Data_Long(26,1,10)

    sweep_index = arange(sweep_length)
    sp_time = arange(par['SP_duration'])*par['cycle_duration']*3.333
    ro_time = arange(par['RO_duration'])*par['cycle_duration']*3.333


    data.save()
    savdat={}
    savdat['counts']=CR_after
    data.save_dataset(name='ChargeRO_after', do_plot=False, 
        data = savdat, idx_increment = False)
    savdat={}
    savdat['time']=sp_time
    savdat['counts']=SP_hist
    data.save_dataset(name='SP_histogram', do_plot=False, 
        data = savdat, idx_increment = False)
    savdat={}
    savdat['time']=ro_time
    savdat['sweep_axis']=sweep_index
    savdat['counts']=RO_data
    savdat['SSRO_counts']=SSRO_data
    data.save_dataset(name='Spin_RO', do_plot=False, 
        data = savdat, idx_increment = False)
    savdat={}
    savdat['par_long']=par_long
    savdat['par_float']=par_float
    data.save_dataset(name='parameters', do_plot=False, 
        data = savdat, idx_increment = False)
    
    ######################
    ###statistics file####
    ######################
    savdat={}
    savdat['completed_repetitions']=(reps_completed/sweep_length)
    savdat['total_repumps']=statistics[0]
    savdat['total_repump_counts']=statistics[1]
    savdat['noof_failed_CR_checks']=statistics[2]
    savdat['mw_center_freq']=f_mw
    savdat['mw_drive_freq']=f_drive
    savdat['mw_power']=mwpower
    savdat['min_pulse_nr']=min_pulse_nr
    savdat['max_pulse_nr']=max_pulse_nr
    savdat['min_pulse_amp']=min_pulse_amp
    savdat['max_pulse_amp']=max_pulse_amp
    savdat['min_time'] = min_time
    savdat['max_time'] = max_time
    savdat['noof_datapoints']=nr_of_datapoints
    
    data.save_dataset(name='statics_and_parameters', do_plot=False, 
        data = savdat, idx_increment = True)
   
    return 
Ejemplo n.º 46
0
    def ssro(self, name, data, par):
        par['green_repump_voltage'] = ins_green_aom.power_to_voltage(
            par['green_repump_amplitude'])
        par['green_off_voltage'] = 0.0
        par['Ex_CR_voltage'] = ins_E_aom.power_to_voltage(
            par['Ex_CR_amplitude'])
        par['A_CR_voltage'] = ins_A_aom.power_to_voltage(par['A_CR_amplitude'])
        par['Ex_SP_voltage'] = ins_E_aom.power_to_voltage(
            par['Ex_SP_amplitude'])
        par['A_SP_voltage'] = ins_A_aom.power_to_voltage(par['A_SP_amplitude'])
        par['Ex_RO_voltage'] = ins_E_aom.power_to_voltage(
            par['Ex_RO_amplitude'])
        par['A_RO_voltage'] = ins_A_aom.power_to_voltage(par['A_RO_amplitude'])


        if (par['SSRO_repetitions'] > max_repetitions) or \
            (par['SP_duration'] > max_SP_bins) or \
            (par['SSRO_repetitions'] * par['SSRO_duration'] > max_SSRO_dim):
            print('Error: maximum dimensions exceeded')
            return (-1)

        #print 'SP E amplitude: %s'%par['Ex_SP_voltage']
        #print 'SP A amplitude: %s'%par['A_SP_voltage']

        adwin.start_singleshot(
            load=True,
            stop_processes=['counter'],
            counter_channel=par['counter_channel'],
            green_laser_DAC_channel=par['green_laser_DAC_channel'],
            Ex_laser_DAC_channel=par['Ex_laser_DAC_channel'],
            A_laser_DAC_channel=par['A_laser_DAC_channel'],
            AWG_start_DO_channel=par['AWG_start_DO_channel'],
            AWG_done_DI_channel=par['AWG_done_DI_channel'],
            send_AWG_start=par['send_AWG_start'],
            wait_for_AWG_done=par['wait_for_AWG_done'],
            green_repump_duration=par['green_repump_duration'],
            CR_duration=par['CR_duration'],
            SP_duration=par['SP_duration'],
            SP_filter_duration=par['SP_filter_duration'],
            sequence_wait_time=par['sequence_wait_time'],
            wait_after_pulse_duration=par['wait_after_pulse_duration'],
            CR_preselect=par['CR_preselect'],
            SSRO_repetitions=par['SSRO_repetitions'],
            SSRO_duration=par['SSRO_duration'],
            SSRO_stop_after_first_photon=par['SSRO_stop_after_first_photon'],
            cycle_duration=par['cycle_duration'],
            green_repump_voltage=par['green_repump_voltage'],
            green_off_voltage=par['green_off_voltage'],
            Ex_CR_voltage=par['Ex_CR_voltage'],
            A_CR_voltage=par['A_CR_voltage'],
            Ex_SP_voltage=par['Ex_SP_voltage'],
            A_SP_voltage=par['A_SP_voltage'],
            Ex_RO_voltage=par['Ex_RO_voltage'],
            A_RO_voltage=par['A_RO_voltage'])

        qt.msleep(1)

        CR_counts = 0
        while (physical_adwin.Process_Status(9) == 1):
            reps_completed = physical_adwin.Get_Par(73)
            CR_counts = physical_adwin.Get_Par(70) - CR_counts
            cts = physical_adwin.Get_Par(26)
            trh = physical_adwin.Get_Par(25)
            print('completed %s / %s readout repetitions, %s CR counts/s' %
                  (reps_completed, par['SSRO_repetitions'], CR_counts))
            print('threshold: %s cts, last CR check: %s cts' % (trh, cts))
            if (msvcrt.kbhit() and (msvcrt.getch() == 'q')): break
            qt.msleep(1)
        physical_adwin.Stop_Process(9)

        reps_completed = physical_adwin.Get_Par(73)
        print('completed %s / %s readout repetitions' %
              (reps_completed, par['SSRO_repetitions']))

        par_long = physical_adwin.Get_Data_Long(20, 1, 25)
        par_float = physical_adwin.Get_Data_Float(20, 1, 10)
        CR_before = physical_adwin.Get_Data_Long(22, 1, reps_completed)
        CR_after = physical_adwin.Get_Data_Long(23, 1, reps_completed)
        SP_hist = physical_adwin.Get_Data_Long(24, 1, par['SP_duration'])
        RO_data = physical_adwin.Get_Data_Long(
            25, 1, reps_completed * par['SSRO_duration'])
        RO_data = reshape(RO_data, (reps_completed, par['SSRO_duration']))
        statistics = physical_adwin.Get_Data_Long(26, 1, 10)

        repetitions = arange(reps_completed)
        sp_time = arange(par['SP_duration']) * par['cycle_duration'] * 3.333
        ssro_time = arange(
            par['SSRO_duration']) * par['cycle_duration'] * 3.333

        stat_str = ''
        stat_str += '# successful repetitions: %s\n' % (reps_completed)
        stat_str += '# total repumps: %s\n' % (statistics[0])
        stat_str += '# total repump counts: %s\n' % (statistics[1])
        stat_str += '# failed CR: %s\n' % (statistics[2])
        data.save()
        savdat = {}
        savdat['repetitions'] = repetitions
        savdat['counts'] = CR_before
        data.save_dataset(name='ChargeRO_before',
                          do_plot=False,
                          txt={'statistics': stat_str},
                          data=savdat,
                          idx_increment=False)
        savdat = {}
        savdat['repetitions'] = repetitions
        savdat['counts'] = CR_after
        data.save_dataset(name='ChargeRO_after',
                          do_plot=False,
                          data=savdat,
                          idx_increment=False)
        savdat = {}
        savdat['time'] = sp_time
        savdat['counts'] = SP_hist
        data.save_dataset(name='SP_histogram',
                          do_plot=False,
                          data=savdat,
                          idx_increment=False)
        savdat = {}
        savdat['time'] = ssro_time
        savdat['repetitions'] = repetitions
        savdat['counts'] = RO_data
        data.save_dataset(name='Spin_RO',
                          do_plot=False,
                          data=savdat,
                          idx_increment=False)
        savdat = {}
        savdat['par_long'] = par_long
        savdat['par_float'] = par_float
        data.save_dataset(name='parameters',
                          do_plot=False,
                          data=savdat,
                          idx_increment=False)
        data.save_dataset(name='parameters_dict',
                          do_plot=False,
                          data=par,
                          idx_increment=True)

        return
Ejemplo n.º 47
0
 def __call__(self):
     try:
         import msvcrt
         return msvcrt.getch()
     except: return raw_input('> ')
Ejemplo n.º 48
0
 def WaitFor(self, key):
     while m.getch() != key.lower():
         pass
     return True
Ejemplo n.º 49
0
        time_released = ("Time Released: " + str(startTime))
        print(time_released)

        time_back = ("Time Back: " + str(endTime))
        print(time_back)

        # file1.write(str(final_list))
        file1.write("Log:" + "\n")
        file1.write(
            str(time_out) + "\n" + str(student_out) + "\n" +
            str(time_released) + "\n" + str(time_back))

        print('\n' +
              "Do you want to continue? (ESC to exit, ENTER to continue)")

        key = ord(getch())
        if key == 27:  #ESC
            break

        # if msvcrt.kbhit():
        # 	if ord(msvcrt.getch()) == 27:
        # 		break
    file1.close()

# except
#------------------------------------------------------------------------

# import os.path

# save_path  = "C:\\Users\\Imam\\Documents\\PROGRAMMING PROJECTS"
# End of program, steps have finished or someone has cancelled the scan process
if curStep < len(steps) and scanconfig.cte_verbose:
    # Scan process was cancelled
    print("Scan process was cancelled")
    dummy = 0  # Dummy for avoiding indentation failures

db.commit()
db.close()

if scanconfig.cte_step_wait_for_key:
    import os
    if os.name == 'nt':
        import msvcrt
        print "Press any key to close document"
        if msvcrt.kbhit():
            ret = msvcrt.getch()
            done = True

    else:
        from getch import getch, pause
        pause("Press any key to close document")

if scanconfig.cte_export_ods:
    doc.save("./db/" + timestr + ".ods")
    doc.close()

if scanconfig.cte_export_openpyxl:
    doc.save("./db/" + timestr + ".xlsx")

if scanconfig.cte_use_cvcam:
    cam.release()
Ejemplo n.º 51
0
def keypress():
    return getch()
Ejemplo n.º 52
0
 def getchar():
     firstChar = getch()
     if firstChar == b'\xe0':
         return {b"H": "up", b"P": "down", b"M": "right", b"K": "left", b"G": "Home", b"O": "End", b"R": "Ins", b"S": "Del", b"I": "PgUp", b"Q": "PgDn"}[getch()]
     else:
         return firstChar
Ejemplo n.º 53
0
    process_record = []
    res_queue = multiprocessing.Queue()
    for ip in ip_list:
        process = multiprocessing.Process(target=ping_res,
                                          args=(ip, res_queue, 5))
        process.start()
        process_record.append(process)

    for process in process_record:
        process.join()

    best = (None, 100)
    for _ in process_record:
        ip_rate = res_queue.get()
        if ip_rate[1] < best[1]:
            best = ip_rate

    print("\nThe recommend choice:{} \n with failure rate: {}%.".format(
        best[0], best[1]))


if __name__ == "__main__":
    print("IP addresses with the minimum failure rate are available.")
    print("Start querying...")
    # select_best
    select_best_mul()
    print("Enter 'y' to end...")
    while msvcrt.getch() != b"y":
        pass
Ejemplo n.º 54
0
import colorama as cr
cr.init()

from msvcrt import getch



UP = '\x1b[1A'
DOWN = '\x1b[1B'
RIGHT = '\x1b[1C'
LEFT = '\x1b[1D'
CLEAR = '\x1b[1J'+'\x1b[0J'

print('@'+LEFT, end='')
while True:
    move = getch()
    if move == b'H':
        print('@'+LEFT+UP, end='@'+LEFT)
    elif move == b'P':
        print('@'+LEFT+DOWN, end='@'+LEFT)
    elif move == b'M':
        print('@'+LEFT+RIGHT, end='@'+LEFT)
    elif move == b'K':
        print('@'+LEFT+LEFT, end='@'+LEFT)
    elif move == b'k':
        quit()
    elif move == b'S':
        print(CLEAR, end='@'+LEFT)


Ejemplo n.º 55
0
# Windows keys...
from msvcrt import getch
while True:
       print(str(ord(getch())))
Ejemplo n.º 56
0
 def GetInput(self):
     return m.getch()
Ejemplo n.º 57
0
def main(asc_file, point, k, bins, fs1, noverlap, nfft, fs2, cut_freq,
         filter_order):
    # 不带K 的
    # def main(asc_file, point, bins, fs1, noverlap, nfft, fs2, cut_freq, filter_order):

    # 读取为dataframe

    print("开始读取文件.....")
    df_file = asc_to_df(asc_file)

    # 取单通道,暂时测试数据只有一列,待使用多线程实现------------问题1
    print("取单通道.....")
    # single_point = df_file.iloc[:, 1]
    single_point = df_file.iloc[:, point]

    # 数据格式规整,科学计数法--> 浮点数
    print("数制转换.....")
    # 带K 的
    temp = partial(format_data, k)
    ylst = list(map(temp, single_point))

    # 不带K 的
    # ylst = list(map(format_data, single_point))

    # PSD计算
    print("开始PSD计算.....")
    [Pxx, freqs] = My_PSD(ylst, fs1, noverlap, nfft)

    # 得到波形开始平滑的点,作为低通截止频率,待实现------------问题2
    # cut_freq = get_fc(Pxx, freqs)
    # cut_freq = 20					# 此处将截止频率暂定为 20Hz,1号线大概我16Hz

    # 滤波
    print("开始滤波.....")
    ylst = My_filter(ylst, fs2, cut_freq, filter_order)

    # 雨流开始
    # 先读取为dataframe格式
    ori_df = pd.DataFrame(ylst)

    # 步骤一:转换为峰谷值序列
    print("开始峰谷值转换.....")
    dfB = covert2_PV_Series(ori_df)
    dfB['index'] = range(dfB.shape[0])
    dfB.set_index('index', inplace=True)

    # 步骤二:判断并剔除range-pairs
    print("开始判断并剔除range-pairs.....")
    [F, J] = judge_del_rangePairs(dfB)

    # ----------------
    # 得到计数结果
    Fcounts = my_count(F, bins)

    # 导出计数结果
    # Jcounts = my_count(J)
    # 画图
    my_plot(Fcounts)  # 暂时显示的是PSD图,而非rainflow图,

    # 退出
    print("请按任意键退出程序:")
    anykey = ord(msvcrt.getch())  # 此刻捕捉键盘,任意键退出
    if anykey in range(0, 256):
        print("Have a nice day =。=")
        time.sleep(1)
        sys.exit()
Ejemplo n.º 58
0
client = airsim.MultirotorClient()
client.confirmConnection()
client.enableApiControl(True)
client.armDisarm(True)
client.takeoffAsync().join()

z = -7

duration = 0.1
speed = 1
delay = duration * speed

keepGoing = True
while (keepGoing):
    input_char = msvcrt.getch()
    if (input_char == b'w'):
        vx = speed
        vy = 0
        client.moveByVelocityZAsync(vx, vy, z, duration,
                                    airsim.DrivetrainType.MaxDegreeOfFreedom,
                                    airsim.YawMode(False, 0)).join()
        time.sleep(delay)
    elif (input_char == b's'):
        vx = -speed
        vy = 0
        client.moveByVelocityZAsync(vx, vy, z, duration,
                                    airsim.DrivetrainType.MaxDegreeOfFreedom,
                                    airsim.YawMode(False, 0)).join()
        time.sleep(delay)
    elif (input_char == b'a'):
Ejemplo n.º 59
0
def keypress():
    global char
    char = getch()
Ejemplo n.º 60
-1
def alarm(seconds):
    time.sleep(seconds)
    while msvcrt.kbhit():
        msvcrt.getch()
    while not msvcrt.kbhit():
        winsound.Beep(440, 250)
        time.sleep(0.25)