def __init__(self): self.states = {'mainmenu': main_menu.MainMenu()} self.active_state = self.states.get('mainmenu') self.display = display.Display(1280, 720) self._running = True
self.last_dir = event.value if event.type == pygame.JOYBUTTONDOWN: if event.button == 1: self.eraseBlock() self.currentBlock.rotateLeft() self.drawBlock() if event.button == 2: self.eraseBlock() self.currentBlock.rotateRight() self.drawBlock() if self.game_over and (event.button == 8): self.game_over = False self.newField() self.getBlock() self.down = 0 if __name__ == "__main__": disp = display.Display() tetris = Tetris(disp) def term_handler(sig, frame): tetris.stop() sys.exit(0) signal.signal(signal.SIGINT, term_handler) tetris.loop()
def __init__(self): self.d = display.Display() self.b = backlight.Backlight() self.k = keyboard.Keyboard() self.l = looper.Looper(self.b, self.d) self.p = polyphony.Polyphony(self.k, self.d, self.l)
def print_balance(self, inputDict): cols = int(inputDict["cols"]) fiat, fiat_symbol, crypto = inputDict["fiat"], inputDict[ "symbol"], inputDict["crypto"] fiat2, fiat_symbol2 = ("USD", "$") if fiat != "USD" else ("EUR", "€") cryptoList = [crypto] + [ coin for coin in ('BTC', 'LTC', 'ETH', 'BCH', 'DASH') if coin != crypto ] with open("updates/fiat-prices", "r") as f: result = json(f.readline()) total_fiat, unlocked_fiat = (bal * float(result.get(fiat)) for bal in (self.total_balance, self.unlocked_balance)) total_crypto, unlocked_crypto = (bal * float(result.get(crypto)) for bal in (self.total_balance, self.unlocked_balance)) #NOTE TO SELF: USE display.fit_floats to make fit int larger displays print( " 1 \033[01;36;40mXMR\033[00;33;40m ≈ \033[00;37;40m{}{:.2f} \033[00;33;40m{}{:.2f} \033[00;37;40m{:.4f} \033[01;36;40m{} \033[00;33;40m{:.4f} \033[01;36;40m{} \033[00;37;40m{:.4f} \033[01;36;40m{} \033[00;33;40m{:.4f} \033[01;36;40m{} \033[00;37;40m{:.4f} \033[01;36;40m{}\n" .format( fiat_symbol, result.get(fiat), fiat_symbol2, result.get(fiat2), result.get(cryptoList[0]), cryptoList[0], result.get(cryptoList[1]), cryptoList[1], result.get(cryptoList[2]), cryptoList[2], result.get(cryptoList[3]), cryptoList[3], result.get(cryptoList[4]), cryptoList[4], )) length = cols - 2 disp_total_fiat = "{}{:.2f}".format(fiat_symbol, total_fiat) disp_unlocked_fiat = "{}{:.2f}".format(fiat_symbol, unlocked_fiat) total_line = " Total Balance (Locked + Unlocked): {} XMR ≈ {} ≈ {}".format( "{0}", disp_total_fiat, "{1} " + crypto) total_line, tfloats = display.fit_floats( total_line, [(self.total_balance, 1), total_crypto], length - 2) unlocked_line = " Unlocked Balance (Unlocked only): {} XMR ≈ {} ≈ {}".format( "{0}", disp_unlocked_fiat, "{1} " + crypto) unlocked_line, ufloats = display.fit_floats( unlocked_line, [(self.unlocked_balance, 1), unlocked_crypto], length - 2) display_lines = [total_line, unlocked_line] if inputDict["type"] != "limited": display_lines.append( "Blocks to Unlock: {} Estimated time: ~{} minutes {}".format( self.blocks, self.unlock_est_time, "(Refresh balance to update)" if cols >= 80 else " ")) colorDict = { "GREEN": [disp_total_fiat, disp_unlocked_fiat], "WHITE_BOLD": [self.total_balance, self.unlocked_balance] + [tfloats[0], ufloats[0]], "WHITE": [tfloats[1], ufloats[1]] + [self.blocks, "~" + str(self.blocks), self.unlock_est_time] } display.Display("YOUR MONERO WALLET BALANCE", display_lines, colorDict, length, cols).print_box() if inputDict["type"] == "full": print( "\033[00;37;40mTotal Balance is everything your Monero wallet has received so far.\033[00;33;40m\n\n" "Unlocked balance is the amount of XMR in your wallet that has confirmed\non the Monero blockchain and is withdrawable now.\n\n\033[00;37;40mLocked balance cannot be sent or converted until it is unlocked.\n\n" "\033[00;33;40mLocked balance typically takes ~2 minutes per block to become unlocked." )
import display import sys url = sws.url all_bots = [] num_msgs = 0 JOYSTICK_MOVEMENT = 1 # Pixel per joystick event SLEEP_AFTER_UPDATE = 0.05 # Seconds USE_JOYSTICK = True SEND_TO_PROCESSING = True if SEND_TO_PROCESSING: oled_display = display.ProcessingAdditionalDisplay() else: oled_display = display.Display() def on_message(ws, message): global num_msgs num_msgs += 1 msg_json = json.loads(message) if sws.is_bot_moved_head(msg_json): handle_bot_moved_head(msg_json['items']) def handle_bot_moved_head(bots_list): maxx, maxy = 0, 0 all_bots.clear() oled_display.clear()
import game import bot import display import experiment exp_game = game.Game() exp_display = display.Display() for discount in (0.2, 0.4, 0.6, 0.8): exp_bot = bot.QLearningBot(discount=discount) exp = experiment.Experiment(exp_bot, exp_game, exp_display) exp.run(verbose=True, epochs=20)
def show(): key = search_key.get() if (bk.search(key) == None): mb.showwarning("Warning", "data not found !") else: display.Display(key)
def displayAblePrice(self, str): if not any(str): return 0 return display.Display().ablePrice(str)
def displayReceivedPrice(self, str): if not any(str): return 0 return display.Display().receivedPrice(str)
def displayDarkScreen(self): return display.Display().darkScreen()
def displayUnitPrice(self, str): if not any(str): return 0 return display.Display().unitPrice(str)
def displayInit(self): return display.Display().init()
import time import contextlib with contextlib.redirect_stdout(None): import pygame import display import board import loaders ai_move_delay = loaders.get_config('ai_move_delay') player = True b = board.Board(player).set_up() d = display.Display(b) d.redraw(player) move_delay = False timer = 0 game_running = True redraw = False while game_running: for event in pygame.event.get(): if event.type == pygame.QUIT: game_running = False elif event.type == pygame.MOUSEBUTTONDOWN: pass elif event.type == pygame.MOUSEBUTTONUP: if not move_delay: x, y = event.pos result = d.handle_click(x, y)
def main(): global setup_data global io_extender_low global io_extender_high global lcd_screen with open(SETUP_FILE, 'r') as json_file: setup_data = json.load(json_file) log_init(setup_data['LOG_LEVEL']) # PIL library may add debug logs on opening files. Let's hide them! pil_logger = logging.getLogger('PIL') pil_logger.setLevel(logging.INFO) control.note_length = setup_data['XYLOPHONE_NOTE_LENGTH'] / 1000.0 if setup_data['START_CONSOLE'] == 1: os.system('clear') print('') print('***** STARTING MY SELF PLAYING XYLOPHONE CONTROL *****') print(' ') print(' |\ ') print(' |--|/------------------|\-------------------- - /|-- ') print(' |--|---4---------------|\\\\------------------|/--_|--') print(' |-/|.-------|~~~~|----_|-\|-----|~~~~|------|--(_)-- ') print(' |(-|-)-4---_|---_|---(_)--|----_|---_|----(_)------- ') print(' |-`|\'-----(_)--(_)-------_|---(_)--(_)--------------') print(' \| (_) ') print(' ') if setup_data['START_CONSOLE'] == 1: print('******** CURRENTLY RUNNING IN CONSOLE MODE *******') else: print('******** CURRENTLY RUNNING IN OPERATIONAL MODE *******') print('') # Check if required PI GPIO daemon is started if (control.gpio_interface == USE_PI_GPIO) and (not utils.is_process_running('pigpiod')): log(ERROR, 'pigpiod process not started') graceful_exit(3) log(INFO, 'Main >>>>>> setting up display') log(INFO, '') lcd_screen = lcdscreen.LcdScreen(control.gpio_interface, setup_data['SPI_BUS_NUMBER'], setup_data['LCD_SPI_ADDRESS']) display_interface = display.Display(lcd_screen) display_interface.draw_init() log(INFO, '') log(INFO, 'Main >>>>>> setting up MIDI files') log(INFO, '') # Setup MIDI files midi_reader = midireader.MidiReader(setup_data['MIDI_MUSIC_DIR']) tracks_count = midi_reader.get_files_count() # Provide MIDI reader reference to display (used to show up tracks) display_interface.register_midi_reader(midi_reader) log(INFO, '') log(INFO, 'Main >>>>>> initiating other HW parts') log(INFO, '') # Setup control buttons mode_button = rotarybutton.RotaryStatesButton( 'MODE', control.gpio_interface, MODE_BUTTON_PIN_1, MODE_BUTTON_PIN_2, MODE_BUTTON_PIN_PRESS, [ MODE.LOOP_ONE_TRACK, MODE.PLAY_ALL_TRACKS, MODE.PLAY_ONE_TRACK, MODE.STOP ], True) track_button = rotarybutton.RotaryStatesButton( 'TRACK', control.gpio_interface, TRACK_BUTTON_PIN_1, TRACK_BUTTON_PIN_2, TRACK_BUTTON_PIN_PRESS, [i for i in range(0, tracks_count)], False) tempo_button = rotarybutton.RotaryStatesButton( 'TEMPO', control.gpio_interface, TEMPO_BUTTON_PIN_1, TEMPO_BUTTON_PIN_2, TEMPO_BUTTON_PIN_PRESS, TEMPO_LIST, False) io_extender_low = ioextender.IoExtender( setup_data['I2C_BUS_NUMBER'], setup_data['MCP_23017_I2C_ADDRESS_1']) io_extender_high = ioextender.IoExtender( setup_data['I2C_BUS_NUMBER'], setup_data['MCP_23017_I2C_ADDRESS_2']) log(INFO, '') log(INFO, 'Main >>>>>> setting up xylophone') log(INFO, '') # Update display with operational interface display_interface.draw_oper() # Setup actual xylophone and highest level controllers xylophone_device = xylophone.Xylophone( setup_data['XYLOPHONE_LOWEST_NOTE'], setup_data['XYLOPHONE_NOTES_COUNT'], setup_data['XYLOPHONE_MAX_SIM_NOTES'], io_extender_low, io_extender_high) main_controller = controller.Controller(mode_button, track_button, tempo_button, midi_reader, xylophone_device, display_interface) controller_buttons_reader = threading.Thread( target=main_controller.buttons_reader_thread, name='controller_buttons_reader', args=[]) controller_buttons_reader.start() controller_file_player = threading.Thread( target=main_controller.file_player_thread, name='controller_file_player', args=[]) controller_file_player.start() log(INFO, '') log(INFO, 'Main >>>>>> playing welcome sound') log(INFO, '') # Play hidden/embedded welcome sound main_controller.play_welcome_sound() log(INFO, '') log(INFO, 'Main >>>>>> starting console') if setup_data['START_CONSOLE'] == 1: console = threading.Thread(target=console_thread, name='console', args=[ midi_reader, main_controller, io_extender_low, io_extender_high ]) console.start() controller_buttons_reader.join() controller_file_player.join() if setup_data['START_CONSOLE'] == 1: console.join() return
#Create lists resultsList = results[startNum:endNum] resultsPagesList.append(resultsList) return resultsPagesList if __name__ == "__main__": end = False while end != True: displayLib = display.Display() option = int(input("Please choose now:")) main = Main() if option == 1: try: try: searchQuery = input("Search Query:") except ValueError: print("Please enter a correct search string...") newShodan = shodandb.ShodanDB_Search(searchQuery) resultsPagesList, keyDataList = newShodan.searchShodan() main.createPageListingShodan(resultsPagesList, keyDataList) except Exception as e: print("\nError Reporting: {0}\n".format(e)) input("Press enter to continue...")
def displayBackPrice(self, str): if not any(str): return 0 return display.Display().backPrice(str)
def compare_rates(inputDict): optionsList = [] loaded_urlList = [] amount = mmutils.fix_amount(inputDict["amount"]) fiat = inputDict["fiat"] fiat_symbol = inputDict["symbol"] coinsList = inputDict["selected_coins"].split("|") print if amount[1] in coinsList and amount[1] != "XMR": coinsList = [amount[1]] elif "XMR" in coinsList: coinsList.remove("XMR") elif "TRUE_C" in coinsList: coinsList.remove("TRUE_C") coinsList.append("TRUE") if inputDict["type"] == "withdraw": is_withdrawal = True if amount[1] == coinsList[0]: invert = True else: invert = False error_title = "ERROR: No withdrawal options available for {} {}".format( amount[0], amount[1]) else: is_withdrawal = False if amount[1] == "XMR": invert = True else: invert = False error_title = "ERROR: No deposit options available for {} {}".format( amount[0], amount[1]) price_urlList = make_price_urlList(coinsList, fiat) with ThreadPoolExecutor() as executor: priceDictList = executor.map(get_priceDictList, price_urlList) priceDict = sync_priceDict(priceDictList) option_dataList = make_option_dataList(coinsList, priceDict, is_withdrawal, amount, fiat) with ThreadPoolExecutor() as executor: optionsMap = executor.map(get_option, option_dataList) initial_optionsList = list(optionsMap) optionsList = [] for option in initial_optionsList: if type(option) is not None and option != None: optionsList.append(option) sortable = False while not sortable: try: sortedList = sorted(optionsList, key=lambda option: option.fee) sortable = True except (ValueError, AttributeError) as e: optionsList.remove(e.__cause__) if len(sortedList) < 1: mmutils.error_out(error_title, "Try again with a different amount and/or coin(s)") with open("options-list", "a") as f: for option in sortedList: f.write(option.zenity_data) size = int(inputDict["cols"]) amount_len = size - 64 #rate_len = size - value_len = len(str(sortedList[0].fiat_out).split(".")[0]) + 6 columns = [[("Rank", 4, 6)], [("Coin", 6, 6)], [("Exchange", 9, 10)], [("Amount You Send" if invert else "Amount You Get", 8, None)], [("Value", value_len, value_len)], [("Fee", 8, None)], [("Rate", 16, None)]] rank = 0 for option in sortedList: rank += 1 table_data = [rank] + option.get_table_data(is_withdrawal, invert, fiat_symbol) for index, column in enumerate(columns): column.append(table_data[index]) colorDict = { "WHITE_BOLD": ["cols=0,2,3,5,6"], "GREEN": ["col=4"], "BLUE": ["col=1"] } title = "Current options for {}ing: {} {}".format( "withdraw" if is_withdrawal else "deposit", amount[0], amount[1]) display.Display(title, columns, colorDict, size, size).print_table()
def displayClearPointer(self): return display.Display().clearPointer()
import display buf = bytearray(296 // 8 * 128) d = display.Display(buf, None, 128, 296, rotation=display.ROTATE_90, invert=True, font=display.FONT_DEJAVU_12) d.clear(display.BACKGROUND) #d.fill_rect(0, 0, 4, 4) d.text(20, 20, 'Test') print('test') d.update()
def displayMovePointer(self, str): return display.Display().movePointer(str)
oled.text(self.format_departure(reachable[2]), 3, 38) if len(self.departures) > 3: oled.text(self.format_departure(reachable[3]), 3, 48) if self.processing: oled.fill_rect(0, 62, 128, 20, 1) oled.show() def reachable_departures(self): now = time.time() return [departure for departure in self.departures if departure.reachable(now)] view = View() i2c = machine.I2C(scl=machine.Pin(4), sda=machine.Pin(5)) oled = display.Display(i2c) scheduler = timer.default(lambda: view.paint(oled)).start() def stop(): print("Shuting down") scheduler.stop() counter = 0 try: view.show_message('Booting...') time.sleep(2) network_connect(lambda: view.show_message('Network...'))
def __init__(self, name, screen_width, screen_height, screen=None): # setup data members and the screen game.Game.__init__(self, name, screen_width, screen_height, screen) ### Display setup ### self.display = display.Display((DISPLAY_X, DISPLAY_Y), DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_BG_COLOR, DISPLAY_O_COLOR) ### Purchaser menu setup ### self.menu = menu.Menu((MENU_P_X, MENU_P_Y), MENU_P_WIDTH, MENU_P_HEIGHT, MENU_P_BG_COLOR, MENU_P_O_COLOR) self.tower_types = [ tower.Tower, tower.RedTower, tower.GreenTower, tower.BlueTower ] ### Trap menu setup ### self.trap_menu = menu.Menu((MENU_TRAP_X, MENU_TRAP_Y), MENU_TRAP_WIDTH, MENU_TRAP_HEIGHT, MENU_TRAP_BG_COLOR, MENU_TRAP_O_COLOR) self.trap_types = [trap.Mud, trap.Lava] ### Button menu setup ### self.b_menu = menu.Menu((MENU_B_X, MENU_B_Y), MENU_B_WIDTH, MENU_B_HEIGHT, MENU_B_BG_COLOR, MENU_B_O_COLOR) self.buttons = [button.NewWave, button.Upgrade, button.Sell] self.creep_types = [ creep.Creep, creep.RedCreep, creep.YellowCreep, creep.BlueCreep ] ### setup font ### self.font = pygame.font.SysFont(FONT, FONT_SIZE) self.font_color = FONT_COLOR ### Main menu setup ### self.mm = menu.Menu(MM_POS, MM_WIDTH, MM_HEIGHT, MM_BG_COLOR, MM_O_COLOR) self.mm_buttons = [button.Play, button.Help, button.Quit] for btn in self.mm_buttons: self.mm.add_button(btn) self.mm.center_x() self.mm_img = pygame.image.load(MM_IMG) ### Level select setup ### self.ls = menu.VerticalMenu(LS_POS, LS_WIDTH, LS_HEIGHT, LS_BG_COLOR, LS_O_COLOR) self.ls.set_banner(LS_IMG) self.ls_buttons = LEVELS for i in range(len(self.ls_buttons)): self.ls.add_button(button.Level, self.ls_buttons[i][0], self.ls_buttons[i][1]) ### setup location for money ### self.money_x = MONEY_X self.money_y = MONEY_Y ### setup location for lives ### self.lives_x = LIVES_X self.lives_y = LIVES_Y ### setup location for wave number ### self.wave_x = WAVE_X self.wave_y = WAVE_Y self.buttons = [ button.NewWave, button.Upgrade, button.Sell, button.Quit ] for btn in self.buttons: self.b_menu.add_button(btn) self.b_menu.center_x() # tracks progress through tutorial self.tut_progress = -1 self.alerts = set() self.empty_data()
def __init__(self): self.status = status.Status() self.display = display.Display() self.play = 0
def mp4(clcs): dsp = dp.Display(logging, clcs) dsp.sensitivityTables() dsp.opticalPowerTables()
def __init__(self, w, h, panels=None): super(DisplaySim, self).__init__() self.d = display.Display(w, h, panels) self.l = threading.RLock() self.frames = 0 self._stop = threading.Event()
#!/usr/local/bin/python #python Version 2.7.2 import numpy as np import experiment as exp import display as dsp import optimize as opt import glob as gb #Define the atmosphere atmFile = './Atacama_1000um_60deg.txt' #Gather experiments designDirs = sorted(gb.glob('./Designs/*/')) experiments = [exp.Experiment(dir, atmFile) for dir in designDirs] displays = [dsp.Display(experiment) for experiment in experiments] #optimizes = [opt.Optimize(experiment) for experiment in experiments] for i in range(len(designDirs)): dsp = displays[i] dsp.textTables() print print '**********************************************************************************************************************' print '**********************************************************************************************************************' print '**********************************************************************************************************************' print
from dl_cmdline import DisplayLegacyCmdline logging.basicConfig(filename="log", format="[%(lineno)d]%(asctime)s:%(levelname)s:%(message)s", level=logging.DEBUG) if __name__ == "__main__": if len(sys.argv) > 1: if os.path.exists(sys.argv[1]): cfg = config.Config(sys.argv[1]) else: # Change it so it at least tries to read default path/values first. print("Invalid configuration file path.") cfg = config.Config() else: cfg = config.Config() board = Board(config=cfg) c = config.Colors() # terminal colors object marker = Marker() dl = DisplayLegacy(cfg, board, c, marker) # Command line legacy interface - used by default if cfg.display_legacy in ("True", "true"): screen = DisplayLegacyCmdline(board, c, cfg, dl, marker) screen.run() # urwid GUI else: screen = display.Display(cfg, board) screen.run()
from ecu import CBR500Sniffer, ECUError from uasyncio import get_event_loop, sleep_ms as d from utime import ticks_diff as tdiff, ticks_ms as tms, sleep_ms as sleep_ms import machine import display # move ssd1306_vert.py & display.py to ESP first! loop = get_event_loop() UART0 = machine.UART(0, 115200) ecu = CBR500Sniffer(UART0) i2c = machine.I2C(-1, machine.Pin(5), machine.Pin(4)) oled = display.Display(i2c, 128, 64) async def task_ecu(): oled.println("task_ecu()") err_counter = 0 while True: for table in ecu.TABLES: try: if not ecu.ready: oled.println("init()") await ecu.init() if not ecu.ready: oled.println("TIMEOUT") await d(3000) continue oled.println("update(%s)" % str(table)) await ecu.update(table)
pin14 = pins.D_Pin(19) pin15 = pins.D_Pin(23) pin16 = pins.D_Pin(5) pin19 = pins.D_Pin(22) pin20 = pins.D_Pin(21) def panic(flag=0): return machine.reset_cause() reset = machine.reset import display Image = display.Image display = display.Display() import button button_a = button.Button(35) button_b = button.Button(27) import temperature __adc = machine.ADC(machine.Pin(34, machine.Pin.IN)) __adc.atten(machine.ADC.ATTN_11DB) temperature = temperature.Temperature(__adc).temperature try: from mpu9250 import MPU9250 from mpu6500 import MPU6500 __i2c = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(21), freq=200000) __dev = __i2c.scan()
def main(): number = 0 #lcd_init() th_flag = False display_update = False index = 0 w = weather.weather_info("seoul") music_thread = music.MusicThread() music_thread.start() display_on = display.Display() weather_list = [w['date'], w['temp'], w['location'], w['weather']] music_list = ['None', 'None'] display_on.set_info(weather_list, music_list) display_on.start() print("start loop") while True: number = getch.getch() #print(number) if (number == '1'): display_update = True w = weather.weather_info("seoul") elif (number == '2'): display_update = True w = weather.weather_info("london") elif (number == '3'): display_update = True w = weather.weather_info("newyork") elif (number == 'a'): index = 0 display_update = True th_flag = not th_flag music_thread.push_power_switch() elif (number == '4'): music_thread.pause() elif (number == '5'): music_thread.unpause() elif (number == 'b'): index = index + 1 display_update = True music_thread.play_next_music() elif (number == 'p'): music_thread.volume_up() elif (number == '-'): music_thread.volume_down() elif (number == '8'): music_thread.exit() display_on.exit() exit() if (display_update == True): print("display update...") weather_list = [w['date'], w['temp'], w['location'], w['weather']] music_list = music_thread.get_current_info(index % 3) display_on.set_info(weather_list, music_list) display_update = False