Example #1
0
    def main(self):
        kb = KBHit()  # needed for windows to handle keyboard interrupt
        print('Hit ESC to exit')
        try:
            #time.sleep(1)
            #self.request_port_mapping()
            time.sleep(0.5)
            self.set_pin_mode(13, AsipClient.OUTPUT)
            time.sleep(0.5)
            self.set_pin_mode(2, AsipClient.INPUT_PULLUP)
            time.sleep(0.5)
        except Exception as e:
            sys.stdout.write(
                "Exception: caught {} in setting pin mode".format(e))

        while True:
            if kb.kbhit():
                c = kb.getch()
                if ord(c) == 27:  # ESC
                    kb.set_normal_term()
                    break
            try:
                self.digital_write(13, 1)
                time.sleep(1.25)
                self.digital_write(13, 0)
                time.sleep(1.25)
            except Exception as e:
                sys.stdout.write(
                    "Exception: caught {} in digital_write".format(e))
Example #2
0
    def main(self):
        if os.name == 'nt':
            kb = KBHit()  # needed for windows to handle keyboard interrupt
            sys.stdout.write('Hit ESC to exit\n')
        try:
            time.sleep(0.5)
            self.asip.set_pin_mode(13, self.asip.OUTPUT)
            time.sleep(0.5)
        except Exception as e:
            sys.stdout.write(
                "Exception caught while setting pin mode: {}\n".format(e))
            self.thread_killer()
            sys.exit(1)

        while True:
            if os.name == 'nt':
                if kb.kbhit():
                    c = kb.getch()
                    if ord(c) == 27:  # ESC
                        kb.set_normal_term()
                        break
            try:
                self.asip.digital_write(13, self.asip.HIGH)
                time.sleep(1.25)
                self.asip.digital_write(13, self.asip.LOW)
                time.sleep(1.25)
            except (KeyboardInterrupt, Exception) as e:
                sys.stdout.write(
                    "Caught exception in main loop: {}\n".format(e))
                self.thread_killer()
                sys.exit()
Example #3
0
    def run(self):
        """Run the CPU."""
        self._running = True
        old_time = time()
        kb = KBHit()
        while self._running:
            # trigger timer interrupt every second (approx)
            new_time = time()
            if new_time - old_time > 1:
                self.interrupt(TIMER_INTERRUPT)
                old_time = new_time

            # trigger keyboard interrupt on keypress
            if kb.kbhit():
                c = kb.getch()
                if ord(c[0]) == 27:  # ESC
                    self._running = False
                    break
                self.ram_write(KEY_BUFFER, ord(c[0]))
                self.interrupt(KEYBOARD_INTERRUPT)

            self.check_interrupts()

            # process instruction at program counter
            self.IR = self.ram_read(self.PC)
            if self.IR & ALU_MASK:
                self.alu(ALU[self.IR], self.OP_A, self.OP_B)
            else:
                OPCODES[self.IR](self)

            # adjust program counter if necessary
            if not self.IR & 0b10000:
                self.PC += (1 + (self.IR >> 6))

        kb.set_normal_term()
    def main(self):   
        kb = KBHit()  # needed for windows to handle keyboard interrupt         
        print('Hit ESC to exit')             
        try:
            #time.sleep(1)
            #self.request_port_mapping()
            time.sleep(0.5)
            self.set_pin_mode(13, AsipClient.OUTPUT)
            time.sleep(0.5)
            self.set_pin_mode(2, AsipClient.INPUT_PULLUP)
            time.sleep(0.5)
        except Exception as e:
            sys.stdout.write("Exception: caught {} in setting pin mode".format(e))

        while True:        
            if kb.kbhit():
                c = kb.getch()                
                if ord(c) == 27: # ESC
                    kb.set_normal_term() 
                    break 
            try:
                self.digital_write(13, 1)
                time.sleep(1.25)
                self.digital_write(13, 0)
                time.sleep(1.25)
            except Exception as e:
                sys.stdout.write("Exception: caught {} in digital_write".format(e))
Example #5
0
    def main(self):
        if os.name == 'nt':
            kb = KBHit()  # needed for windows to handle keyboard interrupt
            sys.stdout.write('Hit ESC to exit\n')
        try:
            time.sleep(0.5)
            self.asip.set_pin_mode(13, self.asip.OUTPUT)
            time.sleep(0.5)
        except Exception as e:
            sys.stdout.write("Exception caught while setting pin mode: {}\n".format(e))
            self.thread_killer()
            sys.exit(1)

        while True:        
            if os.name == 'nt':
                if kb.kbhit():
                    c = kb.getch()
                    if ord(c) == 27:  # ESC
                        kb.set_normal_term()
                        break
            try:
                self.asip.digital_write(13, self.asip.HIGH)
                time.sleep(1.25)
                self.asip.digital_write(13, self.asip.LOW)
                time.sleep(1.25)
            except (KeyboardInterrupt, Exception) as e:
                sys.stdout.write("Caught exception in main loop: {}\n".format(e))
                self.thread_killer()
                sys.exit()
Example #6
0
def waitForInput(running_flag, threads):
    kb = KBHit()
    while True:
        if kb.kbhit():
            c = kb.getch()
            if ord(c) == 27:  # ESC
                break
        e.sleep(0.1)
    kb.set_normal_term()

    socket.stop()
Example #7
0
def console_run(program_file: str,
                autorun_file: Optional[str] = None,
                init_str: str = ''):
    vm = Virtual8080()
    vm.io = AltairWithTerminal()
    with open(program_file, 'rb') as pf:
        program = pf.read()
    vm.load(program)

    if autorun_file is not None:
        init_buffer = init_str
        with open(autorun_file, 'r') as af:
            for line in af.readlines():
                init_buffer += line.replace('\n', '\r')
        vm.io.input_buffer = init_buffer.encode(encoding='ascii')

    kb = KBHit()
    try:
        vm.halted = False
        while not vm.halted:
            ch = vm.io.output_char
            if ch != -1 and ch != 13:
                print(bytes([ch]).decode(encoding='ascii'), end='', flush=True)
            vm.io.output_char = -1
            if kb.kbhit():
                ch = ord(kb.getch())
                if ch == 10:
                    vm.io.input_buffer += bytes([13, 0])
                elif ch == 27:
                    # Break on ESC
                    vm.io.input_buffer += bytes([3])
                else:
                    vm.io.input_buffer += bytes([ch])
            vm.step()
    finally:
        kb.set_normal_term()
Example #8
0
def main():
    # Decorative purpose.
    init()
    # Nope, this is not the real otog.cf password XD.
    mydb = mysql.connector.connect(
        host="localhost",
        user="******",
        passwd="00000000",
        # Original for otog.cf was :
        # passwd='0000',
        database="OTOG",
    )

    myCursor = mydb.cursor(buffered=True)

    # for keybord interupt.
    print(ogogi + "Grader started. Waiting for submission...")
    kb = KBHit()

    while True:
        # Looking for keyboard interupt.
        if kb.kbhit():
            if kb.getch() == ":":
                # Do functions.
                print(ogogi + "Keyboard interupted. Entering command mode.")
                kb.set_normal_term()

                # Command mode
                while True:
                    cmd, args = cmdMode.run()
                    # Shutdown signal
                    if cmd == abb.INCMD["SHUTDOWN"]:
                        # Good-bye message
                        print(ogogi + "Bye")
                        exit(0)
                    elif cmd == abb.INCMD["RELOAD"]:
                        # Reload modules in args
                        for e in args:
                            if e == "grader":
                                print(
                                    abb.error
                                    + "'grader' itself cannot be reloaded. Please restart the program manually."
                                )
                            try:
                                importlib.reload(importlib.import_module(e))
                            except:
                                print(abb.error + "'" + e + "' cannot be reloaded.")
                    elif cmd == abb.INCMD["EXIT"]:
                        break

                kb.set_kbhit_term()
                print(ogogi + "Command mode exited. Continue waiting for submission.")

        myCursor.execute("SELECT * FROM Result WHERE status = 0 ORDER BY time")
        submission = myCursor.fetchone()
        if submission != None:
            print(abb.bold + Fore.GREEN + "\t--> recieved.\n" + Style.RESET_ALL)
            print(
                str(datetime.datetime.now().strftime("[ %d/%m/%y %H:%M:%S ]"))
                + " -----------------------------"
            )

            myCursor.execute(
                "SELECT * FROM Problem WHERE id_Prob = " + str(submission[3])
            )
            probInfo = myCursor.fetchone()

            # Submit result
            sql = "UPDATE Result SET result = %s, score = %s, timeuse = %s, status = 1, errmsg = %s WHERE idResult = %s"
            val = onRecieved(submission, probInfo, mydb)
            myCursor.execute(sql, val)
            print("---------------------------------------------------")
            print("\n" + ogogi + "Finished grading session. Waiting for the next one.")

        mydb.commit()
        time.sleep(config.gradingInterval)
Example #9
0
    def run(self):
        kb = KBHit()
        selectedData = []
        dataToAverage = []
        print('Hit ESC to exit')
        while True:
            if kb.kbhit():
                c = kb.getch()
                if ord(c) == 27:  # ESC
                    kb.set_normal_term()
                    print "Quitting!"
                    os._exit(0)
            now = time.time()
            due = now - self.parent.offset
            search_from = self.parent.index - 1
            if search_from == -1:
                search_from = self.parent.buffer_size - 1
            timestamp = 0
            nextTimestamp = 0
            self.waitForNewData = 0.5
            self.parent.mutex.acquire()

            lastjvalue = 0

            dataArray = []

            for theid in range(self.parent.channel_count):

                data = self.parent.outbuffers[int(theid)][self.parent.index]

                for i in range(search_from,
                               search_from - self.parent.buffer_size, -1):
                    j = i if i >= 0 else i + self.parent.buffer_size
                    timestamp = self.parent.timestamp_buffer[j]
                    if timestamp is not None and timestamp <= due:
                        data = self.parent.outbuffers[int(theid)][j]
                        lastjvalue = j
                        if (j < self.parent.buffer_size - 2):
                            nextTimestamp = self.parent.timestamp_buffer[j + 1]
                        else:
                            nextTimestamp = self.parent.timestamp_buffer[0]
                        break
                if data is not None:
                    dataArray.append(data)

            #print "data array: ", dataArray

            for f in config.streams:
                stream = f['stream']
                if len(dataArray) > stream:
                    #print "stream = ", stream,  dataArray[stream]
                    if 'scale' in f:
                        dataArray[stream] = self.format.scale(
                            dataArray[stream], f['scale'])
                    if 'type' in f and f['type'] == int:
                        #msgString += str(int(dataArray[stream]))
                        selectedData.append(int(dataArray[stream]))
                    else:
                        #msgString += str(dataArray[stream])
                        selectedData.append(dataArray[stream])

                    if len(selectedData) == len(config.streams):
                        self.sendMessage(selectedData)
                        selectedData = []

            if timestamp is not None and nextTimestamp is not None:
                waitTime = nextTimestamp - timestamp
                if waitTime > 0:
                    time.sleep(waitTime)
                else:
                    print "timing out waiting for new data - time < 0"
                    time.sleep(self.waitForNewData)
            else:
                print "timing out waiting for new data - time or nextTime is None"
                time.sleep(self.waitForNewData)
            self.parent.mutex.release()
Example #10
0
        if pomme_sur_personnage(state, x, y):
            x = random.randint(0, 9)
            y = random.randint(0, 7)
        # Affiche le plateau
        print_state(state, x, y)

        # Recupere la touche enfoncee
        c = kb.getch()
        c_ord = ord(c)
        print(c)
        print(c_ord)

        # Action suivant la touche enfoncee
        if c_ord == 27:  # ESC
            break
        if c_ord == 97:  # a
            print("gauche")
            move_personnage_gauche(state)
        if c_ord == 100:  # d
            print("droite")
            move_personnage_droite(state)
        if c_ord == 119:  # w
            print("haut")
            move_personnage_haut(state)
        if c_ord == 115:  # s
            print("bas")
            move_personnage_bas(state)
        # Affiche le plateau
        print_state(state, x, y)
kb.set_normal_term()
    def run(self):
        kb = KBHit()      
        selectedData = []
        dataToAverage = []        
        print('Hit ESC to exit')
        while True:
            if kb.kbhit():
                c = kb.getch()                
                if ord(c) == 27: # ESC
                    kb.set_normal_term() 
                    print "Quitting!"
                    os._exit(0)   
            now = time.time()
            due = now - self.parent.offset
            search_from = self.parent.index - 1
            if search_from == - 1:
                search_from = self.parent.buffer_size - 1
            timestamp = 0
            nextTimestamp = 0
            self.waitForNewData = 0.5
            self.parent.mutex.acquire()

            lastjvalue = 0

            dataArray = []

            for theid in range(self.parent.channel_count):

                data = self.parent.outbuffers[int(theid)][self.parent.index]
                
                for i in range(search_from, search_from - self.parent.buffer_size, -1):
                    j = i if i >= 0 else i + self.parent.buffer_size
                    timestamp = self.parent.timestamp_buffer[j]
                    if timestamp is not None and timestamp <= due:
                        data = self.parent.outbuffers[int(theid)][j]
                        lastjvalue = j
                        if(j<self.parent.buffer_size-2):
                            nextTimestamp = self.parent.timestamp_buffer[j+1]
                        else:
                            nextTimestamp = self.parent.timestamp_buffer[0]
                        break
                if data is not None:                                
                    dataArray.append(data)
            
            #print "data array: ", dataArray     
                         
                
            for f in config.streams:
                stream = f['stream'] 
                if len(dataArray) > stream:  
                    #print "stream = ", stream,  dataArray[stream]                             
                    if 'scale' in f:
                        dataArray[stream] = self.format.scale(dataArray[stream], f['scale'])                  
                    if 'type' in f and f['type'] == int: 
                        #msgString += str(int(dataArray[stream]))
                        selectedData.append(int(dataArray[stream]))                      
                    else:   
                         #msgString += str(dataArray[stream]) 
                         selectedData.append(dataArray[stream]) 
 
                    if len(selectedData) == len(config.streams) :  
                        self.sendMessage(selectedData)                                                                 
                        selectedData = []          

            if timestamp is not None and nextTimestamp is not None:
                waitTime = nextTimestamp - timestamp
                if waitTime > 0:
                    time.sleep(waitTime)
                else:
                    print "timing out waiting for new data - time < 0"
                    time.sleep(self.waitForNewData)
            else:
                print "timing out waiting for new data - time or nextTime is None"
                time.sleep(self.waitForNewData)
            self.parent.mutex.release()