Ejemplo n.º 1
0
    def start(self):
        """
        Initialize the screen and input mode.
        """
        assert self._started == False

        self.s = curses.initscr()
        self.has_color = curses.has_colors()
        if self.has_color:
            curses.start_color()
            if curses.COLORS < 8:
                # not colourful enough
                self.has_color = False
        if self.has_color:
            try:
                curses.use_default_colors()
                self.has_default_colors=True
            except _curses.error:
                self.has_default_colors=False
        self._setup_colour_pairs()
        curses.noecho()
        curses.meta(1)
        curses.halfdelay(10) # use set_input_timeouts to adjust
        self.s.keypad(0)
        
        if not self._signal_keys_set:
            self._old_signal_keys = self.tty_signal_keys()

        super(Screen, self).start()
Ejemplo n.º 2
0
    def __init__ (self):
        self.board = puzzle_2048()
        
        self.screen = curses.initscr()
        self.screen.keypad(1)
        self.screen.leaveok(0)
        curses.start_color()
        curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
        curses.noecho()
        curses.curs_set(0)
        
        self.screen.addstr(0,0,"To play: combine the tiles that match using the arrow keys, and press esc to exit")
        
        #Drawing the lines for the board
        self.screen.hline(5,10,"-", 29, curses.color_pair(1))
        self.screen.hline(9,10,"-", 29, curses.color_pair(1))
        self.screen.hline(13,10,"-", 29, curses.color_pair(1))
        self.screen.hline(17,10,"-", 29, curses.color_pair(1))
        self.screen.hline(21,10,"-", 29, curses.color_pair(1))
        self.screen.vline(5,10,"|", 17, curses.color_pair(1))
        self.screen.vline(5,17,"|", 17, curses.color_pair(1))
        self.screen.vline(5,24,"|", 17, curses.color_pair(1))
        self.screen.vline(5,31,"|", 17, curses.color_pair(1))
        self.screen.vline(5,38,"|", 17, curses.color_pair(1))
        
        self.Update_screen()

        self.run()
Ejemplo n.º 3
0
 def init(self):
     self.window = curses.initscr()
     self.initted = True
     self.ymax, self.xmax = self.window.getmaxyx()
     terminfo = curses.longname()
     assert '256' in terminfo  # your env TERM must be xterm-256color!
     assert curses.has_colors()
     curses.start_color()
     curses.use_default_colors()
     ctr = 1
     for fg in CLRS:
         for bg in CLRS:
             if ctr <= curses.COLORS-1 and fg != bg:
                 curses.init_pair(ctr, CLRS[fg], CLRS[bg])
                 pairs[(fg,bg)] = curses.color_pair(ctr)
                 ctr += 1
     curses.meta(1)
     curses.noecho()
     curses.cbreak()
     curses.curs_set(0)
     curses.delay_output(0)
     curses.mouseinterval(150)
     availmask,_ = curses.mousemask(curses.ALL_MOUSE_EVENTS)
     assert availmask != 0  # mouse must be available!
     self.window.leaveok(1)
     self.window.scrollok(0)
     self.window.keypad(1)
     if NONBLOCKING:
         self.window.nodelay(1)
         self.window.timeout(NONBLOCKING_TIMEOUT)
     else:
         self.window.nodelay(0)
         self.window.timeout(-1)
     self.window.refresh()
Ejemplo n.º 4
0
 def setup_colors(self):
   curses.start_color()
   #0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white
   #curses.init_pair(0, curses.COLOR_WHITE, curses.COLOR_BLACK)
   curses.init_pair( 1, curses.COLOR_WHITE, curses.COLOR_RED)
   curses.init_pair( 2, curses.COLOR_WHITE, curses.COLOR_GREEN)
   curses.init_pair( 3, curses.COLOR_WHITE, curses.COLOR_YELLOW)
   curses.init_pair( 4, curses.COLOR_WHITE, curses.COLOR_BLUE)
   curses.init_pair( 5, curses.COLOR_WHITE, curses.COLOR_MAGENTA)
   curses.init_pair( 6, curses.COLOR_WHITE, curses.COLOR_CYAN)
   ## Black Text on Colored Background
   curses.init_pair(10, curses.COLOR_BLACK, curses.COLOR_WHITE)
   curses.init_pair(11, curses.COLOR_BLACK, curses.COLOR_RED)
   curses.init_pair(12, curses.COLOR_BLACK, curses.COLOR_GREEN)
   curses.init_pair(13, curses.COLOR_BLACK, curses.COLOR_YELLOW)
   curses.init_pair(14, curses.COLOR_BLACK, curses.COLOR_BLUE)
   curses.init_pair(15, curses.COLOR_BLACK, curses.COLOR_MAGENTA)
   curses.init_pair(16, curses.COLOR_BLACK, curses.COLOR_CYAN)
   ## Red Text on Colored Background
   curses.init_pair(20, curses.COLOR_RED, curses.COLOR_WHITE)
   curses.init_pair(21, curses.COLOR_RED, curses.COLOR_BLACK)
   curses.init_pair(22, curses.COLOR_RED, curses.COLOR_GREEN)
   curses.init_pair(23, curses.COLOR_RED, curses.COLOR_YELLOW)
   curses.init_pair(24, curses.COLOR_RED, curses.COLOR_BLUE)
   curses.init_pair(25, curses.COLOR_RED, curses.COLOR_MAGENTA)
   curses.init_pair(26, curses.COLOR_RED, curses.COLOR_CYAN)
Ejemplo n.º 5
0
 def init_curses(self):
     self.screen = curses.initscr()
     curses.noecho()
     curses.start_color()
     curses.cbreak()
     self.screen.keypad(0)
     curses.curs_set(0)
Ejemplo n.º 6
0
    def __init__(self, screen, encoding):
        self.screen   = screen
        self.encoding = encoding
        self.parser   = markup.MarkupParser()

        curses.start_color()

        self.has_default_colors = curses.COLORS > COLOR_COUNT

        if self.has_default_colors:
            # xterm-256color
            curses.use_default_colors()
            FG_COLORS["default"]    = -1
            BG_COLORS["on_default"] = -1
            self.init_color_pairs()
        elif curses.COLORS != 0:
            # ansi linux rxvt ...etc.
            curses.use_default_colors()
            self.init_color_pairs()
            FG_COLORS["default"]    = curses.COLOR_WHITE
            BG_COLORS["on_default"] = curses.COLOR_BLACK
        else: # monochrome, curses.COLORS == 0
            # vt100 x10term wy520 ...etc.
            FG_COLORS["default"]    = curses.COLOR_WHITE
            BG_COLORS["on_default"] = curses.COLOR_BLACK

        self.update_screen_size()
Ejemplo n.º 7
0
def nstart(stdscr):
	global logw
	global cw
	global netstatw
	global trash
	global player
	global kingdom
	global opponent
	curses.start_color()
	maxY, maxX = stdscr.getmaxyx()
	logw = GameInput(windowX=math.floor(maxX/2), windowY=math.floor(maxY/3), height=math.floor(maxY*2/3)-2, width=maxX-math.floor(maxX/2)-1, scrollDepth=1000)
	cw = NetInput(windowX=math.floor(maxX/4), windowY=math.floor(maxY/8*7), height=maxY-math.floor(maxY/8*7)-2, width=math.floor(maxX/4)-1)
	netstatw = curses.newwin(maxY-math.floor(maxY/8*7), math.floor(maxX/4)-1, math.floor(maxY/8*7), 0)
	trash = curses.newwin(math.floor(maxY/8), math.floor(maxX/2), math.floor(maxY*7/16), 0)
	player = Player(math.floor(maxY*7/16), math.floor(maxX/2), 0, 0)
	kingdom = Kingdom(math.floor(maxY/3), math.floor(maxX/2), 0, math.floor(maxX/2))
	opponent = Opponent(math.floor(maxY*5/16), math.floor(maxX/2), math.floor(maxY*9/16), 0)
	trash.addstr('trash')
	trash.refresh()
	if os.path.exists('cccnfg.cfg'):
		with open('cccnfg.cfg', 'r') as f:
			for ln in f.read().splitlines(): cw.command(ln)
	while True:
		cw.run()
		logw.run()
Ejemplo n.º 8
0
    def __init__(self, evm):
        self.evm = evm
        evm.RegisterListener(self)
        # first we must create a window object; it will fill the whole screen
        self.scrn = curses.initscr()
        # turn off keystroke echo
        curses.noecho()
        # keystrokes are honored immediately, rather than waiting for the
        # user to hit Enter
        curses.cbreak()

        self.scrn.keypad(1)

        self.scrn.nodelay(1)
        # start color display (if it exists; could check with has_colors())
        curses.start_color()

        curses.mousemask(curses.BUTTON1_PRESSED)

        curses.curs_set(0)

        # clear screen
        self.scrn.clear()

        i = 1
        for color_background in self.list_of_colors:
            for color_foreground in self.list_of_colors:
                curses.init_pair(i, color_foreground, color_background)
                self.mapping[color_foreground, color_background] = i
                i += 1

        # implement the actions done so far (just the clear())
        self.scrn.refresh()
Ejemplo n.º 9
0
    def initColors (self):
        curses.start_color()

        if self.conf.params_transparency:
            curses.use_default_colors()
            bgcolor = -1
        else:
            bgcolor = 0

        # Setup colors
        # TODO, check the term capability before
        if curses.can_change_color():
            for i in range(len(self.conf.color_set)):
                if not self.conf.color_set[i]:
                    continue
                else:
                    rgb = self.conf.color_set[i]
                    curses.init_color(i, rgb[0], rgb[1], rgb[2])

        curses.init_pair(0, curses.COLOR_BLACK, bgcolor)    # 1 black
        curses.init_pair(1, curses.COLOR_RED, bgcolor)      # 2 red
        curses.init_pair(2, curses.COLOR_GREEN, bgcolor)    # 3 green
        curses.init_pair(3, curses.COLOR_YELLOW, bgcolor)   # 4 yellow
        curses.init_pair(4, curses.COLOR_BLUE, bgcolor)     # 5 blue
        curses.init_pair(5, curses.COLOR_MAGENTA, bgcolor)  # 6 magenta
        curses.init_pair(6, curses.COLOR_CYAN, bgcolor)     # 7 cyan
        curses.init_pair(7, curses.COLOR_WHITE, bgcolor)    # 8 white
Ejemplo n.º 10
0
 def initializeScreen (self):
     self.screen = curses.initscr ()
     curses.start_color ()
     curses.noecho ()
     curses.cbreak ()
     (self.screenHeight, self.screenWidth) = self.screen.getmaxyx ()
     pass
Ejemplo n.º 11
0
 def init(self):
     """init(self) -> None
     Colour initialization.
     """
     curses.start_color()
     for key, color in self._ColorSets.items():
         curses.init_pair( color['id'], color['pair'][0],  color['pair'][1] )
Ejemplo n.º 12
0
def main():
    """
    Main entry point for gunicorn_console.
    """
    # Set up curses.
    stdscr = curses.initscr()
    curses.start_color()
    curses.init_pair(1, foreground_colour, background_colour)
    curses.noecho()
    stdscr.keypad(True)
    stdscr.nodelay(True)
    try:
        curses.curs_set(False)
    except:
        pass
    try:
        # Run main event loop until quit.
        while True:
            try:
                update_gunicorns()
                handle_keypress(stdscr)
                display_output(stdscr)
                curses.napms(int(screen_delay * 1000))
            except KeyboardInterrupt:
                break
    finally:
        # Tear down curses.
        curses.nocbreak()
        stdscr.keypad(False)
        curses.echo()
        curses.endwin()
Ejemplo n.º 13
0
    def __init__(self, player_sub):
        self.player_sub = player_sub
        # self.sea = sea
        self.display_screen = ''

        # setlocale enables UTF chars
        # see: https://docs.python.org/2/library/curses.html
        locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
        self.strcode = locale.getpreferredencoding()
        # print(self.strcode)
        screen = curses.initscr()

        self.screen = screen

        # Applications will also commonly need to react to keys instantly, without requiring the Enter key
        # to be pressed; this is called cbreak mode, as opposed to the usual buffered input mode.
        curses.cbreak()

        # Usually curses applications turn off automatic echoing of keys to the screen, in order to be able to read
        #  keys and only display them under certain circumstances. This requires calling the noecho() function.
        curses.noecho()


        screen.nodelay(1)

        curses.curs_set(0)
        screen.keypad(True)

        curses.start_color()
        curses.use_default_colors()
Ejemplo n.º 14
0
    def setScreen(self, scr):
        """
		Set the screen and create the different windows 
		"""
        log(self.__class__.__name__, sys._getframe().f_code.co_name)
        self.stdscr = scr
        if self.stdscr != None:
            curses.curs_set(0)
            curses.start_color()
            curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
            curses.halfdelay(2 * 10)

            # setup all windows
            self.mainWindow = MainDisplay(0, self.stdscr)

            # self.stdscr.hline(self.WinPositions.headerBlock+self.headerWindow.getmaxyx()[0], 0, '-', 130)
            self.jobWindow = JobDisplay(0, self.stdscr)
            # self.stdscr.hline(self.WinPositions.summaryBlock+self.jobsWindow.getmaxyx()[0], 0, '-', 130)
            ##self.stdscr.hline(self.WinPositions.submitBlock+self.submitWindow.getmaxyx()[0], 0, '-', 130)

            ##self.erroWindow = curses.newwin(5, self.stdscr.getmaxyx()[1], self.WinPositions.debugBlock, 0)
            ##self.finalWindow = curses.newwin(3, self.stdscr.getmaxyx()[1], self.WinPositions.finalizeBlock, 0)
            ##self.finalWindow.addstr(0, 50, "Finalization job result")
            ##self.stdscr.hline(self.WinPositions.finalizeBlock+self.submitWindow.getmaxyx()[0], 0, '-', 130)
            ##
            ##self.stdscr.nooutrefresh()
            ##self.repaint()

            self.mainWindow.generate()
            self.jobWindow.generate()
            self.stdscr.refresh()
            self.activateMainWindow()
Ejemplo n.º 15
0
Archivo: yottu.py Proyecto: yottu/yottu
def main(argv):
	def __call__(self):
		pass

	dlog = DebugLog("debug.log")
	dlog.msg("Logging started\n")
	
	stdscr = curses.initscr()
	curses.noecho()
	curses.cbreak()
	stdscr.keypad(1)
	curses.start_color()
	
	try:
		wl = WindowLogic(stdscr)
		wl.start()

		ci = CommandInterpreter(stdscr, wl)
		ci.start()
	except Exception as e:
		dlog.excpt(e)
		raise

	ci.join()
	dlog.msg("Command Interpreter joined.\n")
	wl.stop()
	wl.join()
	dlog.msg("Thread Fetcher joined.\n")

	curses.nocbreak()
	stdscr.keypad(0)
	curses.echo()
	curses.endwin()
	curses.resetty()
	dlog.msg("Terminal restored.\n")
Ejemplo n.º 16
0
    def initialize(self):
        """initialize curses, then call setup (at the first time) and resize."""
        self.win.leaveok(0)
        self.win.keypad(1)
        self.load_mode = False

        curses.cbreak()
        curses.noecho()
        curses.halfdelay(20)
        try:
            curses.curs_set(int(bool(self.settings.show_cursor)))
        except:
            pass
        curses.start_color()
        curses.use_default_colors()

        self.settings.signal_bind('setopt.mouse_enabled', _setup_mouse)
        _setup_mouse(dict(value=self.settings.mouse_enabled))

        if not self.is_set_up:
            self.is_set_up = True
            self.setup()
            self.win.addstr("loading...")
            self.win.refresh()
            self._draw_title = curses.tigetflag('hs') # has_status_line
        self.update_size()
        self.is_on = True

        if self.settings.update_tmux_title:
            sys.stdout.write("\033kranger\033\\")
            sys.stdout.flush()
Ejemplo n.º 17
0
Archivo: ui.py Proyecto: hunner/irc-256
  def __init__(self, irc, server, room, screen, theme):
    self.theme = theme
    self.screen = screen
    self.irc = irc
    self.server = server
    self.room = room
    self.height, self.width = self._limits();
    self.topic = Line('topic', '', False)
    self.status = Line('status', '', False)
    self.input_line = Line('input', '', False)

    self.lines = []

    curses.echo()
    curses.start_color()
    self.screen.clear()
    self.screen.timeout(0)
    self.screen.scrollok(True)
    self.screen.setscrreg(1, self.height-3)

    self._draw_chat()

    self.irc.add_global_handler("welcome", self.on_connect)
    self.irc.add_global_handler("motd", self.on_motd)
    self.irc.add_global_handler("pubmsg", self.on_pubmsg)
    self.irc.add_global_handler("currenttopic", self.on_currenttopic)
Ejemplo n.º 18
0
def main(scr):
    curses.curs_set(False)

    curses.start_color()
    for i in range(1, 16):
        curses.init_pair(i, i, curses.COLOR_BLACK)

    scry, scrx = scr.getmaxyx()
    pady = scry * 2
    padx = scrx * 2

    pad = curses.newpad(pady, padx)
    pad.nodelay(True)
    mandel(pad)

    oy = 1
    ox = 0

    while True:
        pad.refresh(oy, ox, 0, 0, scry-1, scrx-1)
        key = pad.getch()
        if key in (ord('q'), ord('Q')):
            break
        elif key in (ord('w'), curses.KEY_UP):
            oy = max(oy - 1, 0)
        elif key in (ord('s'), curses.KEY_DOWN):
            oy = min(oy + 1, pady - scry - 1)
        elif key in (ord('a'), curses.KEY_LEFT):
            ox = max(ox - 2, 0)
        elif key in (ord('d'), curses.KEY_RIGHT):
            ox = min(ox + 2, padx - scrx)
        elif key == curses.KEY_RESIZE:
            scry, scrx = scr.getmaxyx()
Ejemplo n.º 19
0
def maze():
    curses.start_color()
    curses.initscr()
    curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)

    for i in range(8, 17):  # penis
        screen.addstr(i, 22, "â–ˆ")
    for i in range(22, 27):
        screen.addstr(8, i, "â–ˆ")
    for i in range(29, 43):
        screen.addstr(8, i, "â–ˆ")
    for i in range(46, 68):
        screen.addstr(8, i, "â–ˆ")
    for i in range(22, 32):
        screen.addstr(17, i, "â–ˆ")
    for i in range(34, 50):
        screen.addstr(17, i, "â–ˆ")
    for i in range(52, 68):
        screen.addstr(17, i, "â–ˆ")
    for i in range(8, 12):
        screen.addstr(i, 68, "â–ˆ")
    for i in range(14, 18):
        screen.addstr(i, 68, "â–ˆ")
    for i in range(15, 18):
        screen.addstr(i, 26, "â–ˆ")
    for i in range(13, 18):
        screen.addstr(i, 36, "â–ˆ")
    for i in range(8, 12):
        screen.addstr(i, 48, "â–ˆ")
    for i in range(8, 12):
        screen.addstr(i, 61, "â–ˆ")
    for i in range(13, 18):
        screen.addstr(i, 57, "â–ˆ")
    for i in range(54, 58):
        screen.addstr(13, i, "â–ˆ")
Ejemplo n.º 20
0
    def start(self):
        """Initialize curses. Mostly copied from curses/wrapper.py"""

        # This might do some good
        locale.setlocale(locale.LC_ALL, "")

        # Initialize curses
        stdscr = curses.initscr()

        # Turn off echoing of keys, and enter cbreak mode,
        # where no buffering is performed on keyboard input
        curses.noecho()
        curses.cbreak()

        # In keypad mode, escape sequences for special keys
        # (like the cursor keys) will be interpreted and
        # a special value like curses.KEY_LEFT will be returned
        stdscr.keypad(1)

        # Start color, too.  Harmless if the terminal doesn't have
        # color; user can test with has_color() later on.  The try/catch
        # works around a minor bit of over-conscientiousness in the curses
        # module -- the error return from C start_color() is ignorable.
        try:
            curses.start_color()
            curses.use_default_colors()
            for i in range(1, curses.COLORS):
                curses.init_pair(i, i, -1)
        except:
            LOG.exception("Exception in curses color init")

        self.stdscr = stdscr
Ejemplo n.º 21
0
 def setup(cls):
     curses.start_color()
     curses.use_default_colors()
     # -1 = transparent
     curses.init_pair(cls.sand, curses.COLOR_YELLOW, curses.COLOR_YELLOW)
     curses.init_pair(cls.hero, curses.COLOR_GREEN, -1)
     curses.init_pair(cls.monster, curses.COLOR_RED, -1)
Ejemplo n.º 22
0
def main(stdscr):
    curses.start_color()
    curses.use_default_colors()

    for bg in range(256):
        for i in range(0, curses.COLORS):
            curses.init_pair(i + 1, i, bg)
        try:
            for i in range(256):
                # c = str(i)
                c = curses.ACS_ULCORNER
                c = ord('a')
                c = u'\u239e'
                c = u'\u2588'
                # c = 9608
                # c = u'\u239e'.encode("utf-8")
                # c = u'\u0438'.encode('utf-8')
                stdscr.addstr(c, curses.color_pair(i))
                # stdscr.addch(9118)
                # stdscr.addstr('\\u239e')
                # stdscr.addch(c)
                if i < 16:
                    stdscr.addstr(' ', curses.color_pair(i))
                if i in (16,52,88,124,160,196,232,):
                    stdscr.addstr('\n', curses.color_pair(i))
            stdscr.addstr('\n', curses.color_pair(i))
        except curses.error:
            # End of screen reached
            pass
        if stdscr.getch() == ord('q'):
            break
        stdscr.clear()
Ejemplo n.º 23
0
    def __init__(self, wallet, config, app=None):
        self.stdscr = curses.initscr()
        curses.noecho()
        curses.cbreak()
        curses.start_color()
        curses.use_default_colors()
        curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
        curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_CYAN)
        self.stdscr.keypad(1)
        self.stdscr.border(0)
        self.maxy, self.maxx = self.stdscr.getmaxyx()
        curses.curs_set(0)
        self.w = curses.newwin(10, 50, 5, 5)

        self.wallet = wallet
        self.config = config
        set_verbosity(False)
        self.tab = 0
        self.pos = 0
        self.popup_pos = 0

        self.str_recipient = ""
        self.str_description = ""
        self.str_amount = ""
        self.str_fee = ""
        
        self.wallet.interface.register_callback('updated', self.refresh)
        self.wallet.interface.register_callback('connected', self.refresh)
        self.wallet.interface.register_callback('disconnected', self.refresh)
        self.wallet.interface.register_callback('disconnecting', self.refresh)
        self.tab_names = [_("History"), _("Send"), _("Receive"), _("Contacts"), _("Wall")]
        self.num_tabs = len(self.tab_names)
Ejemplo n.º 24
0
    def __init__(self):
        self.screen = curses.initscr()
        self.screen.timeout(100)  # the screen refresh every 100ms
        # charactor break buffer
        curses.cbreak()
        self.screen.keypad(1)
        self.netease = NetEase()

        curses.start_color()
        curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
        curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK)
        curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK)
        curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK)
        # term resize handling
        size = terminalsize.get_terminal_size()
        self.x = max(size[0], 10)
        self.y = max(size[1], 25)
        self.startcol = int(float(self.x) / 5)
        self.indented_startcol = max(self.startcol - 3, 0)
        self.update_space()
        self.lyric = ''
        self.now_lyric = ''
        self.tlyric = ''
        self.storage = Storage()
        self.config = Config()
        self.newversion = False
Ejemplo n.º 25
0
  def __init__(self):
    self.myscreen = curses.initscr()
    self.thread = None
    self.threadName = 'CLI'

    curses.noecho()
    curses.cbreak()
    curses.start_color()
    self.myscreen.keypad(1)

    curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)
    self.myscreen_highlighted = curses.color_pair(1)
    self.myscreen_normal = curses.A_NORMAL

    self.menus = {
      'title': "Main Menu", 'type': MENU_TYPES.MENU, 'subtitle': "Select an option...", 'options': [
        { 'title': "Status", 'type': MENU_TYPES.MENU, 'subtitle': "Select an option..", 'options': [
          { 'title': "Media Information", 'type': MENU_TYPES.COMMAND, 'command': 'printMediaInfo' },
          { 'title': "Thread Information", 'type': MENU_TYPES.COMMAND, 'command': 'printThreadInfo' }
          ]
        }
      ]
    }

    self.commands = {
      'printMediaInfo': _printMediaInfo(),
      'printThreadInfo': _printThreadInfo()
    }

    self.initThread()
Ejemplo n.º 26
0
def main_loop(stdscr):
	stdscr.clear()
	userInput = 'g'
	evoRate = .5

	gameboard = world(stdscr, ord('X'))
	gameboard.randSeed()
	stdscr.nodelay(1)

	#set colors
	curses.start_color()
	curses.init_pair(1,curses.COLOR_RED, curses.COLOR_BLACK)
	curses.init_pair(2,curses.COLOR_GREEN, curses.COLOR_BLACK)
	curses.init_pair(3,curses.COLOR_BLUE, curses.COLOR_BLACK)

	while userInput != ord('q'):
		userInput = stdscr.getch()
		gameboard.displayWorld()
		gameboard.evolveWorld()
		time.sleep(evoRate)
		
		if userInput == curses.KEY_RIGHT:
			if evoRate > .1:
				evoRate = evoRate - .02
		elif userInput == curses.KEY_LEFT:
			evoRate = evoRate + .02
Ejemplo n.º 27
0
	def init(self):
		self.screen = curses.initscr()
		curses.noecho()
		curses.cbreak()
		self.screen.keypad(1)

		try:
			curses.curs_set(0)
		except:
			logging.warning("Cursor hiding is not supported")

		curses.halfdelay(1) # block for 0.1s

		if curses.has_colors():
			self.colors = True
			curses.start_color()

			curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
			curses.init_pair(2, curses.COLOR_CYAN, curses.COLOR_BLACK)
			curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK)
			curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK)
			curses.init_pair(5, curses.COLOR_BLUE, curses.COLOR_BLACK)
		else:
			self.colors = False
			logging.warning("Colors are not supported")

		logging.info("Console I/O initialized")
Ejemplo n.º 28
0
	def init_curses(self):
		"""
		This initializes the screen for curses useage.  It must be
		called before Curses can be used.
		"""
		self.user_marker_pos = 1  # Used with curses
		self.curses_row_offset = 0  # Used for marking the visible rows on the screen to allow scrolling
		self.curses_row_offset_store = 0  # Used for storing the row offset when switching from detailed to non-detailed view modes
		self.curses_detailed = None  # Used with curses
		self.screen = curses.initscr()
		curses.start_color()
		curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_WHITE)
		size = self.screen.getmaxyx()
		if size[0] < CURSES_MIN_Y or size[1] < CURSES_MIN_X:
			curses.endwin()
			return 1
		self.curses_max_rows = size[0] - 2  # Minus 2 for the border on the top and bottom
		self.curses_max_columns = size[1] - 2

		self.screen.border(0)
		self.screen.addstr(2, TAB_LENGTH, 'EAPeak Capturing Live')
		self.screen.addstr(3, TAB_LENGTH, 'Found 0 Networks')
		self.screen.addstr(4, TAB_LENGTH, 'Processed 0 Packets')
		self.screen.addstr(self.user_marker_pos + USER_MARKER_OFFSET, TAB_LENGTH, USER_MARKER)
		self.screen.refresh()
		try:
			curses.curs_set(1)
			curses.curs_set(0)
		except curses.error:  # Ignore exceptions from terminals that don't support setting the cursor's visibility
			pass
		curses.noecho()
		curses.cbreak()
		self.curses_enabled = True
		self.curses_lower_refresh_counter = 1
		return 0
def GUI_modify_user(env, screen):
	makechanges = ""
        s = curses.newwin(20, 78, 3, 1)
	s.erase()
	s.keypad(1)
	curses.start_color()
	curses.init_pair(1,curses.COLOR_RED, curses.COLOR_BLACK)
	curses.init_pair(2,curses.COLOR_WHITE, curses.COLOR_BLACK)
	curses.init_pair(3,curses.COLOR_BLACK, curses.COLOR_WHITE)
        s.box()
	s.addstr(2, 2, "Modify user attributes", curses.color_pair(3))
	s.addstr(19, 2, "[Use [ESC] to abort!]", curses.color_pair(1))
	s.addstr(4, 2, "Enter username: "******"":
		s.erase()
		return
	error, result = helper_get_userattr(UID, env)
	if error != "OK":
		s.addstr(4, 2, error, curses.color_pair(2))
		s.getch()
		return
	error, result1 = get_Autofs(UID, env)
	if error != "OK":
		s.addstr(4, 2, error, curses.color_pair(2))
		s.getch()
		return
	result['automountInformation'] = result1[0][1]['automountInformation']
	modified = deepcopy(result)
	s.erase()
	s.box()
	s.addstr(2, 2, "Modify user attributes", curses.color_pair(3))
	if error != "OK":
		s.addstr(4, 2, error, curses.color_pair(2))
		s.getch()
		return
	result, modified = helper_modify_userattr(s, env, result, modified)
	if result != modified:
		# Modifications have taken place:
		dofile, undofile, error = helper_modified_user_to_ldif(env, result, modified)
		# TO LDAPSERVER AND LOG
		s.addstr(16, 2, "Do you wish to commit the changes? [y|n]", curses.color_pair(1))
		makechanges = getInput(s, 15, 40, 1, 0, False)
		if makechanges == "y" or makechanges == "Y":
			s.addstr(16, 2, "%s"%env.LOGS, curses.color_pair(1))
			content,error=apply_ldif.ldif2dict(dofile)
			if error != "OK":return error
			error=apply_ldif.apply_ldif(content,env)
			WriteLog(dofile, "modify_user.done.%s"%(UID), env)
			WriteLog(undofile, "modify_user.undo.%s"%(UID), env)
			s.erase()
			s.box()
			s.addstr(2, 2, "Modify user attributes", curses.color_pair(3))
			if error == "OK":
				s.addstr(4, 2, "User %s modified."%(UID), curses.color_pair(2))
			else:
				s.addstr(6, 2, "%s"%(error), curses.color_pair(2))
			s.getch()
	s.erase()
	return
def GUI_change_password(env,screen):
        s = curses.newwin(20, 78, 3, 1)
	s.erase()
	s.keypad(1)
	curses.start_color()
	curses.init_pair(1,curses.COLOR_RED, curses.COLOR_BLACK)
	curses.init_pair(2,curses.COLOR_WHITE, curses.COLOR_BLACK)
	curses.init_pair(3,curses.COLOR_BLACK, curses.COLOR_WHITE)
        s.box()
	s.addstr(2, 2, "Change password", curses.color_pair(3))
	s.addstr(19, 2, "[Use [ESC] to abort!]", curses.color_pair(1))
	s.addstr(4, 2, "Enter username: "******"":
		s.erase()
		return
	error,newpassword = helper_change_password(UID, env)
	if error != "OK":s.addstr(6, 2, error, curses.color_pair(2))
	else:
		s.addstr(6, 2, "Password reset: %s" % error, curses.color_pair(2))
		s.addstr(7, 2, "New Password: %s" % newpassword, curses.color_pair(2))
	s.addstr(19, 2, "[Press any key to continue]", curses.color_pair(1))
	s.getch()
	s.erase()
	return
Ejemplo n.º 31
0
def main():
    parser = argparse.ArgumentParser(
        description=
        "Hacker typer to impress your friends! Press ESC at any moment to "
        "exit the program.")
    parser.add_argument("-t",
                        "--test",
                        action="store_true",
                        help="Testing mode, uses a shorter file and a shorter"
                        "window.")
    parser.add_argument("-s",
                        "--speed",
                        help="Typing speed, i.e. number of characters per key"
                        "stroke.",
                        required=False,
                        default=4,
                        type=int)
    args = parser.parse_args()

    root = os.path.dirname(os.path.realpath(__file__))
    if args.test:
        input_file = root + "/test"
    else:
        input_file = root + "/in" + str(random.randint(1, 8))
    text_file = open(input_file)
    try:
        speed = args.speed
        default_screen = curses.initscr()
        curses.start_color()
        curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
        default_screen.clear()
        max_xy = default_screen.getmaxyx()
        y_dim = max_xy[0]
        if args.test and y_dim > 10:
            y_dim = 10
        x_dim = max_xy[1]
        pad = curses.newpad(y_dim, x_dim)
        pad.attrset(curses.color_pair(1))
        pad.refresh(0, 0, 0, 0, y_dim - 1, x_dim - 1)
        if not args.test:
            text_file.seek(random.randrange(30000))

        exit_program = False
        pos = 0
        while True:
            key = pad.getch()
            if key == 27:
                exit_program = True
                break

            out_of_chars = False

            for i in range(speed):
                char = text_file.read(1)
                if not char:
                    out_of_chars = True
                    break
                try:
                    pad.addstr(char)
                except curses.error:
                    pos += 1
                    pad.resize(y_dim + pos, x_dim)
                    pad.addstr(char)

            pad.refresh(pos, 0, 0, 0, y_dim - 1, x_dim - 1)
            if out_of_chars:
                break
        if not exit_program:
            pad.erase()
            default_screen.refresh()
            pad.resize(3, 8)
            pad.addstr(1, 0, " HACKED ")
            pad.border()
            pad.refresh(0, 0, 0, 0, 2, 7)
            while pad.getch() != 27:
                i = 0

    finally:
        text_file.close()
        curses.endwin()
Ejemplo n.º 32
0
    def __init__(self, gctx, ctx, analyzer):
        Window.__init__(self, ctx.output, has_statusbar=True)

        self.ctx = ctx
        self.gctx = gctx
        self.mode = MODE_DUMP
        self.dis = gctx.dis
        self.analyzer = analyzer
        self.queue_wait_analyzer = Queue()

        # Last/first address printed (only in MODE_DUMP)
        self.last_addr = max(self.output.addr_line)
        self.first_addr = min(self.output.addr_line)

        self.stack = []
        self.saved_stack = []  # when we enter, go back, then re-enter

        new_mapping = {
            b"z": self.main_cmd_line_middle,
            b"g": self.main_k_top,
            b"G": self.main_k_bottom,
            b";": self.view_inline_comment_editor,
            b"%": self.main_cmd_next_bracket,
            b"\n": self.main_cmd_enter,
            b"\x1b": self.main_cmd_escape,
            b"\t": self.main_cmd_switch_mode,
            b"c": self.main_cmd_code,
            b"p": self.main_cmd_set_function,
            b"{": self.main_k_prev_paragraph,
            b"}": self.main_k_next_paragraph,
            b"x": self.main_cmd_xrefs,
            b"r": self.main_cmd_rename,
            b"I": self.main_cmd_inst_output,

            # I wanted ctrl-enter but it cannot be mapped on my terminal
            b"u": self.main_cmd_reenter,  # u for undo
        }

        self.mapping.update(new_mapping)

        saved_quiet = self.gctx.quiet
        self.gctx.quiet = True

        self.screen = curses.initscr()

        (h, w) = self.screen.getmaxyx()
        h -= 1  # status bar
        self.goto_address(self.first_addr, h, w)

        curses.noecho()
        curses.cbreak()
        curses.mousemask(curses.ALL_MOUSE_EVENTS
                         | curses.REPORT_MOUSE_POSITION)

        curses.start_color()
        curses.use_default_colors()

        if self.gctx.color:
            for i in range(0, curses.COLORS):
                curses.init_pair(i, i, -1)
            curses.init_pair(1, 253, 66)  # for the highlight search
        else:
            for i in range(0, curses.COLORS):
                curses.init_pair(i, 7, -1)  # white

        try:
            curses.wrapper(self.start_view)
        except:
            curses.nocbreak()
            curses.echo()
            curses.endwin()
            traceback.print_exc()
            return

        curses.nocbreak()
        curses.echo()
        curses.endwin()

        self.gctx.quiet = saved_quiet

        if self.stack:
            print(hex(self.ctx.entry))
Ejemplo n.º 33
0
def cGame(stdscr=None, p1ai=None, p2ai=None):
    # Initialize Curses
    if stdscr is None:
        stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()
    stdscr.keypad(True)
    curses.curs_set(0)
    curses.start_color()

    # Setup the color pairs
    curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_RED)
    curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLUE)

    selectedpos = (0, 0)
    b = board()
    psturn = 1

    def drawface(stdscr, selectedpos, b, psturn):

        stdscr.erase()
        stdscr.border()
        stdscr.addstr(0, 10, "HEX ('q'=quit,Space=move)")
        stdscr.addstr(0, 40, "P" + str(psturn) + ' turn',
                      curses.color_pair(psturn))
        # Draw the winner
        stat = b.boardstate()
        stdscr.addstr(17, 10, "Status: " + stat)
        if not stat == 'No Win':
            with open('game.txt', 'w') as f:
                f.write(b.listmoves)

        # TEMPORARY: Add a debug message
        # from AI import hyperScoreAI
        # a = hyperScoreAI(player=1)
        # b.debug = str(a.lightDistance(b))

        # Draw the debug info
        # stdscr.addstr(18, 10, "Debug :" + b.debug)
        # stdscr.addstr(19, 10, "Pos :" + str(selectedpos))

        scrnpos = [4, 5]
        count = 0

        # Add the top row of -'s for 2
        stdscr.addstr(scrnpos[0] - 1, scrnpos[1] + 1,
                      '-' * (b.size[0] * 2 - 1), curses.color_pair(2))

        for y, row in enumerate(b.board):
            count += 1

            # Add the left row of \'s for 1
            stdscr.addstr(scrnpos[0], scrnpos[1] + count - 1, '\\',
                          curses.color_pair(1))

            for x, itm in enumerate(row):

                if itm in [1, 2]:
                    stdscr.addstr(scrnpos[0], scrnpos[1] + count, str(itm),
                                  curses.color_pair(itm))
                    if (x, y) == selectedpos:
                        stdscr.addstr(scrnpos[0], scrnpos[1] + count - 1, '>',
                                      curses.color_pair(itm))
                        stdscr.addstr(scrnpos[0], scrnpos[1] + count + 1, '<',
                                      curses.color_pair(itm))
                else:
                    stdscr.addstr(
                        scrnpos[0], scrnpos[1] + count,
                        str(itm) if itm is not 0 else '*', curses.A_REVERSE
                        if selectedpos == (x, y) else curses.A_NORMAL)

                scrnpos[1] += 2

            # Add the right row of \'s for 1
            stdscr.addstr(scrnpos[0], scrnpos[1] + count - 1, '\\',
                          curses.color_pair(1))

            scrnpos[1] = 5
            scrnpos[0] += 1
        # Add the bottom row of -'s for 2
        stdscr.addstr(scrnpos[0], scrnpos[1] + (b.size[0] * 2 - 11),
                      '-' * (b.size[0] * 2 - 1), curses.color_pair(2))

        stdscr.refresh()

    # Enter main loop
    drawface(stdscr, selectedpos, b, psturn)
    while True:
        # Let the AI move if it exists
        if psturn is 1 and p1ai is not None:
            b.move(p1ai(b), 1)
            psturn = 2
            drawface(stdscr, selectedpos, b, psturn)
            continue
        if psturn is 2 and p2ai is not None:
            b.move(p2ai(b), 2)
            psturn = 1
            drawface(stdscr, selectedpos, b, psturn)
            continue

        c = stdscr.getch()
        if c == ord('q'):
            break  # Quit from game
        elif c == ord('a'):
            selectedpos = ((selectedpos[0] - 1) % 11, (selectedpos[1]) % 11)
            drawface(stdscr, selectedpos, b, psturn)
        elif c == ord('d'):
            selectedpos = ((selectedpos[0] + 1) % 11, (selectedpos[1]) % 11)
            drawface(stdscr, selectedpos, b, psturn)
        elif c == ord('s'):
            selectedpos = ((selectedpos[0]) % 11, (selectedpos[1] + 1) % 11)
            drawface(stdscr, selectedpos, b, psturn)
        elif c == ord('w'):
            selectedpos = ((selectedpos[0]) % 11, (selectedpos[1] - 1) % 11)
            drawface(stdscr, selectedpos, b, psturn)
        elif c == ord(' '):
            if b.legal(selectedpos):
                b.move(selectedpos, psturn)
                psturn = 1 if psturn is 2 else 2
                drawface(stdscr, selectedpos, b, psturn)

    # Clean up the console
    curses.nocbreak()
    stdscr.keypad(False)
    curses.echo()
    curses.endwin()
Ejemplo n.º 34
0
import math, fractions
import pyautogui, sys, curses

# 1366 by 768
#
# math syntax: https://docs.python.org/2/library/math.html

screen = curses.initscr()
curses.noecho()
curses.halfdelay(1)
screen.keypad(True)
curses.start_color()
curses.use_default_colors()
curses.init_pair(1, curses.COLOR_RED, -1)
curses.init_pair(2, curses.COLOR_GREEN, -1)
curses.init_pair(3, curses.COLOR_BLUE, -1)

xmbase, ymbase = pyautogui.size()
xmbase = xmbase / 2
ymbase = ymbase / 2

d_one = 150  #distance from shoulder to elbow
d_two = 150  #distance from elbow to wrist

pyautogui.moveTo(xmbase, ymbase, duration=.1)

while True:  #to end loop if 'q' is hit
    key = screen.getch()
    screen.clear()
    xread, yread = pyautogui.position()
    x = xread - xmbase
Ejemplo n.º 35
0
    def __init__(self,
                 web_port=26000,
                 window_height=40,
                 window_width=130,
                 auto_scoll=True,
                 max_log_lines=500,
                 wait_on_quit=True,
                 min_refresh_rate=1000,
                 bytes_to_str=DEFAULT_HEX_TO_STR):
        """
        :type web_port: int
        :param web_port: Webinterface port. Default 26000

        :type window_height: int
        :param window_height: Default console heigth, set to on startup. Default 40

        :type window_width: int
        :param window_width: Default console width, set to on startup. Default 130

        :type auto_scoll: bool
        :param auto_scoll: Whether to auto-scoll the cases and crashed windows to allways display the last line if there
                           are too many lines to display all of them. Default True

        :type max_log_lines: int
        :param max_log_lines: Maximum log lines to keep in the internal storage. Additional lines exceeding this limit
                              will not be displayed. Default 500

        :type wait_on_quit: bool
        :param wait_on_quit: Whether to keep the GUI open and wait for user-input when the main thread is about to exit.
                             Default True

        :type min_refresh_rate: int
        :param min_refresh_rate: The delay between two checks for a resize of the terminal in milliseconds.
                                 Increment 100 ms. Default 1000 ms

        :type bytes_to_str: function
        :param bytes_to_str: Function that converts sent/received bytes data to string for logging.
        """

        self._title = "boofuzz"
        self._web_port = web_port
        self._max_log_lines = max_log_lines
        self._auto_scroll = auto_scoll
        self._current_data = None
        self._log_storage = []
        self._fail_storage = []
        self._wait_on_quit = wait_on_quit
        self._quit = False
        self._status = 0  # 0: Running 1: Paused 2: Done
        self._refresh_interval = min_refresh_rate
        self._event_resize = True
        self._event_log = False
        self._event_case_close = False
        self._event_crash = False

        self._total_index = 0
        self._total_num_mutations = 0
        self._current_name = ""
        self._current_index = 0
        self._current_num_mutations = 0

        self._format_raw_bytes = bytes_to_str
        self._version = helpers.get_boofuzz_version(helpers)

        # Resize console to minimum size
        self._width, self._height = get_terminal_size()
        if self._height < window_height or self._width < window_width:
            print("\x1b[8;{};{}t".format(window_height, window_width))
            self._height, self._width = window_height, window_width
        self._height_old = 0
        self._width_old = 0
        self._min_size_ok = True

        self._stdscr = curses.initscr()
        curses.start_color()
        curses.use_default_colors()
        curses.noecho()
        curses.curs_set(0)
        self._stdscr.nodelay(1)

        # Curses color pairs
        curses.init_pair(1, curses.COLOR_WHITE, -1)
        curses.init_pair(2, curses.COLOR_CYAN, -1)
        curses.init_pair(3, curses.COLOR_RED, -1)
        curses.init_pair(4, curses.COLOR_YELLOW, -1)
        curses.init_pair(5, curses.COLOR_GREEN, -1)
        curses.init_pair(6, curses.COLOR_MAGENTA, -1)
        curses.init_pair(7, curses.COLOR_BLACK, curses.COLOR_WHITE)

        # Start thread and restore the original SIGWINCH handler
        self._draw_thread = threading.Thread(name="curses_logger",
                                             target=self._draw_screen)
        current_signal_handler = signal.getsignal(signal.SIGWINCH)
        self._draw_thread.start()
        signal.signal(signal.SIGWINCH, current_signal_handler)
Ejemplo n.º 36
0
 def _enable_color(self):
     if curses.has_colors():
         curses.start_color()
Ejemplo n.º 37
0
    def up(self):
        if not self.enabled:
            logger.info("display not enabled")
            return

        logger.info("up")
        self.screen = curses.initscr()
        self.running = True

        # if anything manages to get printed it messes with curses
        self.prev_stdout = sys.stdout
        sys.stdout = open(os.devnull, "w")

        # no cursor
        curses.curs_set(0)

        # turn off echoing of keys, and enter cbreak mode,
        # where no buffering is performed on keyboard input
        curses.noecho()

        # in keypad mode, escape sequences for special keys
        # (like the cursor keys) will be interpreted and
        # a special value like curses.KEY_LEFT will be returned
        self.screen.keypad(1)
        self.screen.nodelay(1)

        # harmless if the terminal doesn't have color;
        # user can test with has_color() later on. the try/catch
        # works around a minor bit of over-conscientiousness in the curses
        # module -- the error return from C start_color() is ignorable.
        try:
            curses.start_color()
        except:
            pass

        curses.use_default_colors()
        curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK)
        curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK)
        curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK)

        # fmt: off

        self.engineCluster = Cluster(0,
                                     0, ("time: {time:.2f}\n"
                                         "frame number: {frame}\n"
                                         "fps: {fps:.2f}/{cap:.0f}\n"
                                         "highest d: {highest_delta:.2f}\n"
                                         "memory used: {mem} MiB\n"),
                                     name="engine")

        self.controllerCluster = Cluster(0,
                                         30, ("throttle: {throttle}\n"
                                              "strafe: {strafe}\n"
                                              "forward: {forward}\n"
                                              "spin: {spin}\n"),
                                         name="controller")

        row_2 = 7
        self.vehicleCluster = Cluster(row_2,
                                      0,
                                      ("altitude: {altitude:>6.2f}cm\n"
                                       "throttle: {throttle:>6.2f}\n"
                                       "temperature: {temperature:>6.2f}\n"),
                                      name="vehicle")

        self.motorCluster = Cluster(row_2,
                                    22, ("{0:>3.3f}  {1:>3.3f}\n"
                                         "{2:>3.3f}  {3:>3.3f}\n"),
                                    name="motors")

        row_3 = 12
        self.accelerometer = Cluster(row_3,
                                     0, ("x: {x:>7.3f}\n"
                                         "y: {y:>7.3f}\n"
                                         "z: {z:>7.3f}\n"),
                                     name="accel")

        self.gyro = Cluster(row_3,
                            15, ("x: {x:>7.3f}\n"
                                 "y: {y:>7.3f}\n"
                                 "z: {z:>7.3f}\n"),
                            name="gyro")

        self.magnet = Cluster(row_3,
                              30, ("x: {x:>7.3f}\n"
                                   "y: {y:>7.3f}\n"
                                   "z: {z:>7.3f}\n"),
                              name="magnet")

        self.deviation = Cluster(row_3,
                                 45, ("x: {x:>7.3f}\n"
                                      "y: {y:>7.3f}\n"
                                      "z: {z:>7.3f}\n"),
                                 name="deviation")

        row_4 = 17
        self.log = Cluster(row_4, 0, "{0}", name="log")
Ejemplo n.º 38
0
def main(screen):
    """
    Snake

    Press 'q' to quit the game.
    """
    screen.clear()

    curses.curs_set(0)

    screen.nodelay(1)

    curses.start_color()
    curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)

    # Get the y,x of the window
    dims = screen.getmaxyx()

    # Get the center of the window
    center = (dims[0]//2), (dims[1]//2)

    screen.border()

    # Main loop
    x = center[1]
    y = center[0]

    dirs = {"x": 1, "y": 0}

    #screen.move(0, 0);
    screen.refresh()

    snake = [[y, x], [y, x-1], [y, x-2]]

    apple = [random.randint(1, dims[0]-2), random.randint(1, dims[1]-2)]
    appleCh = "ö"

    screen.addstr(apple[0], apple[1], appleCh, curses.color_pair(1))

    ch = "O"

    screen.addstr(snake[0][0], snake[0][1], ch, curses.color_pair(2))

    score = 0

    while True:
        screen.border()
        screen.addstr(0, 2, "Score : " + str(score) + " ")
        key = screen.getch()
        if key == ord("q"):
            #screen.clear()
            text = "GAME OVER!"
            screen.addstr(dims[0]//2, dims[1]//2-len(text)//2, text)
            screen.refresh()
            curses.napms(2500)
            break
        elif key == KEY_UP:
            dirs["y"] = -1
            dirs["x"] = 0
        elif key == KEY_DOWN:
            dirs["y"] = 1
            dirs["x"] = 0
        elif key == KEY_LEFT:
            dirs["x"] = -1
            dirs["y"] = 0
        elif key == KEY_RIGHT:
            dirs["x"] = 1
            dirs["y"] = 0

        x += dirs["x"]
        y += dirs["y"]

        # head of snake
        if y <= 0:
            y = 1
        elif y >= dims[0]-1:
            y = dims[0] - 2
        if x <= 0:
            x = 1
        elif x >= dims[1]-1:
            x = dims[1] - 2

        snake.insert(0, [y, x])

        if snake[0] in snake[1:]:
            #screen.clear()
            text = "GAME OVER!"
            screen.addstr(dims[0]//2, dims[1]//2-len(text)//2, text)
            screen.refresh()
            curses.napms(2500)
            break

        if snake[0] == apple:
            score += 1
            while apple in snake:
                apple = [random.randint(2, dims[0]-3), random.randint(2, dims[1]-3)]
            screen.addstr(apple[0], apple[1], appleCh, curses.color_pair(1))
        else:
            last = snake.pop()
            screen.addch(last[0], last[1], " ", curses.color_pair(2))

        screen.addch(snake[0][0], snake[0][1], ch, curses.color_pair(2))

        #time.sleep(0.1)
        nap_time = 100 - len(snake)//2
        curses.napms(nap_time)

    curses.endwin()
    print("Final score:", score)
Ejemplo n.º 39
0
def scanner(scanner_args):
    '''
    Execute exploit against given ip list
    '''

    # looks ugly, but since it works well, im not planning a rewrite
    work_path, exec_path = scanner_args.work_path, scanner_args.exec_path
    custom_args, jobs = scanner_args.custom_args, scanner_args.jobs

    if SESSION.use_proxy:
        e_args = [
            'proxychains4', '-q', '-f', SESSION.proxy_conf, './' + exec_path
        ]
    else:
        e_args = ['./' + exec_path]

    # add custom arguments for different exploits
    e_args += custom_args
    # the last argument is target host
    e_args += ['-t']

    try:
        target_list = open(SESSION.ip_list)
    except BaseException as exc:
        console.print_error('[-] Error occured: {}\n'.format(exc))
        debug_except()
        return

    try:
        os.chdir('./exploits/' + work_path)
    except FileNotFoundError:
        console.print_error("[-] Can't chdir to " + work_path)
        debug_except()
    console.print_warning('\n[!] DEBUG: ' + str(e_args) + '\nWorking in ' +
                          os.getcwd())

    # you might want to cancel the scan to correct some errors
    if input_check('[?] Proceed? [y/n] ', choices=['y', 'n']) == 'n':
        return

    console.print_warning('\n[!] It might be messy, get ready!' + '\n')
    time.sleep(2)

    # save stdout to logfile
    try:
        logfile = open(SESSION.logfile, "a+")
    except FileNotFoundError:
        console.print_error("[-] Log file not found")

    # needed for the loop
    procs = []
    count = len(procs)
    tested = count

    # use curses to display output
    import curses
    stdscr = curses.initscr()
    curses.start_color()
    curses.use_default_colors()
    curses.init_pair(1, curses.COLOR_CYAN, -1)
    curses.init_pair(2, curses.COLOR_WHITE, -1)
    curses.init_pair(3, curses.COLOR_GREEN, -1)

    for line in target_list:
        target_ip = line.strip()

        # clear screen for each output
        stdscr.refresh()

        # display progress info on top
        progress = str(tested) + ' targets found'

        # tail to get the last line of log file
        status = tail(SESSION.logfile)

        # mark this loop as done
        count = len(procs)
        tested += 1

        try:
            # start and display current process
            e_args += [target_ip]

            stdscr.addstr(0, 0, progress + '\n',
                          curses.A_BOLD | curses.color_pair(1))
            stdscr.addstr(2, 0, ' '.join(e_args) + '\n', curses.color_pair(3))
            stdscr.addstr(4, 0, status, curses.color_pair(2))

            proc = subprocess.Popen(e_args, stdout=logfile, stderr=logfile)
            procs.append(proc)

            # continue to next target
            e_args.remove(target_ip)
            time.sleep(.11)

            # process pool
            if count == jobs:
                # if returned any exit code, consider the process as done
                for item in procs:
                    item.communicate()
                    if item.returncode is not None:
                        item.kill()
                procs = []

        except (EOFError, KeyboardInterrupt, SystemExit):
            curses.endwin()
            for item in procs:
                if item.pid is not None:
                    item.kill()
            logfile.close()
            console.print_error("[-] Task aborted")

            # killall running processes
            check_kill_process(exec_path)
            return

    # close logfile, exit curses window, and print done flag
    curses.endwin()
    logfile.close()
    os.chdir(SESSION.init_dir)
    console.print_success('\n[+] All done!\n')
Ejemplo n.º 40
0
 def main(screen):
     curses.start_color()
     curses.use_default_colors()
     pride = Pride(screen)
     pride.run()
Ejemplo n.º 41
0
 def __init__(self):
     self.__scrn = curses.initscr()
     curses.start_color()
     curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)
     curses.use_default_colors()
Ejemplo n.º 42
0
def run_curses(testers):
    rr = RoundRobinSched(0.5, testers)

    rospy.init_node('CentralizedTester', anonymous=True)

    burst_size = 1024 * 1024

    col1 = 0  # Source
    col2 = 4  # Dest
    col3 = 10  # Percentage
    col4 = 31  # Sending
    col5 = 35  # Send rate
    col6 = 46  # Payload size
    col7 = 53  # tx bitrate
    col8 = 64  # rx bitrate
    col9 = 75  # Latency
    col10 = 88  # RSSI

    help_row = 2 + len(testers) + 3

    help_string = """
    Help:
      q              quit
      up/down (j/k)  change selection
      s              start sending selected data
      S              start sending all data
      g              Run round-robin sending
      r (R)          Reset statistics (for all)
      +/-            Increase/decrease transmit rate
      ]/[            Increase/decrease payload size
      B              Send burst of data
      }/{            Increase/decrease burst size
    """

    stdscr_orig = curses.initscr()
    stdscr = curses.newpad(help_row + 15, col10 + 15)
    curses.noecho()
    curses.cbreak()
    curses.start_color()
    curses.curs_set(0)
    stdscr.keypad(1)
    stdscr.nodelay(1)
    #curses.halfdelay(3)

    curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_RED)
    curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_CYAN)

    for x in testers:
        x.start()

    done = False

    stdscr.addstr(0, 0, 'Comms Test Client')
    stdscr.addstr(1, 0, '-' * (col8 + 11))
    stdscr.addstr(2, col1, 'Src')
    stdscr.addstr(2, col2, 'Dest')
    stdscr.addstr(2, col3, '% Recv')
    stdscr.addstr(2, col4, 'Enb')
    stdscr.addstr(2, col5, 'Rate (Hz)')
    stdscr.addstr(2, col6, 'Bytes')
    stdscr.addstr(2, col7, 'Tx (kbps)')
    stdscr.addstr(2, col8, 'Rx (kbps)')
    stdscr.addstr(2, col9, 'Latency (ms)')
    stdscr.addstr(2, col10, 'RSSI (dBm)')

    stdscr.addstr(help_row - 2, 0, '-' * (col8 + 11))
    stdscr.addstr(help_row - 1, 0, 'Burst size (bytes): {}'.format(burst_size))
    stdscr.addstr(help_row, 8, help_string)

    selected_row_idx = 3
    selected_tester = None
    round_robin_run = False
    while not done:

        idx = 3
        for x in testers:

            if idx == selected_row_idx:
                color_selection = curses.color_pair(1)
                selected_tester = x
            else:
                color_selection = curses.color_pair(0)

            stdscr.addstr(idx, 0, ' ' * (col10 + 11), color_selection)

            stats = x.test.GetStatistics()
            stdscr.addstr(idx, col1, '{}'.format(x.test.name1),
                          color_selection)
            stdscr.addstr(idx, col2, '{}'.format(x.test.name2),
                          color_selection)
            stdscr.addstr(
                idx, col3, '{:2.2f} ({}/{})'.format(stats[0] * 100, stats[1],
                                                    len(x.test.outgoing_data)),
                color_selection)
            # stdscr.addstr(idx,col4,'%d' % x.test.GetAverageRSSI(), color_selection)
            if x.test.send:
                stdscr.addstr(idx, col4, 'On', color_selection)
            else:
                stdscr.addstr(idx, col4, 'Off', color_selection)
            stdscr.addstr(idx, col5, '{:2.2f}'.format(x.test.send_rate),
                          color_selection)
            stdscr.addstr(idx, col6, '{}'.format(x.test.payload_size),
                          color_selection)
            # stdscr.addstr(idx, col7, '{:2.2f}'.format(x.test.send_rate * float(x.test.payload_size) / 1024.0), color_selection)
            stdscr.addstr(idx, col7,
                          '{:2.2f}'.format(x.test.GetTXRate() / 1000.0),
                          color_selection)
            stdscr.addstr(idx, col8,
                          '{:2.2f}'.format(x.test.GetRXRate() / 1000.0),
                          color_selection)
            stdscr.addstr(idx, col9,
                          '{:2.2f}'.format(x.test.GetLatency() * 1000.0),
                          color_selection)
            stdscr.addstr(idx, col10, '{:2.2f}'.format(x.test.GetRssi()),
                          color_selection)
            idx = idx + 1

        # stdscr.refresh()

        height, width = stdscr_orig.getmaxyx()
        stdscr.refresh(0, 0, 0, 0, height - 1, width - 1)

        # Key-event handling
        c = stdscr.getch()
        if c == ord('q'):
            done = True
            if round_robin_run:
                rr.stop = True
                rr.join()
            for x in testers:
                x.test.done = True
                x.join()
        if c == ord('s'):
            if selected_tester != None:
                if selected_tester.test.send:
                    selected_tester.test.send = False
                else:
                    selected_tester.test.send = True
        if c == ord('S'):
            for x in testers:
                if x.test.send:
                    x.test.send = False
                else:
                    x.test.send = True
        if c == ord('g'):
            if round_robin_run:
                round_robin_run = False
                rr.stop = True
                rr.join()
            else:
                round_robin_run = True
                rr.start()
        if c == ord('r'):
            if selected_tester != None:
                selected_tester.test.ResetStatistics()
        if c == ord('R'):
            for x in testers:
                x.test.ResetStatistics()
        elif c == curses.KEY_UP or c == ord('k'):
            selected_row_idx = selected_row_idx - 1
            if selected_row_idx < 3:
                selected_row_idx = 3
        elif c == curses.KEY_DOWN or c == ord('j'):
            selected_row_idx = selected_row_idx + 1
            if selected_row_idx >= 3 + len(testers):
                selected_row_idx = 3 + len(testers) - 1

        if c == ord('+'):
            if selected_tester != None:
                selected_tester.test.UpdateRate(
                    selected_tester.test.send_rate + 1)
        if c == ord('-'):
            if selected_tester != None:
                selected_tester.test.UpdateRate(
                    max(selected_tester.test.send_rate - 1, 1.0))

        if c == ord(']'):
            if selected_tester != None:
                selected_tester.test.payload_size = min(
                    selected_tester.test.payload_size + 1, 1000000)

        if c == ord('['):
            if selected_tester != None:
                selected_tester.test.payload_size = max(
                    selected_tester.test.payload_size - 1, 0)

        if c == ord('}'):
            burst_size = burst_size + 10
            stdscr.addstr(help_row - 1, 0,
                          'Burst size (bytes): {}'.format(burst_size))

        if c == ord('{'):
            burst_size = max(burst_size - 10, 1)
            stdscr.addstr(help_row - 1, 0,
                          'Burst size (bytes): {}'.format(burst_size))

        if c == ord('B'):
            if selected_tester != None:
                selected_tester.test.SendBurst(burst_size)

    curses.nocbreak()
    stdscr.keypad(0)
    curses.echo()
    curses.endwin()
Ejemplo n.º 43
0
def main(argv):
    """If this file is the main, create an instance of EstopNoGui and wait for user to terminate.

    This has little practical use, because calling the function this way does not give the user
    any way to trigger an estop from the terminal.
    """
    parser = argparse.ArgumentParser()
    bosdyn.client.util.add_common_arguments(parser)
    parser.add_argument('-t', '--timeout', type=float, default=5, help='Timeout in seconds')
    options = parser.parse_args(argv)

    # Set up curses screen display to monitor for stop request
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()
    stdscr.keypad(True)
    stdscr.nodelay(True)
    curses.start_color()
    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK)
    curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK)
    # If terminal cannot handle colors, do not proceed
    if not curses.has_colors():
        return

    # Create robot object
    sdk = bosdyn.client.create_standard_sdk('estop_nogui')
    robot = sdk.create_robot(options.hostname)
    robot.authenticate(options.username, options.password)

    # Create estop client for the robot
    estop_client = robot.ensure_client(EstopClient.default_service_name)

    # Create nogui estop
    estop_nogui = EstopNoGui(estop_client, options.timeout, "Estop NoGUI")

    # Create robot state client for the robot
    state_client = robot.ensure_client(RobotStateClient.default_service_name)

    def clean_exit(msg=''):
        """Shut down curses and exit the program."""
        print('Exiting')
        #pylint: disable=unused-argument
        estop_nogui.estop_keep_alive.shutdown()

        # Clean up and close curses
        curses.nocbreak()
        stdscr.keypad(False)
        curses.echo()
        stdscr.nodelay(False)
        curses.endwin()
        print(msg)
        exit(0)

    def sigint_handler(sig, frame):
        """Exit the application on interrupt."""
        clean_exit()

    # Curses eats Ctrl-C keyboard input, but keep a SIGINT handler around for
    # explicit kill signals outside of the program.
    signal.signal(signal.SIGINT, sigint_handler)
    
    # Clear screen
    stdscr.clear()

    # Display usage instructions in terminal
    stdscr.addstr('Estop w/o GUI running.\n')
    stdscr.addstr('\n')
    stdscr.addstr('[q] or [Ctrl-C]: Quit\n', curses.color_pair(2))
    stdscr.addstr('[SPACE]: Trigger estop\n', curses.color_pair(2))
    stdscr.addstr('[r]: Release estop\n', curses.color_pair(2))
    stdscr.addstr('[s]: Settle then cut estop\n', curses.color_pair(2))

    # Monitor estop until user exits
    while True:
        # Retrieve user input (non-blocking)
        c = stdscr.getch()

        try:
            if c == ord(' '):
                estop_nogui.stop()
            if c == ord('r'):
                estop_nogui.allow()
            if c == ord('q') or c == 3:
                clean_exit('Exit on user input')
            if c == ord('s'):
                estop_nogui.settle_then_cut()
        # If the user attempts to toggle estop without valid endpoint
        except bosdyn.client.estop.EndpointUnknownError:
            clean_exit("This estop endpoint no longer valid. Exiting...")

        # Check if robot is estopped by any estops
        estop_status = 'NOT_STOPPED\n'
        estop_status_color = curses.color_pair(1)
        state = state_client.get_robot_state()
        estop_states = state.estop_states
        for estop_state in estop_states:
            state_str = estop_state.State.Name(estop_state.state)
            if state_str == 'STATE_ESTOPPED':
                estop_status = 'STOPPED\n'
                estop_status_color = curses.color_pair(3)
                break
            elif state_str == 'STATE_UNKNOWN':
                estop_status = 'ERROR\n'
                estop_status_color = curses.color_pair(3)
            elif state_str == 'STATE_NOT_ESTOPPED':
                pass
            else:
                # Unknown estop status
                clean_exit()

        # Display current estop status
        if not estop_nogui.estop_keep_alive.status_queue.empty():
            latest_status = estop_nogui.estop_keep_alive.status_queue.get()[1].strip()
            if latest_status != '':
                # If you lose this estop endpoint, report it to user
                stdscr.addstr(7, 0, latest_status, curses.color_pair(3))
        stdscr.addstr(6, 0, estop_status, estop_status_color)

        # Slow down loop
        time.sleep(0.5)
Ejemplo n.º 44
0
def game(stdscr):
    # init colors
    curses.start_color()
    curses.use_default_colors()
    for i in range(curses.COLORS):
        curses.init_pair(i + 1, i, -1)

    # init vars
    running = True
    launched = False
    paddle_x = 27
    ball_x, ball_y, ball_v = 32, 18, 0
    spin = None
    block_spin = None

    # init board
    blocks = board.checker("yellow", "blue")

    # gameplay loop
    while running:
        ##############
        # draw scene #
        ##############
        # draw board
        for i in range(len(blocks)):
            color = blocks[i]
            stdscr.addstr(i // B_COLS, i % B_COLS * BLOCK_SIZE,
                          ' ' * BLOCK_SIZE,
                          curses.color_pair(color) | curses.A_REVERSE)

        # draw paddle
        for i in range(PADDLE_SIZE):
            stdscr.addstr(HEIGHT, i + paddle_x, ' ',
                          curses.color_pair(0) | curses.A_REVERSE)

        # draw ball
        stdscr.addstr(ball_y, ball_x, '*',
                      curses.color_pair(4) | curses.A_BOLD)

        ################
        # handle input #
        ################
        # get key
        key = stdscr.getch()

        # move paddle right
        if key == curses.KEY_RIGHT:
            if paddle_x < 49:
                paddle_x += 1
                # ball not yet launched
                if not ball_v:
                    ball_x += 1
            # ball spin
            if ball_y == 18 and ball_v:
                spin = "left"

        # move paddle left
        elif key == curses.KEY_LEFT:
            if paddle_x > 0:
                paddle_x -= 1
                # ball not yet launched
                if not ball_v:
                    ball_x -= 1
            # ball spin
            if ball_y == 18 and ball_v:
                spin = "right"

        # move up (launch ball)
        elif key == curses.KEY_UP:
            if not launched:
                ball_v = -1
                launched = True

        # quit game
        elif key == ord('q'):
            running = False

        ##############
        # game logic #
        ##############
        # ball top collision
        if ball_y == 0:
            ball_v = 1

        # ball/paddle collision
        if launched and ball_y == 18 and \
        (paddle_x <= ball_x < paddle_x+PADDLE_SIZE):
            ball_v = -1

        # ball brick collision
        if ball_y - 1 < B_ROWS:
            # this is hacky (collision should have its own funcs)
            for i in range(1):
                # break block above
                if (blocks[B_COLS *
                           (ball_y - 1) + ball_x // BLOCK_SIZE] != BLK):
                    ball_v = 1
                    blocks[B_COLS * (ball_y - 1) + ball_x // BLOCK_SIZE] = BLK
                    break
                # break block to side and get new spin
                try:
                    if spin == "right":
                        if (blocks[B_COLS * (ball_y) +
                                   (ball_x + 1) // BLOCK_SIZE] != BLK):
                            blocks[B_COLS * (ball_y) +
                                   (ball_x + 1) // BLOCK_SIZE] = BLK
                            spin = "left"
                    elif spin == "left":
                        if (blocks[B_COLS * (ball_y) +
                                   (ball_x - 1) // BLOCK_SIZE] != BLK):
                            blocks[B_COLS * (ball_y) +
                                   (ball_x - 1) // BLOCK_SIZE] = BLK
                            spin = "right"
                except:
                    pass

        # ball misses paddle and passes outside of map
        if ball_y == 20:
            if DEBUG:
                # reset ball
                ball_x, ball_y, ball_v = paddle_x + 5, 18, 0
                spin = None
                launched = False
            else:
                running = False

        # ball spin from paddle
        if spin == "left":
            ball_x -= 1
        elif spin == "right":
            ball_x += 1

        # ball spin wall collision
        if ball_x == 0:
            spin = "right"
        if ball_x == 59:
            spin = "left"

        # ball moving up and down
        if ball_v:
            ball_y += ball_v

        ###########
        # display #
        ###########
        # refresh, delay (24FPS), clear screen
        stdscr.refresh()
        time.sleep(1 / 24.0)
        stdscr.clear()
def main(screen):
    global msgtrade1time, msgtrade1side, msgtrade1size, msgtrade1price
    global msgtrade2time, msgtrade2side, msgtrade2size, msgtrade2price
    global msgtrade3time, msgtrade3side, msgtrade3size, msgtrade3price
    global msgtrade4time, msgtrade4side, msgtrade4size, msgtrade4price
    global msgtrade5time, msgtrade5side, msgtrade5size, msgtrade5price
    global msgtrade6time, msgtrade6side, msgtrade6size, msgtrade6price
    global msgtrade7time, msgtrade7side, msgtrade7size, msgtrade7price
    global msgtrade8time, msgtrade8side, msgtrade8size, msgtrade8price
    global msgtrade9time, msgtrade9side, msgtrade9size, msgtrade9price
    global msgtrade10time, msgtrade10side, msgtrade10size, msgtrade10price

    global msgbookbid1size, msgbookbid1price, msgbookask1size, msgbookask1price
    global msgbookbid2size, msgbookbid2price, msgbookask2size, msgbookask2price
    global msgbookbid3size, msgbookbid3price, msgbookask3size, msgbookask3price
    global msgbookbid4size, msgbookbid4price, msgbookask4size, msgbookask4price
    global msgbookbid5size, msgbookbid5price, msgbookask5size, msgbookask5price
    global msgbookbid6size, msgbookbid6price, msgbookask6size, msgbookask6price
    global msgbookbid7size, msgbookbid7price, msgbookask7size, msgbookask7price
    global msgbookbid8size, msgbookbid8price, msgbookask8size, msgbookask8price
    global msgbookbid9size, msgbookbid9price, msgbookask9size, msgbookask9price
    global msgbookbid10size, msgbookbid10price, msgbookask10size, msgbookask10price

    global mvalor2, mbitmex, symbol, timeframe, limit, params
    mwin3count = 0

    curses.start_color()  # activate color usage
    curses.init_pair(1, curses.COLOR_WHITE,
                     curses.COLOR_RED)  # Sell color on Times & Trades
    curses.init_pair(2, curses.COLOR_WHITE,
                     curses.COLOR_GREEN)  # Buy color on Times&Trades

    # Screen definitions
    height, width = screen.getmaxyx()
    #previous value screen.addstr(0, int(width/2.7),"xxx......
    if mvalor2 == "(1)":
        screen.addstr(
            0, 0,
            "              --- BITMEX PROD DATA Developed by Luciano Lima ---                "
        )
    elif mvalor2 == "(2)":
        screen.addstr(
            0, 0,
            "              --- BITMEX TEST DATA Developed by Luciano Lima ---                "
        )

    win1 = curses.newwin(18, 39, 2, 0)
    win2 = curses.newwin(18, 39, 2, 41)
    win3 = curses.newwin(5, 80, 20, 0)
    win1.box()
    win2.box()
    win3.box()
    height1, width1 = win1.getmaxyx()
    height2, width2 = win2.getmaxyx()
    win1.addstr(1, int(width1 / 3.2), "Book LII " + "%s" % mvalor1)
    win1.addstr(2, 1, "SIZE     BID ")
    win1.addstr(2, 20, "ASK       SIZE")
    win2.addstr(1, int(width2 / 3.3), "Times & Trades " + "%s" % mvalor1)
    win2.addstr(2, 1, "Timestamp")
    win2.addstr(2, 14, "Side")
    win2.addstr(2, 20, "Size")
    win2.addstr(2, 28, "Price")
    win3.addstr(
        1, 1,
        "Chart Data                                            |Amp|Frequency")

    #call_websocket()
    t = Thread(target=call_websocket)
    t.start()

    try:
        while True:
            # book
            win1.addstr(3, 1, msgbookbid1size + "   ")
            win1.addstr(3, 10, msgbookbid1price + "   ")
            win1.addstr(4, 1, msgbookbid2size + "   ")
            win1.addstr(4, 10, msgbookbid2price + "   ")
            win1.addstr(5, 1, msgbookbid3size + "   ")
            win1.addstr(5, 10, msgbookbid3price + "   ")
            win1.addstr(6, 1, msgbookbid4size + "   ")
            win1.addstr(6, 10, msgbookbid4price + "   ")
            win1.addstr(7, 1, msgbookbid5size + "   ")
            win1.addstr(7, 10, msgbookbid5price + "   ")
            win1.addstr(8, 1, msgbookbid6size + "   ")
            win1.addstr(8, 10, msgbookbid6price + "   ")
            win1.addstr(9, 1, msgbookbid7size + "   ")
            win1.addstr(9, 10, msgbookbid7price + "   ")
            win1.addstr(10, 1, msgbookbid8size + "   ")
            win1.addstr(10, 10, msgbookbid8price + "   ")
            win1.addstr(11, 1, msgbookbid9size + "   ")
            win1.addstr(11, 10, msgbookbid9price + "   ")
            win1.addstr(12, 1, msgbookbid10size + "   ")
            win1.addstr(12, 10, msgbookbid10price + "   ")

            win1.addstr(3, 30, msgbookask1size + " ")
            win1.addstr(3, 20, msgbookask1price + "   ")
            win1.addstr(4, 30, msgbookask2size + " ")
            win1.addstr(4, 20, msgbookask2price + "   ")
            win1.addstr(5, 30, msgbookask3size + " ")
            win1.addstr(5, 20, msgbookask3price + "   ")
            win1.addstr(6, 30, msgbookask4size + " ")
            win1.addstr(6, 20, msgbookask4price + "   ")
            win1.addstr(7, 30, msgbookask5size + " ")
            win1.addstr(7, 20, msgbookask5price + "   ")
            win1.addstr(8, 30, msgbookask6size + " ")
            win1.addstr(8, 20, msgbookask6price + "   ")
            win1.addstr(9, 30, msgbookask7size + " ")
            win1.addstr(9, 20, msgbookask7price + "   ")
            win1.addstr(10, 30, msgbookask8size + " ")
            win1.addstr(10, 20, msgbookask8price + "   ")
            win1.addstr(11, 30, msgbookask9size + " ")
            win1.addstr(11, 20, msgbookask9price + "   ")
            win1.addstr(12, 30, msgbookask10size + " ")
            win1.addstr(12, 20, msgbookask10price + "   ")

            # times and trades

            # 1st trade
            win2.addstr(3, 1, msgtrade1time)  # timestamp
            if "Sell" in msgtrade1side:
                win2.addstr(3, 14, msgtrade1side,
                            curses.color_pair(1))  # Sell side
            else:
                win2.addstr(3, 14, msgtrade1side,
                            curses.color_pair(2))  # Buy side
            win2.addstr(3, 20, msgtrade1size + "    ")  # size
            win2.addstr(3, 28, msgtrade1price + "   ")  # price
            #2nd trade
            win2.addstr(4, 1, msgtrade2time)  # timestamp
            if "Sell" in msgtrade2side:
                win2.addstr(4, 14, msgtrade2side,
                            curses.color_pair(1))  # Sell side
            else:
                win2.addstr(4, 14, msgtrade2side,
                            curses.color_pair(2))  # Buy side
                win2.addstr(4, 20, msgtrade2size + "    ")  # size
                win2.addstr(4, 28, msgtrade2price + "   ")  # price
            #3rd trade
            win2.addstr(5, 1, msgtrade3time)  # timestamp
            if "Sell" in msgtrade3side:
                win2.addstr(5, 14, msgtrade3side,
                            curses.color_pair(1))  # Sell side
            else:
                win2.addstr(5, 14, msgtrade3side,
                            curses.color_pair(2))  # Buy side
                win2.addstr(5, 20, msgtrade3size + "    ")  # size
                win2.addstr(5, 28, msgtrade3price + "   ")  # price
            #4th trade
            win2.addstr(6, 1, msgtrade4time)  # timestamp
            if "Sell" in msgtrade4side:
                win2.addstr(6, 14, msgtrade4side,
                            curses.color_pair(1))  # Sell side
            else:
                win2.addstr(6, 14, msgtrade4side,
                            curses.color_pair(2))  # Buy side
                win2.addstr(6, 20, msgtrade4size + "    ")  # size
                win2.addstr(6, 28, msgtrade4price + "   ")  # price
            #5th trade
            win2.addstr(7, 1, msgtrade5time)  # timestamp
            if "Sell" in msgtrade5side:
                win2.addstr(7, 14, msgtrade5side,
                            curses.color_pair(1))  # Sell side
            else:
                win2.addstr(7, 14, msgtrade5side,
                            curses.color_pair(2))  # Buy side
                win2.addstr(7, 20, msgtrade5size + "    ")  # size
                win2.addstr(7, 28, msgtrade4price + "   ")  # price
            #6th trade
            win2.addstr(8, 1, msgtrade6time)  # timestamp
            if "Sell" in msgtrade6side:
                win2.addstr(8, 14, msgtrade6side,
                            curses.color_pair(1))  # Sell side
            else:
                win2.addstr(8, 14, msgtrade6side,
                            curses.color_pair(2))  # Buy side
                win2.addstr(8, 20, msgtrade6size + "    ")  # size
                win2.addstr(8, 28, msgtrade6price + "   ")  # price
            #7th trade
            win2.addstr(9, 1, msgtrade7time)  # timestamp
            if "Sell" in msgtrade7side:
                win2.addstr(8, 14, msgtrade7side,
                            curses.color_pair(1))  # Sell side
            else:
                win2.addstr(9, 14, msgtrade7side,
                            curses.color_pair(2))  # Buy side
                win2.addstr(9, 20, msgtrade7size + "    ")  # size
                win2.addstr(9, 28, msgtrade7price + "   ")  # price
            #8th trade
            win2.addstr(10, 1, msgtrade8time)  # timestamp
            if "Sell" in msgtrade8side:
                win2.addstr(10, 14, msgtrade8side,
                            curses.color_pair(1))  # Sell side
            else:
                win2.addstr(10, 14, msgtrade8side,
                            curses.color_pair(2))  # Buy side
                win2.addstr(10, 20, msgtrade8size + "    ")  # size
                win2.addstr(10, 28, msgtrade8price + "   ")  # price
            #9th trade
            win2.addstr(11, 1, msgtrade9time)  # timestamp
            if "Sell" in msgtrade9side:
                win2.addstr(11, 14, msgtrade9side,
                            curses.color_pair(1))  # Sell side
            else:
                win2.addstr(11, 14, msgtrade9side,
                            curses.color_pair(2))  # Buy side
                win2.addstr(11, 20, msgtrade9size + "    ")  # size
                win2.addstr(11, 28, msgtrade9price + "   ")  # price
            #10th trade
            win2.addstr(12, 1, msgtrade10time)  # timestamp
            if "Sell" in msgtrade10side:
                win2.addstr(12, 14, msgtrade10side,
                            curses.color_pair(1))  # Sell side
            else:
                win2.addstr(12, 14, msgtrade10side,
                            curses.color_pair(2))  # Buy side
                win2.addstr(12, 20, msgtrade10size + "    ")  # size
                win2.addstr(12, 28, msgtrade10price + "   ")  # price

            if mwin3count == 360:
                # Isolating Win3 to avoid braking rate limit
                # Win3 Data	 --> Candle 3min/Chart Data
                # 3 min chart data
                since3min = mbitmex.milliseconds() - limit * 60 * 1000
                # 1 day chart data
                since1day = mbitmex.milliseconds() - 1 * 86400 * 1000
                # drawning 3 min data
                candles3min = mbitmex.fetch_ohlcv(symbol, timeframe, since3min,
                                                  limit, params)
                num_candles3min = len(candles3min)
                ampl_candle3min = candles3min[
                    num_candles3min - 1][2] - candles3min[num_candles3min -
                                                          1][3]
                freq_candle3min = '{0:.3g}'.format(ampl_candle3min * 0.10)
                win3.addstr(
                    2, 1, "3m " + '{}: O:{} H:{} L:{} C:{}'.format(
                        mbitmex.iso8601(candles3min[num_candles3min - 1][0]),
                        candles3min[num_candles3min - 1][1],
                        candles3min[num_candles3min - 1][2],
                        candles3min[num_candles3min - 1][3],
                        candles3min[num_candles3min - 1][4]) + "|" +
                    str(ampl_candle3min) + "|" + str(freq_candle3min) + " ")
                # drawning 1 day data
                #candles1day = mbitmex.fetch_ohlcv(symbol, timeframe, since1day, limit, params)
                candles1day = mbitmex.fetch_ohlcv(symbol, '1d', since1day)
                num_candles1day = len(candles1day)
                ampl_candle1day = candles1day[
                    num_candles1day - 1][2] - candles1day[num_candles1day -
                                                          1][3]
                freq_candle1day = '{0:.3g}'.format(ampl_candle1day * 0.10)
                win3.addstr(
                    3, 1, "1d " + '{}: O: {} H: {} L:{} C:{}'.format(
                        mbitmex.iso8601(candles1day[num_candles1day - 1][0]),
                        candles1day[num_candles1day - 1][1],
                        candles1day[num_candles1day - 1][2],
                        candles1day[num_candles1day - 1][3],
                        candles1day[num_candles1day - 1][4]) + "|" +
                    str(ampl_candle1day) + "|" + str(freq_candle1day) + " ")
                # Sleep to avoid extra load and/or reaching rate limit
                mwin3count = 0
                win3.refresh()
            time.sleep(0.5)
            screen.refresh()
            win1.refresh()
            win2.refresh()
            mwin3count = mwin3count + 1
    except ccxt.NetworkError:
        time.sleep(2)
        curses.wrapper(main)
        pass
    except KeyboardInterrupt:
        #ws.close()
        curses.endwin()
        print("\n \n --- End of Program! Thank You !!! ---")
        time.sleep(1)
        sys.exit()  #  break first streaming
        sys.exit()  #  break ccxt requests
        sys.exit()
        pass
Ejemplo n.º 46
0
	def __init__(self, refresh_time = 1):
		# Global information to display
		self.__version = __version__

		# Init windows positions
		self.term_w = 		80 ; 		self.term_h = 		24
		self.host_x = 		0 ; 		self.host_y = 		0
		self.system_x = 	0 ; 		self.system_y = 	1
		self.cpu_x = 		0 ; 		self.cpu_y = 		3
		self.load_x = 		20; 		self.load_y = 		3
		self.mem_x = 		41; 		self.mem_y = 		3
		self.network_x = 	0 ; 		self.network_y = 	9
		self.diskio_x = 	0 ; 		self.diskio_y = 	-1
		self.fs_x = 		0 ; 		self.fs_y = 		-1
		self.process_x = 	30;			self.process_y = 	9
		self.help_x = 		30;			self.help_y = 		12
		self.now_x = 		79;			self.now_y = 		3
		self.caption_x = 	0 ;			self.caption_y = 	3

		# Init the curses screen
		self.screen = curses.initscr() 
		if not self.screen:
			print _("Error: Can not init the curses library.\n")
		curses.start_color()
		curses.use_default_colors()
		curses.noecho() ; curses.cbreak() ; curses.curs_set(0)
		
		# Init colors
		self.hascolors = False
		if curses.has_colors():
			self.hascolors = True
			# Init				FG color				BG color
			curses.init_pair(1, curses.COLOR_WHITE, 	-1)
			curses.init_pair(2, curses.COLOR_WHITE, 	curses.COLOR_RED)
			curses.init_pair(3, curses.COLOR_WHITE, 	curses.COLOR_GREEN)
			curses.init_pair(4, curses.COLOR_WHITE, 	curses.COLOR_BLUE)
			curses.init_pair(5, curses.COLOR_WHITE, 	curses.COLOR_MAGENTA)
			curses.init_pair(6, curses.COLOR_WHITE, 	curses.COLOR_CYAN)
			curses.init_pair(7, curses.COLOR_BLACK, 	curses.COLOR_YELLOW)

			# Text colors/styles
			self.title_color = curses.A_BOLD|curses.A_UNDERLINE			
			self.help_color = curses.A_BOLD
			self.no_color = curses.color_pair(1)
			self.default_color = curses.color_pair(3)|curses.A_BOLD
			self.if50pc_color = curses.color_pair(4)|curses.A_BOLD
			self.if70pc_color = curses.color_pair(5)|curses.A_BOLD
			self.if90pc_color = curses.color_pair(2)|curses.A_BOLD

		# By default all the stats are displayed
		self.network_tag = True
		self.diskio_tag = True
		self.fs_tag = True

		# Init main window		
		self.term_window = self.screen.subwin(0, 0)

		# Init help panel
		term_help = self.screen.subwin(self.term_h-self.help_y-2, self.term_w-self.help_x, self.help_y, self.help_x)		
		self.panel_help = curses.panel.new_panel(term_help)
		self.hideHelp()

		# Init refresh time
		self.__refresh_time = refresh_time

		# Catch key pressed with non blocking mode
		self.term_window.keypad(1) ; self.term_window.nodelay(1) ; self.pressedkey = -1
Ejemplo n.º 47
0
def main(argv = None):
  
  parser = argparse.ArgumentParser(description="A cross-platform script for creating and playing sound waves through mathematical expressions", prog="calcwave")
  
  parser.add_argument('expression', type = str,
                      help = "The expression, in terms of x. When using the command line, it may help to surround it in single quotes. If --gui is specified, use 0 for this parimeter")
  parser.add_argument("-s", "--start", type = int, default = -100000,
                      help = "The lower range of x to start from.")
  parser.add_argument("-e", "--end", type = int, default = 100000,
                      help = "The upper range of x to end at.")
  parser.add_argument("-o", "--export", type = str, default = "", nargs = '?',
                      help = "Export to specified file as wav. File extension is automatically added.")
  parser.add_argument("--channels", type = int, default = 1,
                      help = "The number of audio channels to use")
  parser.add_argument("--rate", type = int, default = 44100,
                      help = "The audio rate to use")
  parser.add_argument("--buffer", type = int, default = 1024,
                      help = "The audio buffer frame size to use. This is the length of the list of floats, not the memory it will take.")
  parser.add_argument("--gui", default = False, action = "store_true",
                      help = "Start with the GUI")
  
  if argv is None:
    argv = sys.argv
  
  # The class that is passed to other threads and holds
  # information about how to play sound and act
  tArgs = threadArgs()
  
  isGuiArgument = False
  isExportArgument = False
  isExpressionProvided = False
  args = None
  if len(sys.argv) > 1:
    args = parser.parse_args() #Parse arguments
    #Set variables
    tArgs.expression = args.expression
    tArgs.start = args.start
    tArgs.end = args.end
    tArgs.channels = args.channels
    tArgs.rate = args.rate
    tArgs.frameSize = args.buffer
    
    isExportArgument = args.export != ""
    isGuiArgument = args.gui
    isExpressionProvided = args.expression != ""
    
  # Initialize AudioPlayer
  audioClass = AudioPlayer(tArgs)
  
  window = None
  scr = None
  menu = None
  
  #The program may be started either in GUI mode or CLI mode. Test for GUI mode vvv
  if len(sys.argv) == 1 or isGuiArgument or not(isExportArgument or isExpressionProvided):
    #If no arguments are supplied - GUI
    if isExpressionProvided:
      tArgs.expression = args.expression
    sys.stderr.write("Starting GUI mode\n")
    tArgs.isGUI = True
    
    scr = curses.initscr()
    rows, cols = scr.getmaxyx()
    
    if curses.has_colors():
      curses.start_color()
      curses.use_default_colors()
    
    # ySize, xSize, yStart, xStart
    menu = UIManager(2, cols, rows - 4, 0, tArgs, audioClass)
    #Start the GUI input thread
    window = WindowManager(tArgs, scr, menu)
    
    tArgs.expression = "0" # Default value
  else:
    tArgs.isGUI = False
    
    
  
  if len(sys.argv) >= 1 and isExportArgument:
    exportAudio(args.export, tArgs, None, None)
  else:
    # Keep in mind that menu will be None when it is not in GUI mode...
    audioClass.play()
  
  
  # When that exits
  tArgs.shutdown = True
  
  if window:
    window.thread.join()
Ejemplo n.º 48
0
def init():
    global scr
    scr = curses.initscr()
    curses.start_color()
    scr.keypad(False)
    curses.noecho()
Ejemplo n.º 49
0
# NOTE: The screen goes away if an exception is raised, getting rid of potentially
# useful information. Maybe we should "save" the screen and display it before
# re-raising the exception.

ALL_FG_COLORS = ('black', 'blue', 'green', 'cyan', 'red', 'magenta', 'yellow', 'white',
                 'light black', 'light blue', 'light green', 'light cyan', 'light red',
                 'light magenta', 'light yellow', 'light white')
ALL_BG_COLORS = ('black', 'blue', 'green', 'cyan', 'red', 'magenta', 'yellow', 'white')

_ALL_CURSES_COLORS = [curses.COLOR_BLACK, curses.COLOR_BLUE, curses.COLOR_GREEN,
                      curses.COLOR_CYAN, curses.COLOR_RED, curses.COLOR_MAGENTA,
                      curses.COLOR_YELLOW, curses.COLOR_WHITE]

# Initialize the curses library
_G_SCR = curses.initscr() # Initialize the screen.
curses.start_color() # Initialize colors.

# Initialize all the color pairs:
ALL_COLOR_PAIRS = {}
for fgi, fgc in enumerate(_ALL_CURSES_COLORS):
    for bgi, bgc in enumerate(_ALL_CURSES_COLORS):
        colorPairNum = 1 + (fgi + (bgi * 8))
        ALL_COLOR_PAIRS[(ALL_FG_COLORS[fgi], ALL_BG_COLORS[bgi])] = colorPairNum
        curses.init_pair(colorPairNum, _ALL_CURSES_COLORS[fgc], _ALL_CURSES_COLORS[bgc])

_G_CURRENT_FG_COLOR = 'white'
_G_CURRENT_BG_COLOR = 'black'

_G_SCR.scrollok(True) # When stuff is printed on the last line, scroll the window.
curses.noecho() # Don't echo key presses unless input() has been called. TODO - maybe not even then.
_G_SCR.keypad(True) #
Ejemplo n.º 50
0
    def __init__(self, screen, startLevel):
        self.length = 10  # Cannot be Modified Yet
        self.height = 20  # Cannot be Modified Yet
        self.board = None  # Game Board Object
        self.threads = []  # Player and Computer Threads
        self.lock = threading.RLock()

        self.screen = screen
        curses.halfdelay(1)

        self.rowsToClear = []  # Used By Computer to Draw Row Clear Effects
        self.board = None  # Game Board Object
        self.level = None
        self.blocksPlaced = None
        self.tetrises = None
        self.triples = None
        self.doubles = None
        self.singles = None
        self.lastCommandTime = None

        self.extraTime = False
        self.hasExtraTime = False
        self.isComplete = False
        self.isPaused = False
        self.didLose = False
        self.isSuspended = False

        self.startLevel = startLevel

        ## Calculate Coordinates ##

        self.spaceCoordinates = []
        for x in range(10):
            for y in range(22):
                self.spaceCoordinates.append((x, y))

        self.spaceCoordinatesReversed = []
        for y in range(22):
            for x in range(10):
                self.spaceCoordinatesReversed.append((x, y))

        self.nextCoordinates = []
        self.afterCoordinates = []
        for x in range(9):
            for y in range(2):
                self.nextCoordinates.append((x, y))

        ## Set Up Curses Colors ##

        curses.curs_set(0)
        curses.start_color()
        ### BLOCKS ###
        curses.init_pair(1, 15, curses.COLOR_BLACK)  # No Block / White Text
        curses.init_pair(2, 15, 39)  # Blue Block
        curses.init_pair(3, 15, 11)  # Yellow Block
        curses.init_pair(4, 15, 208)  # Orange Block
        curses.init_pair(5, 15, 10)  # Green Block
        curses.init_pair(6, 15, 13)  # Purple Block
        curses.init_pair(7, 15, 9)  # Red Block
        curses.init_pair(8, 15, 14)  # Cyan Block
        curses.init_pair(16, 15, 199)  # Dead Block
        curses.init_pair(17, 9, 15)
        ### TEXT ###
        curses.init_pair(9, 39, curses.COLOR_BLACK)  # Blue Text
        curses.init_pair(10, 11, curses.COLOR_BLACK)  # Yellow Text
        curses.init_pair(11, 208, curses.COLOR_BLACK)  # Orange Text
        curses.init_pair(12, 10, curses.COLOR_BLACK)  # Green Text
        curses.init_pair(13, 13, curses.COLOR_BLACK)  # Purple Text
        curses.init_pair(14, 9, curses.COLOR_BLACK)  # Red Text
        curses.init_pair(15, 14, curses.COLOR_BLACK)  # Cyan Text

        self.CURSES_COLOR_DICT = {
            'O': curses.color_pair(3),
            'L': curses.color_pair(2),
            'J': curses.color_pair(4),
            'S': curses.color_pair(6),
            'Z': curses.color_pair(5),
            'T': curses.color_pair(8),
            'I': curses.color_pair(7),
        }