コード例 #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
コード例 #2
7
ファイル: stools.py プロジェクト: AdriaanRol/measurement
def recalibrate_lasers(names = ADWINAOMS, awg_names = AWGAOMS):    
    turn_off_all_lasers()
    for n in names:
        if (msvcrt.kbhit() and (msvcrt.getch() == 'q')): break
        stools.recalibrate_laser(n, PMSERVO, ADWIN)
    
    for n in awg_names:
        if (msvcrt.kbhit() and (msvcrt.getch() == 'q')): break
        stools.recalibrate_laser(n, PMSERVO, ADWIN, awg=True)
コード例 #3
0
ファイル: recipe-510390.py プロジェクト: bhramoss/code
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)
コード例 #4
0
ファイル: labutils.py プロジェクト: Agueeva/bert100
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
コード例 #5
0
ファイル: pong.py プロジェクト: rmccampbell/PythonProjects
def update():
    global bx, by, vx, vy, p1, p2, score, paused
    if msvcrt.kbhit():
        k = msvcrt.getch()
        if msvcrt.kbhit():
            k += msvcrt.getch()
        if k == b'\xe0K' and not paused:
            p1 -= 2
        elif k == b'\xe0M' and not paused:
            p1 += 2
        elif k == b'p':
            paused = not paused
        elif k in (b'\x1b', b'q'):
            return QUIT
    if paused:
        return CONT
    p1 = max(4, min(W-5, p1))
    p2 = max(4, min(W-5, bx))
    bx += vx
    by += vy
    if bx == 0 or bx == W-1:
        vx = -vx
    if by == 1 and abs(bx - p2) < 5:
        vy = -vy
    if by == H-2 and abs(bx - p1) < 5:
        vy = -vy
        score += 1
    if by < 0:
        return WIN
    if by >= H:
        return LOSE
    return CONT
コード例 #6
0
ファイル: ai.py プロジェクト: 0xFAIL/lantern
def player(sm, sprite, fb, global_frame_number: int):
    fb_width = len(fb[0])
    fb_height = len(fb)
    # Reduce invincibility frames TODO checks if attribute exists or better, make invincibility more generic
    if sprite.info['invincibility'] > 0:
        sprite.info['invincibility'] -= 1
    # Player movement
    if msvcrt.kbhit():
        x = sprite.info['x']
        y = sprite.info['y']
        parsed_chars = set()
        while msvcrt.kbhit():
            input_char = msvcrt.getch()
            input_int = struct.unpack('B', input_char)[0]
            if input_int in parsed_chars:
                continue
            parsed_chars.add(input_int)
            if input_char == b'w':
                sprite.info['y'] = max(0, y - 2)
            if input_char == b's':
                sprite.info['y'] = min(fb_height - sprite.info['height'], y + 2)
            if input_char == b'a':
                sprite.info['x'] = max(0, x - 3)
            if input_char == b'd':
                sprite.info['x'] = min(fb_width - sprite.info['width'], x + 3)
            if input_char == b'\x1b':
                # See game loop for details
                sprite.info['ai_quit_to_main_menu'] = True
    # Player is shooting every 10 frames
    sprite.info['ai_last_move'] += 1
    if sprite.info['ai_last_move'] > 3:
        sm.add_sprite('projectile_p_big', sprite.info['x'] + sprite.info['width'], sprite.info['y'])
        sprite.info['ai_last_move'] = 0
コード例 #7
0
ファイル: fsm_back_and_forth.py プロジェクト: liuche/qtlab
def main():
    channel = 'X' # This can be 'X' or 'Y' channels
    min_position = -10 # Volts
    max_position = 10 # Volts
    rate = 100 # number of points written per second to DAQ
    density = 100 # number of points across the full scale range
    wait = 1 # Wait time before sweeping back in seconds

    x_V_array_f = numpy.linspace(min_position,max_position,density)
    x_V_array_b = numpy.linspace(max_position,min_position,density)
    fsm = qt.instruments['fsm']

    while 1:
        if (msvcrt.kbhit() and (msvcrt.getch() == 'q')): break
        print 'Sweeping %s forward...' % channel
        fsm.simple_sweep_V(x_V_array_f,rate,channel)
        time.sleep(wait)
        if (msvcrt.kbhit() and (msvcrt.getch() == 'q')): break
        print 'Sweeping %s backward...' % channel
        fsm.simple_sweep_V(x_V_array_b,rate,channel)
        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(fsm, f_string)
    reset_channel(0.0)
    return
コード例 #8
0
def ingreso_rapido():
    print "Ingrese el numero de la carta: "
    cr = 0
    while True:
        if kbhit():
            n = getch()
            if (n.isdigit() == False) or (int(n) < 1) or (int(n) > 12):
                print "Numero ingresado incorrecto"
            else:
                n2 = int(n)
                if (cr == 0) and (n2 == 1):
                    tt = n2
                    cr = 1
                elif (cr == 1) and (n2 == 1):
                    n2 += tt
                    break
                else:
                    break
                n = str(n2)
    print "Ingrese el palo de la carta: "
    while True:
        if kbhit():
            palo = getch()
            if palo not in ['c', 'o', 'e', 'b']:
                print "Palo ingresado incorrecto"
            else:
                break
    return n+palo
コード例 #9
0
ファイル: Interface.py プロジェクト: BackupTheBerlios/pws
def getKey():
    import msvcrt
    if msvcrt.kbhit():
        msvcrt.getch()
    while (1):
        if msvcrt.kbhit():
            msvcrt.getch()
            break
コード例 #10
0
ファイル: stools.py プロジェクト: AdriaanRol/measurement
def recalibrate_lt2_lasers(names=['MatisseAOM', 'NewfocusAOM', 'GreenAOM', 'YellowAOM'], awg_names=['NewfocusAOM']):
    turn_off_all_lt2_lasers()
    for n in names:
        if (msvcrt.kbhit() and (msvcrt.getch() == 'q')): break
        recalibrate_laser(n, 'PMServo', 'adwin')
    for n in awg_names:
        if (msvcrt.kbhit() and (msvcrt.getch() == 'q')): break
        recalibrate_laser(n, 'PMServo', 'adwin',awg=True)
コード例 #11
0
ファイル: exitcontrol.py プロジェクト: takluyver/latus
 def run(self):
     this_char = ''
     while this_char != self.exit_criteria:
         # print("waiting for", self.exit_criteria)
         msvcrt.kbhit() # waits for the keyboard hit
         this_char = msvcrt.getwch() # eats the character just hit
         if this_char == self.exit_criteria:
             self.trigger_all_events()
         else:
             print("waiting for '%s' : got '%s'" % (str(self.exit_criteria), this_char))
コード例 #12
0
 def __call__(self):
   import msvcrt
   if msvcrt.kbhit():
     while msvcrt.kbhit():
       ch = msvcrt.getch()
     while ch in b'\x00\xe0':
       msvcrt.getch()
       ch = msvcrt.getch()
     return ord( ch.decode() )
   else:
     return -1
コード例 #13
0
def countdown(timeout):
    '''A countdown function, asking for a keypress.
    It returns whether a key was pressed during countdown or not.
    Works on both linux on windows. Timeout in seconds.'''
    sys.stdout.write("Press any key to abort... %02d" % (timeout))
    sys.stdout.flush()
    keypressed = False
    try:
        # Windows
        import msvcrt
        while not msvcrt.kbhit() or timeout == 0:
            time.sleep(1)
            timeout = timeout - 1
            sys.stdout.write("\b"*len("%02d"%(timeout+1)) + "%02d"%(timeout))
            sys.stdout.flush()
        if msvcrt.kbhit():
            keypressed = True
    except:
        # Linux
        try:
            import termios, select
            fd = sys.stdin.fileno()
            new_term = termios.tcgetattr(fd)
            old_term = termios.tcgetattr(fd)
            # new terminal setting unbuffered
            new_term[3] = (new_term[3] & ~termios.ICANON & ~termios.ECHO)
            # switch to unbuffered terminal
            termios.tcsetattr(fd, termios.TCSAFLUSH, new_term)

            dr, _, _ = select.select([sys.stdin], [], [], 0)
            while dr == [] and timeout > 0:
                time.sleep(1)
                timeout = timeout - 1
                sys.stdout.write("\b"*len("%02d"%(timeout+1)) + "%02d"%(timeout))
                sys.stdout.flush()
                dr, _, _ = select.select([sys.stdin], [], [], 0)

            if dr != []:
                keypressed = True
        finally:
            try:
                # switch to normal terminal
                termios.tcsetattr(fd, termios.TCSAFLUSH, old_term)
            except:
                sys.stdout.write("\nAttention: Terminal unacessable. If SGpp was built within Eclipse, everything is fine!\n")
                sys.stdout.flush()
                return keypressed

    sys.stdout.write("\n")
    sys.stdout.flush()
    return keypressed
コード例 #14
0
ファイル: game_play.py プロジェクト: q2nev/MixMaster
def ascii_challenge(stop):
    '''
    separate image_to_ascii function to have guessing game.
    image_folder: where the images are stored
    (All images need to have 3-letter formats a.k.a. .jpegs won't work)
    img: string from stop.attrs
    img_txt: possible text string that would've already been generated
    '''
    global rhymes
    global ats
    play_music(stop,True) #pauses music
    image_folder = os.listdir('images/')
    img = str(stop.attrs["im"]).strip(string.whitespace)
    img_txt = img[:-4]+'.txt'
    logging.debug("Image Text:",img_txt) #log image text for debugging
    play_music(stop)
    boss = str(stop.attrs["kw"]).strip(string.whitespace)
    if img_txt not in image_folder: #convert image to txt file if not already.
        print "Converting jpg to txt!"
        ascii_string = ASC.image_diff('images/'+img)
        fin = open('images/'+img_txt,'w')
        print "file opened"
        for i in range(len(ascii_string)):
            fin.write(ascii_string[i]+'\t')
        fin.close()
    with open('images/'+img_txt) as f:
        lines = f.read()
        print "Guess ascii by pressing enter!"
        for l in lines.split('\t'):
            while not msvcrt.kbhit():
                time.sleep(1.2)
                print l
                break

            while msvcrt.kbhit():
                play_music(stop,True)
                msvcrt.getch()
                print "_________________________________________________________________"
                print "What's your guess?"
                print boss
                boss_guess = raw_input(">>")
                if boss_guess[:2] == boss[:2]:
                    play_music(stop)
                    print "You guessed right! Here are 5 hashes and ats for your prowess!"
                    rhymes += 5
                    ats += 5
                    return rhymes, ats
                else:
                    print "You guessed wrong!"
                    play_music(stop)
    return rhymes,ats
コード例 #15
0
ファイル: game_play2.py プロジェクト: q2nev/PusherMan
def image_to_ascii(stop):
    '''
    separate image_to_ascii function to have guessing game.
    image_folder: where the images are stored
    img:
    img_txt: possible text string that would've already been generated
    '''
    global hashes
    global ats
    image_folder = os.listdir('images/')
    img= str(stop.attrs["im"]).strip(string.whitespace)
    img_txt = img[:-4]+'.txt'

    play_music(stop)
    boss_kw = str(stop.attrs["nomen"]).strip(string.whitespace)
    if img_txt in image_folder:
        with open('images/'+img_txt) as f:
            lines = f.read()
            print "Guess ascii by pressing enter!"

            for l in lines.split('\t'):

                while not msvcrt.kbhit():
                    time.sleep(1.5)
                    break
                print l

                while msvcrt.kbhit():
                    msvcrt.getch()
                    play_music(stop,False)
                    print "-----------------------------------------------"
                    print "What's your guess?"
                    boss_guess = raw_input(">>")

                    if boss_guess == boss_kw:
                        print "You guessed right! Here are 5 hashes and ats for your prowess!"
                        hashes += 5
                        ats += 5

                        break
    else:
        #try:
        ascii_string = ASC.image_diff('images/'+img)
        print type(ascii_string)
        fin = open('../images/'+img_txt,'w')
        print "file opened"
        for i in range(len(ascii_string)):
            fin.write(ascii_string[i]+'\t')
        fin.close()
コード例 #16
0
ファイル: ttx.py プロジェクト: MauricioAndrades/fonttools
def waitForKeyPress():
	"""Force the DOS Prompt window to stay open so the user gets
	a chance to see what's wrong."""
	import msvcrt
	print('(Hit any key to exit)', file=sys.stderr)
	while not msvcrt.kbhit():
		pass
コード例 #17
0
    def _wait_for_interval(self):
        """Wait for the time interval to expire
        
        This method issues a timing loop to wait for the specified interval to
        expire or quit if the user presses 'q' or 'Q'. The method passes all
        other keyboard requests to the _do_command() method for processing.

        If the interval expires, the method returns None.
        If the user presses a key, the method returns the numeric key number.
        
        Returns - None or int (see above)        
        """
        # If on *nix systems, set the terminal IO sys to not echo
        if os.name == "posix":
            import tty, termios
            old_settings = termios.tcgetattr(sys.stdin)
            tty.setcbreak(sys.stdin.fileno())
            
        key = None
        done = False
        # loop for interval in seconds while detecting keypress 
        while not done:
            done = self.alarm <= time.time()
            if kbhit() and not done:
                key = getch()
                done = True

        # Reset terminal IO sys to older state
        if os.name == "posix":
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)

        return key
コード例 #18
0
ファイル: application.py プロジェクト: zfn-ww/frida-python
def input_with_timeout(timeout):
    if platform.system() == 'Windows':
        start_time = time.time()
        s = ''
        while True:
            while msvcrt.kbhit():
                c = msvcrt.getche()
                if ord(c) == 13: # enter_key
                    break
                elif ord(c) >= 32: #space_char
                    s += c
            if time.time() - start_time > timeout:
                return None

        return s
    else:
        while True:
            try:
                rlist, _, _ = select.select([sys.stdin], [], [], timeout)
                break
            except (OSError, select.error) as e:
                if e.args[0] != errno.EINTR:
                    raise e
        if rlist:
            return sys.stdin.readline()
        else:
            return None
コード例 #19
0
ファイル: term.py プロジェクト: dangjoeltang/SimpleShop
 def readInput():
     start_time = time.time()
     while True:
         if kbhit():
             return _getch()
         if (time.time() - start_time) > timeout:
             return None
コード例 #20
0
ファイル: 2048.py プロジェクト: rmccampbell/PythonProjects
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
コード例 #21
0
 def getPressedKey(self): 
     
     try:
         #LINUX implementation
         import select
     
         i,o,e = select.select([sys.stdin],[],[],0.0001)
         for s in i:
             if s == sys.stdin:
                 input = sys.stdin.readline()
                 return input
         return 0
     except Exception:
         pass
         
     try:
         #WINDOWS implementation
         import msvcrt
         
         x = msvcrt.kbhit()
         if x: 
             ret = ord(msvcrt.getch()) 
         else: 
             ret = 0 
         return ret
     except Exception:
         pass
コード例 #22
0
ファイル: libastyle.py プロジェクト: amremam2004/astyle
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')
コード例 #23
0
def main():
    m.generate_sequence()
    adpar["max_LDE_duration"] = int(m.seq.element_lengths["lde"] * float(m.max_LDE_attempts) * 1e6 + 1.0)

    for idx in arange(m.measurement_cycles):
        m.setup(adwin_mdevice_lt2=adwin_mdevice_lt2)

        print "============================="
        print "Starting measurement cycle", idx
        print "current time:", time.strftime("%H:%M", time.localtime())
        print "============================="

        ch0, ch1, mrkr = m.measure(adwin_lt2_params=adpar)
        addata = m.get_adwin_data()
        m.save(ch0_events=ch0, ch1_events=ch1, markers=mrkr, **addata)

        if m.measurement_cycles != 0:
            print "Press q to abort next cycle"
            qt.msleep(2)
            if msvcrt.kbhit():
                kb_char = msvcrt.getch()
                if kb_char == "q":
                    break

        # if  idx < m.measurement_cycles-1: m.optimize(lt1 = False, lt2 = True)

        # if False in m.check_suppression(lt1 = False, lt2 = True):
        #    print 'Bad suppression detected, breaking.'
        #    break

    m.end()
    print "Measurement finished!"
コード例 #24
0
ファイル: termutils.py プロジェクト: Kopachris/py-id003
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
コード例 #25
0
def kbfunc(): 
   x = msvcrt.kbhit()
   if x: 
      ret = ord(msvcrt.getch()) 
   else: 
      ret = 0 
   return ret
コード例 #26
0
ファイル: utils.py プロジェクト: GunioRobot/pymc
def getInput():
    """Read the input buffer without blocking the system."""
    input = ''

    if sys.platform=='win32':
        import msvcrt
        if msvcrt.kbhit():  # Check for a keyboard hit.
            input += msvcrt.getch()
            print input
        else:
            time.sleep(.1)


    else: # Other platforms
        # Posix will work with sys.stdin or sys.stdin.fileno()
        # Mac needs the file descriptor.
        # This solution does not work for windows since select
        # expects a socket, and I have no idea how to create a
        # socket from standard input.
        sock = sys.stdin.fileno()

        #select(rlist, wlist, xlist, timeout)
        while len(select.select([sock], [], [], 0.1)[0])>0:
            input += os.read(sock, 4096)

    return input
コード例 #27
0
ファイル: ssro.py プロジェクト: wpfff/teamdiamond_measuring
def RO_saturation_power(name):
    m = ssro.AdwinSSRO('RO_saturation_power_'+name)
    
    m.params.from_dict(qt.cfgman['protocols']['AdwinSSRO'])
    m.params.from_dict(qt.cfgman['protocols'][SAMPLE_CFG]['AdwinSSRO']) 
    
    m.params['SSRO_repetitions'] = 2000
    m.params['pts'] = 15
    pts = m.params['pts']
    step = 1e-9

    m.params['CR_preselect'] = 1000
    m.params['CR_probe'] = 10
    m.params['A_SP_amplitude'] =  10e-9
    m.params['Ex_SP_amplitude'] = 0.
    m.params['Ex_RO_amplitudes'] = np.arange(pts) * step + step
    m.params['SSRO_duration'] = 50

    for i,p in enumerate(m.params['Ex_RO_amplitudes']):
        if (msvcrt.kbhit() and (msvcrt.getch() == 'c')): break
        
        print
        print '{}/{}: P = {} '.format(i+1, pts, p) 
        m.params['Ex_RO_amplitude'] = p
        #m.params['A_RO_amplitude'] = p
        m.run()
        m.save('P_{:.1f}_nW'.format(p*1e9))
        
    m.finish()
コード例 #28
0
ファイル: pySync.py プロジェクト: snullp/pySync
 def flush_input(str):
     while msvcrt.kbhit():
         ch = msvcrt.getch()
         if ch == '\xff':
             print("msvcrt is broken, this is weird.")
             sys.exit(0)
     return input(str)
コード例 #29
0
ファイル: puzzle_16.py プロジェクト: madolinn/Development
def begin():
	global completed
	if (completed != 0):
		write("I can't deal with the creepers anymore.")
		puzzles.functions.wait()
		return
	os.system('cls')
	write("Oh jeeze what now. Who is this clown? Dressed in a clown suit in the middle\nof a forest.")
	puzzles.functions.wait()
	write("\n\nHe gestures me over. Whatever. Let's get this over with.\nHe begins talking.. But I have other plans")
	puzzles.functions.wait()
	time.sleep(1)
	os.system('cls')
	write("Press the corresponding keys on the keyboard as they appear on the screen.\nPressing them quickly will net you a better score.")
	puzzles.functions.wait()
	time.sleep(1)
	os.system('cls')
	time.sleep(1)
	set_color(4)
	write("\tWELCOME")
	time.sleep(1)
	write("\n\t\tTO")
	time.sleep(1)
	write("\n\t\t\tPUNCH PUNCH")
	time.sleep(1)
	write("\n\t\t\t\t\t~REVOLUTION~")
	time.sleep(2)
	os.system('cls')
	
	score = 0
	letter = -1
	timer = 0
	
	start = time.clock()
	
	set_cursor_attr(100,False)
	
	while score < 30:
		set_color(6)
		set_cursor(0,0)
		write(["SCORE: ",score," "*20])
		if (letter == -1):
			timer = time.clock()
			letter = random.randint(0,25)
		else:
			set_color(8)
			set_cursor(40,5)
			write(chr(letter+97))
		if msvcrt.kbhit():
			keycode = int.from_bytes(msvcrt.getch(), byteorder='big')
			if (keycode >= 97 and keycode <= 122):
				if (keycode-97 == letter):
					score += int(((timer+4)-time.clock()))
					letter = -1
	os.system('cls')
	write(["Congratulations, you punched out the creeper in ",str(int((time.clock()-start)*10)/10)," seconds!"])
	time.sleep(1)
	puzzles.functions.wait()
	return True
	
コード例 #30
0
        for x in range(gridSizeX):
            field = _grid[(x, y)].field
            if field > 0:
                sys.stdout.write(Back.RED)
            if cursor[0] == x and cursor[1] == y:
                sys.stdout.write(Back.WHITE)
            sys.stdout.write(str("{:10.4f}".format(field)))
            sys.stdout.write(Style.RESET_ALL+" ")
        sys.stdout.write("\n")
        sys.stdout.flush()


buildGrid()
while True:
    time.sleep(TimePerStep)
    if kbhit():
        key = ord(getch())
        if key == 120:  # x
            print("Exit")
            break
        elif key == 32:  # space
            print("Pause")
            simulate = not simulate
        elif key == 113:  # q
            print("spawn")
            Grid[cursor[0], cursor[1]].item = "source"
            Grid[cursor[0], cursor[1]].field = 9
            simulate = True
        elif key == 97:  # a
            print("left")
            cursor[0] -= 1
コード例 #31
0
 def close(self, delay = 0):
     if delay:
         time.sleep(delay)
         while msvcrt.kbhit():
             msvcrt.getch()
コード例 #32
0
        "class": "DFlfde SwHCTb",
        "data-precision": 2
    })
    print(f"1$ = {convert[0].text}₽")


def euro():
    full_page = requests.get(URL_EURO,
                             headers=headers)  # содержиться вся html разметка

    # указываем через что будет парситься данная разметка bs4
    soup = BeautifulSoup(full_page.content, 'html.parser')

    # поиск по тегам
    convert = soup.findAll("span", {
        "class": "DFlfde SwHCTb",
        "data-precision": 2
    })
    print(f"1€ = {convert[0].text}₽")


while True:
    dollar()
    euro()
    time.sleep(3)

    if msvcrt.kbhit():  # если нажата клавища
        k = ord(msvcrt.getch())  # считываем код клавиши
        if k == 27:  # если клавиша Esc
            sys.exit()  # завершаем программу
コード例 #33
0
                            male+=1

        if old==0 and count>0:
            print("No of Humans are:",count)
            print("Female :",female)
            print("Male :",male)
            send=str(count) # +" "+str(male)+" "+str(female) this was removed
            s.sendto(send.encode('ascii'),soc)
            old=count
        elif count>=old+ranger:
            print("No of Humans are:",count)
            print("Female :",female)
            print("Male :",male)
            send=str(count)# +" "+str(male)+" "+str(female)
            s.sendto(send.encode('ascii'),soc)
            old=count
        elif count<old:
            print("No of Humans are:",count)
            print("Female :",female)
            print("Male :",male)
            send=str(count)# +" "+str(male)+" "+str(female)
            s.sendto(send.encode('ascii'),soc)
            old=count
        if cv2.waitKey(1) & msvcrt.kbhit():
            if ord(msvcrt.getch()) == 27:
                break

    cv2.destroyAllWindows()
    cap.release()
    print("\n\n\tBYEBYE\n\n")
コード例 #34
0
ファイル: film_images.py プロジェクト: edgarskos/Film-bot
 def kbfunc(self):
     return msvcrt.getch() if msvcrt.kbhit() else "Z"
コード例 #35
0
        #Run faster because it only walk calc window once
        id2char = {v: k for k, v in char2Id.items()}
        char2Button = {}
        for c, d in auto.WalkControl(calcWindow, maxDepth=4):
            if c.AutomationId in id2char:
                char2Button[id2char[c.AutomationId]] = c
    Calc(calcWindow, char2Button, '1234 * (4 + 5 + 6) - 78 / 90.8')
    Calc(calcWindow, char2Button, '3*3+4*4')
    Calc(calcWindow, char2Button, '2*3.14159*10')
    calcWindow.CaptureToImage(
        'calc.png', 7, 0, -14,
        -7)  # on windows 10, 7 pixels of windows border are transparent
    calcWindow.Disappears(1)
    calcWindow.GetWindowPattern().Close()
    calcWindow.Exists(1)


if __name__ == '__main__':
    osVersion = os.sys.getwindowsversion().major
    if osVersion < 6:
        CalcOnXP()
    elif osVersion == 6:
        CalcOnWindows7And8()
    elif osVersion >= 10:
        CalcOnWindows10()

    auto.Logger.Write('\nPress any key to exit', auto.ConsoleColor.Cyan)
    import msvcrt
    while not msvcrt.kbhit():
        pass
コード例 #36
0
 def keypressed():
     x = msvcrt.kbhit()
     if x:
        return ord(msvcrt.getch())
     else:
        return 0
コード例 #37
0
			NuclearRamseyWithInitialization_cal(SAMPLE+'_msm1_freq_C'+str(c), carbon_nr= c, detuning = detuning, el_state = 1)
			# fit
			f0, uf0 = cr.Carbon_Ramsey(timestamp=None, 
			              offset = 0.5, amplitude = 0.3, x0=0, decay_constant = 1e5, exponent = 2, 
			              frequency = detuning, phase =0, 
			              plot_fit = True, show_guess = False,fixed = [2,3,4],            
			              return_freq = True,
			              return_results = False,
			              title = 'msm1_freq_C'+str(c))
			#update
			qt.exp_params['samples']['111_1_sil18']['C'+str(c)+'_freq_1'] += -f0 + detuning
			print 'press q to stop measurement loop'
			print '--------------------------------'
			qt.msleep(5)
			if msvcrt.kbhit() and msvcrt.getch() == 'q':
				n = 0
	
	
###############################################################
###### 				Calibrate ms=0 frequencies 	 		 ######
###############################################################
if n == 1 and f_ms0:
	qt.exp_params['protocols']['111_1_sil18']['AdwinSSRO+C13']['C13_MBI_RO_duration'] = 60
	qt.exp_params['protocols']['111_1_sil18']['AdwinSSRO+C13']['SP_duration_after_C13'] = 250
	qt.exp_params['protocols']['111_1_sil18']['AdwinSSRO+C13']['A_SP_amplitude_after_C13_MBI'] = 15e-9
	print 'Calibrate ms=0 frequencies'
	# measure
	for c in carbons:
		if n == 1:
			NuclearRamseyWithInitialization_cal(SAMPLE+'_msm0_freq_C'+str(c), carbon_nr= c, 
コード例 #38
0
        if safemode == True: 
            print '\a\a\a' 
            ri = raw_input ('move magnet? (y/n)')
            if str(ri) != 'y': 
                break
        
        ## Actually move the magnet
        magnet_Z_scanner.MoveRelative(delta_position)
        print 'moving magnet...'

        print '--------------------------------'
        print 'press q to stop measurement loop'
        print '--------------------------------'
        qt.msleep(2)
        if (msvcrt.kbhit() and (msvcrt.getch() == 'q')) or abs(move_to_position-current_position) < 0.000025:
            break

        # Measure new magnetic field
        if delta_f0_temp > 300 and only_fine == False:
            darkesr('magnet_Zpos_optimize_coarse_repeat', range_MHz=coarse_range, pts=coarse_pts, reps=coarse_reps, 
                power = coarse_amplitude, MW_power = coarse_MW_power, pulse_length=coarse_pulse_length)

            f0_temp, u_f0_temp = dark_esr_auto_analysis.analyze_dark_esr(current_f_msm1*1e-9, 
            qt.exp_params['samples'][SAMPLE]['N_HF_frq']*1e-9)
 
        else:
            darkesr('magnet_Zpos_optimize_fine_repeat', range_MHz=fine_range, pts=fine_pts, reps=fine_reps, 
                power = fine_amplitude, MW_power = fine_MW_power, pulse_length=fine_pulse_length)
        
            f0_temp, u_f0_temp = dark_esr_auto_analysis.analyze_dark_esr_double(do_plot=True)
コード例 #39
0
ファイル: APD_timetrace.py プロジェクト: uetke/SmartScan
  integration_time = .00005 # In seconds
  number_elements = int(timetrace_time/integration_time)
  
  data = np.zeros([120,number_elements+1])
  print('Click to start')
  print('Press q to quit')
  i=0
  while True:       
      if not adw.get_digin(0):
          print('Acquiring Timetrace')
          Beep(840,200)
          dd,ii = adw.get_timetrace_static([counter],duration=timetrace_time,acc=integration_time)
          dd = np.array(dd)
          try:
              power = pmeter.data*1000000
          except:
              power = 0
          data[i,0] = power
          data[i,1:] = dd
          i+=1
          Beep(440,200)
          
      if msvcrt.kbhit(): # <--------
          key = msvcrt.getch()
          if ord(key) == 113:
              break
 
  header = "Timetrace of APD"
  np.savetxt("%s%s" %(savedir,filename), data,fmt='%s', delimiter=",", header=header)   
  logger.info('Initial file saved as %s%s_init.txt' %(savedir,filename))
  print('Data saved in %s%s'%(savedir,filename))
コード例 #40
0
ファイル: init.py プロジェクト: shalini6/VisionAid
def exit(self):
    speak.say('Exiting tasks')
    #Clear the input flush
    while msvcrt.kbhit():
        msvcrt.getch()
    os._exit(1)
コード例 #41
0
def kbfunc():
    return msvcrt.getch() if msvcrt.kbhit() else 0
コード例 #42
0
def kbhit():
    return msvcrt.kbhit()
コード例 #43
0
def wait_for_keypress():

    if kbhit() == 0:
        getch()

    return True
コード例 #44
0
ファイル: main.py プロジェクト: joostpieters/SnakeGame
def SnakeMove(Board, PrintBoard, Snake, KeyStroke, Suggested_KeyStroke,
              SnakeHeadY, SnakeHeadX, SnakeTailY, SnakeTailX, FruitY, FruitX):
    while True:

        time.sleep(Speed)

        if msvcrt.kbhit():
            Suggested_KeyStroke = msvcrt.getch()

        if Suggested_KeyStroke == b"w":
            if KeyStroke == b"s":
                Suggested_KeyStroke = b"s"

            if not Board[SnakeHeadY - 1][SnakeHeadX] == "X":
                KeyStroke = Suggested_KeyStroke

        elif Suggested_KeyStroke == b"a":
            if KeyStroke == b"d":
                Suggested_KeyStroke = b"d"

            if not Board[SnakeHeadY][SnakeHeadX - 1] == "X":
                KeyStroke = Suggested_KeyStroke

        elif Suggested_KeyStroke == b"s":
            if KeyStroke == b"w":
                Suggested_KeyStroke = b"w"

            if not Board[SnakeHeadY + 1][SnakeHeadX] == "X":
                KeyStroke = Suggested_KeyStroke

        elif Suggested_KeyStroke == b"d":
            if KeyStroke == b"a":
                Suggested_KeyStroke = b"a"

            if not Board[SnakeHeadY][SnakeHeadX + 1] == "X":
                KeyStroke = Suggested_KeyStroke

        if KeyStroke == b"w":

            UpdateBoard(Board, SnakeHeadY - 1, SnakeHeadX, '"')
            UpdateBoard(Board, SnakeHeadY, SnakeHeadX, "0")
            SnakeHeadY = SnakeHeadY - 1

        elif KeyStroke == b"a":

            UpdateBoard(Board, SnakeHeadY, SnakeHeadX - 1, ":")
            UpdateBoard(Board, SnakeHeadY, SnakeHeadX, "0")
            SnakeHeadX = SnakeHeadX - 1

        elif KeyStroke == b"s":

            UpdateBoard(Board, SnakeHeadY + 1, SnakeHeadX, '"')
            UpdateBoard(Board, SnakeHeadY, SnakeHeadX, "0")
            SnakeHeadY = SnakeHeadY + 1

        elif KeyStroke == b"d":

            UpdateBoard(Board, SnakeHeadY, SnakeHeadX + 1, ":")
            UpdateBoard(Board, SnakeHeadY, SnakeHeadX, "0")
            SnakeHeadX = SnakeHeadX + 1

        UpdateBoard(Board, SnakeTailY, SnakeTailX, " ")

        if Board[SnakeTailY - 1][SnakeTailX] == "0":

            if Grow(SnakeHeadY, SnakeHeadX, FruitY, FruitX):
                FruitY = FruitSpaces.index(random.choice(FruitSpaces))
                FruitX = FruitSpaces[FruitY][random.randint(
                    0, (len(FruitSpaces[FruitY]) - 1))]
                UpdateBoard(Board, FruitY, FruitX, "F")
            else:
                SnakeTailY = SnakeTailY - 1

        elif Board[SnakeTailY + 1][SnakeTailX] == "0":

            if Grow(SnakeHeadY, SnakeHeadX, FruitY, FruitX):
                FruitY = FruitSpaces.index(random.choice(FruitSpaces))
                FruitX = FruitSpaces[FruitY][random.randint(
                    0, (len(FruitSpaces[FruitY]) - 1))]
                UpdateBoard(Board, FruitY, FruitX, "F")
            else:
                SnakeTailY = SnakeTailY + 1

        elif Board[SnakeTailY][SnakeTailX - 1] == "0":

            if Grow(SnakeHeadY, SnakeHeadX, FruitY, FruitX):
                FruitY = FruitSpaces.index(random.choice(FruitSpaces))
                FruitX = FruitSpaces[FruitY][random.randint(
                    0, (len(FruitSpaces[FruitY]) - 1))]
                UpdateBoard(Board, FruitY, FruitX, "F")
            else:
                SnakeTailX = SnakeTailX - 1

        elif Board[SnakeTailY][SnakeTailX + 1] == "0":

            if Grow(SnakeHeadY, SnakeHeadX, FruitY, FruitX):
                FruitY = FruitSpaces.index(random.choice(FruitSpaces))
                FruitX = FruitSpaces[FruitY][random.randint(
                    0, (len(FruitSpaces[FruitY]) - 1))]
                UpdateBoard(Board, FruitY, FruitX, "F")
            else:
                SnakeTailX = SnakeTailX + 1

        if IsFailState(Board, KeyStroke, SnakeHeadY, SnakeHeadX):
            Fail()

        GetPrintBoard(Board, PrintBoard)
        driver.quit()
        try:
            print('Delete driver for {0}: {1}'.format(symbol,
                                                      driver.session_id))
            del dictWebDriver[symbol]
        except KeyError as ex:
            print("No such key: '%s'" % ex.message)

        return returnMsg

    return returnMsg


#While loop to keep calling function to get and save real-time stock data
while (True):
    if m.kbhit():
        if m.getch() == b'q':
            break

    try:
        # with Parallel(n_jobs=5, prefer="threads") as parallel:
        # retMsg = parallel(delayed(GetStockDatafromMoney18)(ticker) for ticker in df['Ticker'])
        # print(retMsg)

        # We can use a with statement to ensure threads are cleaned up promptly
        with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
            dictFuture = {
                executor.submit(GetStockDatafromMoney18, ticker): ticker
                for ticker in df['Ticker']
            }
            #print(dictFuture)
コード例 #46
0
start = timeit.default_timer()
myLine = open("adj_mat.txt").readlines()[int(routerName) - 1]
myLine = myLine.rstrip('\n')
initialCost = re.split(" ", myLine)
print('Initial Cost is {}\n'.format(initialCost))

myBf = BFA(routerCount, initialCost, routerName, whichPort, adrToName)
myBf.who_to_send()
try:
    s = input("To start BellmanFord Algorithm, Enter 's'\n")
    assert s == 's'
except AssertionError:
    s = input("Wrong input! To start BellmanFord Algorithm, Enter 's'\n")
myBf.send()
while True:
    hit = msvcrt.kbhit()
    elapsedTime = timeit.default_timer() - start
    # myBf.send()
    if elapsedTime > 0.1:
        myBf.send()
        start = elapsedTime

    myBf.receive()
    if hit:
        key = ord(msvcrt.getch())
        if key == ord('u'):
            myLine = open("adj_mat.txt").readlines()[int(routerName) - 1]
            myLine = myLine.rstrip('\n')
            newCost = re.split(" ", myLine)
            print('New cost is {}\n'.format(newCost))
            myBf.check_cost(newCost)
コード例 #47
0
def main():

    #create socket
    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    #get local machine name
    host = socket.gethostname()

    port = 9999

    #bind the port
    serversocket.bind((host, port))

    #queue up requests
    serversocket.listen(5)

    #establish connection
    clientsocket, addr = serversocket.accept()

    #open motion builder
    '''try:
		subprocess.Popen('C:\\Program Files\\Autodesk\\MotionBuilder 2016\\bin\\x64\\motionbuilder.exe')
	except:
		print 'Motion Builder Failed To Open'
	else:
		print 'Motion Builder Opened Successfully'''

    #create csv
    dir = os.path.dirname(os.path.realpath(__file__))
    csv = open(str(dir.replace("\\", "/")) + "/animDataLocal.csv", 'w+b')

    listener = SampleListener()
    controller = Leap.Controller()
    LFrame = Leap.Frame()

    controller.add_listener(listener)
    connected = listener.on_connect(controller)

    #recieve returns
    oldFrame, leftWristPosition, leftWristRotation, rightWristPosition, rightWristRotation, IndexLeftData, ThumbLeftData, MiddleLeftData, RingLeftData, PinkyLeftData, IndexRightData, ThumbRightData, MiddleRightData, RingRightData, PinkyRightData = listener.on_frame(
        controller)

    #set some variables for counting and checking
    frameCount = 0
    testArray = [0, 0, 0]

    while True:
        if not msvcrt.kbhit():
            if oldFrame != listener.on_frame(controller)[0]:
                if (str(leftWristPosition) != '0'):
                    #if we have legit values continue
                    if (leftWristPosition[0]
                            == 0) and (leftWristPosition[1]
                                       == 0) and (leftWristPosition[2] == 0):
                        #write 0's if we cant find wrist
                        csv.write(('"leftWrist"') + "," + str(frameCount) +
                                  "," + "0" + "," + "0" + "," + "0" + "," +
                                  "0" + "," + "0" + "," + "0" + "\n")
                    else:
                        #write wrist location and rotations and bone rotations
                        leftWristPosition = re.sub('[()]', '',
                                                   str(leftWristPosition))
                        leftWristPosition = re.sub(r'\s+', '',
                                                   str(leftWristPosition))
                        csv.write(('"leftWrist"') + "," + str(frameCount) +
                                  "," + str(leftWristPosition) + "," +
                                  str(360 - leftWristRotation[1]) + "," +
                                  str(leftWristRotation[0]) + "," +
                                  str(leftWristRotation[2]) + "," + "\n")
                        for i in range(0, 4):
                            csv.write(('"Left Thumb "') +
                                      str(ThumbLeftData[i][0]) + ":" + "," +
                                      str(frameCount) + "," +
                                      str(ThumbLeftData[i][1][0]) + "," +
                                      str(ThumbLeftData[i][1][1]) + "," +
                                      str(ThumbLeftData[i][1][2]) + "\n")
                        for i in range(0, 4):
                            csv.write(('"Left Index "') +
                                      str(IndexLeftData[i][0]) + ":" + "," +
                                      str(frameCount) + "," +
                                      str(IndexLeftData[i][1][0]) + "," +
                                      str(IndexLeftData[i][1][1]) + "," +
                                      str(IndexLeftData[i][1][2]) + "\n")
                        for i in range(0, 4):
                            csv.write(('"Left Middle "') +
                                      str(MiddleLeftData[i][0]) + ":" + "," +
                                      str(frameCount) + "," +
                                      str(MiddleLeftData[i][1][0]) + "," +
                                      str(MiddleLeftData[i][1][1]) + "," +
                                      str(MiddleLeftData[i][1][2]) + "\n")
                        for i in range(0, 4):
                            csv.write(('"Left Ring "') +
                                      str(RingLeftData[i][0]) + ":" + "," +
                                      str(frameCount) + "," +
                                      str(RingLeftData[i][1][0]) + "," +
                                      str(RingLeftData[i][1][1]) + "," +
                                      str(RingLeftData[i][1][2]) + "\n")
                        for i in range(0, 4):
                            csv.write(('"Left Pinky "') +
                                      str(PinkyLeftData[i][0]) + ":" + "," +
                                      str(frameCount) + "," +
                                      str(PinkyLeftData[i][1][0]) + "," +
                                      str(PinkyLeftData[i][1][1]) + "," +
                                      str(PinkyLeftData[i][1][2]) + "\n")
                if (str(rightWristPosition) != '0'):
                    #if we have legit values continue
                    if (rightWristPosition[0]
                            == 0) and (rightWristPosition[1]
                                       == 0) and (rightWristPosition[2] == 0):
                        csv.write(('"rightWrist"') + "," + str(frameCount) +
                                  "," + "0" + "," + "0" + "," + "0" + "," +
                                  "0" + "," + "0" + "," + "0" + "\n")
                    else:
                        #write wrist location and rotations and bone rotations
                        rightWristPosition = re.sub('[()]', '',
                                                    str(rightWristPosition))
                        rightWristPosition = re.sub(r'\s+', '',
                                                    str(rightWristPosition))
                        csv.write(('"rightWrist"') + "," + str(frameCount) +
                                  "," + str(rightWristPosition) + "," +
                                  str(360 - rightWristRotation[1]) + "," +
                                  str(rightWristRotation[0]) + "," +
                                  str(rightWristRotation[2]) + "," + "\n")
                        for i in range(0, 4):
                            csv.write(('"Right Thumb "') +
                                      str(ThumbRightData[i][0]) + ":" + "," +
                                      str(frameCount) + "," +
                                      str(ThumbRightData[i][1][0]) + "," +
                                      str(ThumbRightData[i][1][1]) + "," +
                                      str(ThumbRightData[i][1][2]) + "\n")
                        for i in range(0, 4):
                            csv.write(('"Right Index "') +
                                      str(IndexRightData[i][0]) + ":" + "," +
                                      str(frameCount) + "," +
                                      str(IndexRightData[i][1][0]) + "," +
                                      str(IndexRightData[i][1][1]) + "," +
                                      str(IndexRightData[i][1][2]) + "\n")
                        for i in range(0, 4):
                            csv.write(('"Right Middle "') +
                                      str(MiddleRightData[i][0]) + ":" + "," +
                                      str(frameCount) + "," +
                                      str(MiddleRightData[i][1][0]) + "," +
                                      str(MiddleRightData[i][1][1]) + "," +
                                      str(MiddleRightData[i][1][2]) + "\n")
                        for i in range(0, 4):
                            csv.write(('"Right Ring "') +
                                      str(RingRightData[i][0]) + ":" + "," +
                                      str(frameCount) + "," +
                                      str(RingRightData[i][1][0]) + "," +
                                      str(RingRightData[i][1][1]) + "," +
                                      str(RingRightData[i][1][2]) + "\n")
                        for i in range(0, 4):
                            csv.write(('"Right Pinky "') +
                                      str(PinkyRightData[i][0]) + ":" + "," +
                                      str(frameCount) + "," +
                                      str(PinkyRightData[i][1][0]) + "," +
                                      str(PinkyRightData[i][1][1]) + "," +
                                      str(PinkyRightData[i][1][2]) + "\n")

                oldFrame, leftWristPosition, leftWristRotation, rightWristPosition, rightWristRotation, IndexLeftData, ThumbLeftData, MiddleLeftData, RingLeftData, PinkyLeftData, IndexRightData, ThumbRightData, MiddleRightData, RingRightData, PinkyRightData = listener.on_frame(
                    controller)
                frameCount += 1
        else:
            break

    connected = listener.on_disconnect(controller)
    csv.close()
コード例 #48
0
    def _receive():
        '''returns True if packet received, False if timed out'''

        if not qutest._is_debug:
            try:
                data = qspy._sock.recv(4096)
            except socket.timeout:
                qutest._last_record = qspy._EMPTY_RECORD
                return False  # timeout
            # don't catch OSError
        else:
            while True:
                try:
                    data = qspy._sock.recv(4096)
                    break
                except socket.timeout:
                    print(
                        "\nwaiting for Target (press Enter to skip this test)...",
                        end='')
                    if os.name == 'nt':
                        if msvcrt.kbhit():
                            if msvcrt.getch() == '\r':
                                print()
                                return False
                                # timeout
                    else:
                        dr, dw, de = select.select([sys.stdin], [], [], 0)
                        if dr != []:
                            sys.stdin.readline()  # consue the Return key
                            print()
                            return False
                            # timeout
                # don't catch OSError

        dlen = len(data)
        if dlen < 2:
            qutest._last_record = qspy._EMPTY_RECORD
            raise RuntimeError('UDP packet from QSPY too short')

        # binary conversion compatible with Python 2
        recID = struct.unpack('B', data[1:2])[0]

        if recID == 0:  # text data? (most common)
            qutest._last_record = data
            # QS_ASSERTION?
            if dlen > 3 and struct.unpack('B', data[2:3])[0] == 69:
                qutest._need_reset = True

        elif recID == 64:  # target info?
            if dlen != 18:
                qutest._last_record = qspy._EMPTY_RECORD
                raise RuntimeError('Incorrect Target info')

            fmt = 'xBHxLxxxQ'
            bytes = struct.unpack('>BBBBBBBBBBBBB', data[5:18])
            qspy._target_info['objPtr'] = fmt[bytes[3] & 0x0F]
            qspy._target_info['funPtr'] = fmt[bytes[3] >> 4]
            qspy._target_info['tstamp'] = fmt[bytes[4] & 0x0F]
            qspy._target_info['sig'] = fmt[bytes[0] & 0x0F]
            qspy._target_info['evtSize'] = fmt[bytes[0] >> 4]
            qspy._target_info['queueCtr'] = fmt[bytes[1] & 0x0F]
            qspy._target_info['poolCtr'] = fmt[bytes[2] >> 4]
            qspy._target_info['poolBlk'] = fmt[bytes[2] & 0x0F]
            qspy._target_info['tevtCtr'] = fmt[bytes[1] >> 4]
            qspy._target_info['target']  = '%02d%02d%02d_%02d%02d%02d' \
                %(bytes[12], bytes[11], bytes[10],
                  bytes[9], bytes[8], bytes[7])
            #print('******* Target:', qspy._target_info['target'])
            qutest._last_record = data
            qutest._have_info = True

        elif recID == 128:  # attach
            qutest._last_record = data
            qspy._is_attached = True

        elif recID == 129:  # detach
            qutest._quit_host_exe()
            qutest._last_record = data
            qspy._detach()
            qspy._is_attached = False

        else:
            qutest._last_record = qspy._EMPTY_RECORD
            raise RuntimeError('Unrecognized UDP data type from QSPY')

        return True  # some input received
コード例 #49
0
ファイル: button_engine.py プロジェクト: ebaccay/hxh
def key_poll():
    keystroke = msvcrt.kbhit()
    if keystroke:
        return int(str(ord(msvcrt.getch())))
    return 0
コード例 #50
0
#print("Puerto? COM:")
#puerto = input()
#PUERTO = 'COM'+str(puerto)
#print("BaurRate? BR=")
#BR = input()
#BAUDRATE = BR

PUERTO = 'COM7'
BAUDRATE = 54600

ser = serial.Serial(PUERTO, BAUDRATE)
print('Se imprimira por el puerto ' + PUERTO +
      ' lo introducido por teclado a ' + str(BAUDRATE) + ' Baudios...')

while True:
    if msvcrt.kbhit():
        key = msvcrt.getch()
        print('Pulsado')
        if (key == 'w'):
            print(
                'Enviando trama: 0xFF 0x5A 0 128 128 128 128 128 128 128 0 0 0 0 0 0'
            )
            print('Equivalente en tiempo a: nulo medio medio medio')
            print('Delay 1000ms')
            print(
                'Enviando trama: 0xFF 0x5A 50 128 128 128 128 128 128 128 0 0 0 0 0 0'
            )
            print('Equivalente en tiempo a: bajo medio medio medio')
            print('Delay 500ms')
            print(
                'Enviando trama: 0xFF 0x5A 0 128 128 128 128 128 128 128 0 0 0 0 0 0'
コード例 #51
0
num = joystickapi.joyGetNumDevs()
ret, caps, startinfo = False, None, None
for id in range(num):
    ret, caps = joystickapi.joyGetDevCaps(id)
    if ret:
        print("joystick detected: " + caps.szPname)
        ret, startinfo = joystickapi.joyGetPosEx(id)
        break
else:
    print("no joystick detected")
    

run = ret
while run:
    time.sleep(0.1)
    if msvcrt.kbhit() and msvcrt.getch() == chr(27).encode(): # detect ESC
        run = False

    ret, info = joystickapi.joyGetPosEx(id)
    if ret:
        btns = [(1 << i) & info.dwButtons != 0 for i in range(caps.wNumButtons)]
        axisXYZ = [info.dwXpos-startinfo.dwXpos, info.dwYpos-startinfo.dwYpos, info.dwZpos-startinfo.dwZpos]
        axisRUV = [info.dwRpos-startinfo.dwRpos, info.dwUpos-startinfo.dwUpos, info.dwVpos-startinfo.dwVpos]
        if info.dwButtons:
            print("buttons: ", btns)
        if any([abs(v) > 10 for v in axisXYZ]):
            print("axis:", axisXYZ)
        if any([abs(v) > 10 for v in axisRUV]):
            print("roation axis:", axisRUV)

print("end")
コード例 #52
0
 def non_blocking(self):
     import msvcrt
     if msvcrt.kbhit():
         return msvcrt.getch()
コード例 #53
0
print "Scanning...\n"
daq.AdcTransferStart(handle)
daq.AdcArm(handle)

#Note, kbhit() doesn't work in interpreter, only in console mode
#print "Hit any key to issue software trigger...\n"
#while not msvcrt.kbhit():
#    time.sleep(0.1)

key = raw_input("Hit return to issue software trigger...\n")

daq.AdcSoftTrig(handle)  #issue software trigger
print "--triggered--\n"

active = 1
while not msvcrt.kbhit() and (active & daqh.DaafAcqActive):
    time.sleep(0.1)
    #transfer data into computer memory and halt acquisition when done
    active, retCount = daq.AdcTransferGetStat(handle)
    print active, retCount

#Disarm when completed
daq.AdcDisarm(handle)
print "Scan Completed\n"

#close device connections
daq.Close(handle)

#convert the data to volts:
#DaqBoards convert all data to an unsigned, 16-bit number (range 0 to 65535).  Zero corresponds
#to the minimum voltage, which is -maxVolt if in bipolar mode, or zero if unipolar.
コード例 #54
0
 def getch():
     if msvcrt.kbhit():
         return msvcrt.getch()
コード例 #55
0
    def ssro(self,name, data, par):
        
        par['green_repump_voltage'] = self.ins_green_aom.power_to_voltage(par['green_repump_amplitude'])
        par['green_off_voltage'] = 0.0
        par['Ex_CR_voltage'] = self.ins_E_aom.power_to_voltage(par['Ex_CR_amplitude'])
        par['A_CR_voltage'] = self.ins_A_aom.power_to_voltage(par['A_CR_amplitude'])
        par['Ex_SP_voltage'] = self.ins_E_aom.power_to_voltage(par['Ex_SP_amplitude'])
        par['A_SP_voltage'] = self.ins_A_aom.power_to_voltage(par['A_SP_amplitude'])
        par['Ex_RO_voltage'] = self.ins_E_aom.power_to_voltage(par['Ex_RO_amplitude'])
        par['A_RO_voltage'] = self.ins_A_aom.power_to_voltage(par['A_RO_amplitude'])


        if (par['SSRO_repetitions'] > self.max_repetitions) or \
            (par['SP_duration'] > self.max_SP_bins) or \
            (par['SSRO_repetitions'] * par['SSRO_duration'] > self.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']

        if not(self.lt1):
            self.adwin.set_spincontrol_var(set_phase_locking_on = self.set_phase_locking_on)
            self.adwin.set_spincontrol_var(set_gate_good_phase =  self.set_gate_good_phase)            

        self.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 (self.physical_adwin.Process_Status(9) == 1):
            reps_completed = self.physical_adwin.Get_Par(73)
            CR_counts = self.physical_adwin.Get_Par(70) - CR_counts
            cts = self.physical_adwin.Get_Par(26)
            trh = self.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)
        self.physical_adwin.Stop_Process(9)
        
        reps_completed      = self.physical_adwin.Get_Par(73)
        print('completed %s / %s readout repetitions'%(reps_completed,par['SSRO_repetitions']))

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

        repetitions = np.arange(reps_completed)
        sp_time = np.arange(par['SP_duration'])*par['cycle_duration']*3.333
        ssro_time = np.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 
コード例 #56
0
def genetic_algorithm():

    ps = runps.run_ps()

    warnings.filterwarnings(
        "ignore", ".*GUI is implemented.*"
    )  # filter out the plotting warning about deprecation
    """Start, run, and end the genetic algorithm."""

    print('You are running the genetic algorithm')

    #This function sets all of the values of the number of parents, children, and mutation amount
    num_genes, num_init_parents, num_init_children, init_voltage, filename, num_parents, num_children, mutation_percentage = initialization_f.initialize(
    )
    """Note: To change the default values, go into inialization_functions.py in the initialize function"""

    print('\nNOTE: LabView must be open in order to run the program\n')
    print('Here are the options you have while the program is running:')
    print('\tPress the enter key (or s) to stop the program')
    print('\tPress "m" if you would like to change the mutation percentage')
    #print('\tPress "c" if you would like to change the number of children')
    #print('\tPrees "p" if you would like to change the number of parents')
    print('Press "r" then enter enter to run the program')
    while True:  # run an infinite loop until a key is pressed
        keyboard_input = input()  # if the keyboard was hit
        if keyboard_input == '\r' or keyboard_input == '\n' or keyboard_input == 'r':  # if the key pressed was the enter key
            break  # break out of the infinite loop

    print('Starting...')
    start_time = time.time()  # determine the time when the algorithm starts
    dm_actuators = mirror_f.acuator_array(
    )  # initialize the class to determine if actuator voltages break the mirror or not
    iteration_number = 0

    parents = people.parent_group(
        num_init_parents, num_genes, init_voltage,
        filename)  # create parents from above constraints
    children = people.child_group(
        num_init_children, parents,
        dm_actuators)  # create children from the given parents
    children.mutate(mutation_percentage, dm_actuators)  # mutate the children

    # all_people = people.person_group(parents, children)     # combine all of the children and parents into a single container

    all_people = people.person_group(parents, children, children, children,
                                     children, children)

    all_people.test_and_sort_people(
        dm_actuators, ps
    )  # measure the figures of merits and sort the people so the highest figure of merit is 0th indexed

    best_person = all_people.people[
        0]  # the best person is the 0th indexed person in all_people
    print('best_person\n', best_person.figure_of_merit
          )  # show the best person's genes and figure of merit

    past_figures_of_merit = all_people.best_figures_of_merit(num_parents)

    print('Total running time: ',
          time.time() - start_time, ' seconds'
          )  # print out the number of seconds since the algorithm started

    while True:  # run an infinite loop until user says to stop
        if msvcrt.kbhit():  # if the keyboard was hit
            keyboard_input = msvcrt.getwche()  # determine what key was pressed
            if keyboard_input == 's':  # if the enter key was pressed ######fix me
                # if keyboard_input == '\r' or keyboard_input == 's':  # if the enter key was pressed ######fix me

                break  # get out of the while loop
            elif keyboard_input == 'm':  # if the m key was pressed######fix me
                print('\nThis is the current mutation percentage: ',
                      mutation_percentage)
                mutation_percentage = initialization_f.change_value(
                    'float', 0, 100
                )  # change the mutation percentage to what the user wants
            """
			elif keyboard_input == 'c':   # if the c key was pressed
				print('\nThis is the current number of children: ', num_children)   
				mutation_percentage = initialization_f.change_value('int', num_parents-1)   # change the number of children to what the user wants
			elif keyboard_input == 'p':   # if the p key was pressed
				print('\nThis is the current number of parents: ', num_parents)
				mutation_percentage = initialization_f.change_value('float', 0, num_children+1) # change the number of parents to what the user wants
			"""

        parents = people.parent_group(
            num_parents, num_genes, None, None,
            all_people)  # create parents from the best performing children
        children = people.child_group(
            num_children, parents,
            dm_actuators)  # create children from the just created parents
        children.mutate(mutation_percentage,
                        dm_actuators)  # mutate the children

        # all_people = people.person_group(parents, children)     # combine all of the children and parents into a single container

        all_people = people.person_group(parents, children, children, children,
                                         children, children)

        all_people.test_and_sort_people(
            dm_actuators, ps
        )  # measure the figures of merits and sort the people so the highest figure of merit is 0th indexed

        new_best_person = all_people.people[
            0]  # the best person is the 0th indexed person in all_people
        if new_best_person.figure_of_merit > best_person.figure_of_merit:  # determine if the best person's figure of merit in this run is better than the current best person's figure of merit
            best_person = new_best_person  # if the new best person is better, they are the overall best person ever
        print(
            'best_person\n',
            best_person.figure_of_merit)  # print out the best person ever made

        figures_of_merit = np.concatenate(
            (past_figures_of_merit,
             all_people.best_figures_of_merit(num_parents)),
            axis=1
        )  # concatenate the previous figure of merit matrix with the current figures of merit
        iteration_number, past_figures_of_merit = plot_f.plot_performance(
            iteration_number,
            figures_of_merit)  # plot the progressions of figures of merit

        print('Total running time: ',
              time.time() - start_time, ' seconds'
              )  # print out the number of seconds since the algorithm started

    runps.close_ps(ps)
    # ps.stop()
    # ps.close()

    print(
        'What would you like to do with the best person?'
    )  # once the loop has finished, the user decides what to do with the genes made
    while True:  # create an infinite loop
        print('\tFor writing the actuator voltages to a file, input "write"')
        print('\tFor saving graph data, input "graph"')
        print('\tFor doing nothing, input "none"')
        saving_option = input()  # get user input for what they want to do
        if saving_option == 'write':  # if they want to write the genes to a file
            directory = ADF_FOLDER
            print("\tThe default directory is " + ADF_FOLDER)
            directory = save_different_directory(directory)
            print(
                "Enter the file name you want to be saved (for test.adf, input test):\nNote: this will overwrite a file with the same name"
            )
            filename = input(
            )  # get user input from for what filename they want
            file_f.write_adf(best_person, directory +
                             filename)  # write the genes to the input file
            if anything_else(
            ) == 'n':  # if they don't want to do anything else
                break  # break out of the while loop
        elif saving_option == 'graph':  # if the user wants to save the graph
            directory = FOM_GRAPH_FOLDER
            print("\tThe default directory is " + FOM_GRAPH_FOLDER)
            directory = save_different_directory(directory)
            print(
                "Enter the file name you want to be saved (for test.csv, input test):\nNote: this will overwrite a file with the same name"
            )
            filename = input(
            )  # get user input from for what filename they want
            file_f.write_figures_of_merit(
                figures_of_merit, directory + filename
            )  # write the figures of merit to a comma separated value file
            if anything_else(
            ) == 'n':  # if they don't want to do anything else
                break  # break out of the while loop
        elif saving_option == 'none':  # if the user doesn't want to do anything with the data
            break  # break out of the while loop
        else:  # if they didn't enter one of the options
            print("You didn't enter a correct command")
コード例 #57
0
 def _kbhit(self):
     if sys.platform == "win32":
         return msvcrt.kbhit()
     else:
         (dr, dw, de) = select.select([sys.stdin], [], [], 0)
         return (dr != [])
コード例 #58
0
ファイル: metasploit.py プロジェクト: zfg88287508/sqlmap
    def _controlMsfCmd(self, proc, func):
        initialized = False
        start_time = time.time()
        stdin_fd = sys.stdin.fileno()

        while True:
            returncode = proc.poll()

            if returncode is None:
                # Child hasn't exited yet
                pass
            else:
                logger.debug("connection closed properly")
                return returncode

            try:
                if IS_WIN:
                    timeout = 3

                    inp = ""
                    _ = time.time()

                    while True:
                        if msvcrt.kbhit():
                            char = msvcrt.getche()

                            if ord(char) == 13:  # enter_key
                                break
                            elif ord(char) >= 32:  # space_char
                                inp += char

                        if len(inp) == 0 and (time.time() - _) > timeout:
                            break

                    if len(inp) > 0:
                        try:
                            send_all(proc, inp)
                        except (EOFError, IOError):
                            # Probably the child has exited
                            pass
                else:
                    ready_fds = select.select([stdin_fd], [], [], 1)

                    if stdin_fd in ready_fds[0]:
                        try:
                            send_all(proc, blockingReadFromFD(stdin_fd))
                        except (EOFError, IOError):
                            # Probably the child has exited
                            pass

                out = recv_some(proc, t=.1, e=0)
                blockingWriteToFD(sys.stdout.fileno(), out)

                # For --os-pwn and --os-bof
                pwnBofCond = self.connectionStr.startswith("reverse")
                pwnBofCond &= any(_ in out
                                  for _ in ("Starting the payload handler",
                                            "Started reverse"))

                # For --os-smbrelay
                smbRelayCond = "Server started" in out

                if pwnBofCond or smbRelayCond:
                    func()

                timeout = time.time() - start_time > METASPLOIT_SESSION_TIMEOUT

                if not initialized:
                    match = re.search(r"Meterpreter session ([\d]+) opened",
                                      out)

                    if match:
                        self._loadMetExtensions(proc, match.group(1))

                        if "shell" in self.payloadStr:
                            send_all(
                                proc, "whoami\n" if Backend.isOs(OS.WINDOWS)
                                else "uname -a ; id\n")
                            time.sleep(2)

                        initialized = True
                    elif timeout:
                        proc.kill()
                        errMsg = "timeout occurred while attempting "
                        errMsg += "to open a remote session"
                        raise SqlmapGenericException(errMsg)

                if conf.liveTest and timeout:
                    if initialized:
                        send_all(proc, "exit\n")
                        time.sleep(2)
                    else:
                        proc.kill()

            except (EOFError, IOError, select.error):
                return proc.returncode
            except KeyboardInterrupt:
                pass
コード例 #59
0
ファイル: inputhookglut.py プロジェクト: 18636800170/movieApi
 def stdin_ready():
     return msvcrt.kbhit()
コード例 #60
-1
ファイル: recipe-578362.py プロジェクト: bhramoss/code
def alarm(seconds):
    time.sleep(seconds)
    while msvcrt.kbhit():
        msvcrt.getch()
    while not msvcrt.kbhit():
        winsound.Beep(440, 250)
        time.sleep(0.25)