def on_init(self): pygame.init() pygame.font.init() self._display_surf = pygame.display.set_mode( self.size, pygame.HWSURFACE | pygame.DOUBLEBUF) self.player = ship.Ship(self.width / 1.5, self.height / 1.5) self.keyboard = keyboard.Keyboard() self.mainMenuFont = basic_font.basic_Text() self.mainMenuFont.setCenter(self.width / 2 - 50, self.height / 3) self.mainMenuFont.setText("Main Menu") self.playFont = basic_font.basic_Text() self.playFont.setCenter(self.width / 2 - 20, self.height / 2) self.playFont.setColor((0, 0, 0)) self.playFont.setText("Play") self.playAstroid = astroid.Astroid(self.width / 2, self.height / 2, 0) self.playAstroid.changeAngles([[67, 22.5], [35, 67.5], [42, 112.5], [60, 157.5], [52, 202.5], [31, 247.5], [33, 292.5], [62, 337.5]]) self.playAstroid.calculateRectangle()
def connect_to_windows(self): time.sleep(1) global window_owners open_windows = Harness.GetAllWindowsWithName( self.app_config["window_title"], self.root_window, []) if len(open_windows) == 0: print("Still looking for window with title: ", self.app_config["window_title"]) for w in open_windows: if w not in self.windows: # Make sure we haven't opened too many instances assert (None in self.windows) loc = self.windows.index(None) self.windows[loc] = w self.keyboards[loc] = keyboard.Keyboard(self.display, w) print(w) print(hex(w.id)) subprocess.Popen(["i3-msg", "[id=" + hex(w.id) + "]", "floating", "enable;", \ "border", "pixel", "0"]) self.display.flush() time.sleep(.5) self.display.flush() w.configure(x = self.run_config["x_res"] * (loc % x_tiles), \ y = self.run_config["y_res"] * (loc // x_tiles), \ width = self.run_config["x_res"], height = self.run_config["y_res"]) self.display.flush() self.full_screen_capture = self.add_capture( (0, 0, self.run_config["x_res"], self.run_config["y_res"])) window_owners[w.id] = self if not None in self.windows: self.ready = True
def __init__(self): Gtk.Window.__init__(self, title=cn.App.application_name) self.settings.set_property("gtk-application-prefer-dark-theme", True) hbar = hb.Headerbar() self.set_titlebar(hbar) self.rotorboard = rb.Rotorboard() self.rotorboard.set_margin_left(8) self.rotorboard.make_ui() self.lampboard = lb.Lampboard() self.lampboard.make_ui() self.keyboard = kb.Keyboard() self.keyboard.make_ui() self.plugboard = pb.PlugBoardUI() self.plugboard.make_ui() self.plugboard.set_margin_top(4) self.plugboard.props.height_request = 150 self.plugboard.connect("plug_selected", self.remap_plugboard) self.show_plug_board_button = Gtk.Button.new_with_label( "Toggle Plugboard") self.plugboard_revealer = Gtk.Revealer() self.plugboard_revealer.add(self.plugboard) self.show_plug_board_button.connect("clicked", self.revealer_handler) self._create_enigma_machine() self.rotor_selector = rs.RotorSelector( self.enigma_machine.get_all_rotor_names(), self.rotor_selection_handler) self.scratchpad = sp.ScratchPad() self.scratchpad.set_margin_top(8) self.scratchpad.set_margin_right(8) self.scratchpad.connect("batch_encrypt", self._batch_compile_handler) main_grid = Gtk.Grid() main_grid.attach(self.rotorboard, 0, 0, 1, 1) main_grid.attach(self.rotor_selector, 1, 0, 1, 1) main_grid.attach(self.scratchpad, 2, 0, 1, 1) main_grid.attach(self.lampboard, 0, 1, 3, 1) main_grid.attach(self.keyboard, 0, 2, 3, 1) main_grid.attach(self.show_plug_board_button, 0, 3, 3, 1) main_grid.attach(self.plugboard_revealer, 0, 4, 3, 1) main_grid.set_column_spacing(8) self.add(main_grid) self.keyboard.connect("key_button_pressed", self._press_keys) self.keyboard.connect("key_button_released", self._release_keys) self.rotorboard.connect("manual_rotate1", self._manual_rotate1) self.rotorboard.connect("manual_rotate2", self._manual_rotate2) self.rotorboard.connect("manual_rotate3", self._manual_rotate3)
def __init__(self): self.__title = "Chip-8 Emulator" self.__display = display.Display() self.__keyboard = keyboard.Keyboard() self.__processor = processor.Processor(self.__display, self.__keyboard) self.__isRunning = False self.__debugMode = True self.__display.setTitle(self.__title)
def __init__(self): self.keyboard = keyboard.Keyboard() self.graphics = ggraphics.Graphics(self.keyboard.handle_event) self.numbers = [] self.start_wait = True self.player_wait = True self.best_score = 0 self.last_playername = u"Anonym" self.scores = [] self.load_scores() self.init_new_game()
def run(self, style, auto): utils.createKeymap() bkgnd = keyboard.Background() bkgnd.show() while style != utils.CLOSED: kb = keyboard.Keyboard(style) style = kb.run(auto) auto = False del kb del bkgnd utils.deleteKeymap()
def __init__(self, KT, context): self.keyboard = keyboard.Keyboard(KT, constants.shortcuts) self.context = context self.KT = KT self._toolbar = Document_toolbar(self.PDF, self.keyboard) self.shortcuts() self._region_active, self._region_hover = 'view', 'view' self._mode_switcher = Mode_switcher(self.change_mode, default= self._mode) self._stake = None self._xy_at = 0, 0 self._font = ISTYLES[('strong',)]
def CheckHighScore(self): current_song_name = self.songs[self.current_song] if not self.score: return # No score, hence no new high score. if (current_song_name in self.high_scores and self.score <= self.high_scores[current_song_name][0]): return # Current score is lower than high score. self.piano_display.SetKeyText(65, self.piano_display.KEYBOARD_HEIGHT + 100, "New High Score! Enter your name:") self.piano_display.Refresh() k = keyboard.Keyboard(self.piano_input_obj, self.piano_display) your_name = k.GetTypedString() self.high_scores[current_song_name] = (self.score, your_name) self.SaveHighScores()
def __init__(self, game_display, alvo, numjog, teclas=None): self.game_display = game_display if teclas is None: self.teclas = ['+', '/', '*', '-', '7', '4', '1', '.', '8', '5', '2', '0', '9', '6', '3', '=','(',')'] else: self.teclas = teclas self.calculator = keyboard.Keyboard(self.game_display, self.teclas) self.alvo = alvo self.font = pygame.font.Font('OdibeeSans-Regular.ttf', 50) self.font2 = pygame.font.Font('Poppins-Light.ttf', 30) self.numjog = numjog self.numjogi = numjog self.display_text = [] self.result_text = False self.correto = self.font2.render("Correto", True, (0, 0, 0)) self.incorreto = self.font2.render("Incorreto", True, (0, 0, 0)) self.perdeu = self.font2.render("Perdeu", True, (0, 0, 0)) self.animation = GIFImage.GIFImage('girafa.gif') self.perdeuAnimation = GIFImage.GIFImage('incorreto.gif')
def main(ui): if len(sys.argv) > 1: midifile = sys.argv[1] else: midifile = 'rondo-alla-turca-a.mid' score = readmidi.buildScore(midifile) player = AutoPlayer(score) liveKeyboard = keyboard.Keyboard() device.pyCallback = liveKeyboard ui.hand = BOTH_HANDS ui.separate(30) ui.drawScore(score) ui.drawBracket(player.whereToStart, player.whereToStop) ui.flip() # ----- cursor = Cursor(len(score)) while True: ui.clearBright(score, cursor.pos) ui.clearBright(score, player.pos) clockwork.tick() anymidi.tick() e = ui.getEvent() if e == EXIT: break elif e == DOWN: cursor.down() elif e == UP: cursor.up() elif e == DOWNFAST: cursor.down(8) elif e == UPFAST: cursor.up(8) elif e == FASTER: player.faster() elif e == SLOWER: player.slower() elif e == METRONOME: player.metronome() # loopback support: elif e == SETSTART: player.whereToStart = cursor.pos ui.drawBracket(player.whereToStart, player.whereToStop) elif e == SETSTOP: player.whereToStop = cursor.pos ui.drawBracket(player.whereToStart, player.whereToStop) elif e == TOSTART: cursor.jump(player.whereToStart) elif e == TOEND: cursor.jump(player.whereToStop) elif e == ROTATE_HANDS: if ui.hand == LEFT_HAND: ui.hand = BOTH_HANDS elif ui.hand == RIGHT_HAND: ui.hand = LEFT_HAND else: ui.hand = RIGHT_HAND ui.drawScore(score) elif e == SEPLEFT: ui.sep -= 1 if ui.sep <= 0: ui.sep = 0 ui.drawScore(score) elif e == SEPRIGHT: maxsep = 80 # @TODO: FIX! ui.sep += 1 if ui.sep >= maxsep: ui.sep = maxsep ui.drawScore(score) # player support: elif e == PLAY: player.play() elif e == STOP: player.stop() snap = liveKeyboard.snapshot() # if input matches the goal, move forward one line if ui.hand == LEFT_HAND: r = None, ui.sep elif ui.hand == RIGHT_HAND: r = ui.sep, None else: r = None, None if snap[r[0]:r[1]] == map(abs, score[cursor.pos][r[0]:r[1]]): cursor.jump( loopback(player.whereToStop, player.whereToStart, cursor.pos + 1)) # always draw the computer's cursor first... if player.visible: ui.drawPiano(10, yPos(player.pos), computerCursor, score[player.pos]) # so that the user's cursor covers it: ui.drawPiano(10, yPos(cursor.pos), midiCursor, comparison(score[cursor.pos], snap)) ui.flip() ui.quit()
self.myKeyboard = myKeyboard self.which = which def run(self): lab = Labirynth(self.myLcd, self.myKeyboard, self.which) result = lab.playloop() result = result.seconds self.myLcd.win(result) key = self.myKeyboard.check() nick = '' while key != '*': key = self.myKeyboard.check() if key != '' and key != '*': self.myLcd.nick(key) nick += key sleep(0.3) self.rank.reloadRanking((nick, result)) if __name__ == "__main__": while True: rank = Ranking("dane.db") my_keyboard = keyboard.Keyboard() main_screen = MainScreen(lcd.LcdMainScreen(), my_keyboard) which = main_screen.choose() mylcd = lcd.Lcd() localStaff(rank, mylcd, my_keyboard, which).run() main_screen.end() while my_keyboard.check() != ENTER: pass
dotenv_path = os.path.join(os.path.dirname(__file__), "..", ".env") if os.path.exists(dotenv_path): with open(dotenv_path, encoding='utf-8-sig') as env: for i in env: k, v = i.rstrip().split("=") os.environ[k] = v # variables token = os.environ.get("TOKEN") database_url = os.environ.get("DATABASE_URL") first_semestr = "https://www.polessu.by/ruz/cab/" second_semestr = "https://www.polessu.by/ruz/cab/term2/" semestr = second_semestr bot = telebot.TeleBot(token) keyboard = keyboard.Keyboard(bot) scheduler = BackgroundScheduler() sql = sql.Sql(database_url) sql.create_user_position() # start message @bot.message_handler(commands=["start"]) def handle_text(message): user_keyboard = telebot.types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True) user_keyboard.row( "🏫 Ввести полное название группы / преподавателя / аудитории:") user_keyboard.row("🔎 Поиск названия группы / преподавателя / аудитории:") user_keyboard.row("📨 Обратная связь") start_message = "Вас приветствует бот показа расписания занятий в Полесском государственном " \
import vk import time import random import keyboard import SFP_Function import Config import json token = Config.token session = vk.Session() api = vk.API(session, lang='ru', v=5.85) keyboard1 = keyboard.Keyboard(True) keyboard1.add_button('Картинка', 'primary', 'picture') keyboard1.add_button('Музыка', 'positive', 'music') keyboard1.add_button('Текст', 'negative', 'text') kb = keyboard1.get() print(keyboard) while True: time.sleep(1) try: data = api.messages.getConversations(filter='unread', access_token=token)['items'] for j in range(len(data)): #print(data) id_message = data[j]['conversation'] id = id_message['peer']['id'] k = id_message['unread_count'] message = api.messages.getHistory(user_id=id,
#Piano frame_piano = tk.Frame(mw, borderwidth=5, width=360, height=300) octaves = 4 #Pas la meilleure méthode, mais c'est la seule avec laquelle j'arrive à visualiser la note jouée #Avec cette méthode, j'attache manuellement tous les keyboards à la vue (plus bas dans le code après création de la view_signal) model_piano = [] control_piano = [] view_piano = [] for i in range(octaves): model_piano.append(i) control_piano.append(i) view_piano.append(i) for octave in range(octaves): model_piano[octave] = keyboard.Octave(octave + 1) control_piano[octave] = keyboard.Keyboard(frame_piano, model_piano[octave]) view_piano[octave] = keyboard.Screen(frame_piano) model_piano[octave].attach(view_piano[octave]) control_piano[octave].get_keyboard().grid(column=octave, row=0) view_piano[octave].get_screen().grid(column=octave, row=1) #Wave visualizer visuModel = visualizer.Generator() frame_signal = tk.Frame(mw, borderwidth=5, width=360, height=300) view_signal = visualizer.View(frame_signal, mod=visuModel) view_signal.grid(4) view_signal.packing() for octave in range(octaves): model_piano[octave].attach(view_signal)
acc.set_callback(acc_cb) ###acc_cb.wait() print "\n" print "Registration complete, status=", acc.info().reg_status, \ "(" + acc.info().reg_reason + ")" neopixels_green() time.sleep(1) neopixels_off() except pj.Error, e: print "Exception: " + str(e) lib.destroy() neopixels_red() d = DelegateForCX300() keyb = keyboard.Keyboard(d) try: cx300 = CX300(d) except: print( "Could not open CX300, will not be able to respond to CX300 commands" ) if (cx300): # cx300.display_clear() cx300.display_two_lines(_("Started")) cx300_listen_keys() speak(_("Started")) app.run(host='0.0.0.0', port=80)
import threading as th import concurrent.futures as cf import os import keyboard import mouse import system import window import gui if __name__ == "__main__": #x = input("Write over old data? (y/n) ") x = 'y' msg = "testing thread from main.py" kb = keyboard.Keyboard(erase=x) mo = mouse.Mouse(erase=x) sy = system.System(erase=x) wn = window.Window(erase=x) dash = gui.Gui() th0 = th.Thread(target=kb.data_stream, daemon=True) th1 = th.Thread(target=mo.data_stream, daemon=True) th2 = th.Thread(target=sy.data_stream, daemon=True) th3 = th.Thread(target=wn.data_stream, daemon=True) try: """ with cf.ThreadPoolExecutor() as exe: th1 = exe.submit(kb.data_stream) th2 = exe.submit(mo.data_stream) th3 = exe.submit(sy.data_stream)
import processor import ram import storage import display import keyboard import mouse import computer processor = processor.Processor('3.4 GHz', 2) ram = ram.Ram(500) storage = storage.Storage(5000) display = display.Display('LG', '1920x1080') keyboard = keyboard.Keyboard('Samsung') mouse = mouse.Mouse('Apple') class ComputerBuilder: def build(self): return computer.Computer(processor, ram, storage, display, keyboard, mouse)
if num_devices == 0: print "Do not find keyboards" quitCautious() for _fd in devices.keys(): try: devices[_fd].grab() print "Grabbed keyboard", devices[_fd] except IOError: print "Already grabbed" # Setup keyboards keyboards = dict() _number = 1 for d in devices: _keyboard = keyboard.Keyboard(_number, _number-1, inst_mem[mem-1], vol_mem[mem-1], 30, 70, base_mem[mem-1], 0) keyboards[d] = _keyboard _number += 1 mem += 1 print keyboards # Configure keyboard kbCount = 0 for kb in keyboards.values(): kb.config(mi) for keyname in getCode.keys(): kb.pressed[keyname] = 0 kbCount += 1
def keyboard_url(self): entry = keyboard.Keyboard() url = entry.get_url() return url
def main(self, ): """Main program loop. """ FORMAT = "%(asctime)s %(message)s" logging.basicConfig(filename="./activity.log", format=FORMAT, level=logging.DEBUG) self.cam = camera.Camera() # self.past_detection = yolo.YOLO() logging.info("Camera detected") # self.cam.saveConf() # logging.info("Camera configuration saved") self.cam.loadConf("acA5472-17um.pfs") logging.info("Camera configuration loaded") # Start detectors self.past_detection = yolo.YOLO() #self.text_detection = yolo_text.YOLO() #self.char_detection = yolo_char.YOLO() ChipD = chip_detector.ChipDetector() OrienF = orientation_fixer.OrientationFixer() CaracD = caracter_detector.CaracDetector() # Connect to keyboard kbd = keyboard.Keyboard() # Keep track of the previous barcode previous_text = None # Until death stikes, we read images continuously. while True: # Grab image from camera print("PRESENTER PRODUIT...") start_cycle = time.time() fullimg, img = self.cam.grabbingImage() # Convert to PIL format img_pil = Image.fromarray(fullimg) # computeResults = image.Image(fullimg) # Pastille detection, save image on-the-fly. # The goal here is to perform a FIRST detection, wait for 1s and perform a SECOND detection # in order to avoid keeping/getting blurry images. is_detected, out_boxes, out_scores, out_classes = self.past_detection.detect_image( img_pil) if not is_detected: continue print(" NE BOUGEZ PLUS !") time.sleep(1) start_subcycle = time.time() fullimg, img = self.cam.grabbingImage() is_detected, out_boxes, out_scores, out_classes = self.past_detection.detect_image( img_pil) if not is_detected: # print("You moved...") continue # Get detected zone print(" Vous pouvez retirer le produit.") end_capture = time.time() # self.detect = detection_instance.DetectionInstance(fullimg) # is_cropped, img_chip = self.detect.get_chip_area(out_boxes) # Save chip image output_fn = os.path.join( ACQUISITIONS_PATH, "CHIP-{}.png".format(time.strftime("%Y-%m-%d-%H%M%S")), ) # Image.fromarray(img_chip).save(output_fn) output_fn = output_fn.replace("CHIP", "FULL") Image.fromarray(fullimg).save(output_fn) # print("Image saved: {}".format(output_fn)) # img_chip.save(output_fn) # Perform the full detection cycle. # Start by cropping the chip (in 2 steps) # THIS part can be vastly optimized especially considering what's done above. start_chip = time.time() box, score = ChipD.detect_chip(fullimg) if box is None: print( " Pas de pastille détectée. Tournez la prothèse de 90 degrés." ) continue elif score < 0.1: print( " Pastille pas suffisamment nette. Tournez la prothèse de 90 degrés." ) continue chip_step1 = ChipD.crop_chip(fullimg, box) chip = better_circle.circle_finder(chip_step1) end_chip = time.time() # STEP 3: we rotate the chip (predict chip angle) start_orientation = time.time() predicted_orientation, rotated_chip = OrienF.classify_angle(chip) end_orientation = time.time() # Detect characters and send to the keyboard interface. Save image on the fly start_ocr = time.time() outlined_text, lines = CaracD.carac_detection(rotated_chip) end_ocr = time.time() output_fn = output_fn.replace("FULL", "TEXT") Image.fromarray(outlined_text).save(output_fn) text = "\t".join(lines) print(" NUMERO DE SERIE: {}".format(" ".join(lines))) print(" [TIME] Temps prise de vue : %.4f" % (end_capture - start_subcycle)) print(" [TIME] Temps détection pastille : %.4f" % (end_chip - start_chip)) print(" [TIME] Temps rotation : %.4f" % (end_orientation - start_orientation)) print(" [TIME] Temps OCR : %.4f" % (end_ocr - start_ocr)) # Send text to keyboard *if and only if* it's different from the previous one if text == previous_text: print(" [SAME AS PREVIOUS CODE, WE DON'T SEND IT]") else: kbd.send(text) previous_text = text time.sleep(1)