Exemple #1
0
	def printStats(self):
		
		# initialize colorama
		reinit()

		width = 10

		print("Previous Numbers: ")
		# break what you're fetching into fifteen numbers per row at the most
		# algorithmically determine the number of items to print, and create formatting instructions
		# if you reach the maximum number of items, create a new row

		# maximum height is 16
		
		if(len(self.previous_numbers) > 0):
				for x in reversed(self.previous_numbers):
					if(x.color == 'red'):
						print(Back.RED + "{0: <3}".format(x.number))
					elif(x.color == 'black'):
						print(Back.BLACK + "     {0: <3}".format(x.number))
					else:
						print(Back.GREEN + "  {0: <3}".format(x.number))
		print(Style.RESET_ALL)

		deinit()
Exemple #2
0
def _start_exec_pipe_windows(web_socket_uri, password):
    import colorama
    colorama.deinit()
    enable_vt_mode()
    buff = bytearray()
    lock = threading.Lock()

    def _on_ws_open_windows(ws):
        ws.send(password)
        readKeyboard = threading.Thread(target=_capture_stdin, args=[_getch_windows, buff, lock], daemon=True)
        readKeyboard.start()
        flushKeyboard = threading.Thread(target=_flush_stdin, args=[ws, buff, lock], daemon=True)
        flushKeyboard.start()
    ws = websocket.WebSocketApp(web_socket_uri, on_open=_on_ws_open_windows, on_message=_on_ws_msg)
    # in windows, msvcrt.getch doesn't give us ctrl+C so we have to manually catch it with kb interrupt and send it over the socket
    websocketRun = threading.Thread(target=ws.run_forever)
    websocketRun.start()
    while websocketRun.is_alive():
        try:
            time.sleep(0.01)
        except KeyboardInterrupt:
            try:
                ws.send(b'\x03')  # CTRL-C character (ETX character)
            finally:
                pass
    colorama.reinit()
Exemple #3
0
 def __write_message(self, message):
     if self.initialized:
         colorama.reinit()
     else:
         colorama.init()
         self.initialized = True
     print(message)
     colorama.deinit()
Exemple #4
0
    def set_colorama(foreground=foreground, background=background):
        try:
            import colorama
            colorama.init(True, wrap=True)
            colors_fore = {
                "white": colorama.Fore.WHITE,
                "black": colorama.Fore.BLACK,
                "blue": colorama.Fore.BLUE,
                "cyan": colorama.Fore.CYAN,
                "green": colorama.Fore.GREEN,
                "red": colorama.Fore.RED,
                "magenta": colorama.Fore.MAGENTA,
                "yellow": colorama.Fore.YELLOW,
                "lightwhite": colorama.Fore.LIGHTWHITE_EX,
                "lightblack": colorama.Fore.LIGHTBLACK_EX,
                "lightblue": colorama.Fore.LIGHTBLUE_EX,
                "lightcyan": colorama.Fore.LIGHTCYAN_EX,
                "lightgreen": colorama.Fore.LIGHTGREEN_EX,
                "lightred": colorama.Fore.LIGHTRED_EX,
                "lightmagenta": colorama.Fore.LIGHTMAGENTA_EX,
                "lightyellow": colorama.Fore.LIGHTYELLOW_EX,
            }

            colors_back = {
                'white': colorama.Back.WHITE,
                'black': colorama.Back.BLACK,
                'blue': colorama.Back.BLUE,
                'cyan': colorama.Back.CYAN,
                'green': colorama.Back.GREEN,
                'red': colorama.Back.RED,
                'magenta': colorama.Back.MAGENTA,
                'yellow': colorama.Back.YELLOW,
                'lightwhite': colorama.Back.LIGHTWHITE_EX,
                'lightblack': colorama.Back.LIGHTBLACK_EX,
                'lightblue': colorama.Back.LIGHTBLUE_EX,
                'lightcyan': colorama.Back.LIGHTCYAN_EX,
                'lightgreen': colorama.Back.LIGHTGREEN_EX,
                'lightred': colorama.Back.LIGHTRED_EX,
                'lightmagenta': colorama.Back.LIGHTMAGENTA_EX,
                'lightyellow': colorama.Back.LIGHTYELLOW_EX,
            }

            foreground1 = colors_fore.get(str(foreground))
            background1 = colors_back.get(str(background))
            if not foreground1:
                foreground1 = ''
            if not background1:
                background1 = ''
            if foreground == None or background == "None":
                return string
            colorama.reinit()
            return foreground1 + background1 + string
        except ImportError:
            print 'NO MODULE NAME: "colorama"'
            return string
        colorama.init()
Exemple #5
0
 def debug_talk(self, message):
     import colorama
     from colorama import Fore
     colorama.reinit()
     colored_client_message = f"{Fore.GREEN} {message}"
     response = f" {Fore.GREEN} {self.talk(colored_client_message)}"
     print_response = f"From server: {response}"
     client_msg = f"{Fore.BLUE} {message}"
     print_client_msg = f"To server: {client_msg}"
     return print_client_msg, print_response
Exemple #6
0
def print_error(error, first_build):
    global COLORAMA_INIT
    if first_build:
        if COLORAMA_INIT:
            init()
            COLORAMA_INIT = False
        else:
            reinit()
        print(Fore.RED, error)
        print(Style.RESET_ALL)
        deinit()
    else:
        with open("_build/_static/error_log.txt", "w+", encoding="utf-8") as f:
            f.write(error)
Exemple #7
0
    def interactive_loop(self):
        self.print_interactive_intro()
        # initialise autocomplete
        self.words = self._utils.keys()
        # completer = Completer(words)
        colorama.deinit()  # make colorama to release stderr and stdout
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self.complete)
        try:
            readline.read_history_file()
        except:
            pass  # eat it

        # readline..set_completion_display_matches_hook(self.show_completions)
        # readline.set_completion_display_matches_hook([function])

        # Set or remove the completion display function. If function is specified, it will be used as the new completion
        # display function; if omitted or None, any completion display function already installed is removed.
        # The completion display function is called as function(substitution, [matches], longest_match_length) each
        # time matches need to be displayed.

        # Begin user commands read loop
        while 1:
            colorama.deinit()

            # read command from user
            try:
                user_input = raw_input(self.current_path + "> ")
            except EOFError:
                log.debug("EOF sequence received. Ending interactive loop")
                break
            except KeyboardInterrupt:
                log.debug("Break sequence received. Ending interactive loop")
                break

            colorama.reinit()

            # exit if user wishes so
            if user_input in ("quit", "q", "exit"):
                break  # quit!

            # process user input
            self.process_command_line(user_input)

            # loop ended
        try:
            readline.write_history_file()
        except:
            log.warn("unable to write history file")
    def interactive_loop(self):
        self.print_interactive_intro()
        #initialise autocomplete
        self.words = self._utils.keys()
        #completer = Completer(words)
        colorama.deinit()  # make colorama to release stderr and stdout
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self.complete)
        try:
            readline.read_history_file()
        except:
            pass  # eat it

        #readline..set_completion_display_matches_hook(self.show_completions)
        #readline.set_completion_display_matches_hook([function])

        #Set or remove the completion display function. If function is specified, it will be used as the new completion
        # display function; if omitted or None, any completion display function already installed is removed.
        # The completion display function is called as function(substitution, [matches], longest_match_length) each
        # time matches need to be displayed.

        # Begin user commands read loop
        while 1:
            colorama.deinit()

            # read command from user
            try:
                user_input = raw_input(self.current_path + "> ")
            except EOFError:
                log.debug("EOF sequence received. Ending interactive loop")
                break
            except KeyboardInterrupt:
                log.debug("Break sequence received. Ending interactive loop")
                break

            colorama.reinit()

            # exit if user wishes so
            if user_input in ("quit", "q", "exit"):
                break  #quit!

            #process user input
            self.process_command_line(user_input)

            #loop ended
        try:
            readline.write_history_file()
        except:
            log.warn("unable to write history file")
Exemple #9
0
def _mode():
    """
    What Trading Mode?

    :return: Trading Mode. True means Default. False means FAST.
    :rtype: bool
    """
    reinit()
    print(Fore.WHITE + '   1: Default Trading')
    print(Fore.WHITE + '   2: Fast Trading')
    choice = GetNum()
    if choice == 1:
        return True
    elif choice == 2:
        return False
    print(Fore.RESET + "")
Exemple #10
0
        def _summarize(ap=1,
                       iouThr=None,
                       areaRng='all',
                       maxDets=100,
                       highlight=False):
            colorama.reinit()
            color_prefix = color_suffix = ''
            if highlight:
                color_prefix = colorama.Fore.CYAN
                color_suffix = colorama.Fore.RESET

            p = self.params
            iStr = ' {}{:<18} {} @[ IoU={:<9} | area={:>6s} | maxDets={:>3d} ] = {:0.3f}{}'
            titleStr = 'Average Precision' if ap == 1 else 'Average Recall'
            typeStr = '(AP)' if ap == 1 else '(AR)'
            iouStr = '{:0.2f}:{:0.2f}'.format(p.iouThrs[0], p.iouThrs[-1]) \
                if iouThr is None else '{:0.2f}'.format(iouThr)

            aind = [
                i for i, aRng in enumerate(p.areaRngLbl) if aRng == areaRng
            ]
            mind = [i for i, mDet in enumerate(p.maxDets) if mDet == maxDets]
            if ap == 1:
                # dimension of precision: [TxRxKxAxM]
                s = self.eval['precision']
                # IoU
                if iouThr is not None:
                    t = np.where(iouThr == p.iouThrs)[0]
                    s = s[t]
                s = s[:, :, :, aind, mind]
            else:
                # dimension of recall: [TxKxAxM]
                s = self.eval['recall']
                if iouThr is not None:
                    t = np.where(iouThr == p.iouThrs)[0]
                    s = s[t]
                s = s[:, :, aind, mind]
            if len(s[s > -1]) == 0:
                mean_s = -1
            else:
                mean_s = np.mean(s[s > -1])
            print(
                iStr.format(color_prefix, titleStr, typeStr, iouStr, areaRng,
                            maxDets, mean_s, color_suffix))
            colorama.deinit()
            return mean_s
Exemple #11
0
def screenblink(width=None, height=None, symbol="#", sleep=0.5, mode="fast"):
    if width != None and height != None:
        os.system("mode con cols=" + str(width) + " lines=" + str(height))
    if width == None:
        width = checkWidthOfConsole()
    if height == None:
        height = checkHeightOfConsole()
    colorama.reinit()
    while True:
        colors = [
            "grey", "red", "green", "yellow", "blue", "magenta", "cyan",
            "white"
        ]
        highlights = [
            "on_grey", "on_red", "on_green", "on_yellow", "on_blue",
            "on_magenta", "on_cyan", "on_white"
        ]
        string = symbol * width
        color = random.choice(colors)
        colors.pop(colors.index(color))
        highlight = random.choice(highlights)
        if mode == "fast":
            try:  # New version with one long line. Works perfect, as I see.
                string = string * height
                print(termcolor.colored(string, color, highlight))
                time.sleep(sleep)
            except KeyboardInterrupt as err:
                print(termcolor.colored("OK", "white", "on_grey"))
                colorama.deinit()
                cls()
                break
        else:
            try:  #old multiline version. Have bug with get width of console and so create blank lines. Unexpected
                height_ = height
                while height_ > 0:
                    print(termcolor.colored(string, color, highlight))
                    height_ -= 1
                time.sleep(sleep)
            except KeyboardInterrupt as err:
                print(termcolor.colored("OK", "white", "on_grey"))
                colorama.deinit()
                cls()
                break
    colorama.deinit()
Exemple #12
0
def ping(domain="127.0.0.1",
         count=1,
         quiet=False,
         logfile=None,
         timeout=10000):  # с таким эксепшном можно сделать куда проще это всё
    domain = getDomainOfUrl(domain)
    if not quiet:
        colorama.reinit()
        print("Pinging", domain, count, "times...")
        upmessage = domain + " is up!"
        downmessage = domain + " is down."
    try:
        if get_os() == "windows":
            count_arg = "n"
            timeout_arg = "w"
        if (get_os() == "macos") or (get_os() == "linux"):
            count_arg = "c"
            timeout_arg = "W"
        command = "ping " + domain + " -" + count_arg + " " + str(count) + \
                  " -" + timeout_arg + " " + str(timeout)
        pingoutput = getOutPutFromCommand(command)
    except KeyboardInterrupt:
        sys.exit()
    except:
        pingoutput = ""
    if ("TTL" in pingoutput) or ("ttl" in pingoutput):
        up = True
    else:
        up = False
    if logfile:
        if up:
            plog(logfile, domain + " is up!", quiet=True)
            cprint(upmessage, "white", "on_green")
        else:
            plog(logfile, downmessage, quiet=True)
            cprint(downmessage, "white", "on_red")
    elif not quiet:
        if up:
            cprint(upmessage, "white", "on_green")
        else:
            cprint(downmessage, "white", "on_red")
        colorama.deinit()
    return up
Exemple #13
0
                print wrapped_line
        _display_pending = []

        client_input_pending = None
        while kbhit():
            ch = getch()
            if ch == chr(27):  # escape
                print 'exiting...'
                client_output(':source QUIT :exiting...')
                _exiting = True
            # wish: go to input mode using any key and including that key as first key typed
            elif ch == '\r':
                colorama.deinit()
                stdout.write('input')
                client_input_pending = raw_input(': ').strip()
                colorama.reinit()

        if client_input_pending:
            # proc client input
            client_input_split = client_input_pending.split(' ')
            first = client_input_split[0]
            arg1 = arg(client_input_split, 1)
            if not first.startswith('/'):
                # msg to current target
                target = _active_target
                msg = param(client_input_split, 0)
                client_output(':source PRIVMSG {0} :{1}'.format(target, msg))
                display_lines = ui_chanmsg(target, _nick, msg)
                client_echo(display_lines)
            elif first == '/login':
                if arg1:
Exemple #14
0
    def make_colors(self, string, foreground='', background='', attrs=''):
        string = str(string)
        try:
            colorama.init(True, wrap=True)
            if sys.platform == 'win32':
                colors_fore = {
                    "white": colorama.Fore.WHITE,
                    "black": colorama.Fore.BLACK,
                    "blue": colorama.Fore.BLUE,
                    "cyan": colorama.Fore.CYAN,
                    "green": colorama.Fore.GREEN,
                    "red": colorama.Fore.RED,
                    "magenta": colorama.Fore.MAGENTA,
                    "yellow": colorama.Fore.YELLOW,
                    "lightwhite": colorama.Fore.LIGHTWHITE_EX,
                    "lightblack": colorama.Fore.LIGHTBLACK_EX,
                    "lightblue": colorama.Fore.LIGHTBLUE_EX,
                    "lightcyan": colorama.Fore.LIGHTCYAN_EX,
                    "lightgreen": colorama.Fore.LIGHTGREEN_EX,
                    "lightred": colorama.Fore.LIGHTRED_EX,
                    "lightmagenta": colorama.Fore.LIGHTMAGENTA_EX,
                    "lightyellow": colorama.Fore.LIGHTYELLOW_EX,
                }

                colors_back = {
                    'white': colorama.Back.WHITE,
                    'black': colorama.Back.BLACK,
                    'blue': colorama.Back.BLUE,
                    'cyan': colorama.Back.CYAN,
                    'green': colorama.Back.GREEN,
                    'red': colorama.Back.RED,
                    'magenta': colorama.Back.MAGENTA,
                    'yellow': colorama.Back.YELLOW,
                    'lightwhite': colorama.Back.LIGHTWHITE_EX,
                    'lightblack': colorama.Back.LIGHTBLACK_EX,
                    'lightblue': colorama.Back.LIGHTBLUE_EX,
                    'lightcyan': colorama.Back.LIGHTCYAN_EX,
                    'lightgreen': colorama.Back.LIGHTGREEN_EX,
                    'lightred': colorama.Back.LIGHTRED_EX,
                    'lightmagenta': colorama.Back.LIGHTMAGENTA_EX,
                    'lightyellow': colorama.Back.LIGHTYELLOW_EX,
                }
            else:
                colors_fore = {
                    "white": colorama.Fore.WHITE,
                    "black": colorama.Fore.BLACK,
                    "blue": colorama.Fore.BLUE,
                    "cyan": colorama.Fore.CYAN,
                    "green": colorama.Fore.GREEN,
                    "red": colorama.Fore.RED,
                    "magenta": colorama.Fore.MAGENTA,
                    "yellow": colorama.Fore.YELLOW,
                    "lightwhite": colorama.Fore.white,
                    "lightblack": colorama.Fore.black,
                    "lightblue": colorama.Fore.blue,
                    "lightcyan": colorama.Fore.cyan,
                    "lightgreen": colorama.Fore.green,
                    "lightred": colorama.Fore.red,
                    "lightmagenta": colorama.Fore.magenta,
                    "lightyellow": colorama.Fore.yellow,
                }

                colors_back = {
                    'white': colorama.Back.WHITE,
                    'black': colorama.Back.BLACK,
                    'blue': colorama.Back.BLUE,
                    'cyan': colorama.Back.CYAN,
                    'green': colorama.Back.GREEN,
                    'red': colorama.Back.RED,
                    'magenta': colorama.Back.MAGENTA,
                    'yellow': colorama.Back.YELLOW,
                    "lightwhite": colorama.Fore.white,
                    "lightblack": colorama.Fore.black,
                    "lightblue": colorama.Fore.blue,
                    "lightcyan": colorama.Fore.cyan,
                    "lightgreen": colorama.Fore.green,
                    "lightred": colorama.Fore.red,
                    "lightmagenta": colorama.Fore.magenta,
                    "lightyellow": colorama.Fore.yellow,
                }

            foreground1 = colors_fore.get(str(foreground))
            background1 = colors_back.get(str(background))

            if not foreground1:
                foreground1 = ''
            if not background1:
                background1 = ''
            if foreground == None or background == "None":
                return string
            colorama.reinit()
            return foreground1 + background1 + string
        except ImportError:
            print 'NO MODULE NAME: "colorama"'
            return string
Exemple #15
0
def print_green(string):
    if find_client() == 2: reinit()
    print(Fore.GREEN + Style.BRIGHT + string + Style.RESET_ALL)
    if find_client() == 2: deinit()
    def process_command(self, command, args):
        #>oO debug
        if log.isEnabledFor(logging.DEBUG):
            log.debug(
                lfm("{0}Processing command: '{1}'{0}\\", os.linesep, command))
            log.debug(lfm(" |- arguments : '{0}'", "' '".join(args)))

        #try to find function...
        try:
            util = self._utils[command]
        except KeyError:
            log.error(
                "Command " + command +
                " is unknown! Please, use help to see available commands")
            if not self.silent_exceptions:
                raise
            else:
                return 1

        #check connection and connect if needed
        if util.uses_db and (not self.provider.is_connected):
            if not self.check_connection(util):
                return False

        #is there file redirect?
        redir_to_file = False  # should we redirect to file?
        redir_file = None  # file to redirect
        redir_stream_backup = sys.stdout
        redir_theme_backup = self.theme

        if ">" in args and args.index(">") == len(args) - 2:

            redir_fname = args[-1]
            redir_to_file = True
            args = args[:-2]
            log.debug(" |- redirecting to file : {0}".format(redir_fname))

            #open file
            try:
                redir_file = file(redir_fname, 'w')
            except Exception as ex:
                log.error("Cannot open file '{0}' {1} ".format(
                    redir_fname, ex))
                if not self.silent_exceptions:
                    raise
                else:
                    return 1

        #execute command
        try:
            if redir_to_file:
                colorama.deinit()
                sys.stdout = redir_file
                self.theme = themes.NoColorTheme()

            result = util.process(args)

        except Exception as ex:
            log.error(ex)
            if not self.silent_exceptions:
                raise
            else:
                return 1
        finally:
            if redir_to_file:
                sys.stdout = redir_stream_backup
                redir_file.close()
                self.theme = redir_theme_backup
                colorama.reinit()
        return result
Exemple #17
0
    def menu_system(self):

        # Reinitialize colorama as sys.stdout/stderr may have changed since program started
        colorama.reinit()

        while self.user_command == "":

            try:

                if self.cli_args is not None:

                    if self.cli_args.list is not None:
                        self.run_list_command(self.cli_args.list)

                    if self.cli_args.load is not None:
                        try:
                            self.load_ips(self.cli_args.load)
                        except IndexError:
                            print helpers.color("\n\n[*] Error: Load command requires a path to a file!", warning=True)
                            print helpers.color("[*] Ex: load /root/file.txt", warning=True)
                            sys.exit()

                    if self.cli_args.file_import is not None:
                        self.run_import_command(self.cli_args.file_import)

                    if self.cli_args.gather is not None:
                        self.run_gather_command(self.cli_args.gather)

                    if self.cli_args.save:
                        self.save_state()

                    if self.cli_args.analyze is not None:
                        self.run_analyze_command(self.cli_args.analyze)

                    if self.cli_args.ip_info is not None:
                        self.run_ipinfo_command(self.cli_args.ip_info)

                    if self.cli_args.export:
                        self.export_info()

                    sys.exit()

                else:

                    while True:
                        self.user_command = raw_input(' \n\n[>] Please enter a command: ').strip()
                        helpers.print_header()

                        if self.user_command is not "":
                            # Check if command is to load IP addresses into framework
                            if self.user_command.startswith('load'):
                                try:
                                    self.load_ips(self.user_command.split()[1])
                                except IndexError:
                                    print helpers.color("\n\n[*] Error: Load command requires a path to a file!", warning=True)
                                    print helpers.color("[*] Ex: load /root/file.txt", warning=True)
                                self.user_command = ""

                            elif self.user_command.startswith('gather'):
                                try:
                                    self.run_gather_command(
                                        self.user_command.split()[1])
                                except IndexError:
                                    print helpers.color("\n\n[*] Error: Module command requires a module to load!", warning=True)
                                    print helpers.color("[*] Ex: gather geoinfo", warning=True)
                                self.user_command = ""

                            elif self.user_command.startswith('help'):
                                self.print_commands()
                                self.user_command = ""

                            elif self.user_command.startswith('exit'):
                                print helpers.color(
                                    "\n\n[!] Exiting Just Metadata..\n",
                                    warning=True)
                                sys.exit()

                            # Code for saving current state to disk
                            elif self.user_command.startswith('save'):
                                self.save_state()
                                self.user_command = ""

                            # Code for loading state from disk
                            elif self.user_command.startswith('import'):
                                try:
                                    self.run_import_command(
                                        self.user_command.split()[1])
                                except IndexError:
                                    print helpers.color("[*] Error: Please provide path to file that will be imported.", warning=True)
                                    print helpers.color("[*] Ex: import metadata1111_1111.state", warning=True)
                                self.user_command = ""

                            elif self.user_command.startswith('ip_info'):
                                try:
                                    self.run_ipinfo_command(
                                        self.user_command.split()[1])
                                except IndexError:
                                    print helpers.color("[*] Error: The \"ip_info\" command requires an IP address!", warning=True)
                                    self.check_cli()
                                self.user_command = ""

                            # This will be the export command, used to export
                            # all information into a csv file
                            elif self.user_command.startswith('export'):
                                self.export_info()
                                self.user_command = ""

                            elif self.user_command.startswith('analyze'):
                                try:
                                    self.run_analyze_command(
                                        self.user_command.split()[1])
                                except IndexError:
                                    print helpers.color("\n\n[*] Error: Analyze command requires a module to load!", warning=True)
                                    print helpers.color("[*] Ex: analyze GeoInfo", warning=True)
                                self.user_command = ""

                            elif self.user_command.startswith('list'):
                                try:
                                    self.run_list_command(
                                        self.user_command.split()[1])
                                except IndexError:
                                    print helpers.color("\n\n[*] Error: You did not provide a module type to display!", warning=True)
                                    print helpers.color("[*] Ex: list analysis", warning=True)
                                self.user_command = ""

                            else:
                                print helpers.color("\n\n[*] Error: You did not provide a valid command!", warning=True)
                                print helpers.color("[*] Type \"help\" to view valid commands", warning=True)

            except KeyboardInterrupt:
                print helpers.color("\n\n[!] You just rage quit...", warning=True)
                sys.exit()

            except Exception as e:
                print helpers.color("\n\n[!] Encountered Error!", warning=True)
                print helpers.color(e)
                print helpers.color("[!] Saving state to disk...", warning=True)
                print helpers.color("[!] Please report this info to the developer!", warning=True)
                self.save_state()

        return
Exemple #18
0
def print_green(string):
    if windows_client(): reinit()
    print(Fore.GREEN + Style.BRIGHT + string + Style.RESET_ALL)
    if windows_client(): deinit()
def test(*variables):
    colorama.reinit()
    if len(variables) == 0:
        print(bold(blue('here')))
    else:
        print(_recursively_add_vars(variables))
Exemple #20
0
    def menu_system(self):

        # Reinitialize colorama as sys.stdout/stderr may have changed since program started
        colorama.reinit()

        while self.user_command == "":

            try:

                if self.cli_args is not None:

                    if self.cli_args.list is not None:
                        self.run_list_command(self.cli_args.list)

                    if self.cli_args.load is not None:
                        try:
                            self.load_ips(self.cli_args.load)
                        except IndexError:
                            print helpers.color(
                                "\n\n[*] Error: Load command requires a path to a file!",
                                warning=True)
                            print helpers.color("[*] Ex: load /root/file.txt",
                                                warning=True)
                            sys.exit()

                    if self.cli_args.file_import is not None:
                        self.run_import_command(self.cli_args.file_import)

                    if self.cli_args.gather is not None:
                        self.run_gather_command(self.cli_args.gather)

                    if self.cli_args.save:
                        self.save_state()

                    if self.cli_args.analyze is not None:
                        self.run_analyze_command(self.cli_args.analyze)

                    if self.cli_args.ip_info is not None:
                        self.run_ipinfo_command(self.cli_args.ip_info)

                    if self.cli_args.export:
                        self.export_info()

                    sys.exit()

                else:

                    while True:
                        self.user_command = raw_input(
                            ' \n\n[>] Please enter a command: ').strip()
                        helpers.print_header()

                        if self.user_command is not "":
                            # Check if command is to load IP addresses into framework
                            if self.user_command.startswith('load'):
                                try:
                                    self.load_ips(self.user_command.split()[1])
                                except IndexError:
                                    print helpers.color(
                                        "\n\n[*] Error: Load command requires a path to a file!",
                                        warning=True)
                                    print helpers.color(
                                        "[*] Ex: load /root/file.txt",
                                        warning=True)
                                self.user_command = ""

                            elif self.user_command.startswith('gather'):
                                try:
                                    self.run_gather_command(
                                        self.user_command.split()[1])
                                except IndexError:
                                    print helpers.color(
                                        "\n\n[*] Error: Module command requires a module to load!",
                                        warning=True)
                                    print helpers.color(
                                        "[*] Ex: gather geoinfo", warning=True)
                                self.user_command = ""

                            elif self.user_command.startswith('help'):
                                self.print_commands()
                                self.user_command = ""

                            elif self.user_command.startswith('exit'):
                                print helpers.color(
                                    "\n\n[!] Exiting Just Metadata..\n",
                                    warning=True)
                                sys.exit()

                            # Code for saving current state to disk
                            elif self.user_command.startswith('save'):
                                self.save_state()
                                self.user_command = ""

                            # Code for loading state from disk
                            elif self.user_command.startswith('import'):
                                try:
                                    self.run_import_command(
                                        self.user_command.split()[1])
                                except IndexError:
                                    print helpers.color(
                                        "[*] Error: Please provide path to file that will be imported.",
                                        warning=True)
                                    print helpers.color(
                                        "[*] Ex: import metadata1111_1111.state",
                                        warning=True)
                                self.user_command = ""

                            elif self.user_command.startswith('ip_info'):
                                try:
                                    self.run_ipinfo_command(
                                        self.user_command.split()[1])
                                except IndexError:
                                    print helpers.color(
                                        "[*] Error: The \"ip_info\" command requires an IP address!",
                                        warning=True)
                                    self.check_cli()
                                self.user_command = ""

                            # This will be the export command, used to export
                            # all information into a csv file
                            elif self.user_command.startswith('export'):
                                self.export_info()
                                self.user_command = ""

                            elif self.user_command.startswith('analyze'):
                                try:
                                    self.run_analyze_command(
                                        self.user_command.split()[1])
                                except IndexError:
                                    print helpers.color(
                                        "\n\n[*] Error: Analyze command requires a module to load!",
                                        warning=True)
                                    print helpers.color(
                                        "[*] Ex: analyze GeoInfo",
                                        warning=True)
                                self.user_command = ""

                            elif self.user_command.startswith('list'):
                                try:
                                    self.run_list_command(
                                        self.user_command.split()[1])
                                except IndexError:
                                    print helpers.color(
                                        "\n\n[*] Error: You did not provide a module type to display!",
                                        warning=True)
                                    print helpers.color(
                                        "[*] Ex: list analysis", warning=True)
                                self.user_command = ""

                            else:
                                print helpers.color(
                                    "\n\n[*] Error: You did not provide a valid command!",
                                    warning=True)
                                print helpers.color(
                                    "[*] Type \"help\" to view valid commands",
                                    warning=True)

            except KeyboardInterrupt:
                print helpers.color("\n\n[!] You just rage quit...",
                                    warning=True)
                sys.exit()

            except Exception as e:
                print helpers.color("\n\n[!] Encountered Error!", warning=True)
                print helpers.color(e)
                print helpers.color("[!] Saving state to disk...",
                                    warning=True)
                print helpers.color(
                    "[!] Please report this info to the developer!",
                    warning=True)
                self.save_state()

        return
Exemple #21
0
def print_red(string):
    if find_client() == 2: reinit()
    print(Fore.RED + Style.BRIGHT + string + Style.RESET_ALL)
    if find_client() == 2: deinit()
Exemple #22
0
def print_yellow(string):
    if windows_client(): reinit()
    print(Fore.YELLOW + Style.BRIGHT + string + Style.RESET_ALL)
    if windows_client(): deinit()
Exemple #23
0
    def process_command(self, command, args):
        # >oO debug
        if log.isEnabledFor(logging.DEBUG):
            log.debug(lfm("{0}Processing command: '{1}'{0}\\", os.linesep, command))
            log.debug(lfm(" |- arguments : '{0}'", "' '".join(args)))

        # try to find function...
        try:
            util = self._utils[command]
        except KeyError:
            log.error("Command " + command + " is unknown! Please, use help to see available commands")
            if not self.silent_exceptions:
                raise
            else:
                return 1

        # check connection and connect if needed
        if util.uses_db and (not self.provider.is_connected):
            if not self.check_connection(util):
                return False

        # is there file redirect?
        redir_to_file = False  # should we redirect to file?
        redir_file = None  # file to redirect
        redir_stream_backup = sys.stdout
        redir_theme_backup = self.theme

        if ">" in args and args.index(">") == len(args) - 2:

            redir_fname = args[-1]
            redir_to_file = True
            args = args[:-2]
            log.debug(" |- redirecting to file : {0}".format(redir_fname))

            # open file
            try:
                redir_file = file(redir_fname, "w")
            except Exception as ex:
                log.error("Cannot open file '{0}' {1} ".format(redir_fname, ex))
                if not self.silent_exceptions:
                    raise
                else:
                    return 1

        # execute command
        try:
            if redir_to_file:
                colorama.deinit()
                sys.stdout = redir_file
                self.theme = themes.NoColorTheme()

            result = util.process(args)

        except Exception as ex:
            log.error(ex)
            if not self.silent_exceptions:
                raise
            else:
                return 1
        finally:
            if redir_to_file:
                sys.stdout = redir_stream_backup
                redir_file.close()
                self.theme = redir_theme_backup
                colorama.reinit()
        return result
Exemple #24
0
def print_red(string):
    if windows_client(): reinit()
    print(Fore.RED + Style.BRIGHT + string + Style.RESET_ALL)
    if windows_client(): deinit()
Exemple #25
0
def color_enable():
    global COLORS_ENABLED
    COLORS_ENABLED = True
    colorama.reinit()
Exemple #26
0
def print_cyan(string):
    if find_client() == 2: reinit()
    print(Fore.CYAN + Style.BRIGHT + string + Style.RESET_ALL)
    if find_client() == 2: deinit()
Exemple #27
0
 def __enter__(self):
     if self._has_initialized:
         reinit()
Exemple #28
0
from colorama import Fore, Back, init, deinit, reinit

# print('{:.2f}'.format(1.68 * 1.68))
# print(74.1 / 2.82)

peso = None
altura = None
deinic = deinit()
init()
print(Fore.LIGHTBLUE_EX + '-=-' * 15)
print('Calculador de IMC')
print('-=-' * 15)
deinit()
reinit()
try:
    peso = float(input(Fore.YELLOW + 'Por favor, informe seu peso: '))
    altura = float(input(Fore.YELLOW + 'Agora, insira sua altura: '))
except ValueError:
    exit()

calc = altura * altura
imc = peso / calc

if imc < 18.5:
    print(Fore.LIGHTRED_EX + 'Seu IMC é de {:.2f}.\n'.format(imc))
    print(Back.RED + Fore.LIGHTWHITE_EX + 'VOCÊ ESTÁ ABAIXO DO PESO.')
    print(Fore.LIGHTRED_EX + 'Por favor, procure um nutricionista e um médico urgentemente.')
elif 18.5 <= imc < 25:
    print(Fore.LIGHTGREEN_EX + 'Seu IMC é de {:.2f}.'.format(imc))
    print(Fore.GREEN + 'Você está num ótimo peso! Continue assim!!')
elif 25 <= imc < 29:
Exemple #29
0
    def printlist(self,
                  defname=None,
                  debug=None,
                  filename='',
                  linenumbers='',
                  print_function_parameters=False,
                  **kwargs):

        if DEBUG_SERVER:
            debug_server = True

        if not filename:
            filename = self.FILENAME

        frame = inspect.currentframe()
        args, _, _, values = inspect.getargvalues(frame)

        if not debug:
            debug = self.DEBUG
        if sys.platform == 'win32':
            try:
                color_random_1 = [
                    colorama.Fore.GREEN, colorama.Fore.YELLOW,
                    colorama.Fore.LIGHTWHITE_EX, colorama.Fore.LIGHTCYAN_EX,
                    colorama.Fore.LIGHTMAGENTA_EX, colorama.Fore.GREEN,
                    colorama.Fore.YELLOW, colorama.Fore.LIGHTWHITE_EX,
                    colorama.Fore.LIGHTCYAN_EX, colorama.Fore.LIGHTMAGENTA_EX,
                    colorama.Fore.GREEN, colorama.Fore.YELLOW,
                    colorama.Fore.LIGHTWHITE_EX, colorama.Fore.LIGHTCYAN_EX,
                    colorama.Fore.LIGHTMAGENTA_EX, colorama.Fore.GREEN,
                    colorama.Fore.YELLOW, colorama.Fore.LIGHTWHITE_EX,
                    colorama.Fore.LIGHTCYAN_EX, colorama.Fore.LIGHTMAGENTA_EX,
                    colorama.Fore.GREEN, colorama.Fore.YELLOW,
                    colorama.Fore.LIGHTWHITE_EX, colorama.Fore.LIGHTCYAN_EX,
                    colorama.Fore.LIGHTMAGENTA_EX, colorama.Fore.GREEN,
                    colorama.Fore.YELLOW, colorama.Fore.LIGHTWHITE_EX,
                    colorama.Fore.LIGHTCYAN_EX, colorama.Fore.LIGHTMAGENTA_EX
                ]
                self.color_random_error = False
            except:
                self.color_random_error = True
                pass
        else:
            color_random_1 = [
                colorama.Fore.GREEN, colorama.Fore.YELLOW, colorama.Fore.WHITE,
                colorama.Fore.CYAN, colorama.Fore.MAGENTA, colorama.Fore.GREEN,
                colorama.Fore.YELLOW, colorama.Fore.WHITE, colorama.Fore.CYAN,
                colorama.Fore.MAGENTA, colorama.Fore.GREEN,
                colorama.Fore.YELLOW, colorama.Fore.WHITE, colorama.Fore.CYAN,
                colorama.Fore.MAGENTA, colorama.Fore.GREEN,
                colorama.Fore.YELLOW, colorama.Fore.WHITE, colorama.Fore.CYAN,
                colorama.Fore.MAGENTA, colorama.Fore.GREEN,
                colorama.Fore.YELLOW, colorama.Fore.WHITE, colorama.Fore.CYAN,
                colorama.Fore.MAGENTA, colorama.Fore.GREEN,
                colorama.Fore.YELLOW, colorama.Fore.WHITE, colorama.Fore.CYAN,
                colorama.Fore.MAGENTA
            ]
        try:
            colorama.init()
        except:
            pass
        formatlist = ''
        try:
            arrow = colorama.Fore.YELLOW + ' -> '
        except:
            arrow = ' -> '
        if print_function_parameters:
            for i in args:
                if i == 'self':
                    pass
                else:
                    try:
                        formatlist = termcolor.colored(
                            (str(i) + ": "),
                            'white', 'on_blue') + color_random_1[int(
                                args.index(i))] + str(values[i]) + arrow
                    except:
                        formatlist = str(i) + ": " + str(values[i]) + arrow
                    if not defname:
                        defname = str(inspect.stack()[1][3])
                    if filename == None:
                        filename = sys.argv[0]
                    linenumbers = str(inspect.stack()[1][2])
                    try:
                        formatlist = termcolor.colored(
                            datetime.datetime.strftime(datetime.datetime.now(),
                                                       '%Y:%m:%d~%H:%M:%S:%f'),
                            'white') + " " + termcolor.colored(
                                defname + arrow, 'white',
                                'on_red') + formatlist + " " + "[" + str(
                                    filename) + "]" + " [" + termcolor.colored(
                                        str(linenumbers), 'white',
                                        'on_cyan') + "] "
                    except:
                        formatlist = datetime.datetime.strftime(
                            datetime.datetime.now(), '%Y:%m:%d~%H:%M:%S:%f'
                        ) + " " + defname + arrow + formatlist + " " + "[" + str(
                            filename) + "]" + " [" + str(linenumbers) + "] "
                    if debug:
                        print formatlist
                    if DEBUG_SERVER:
                        self.debug_server_client(formatlist)
            return formatlist
        if not kwargs == {}:
            for i in kwargs:
                #formatlist += color_random_1[kwargs.keys().index(i)] + i + ": " + color_random_1[kwargs.keys().index(i)] + str(kwargs.get(i)) + arrow
                try:
                    if str(kwargs.get(str(i))) == '':
                        formatlist += termcolor.colored(
                            (str(i)), 'white', 'on_blue') + arrow
                    else:
                        formatlist += termcolor.colored(
                            (str(i) + ": "), 'white',
                            'on_blue') + color_random_1[kwargs.keys().index(
                                i)] + str(kwargs.get(str(i))) + arrow
                except:
                    try:
                        print termcolor.colored("DEBUGGER ERROR !",
                                                'white',
                                                'on_red',
                                                attrs=['bold', 'blink'])
                    except:
                        pass
                    #traceback.format_exc()
                    try:
                        if str(kwargs.get(str(i))) == '':
                            formatlist += str(i) + arrow
                        else:
                            formatlist += str(i) + ": " + str(
                                kwargs.get(str(i))) + arrow
                    except:
                        traceback.format_exc()
        else:
            try:
                formatlist += random.choice(
                    color_random_1) + " start... " + arrow
            except:
                try:
                    formatlist += " start... " + arrow
                except:
                    formatlist += " start... " + ' -> '
        formatlist = formatlist[:-4]

        if defname:
            if filename == None:
                #frame = inspect.stack()[1]
                #module = inspect.getmodule(frame[0])
                #filename = module.__file__
                #filename = inspect.stack()[2][3]
                filename = sys.argv[0]
            #defname = defname + " [" + str(inspect.stack()[0][2]) + "] "
            try:
                formatlist = termcolor.colored(
                    datetime.datetime.strftime(datetime.datetime.now(),
                                               '%Y:%m:%d~%H:%M:%S:%f'),
                    'white') + " " + termcolor.colored(
                        defname + arrow, 'white',
                        'on_red') + formatlist + " " + "[" + str(
                            filename) + "]" + " " + termcolor.colored(
                                "[", "cyan") + termcolor.colored(
                                    str(linenumbers)[2:-2], 'white',
                                    'on_cyan') + termcolor.colored(
                                        "]", "cyan")
            except:
                formatlist = datetime.datetime.strftime(
                    datetime.datetime.now(), '%Y:%m:%d~%H:%M:%S:%f'
                ) + " " + defname + arrow + formatlist + " " + "[" + str(
                    filename) + "]" + " " + "[" + str(linenumbers)[2:-2] + "]"
        else:
            defname = str(inspect.stack()[1][3])
            try:
                line_number = " [" + termcolor.colored(
                    str(inspect.stack()[1][2]), 'white', 'on_cyan') + "] "
            except:
                line_number = " [" + str(inspect.stack()[1][2]) + "] "
            if filename == None:
                filename = sys.argv[0]
                #filename = inspect.stack()[2][3]
                #frame = inspect.stack()[1]
                #module = inspect.getmodule(frame[0])
                #filename = module.__file__
                #f = sys._current_frames().values()[0]
                #filename = f.f_back.f_globals['__file__']
            try:
                formatlist = termcolor.colored(
                    datetime.datetime.strftime(datetime.datetime.now(),
                                               '%Y:%m:%d~%H:%M:%S:%f'),
                    'white') + " " + termcolor.colored(
                        defname + arrow, 'white',
                        'on_red') + formatlist + " " + "[" + str(
                            filename) + " [" + termcolor.colored(
                                str(inspect.stack()[1][2]), 'white',
                                'on_cyan') + "] " + line_number
            except:
                formatlist = datetime.datetime.strftime(
                    datetime.datetime.now(), '%Y:%m:%d~%H:%M:%S:%f'
                ) + " " + defname + arrow + formatlist + " " + "[" + str(
                    filename) + " [" + str(
                        inspect.stack()[1][2]) + "] " + line_number
        if debug:
            try:
                print formatlist
                colorama.reinit()
            except:
                pass
        if DEBUG_SERVER:
            self.debug_server_client(formatlist + " [%s]" % (PID))
        #if debug_server:
        #self.debug_server_client(formatlist)
        return formatlist
Exemple #30
0
def print_cyan(string):
    if windows_client(): reinit()
    print(Fore.CYAN + Style.BRIGHT + string + Style.RESET_ALL)
    if windows_client(): deinit()
Exemple #31
0
    def _verbose(self,
                 epoch,
                 step,
                 loss_list,
                 cumulated_reward_list,
                 eval_trajectory_list,
                 oneline=True,
                 dry_run=False):
        # TODO: Check flow code:
        #       Often values to be printed are calculated "a priori" but then conditions to be printed aren't met being useless the first calculations
        def compute_gap(value, threshold):
            if threshold is None:
                return float("nan")
            return (value - threshold) / threshold

        reward_threshold_list = [
            env.spec.reward_threshold for env in self.env_eval_list
        ]
        loss_array = np.array(loss_list)
        loss_mean, loss_std = (loss_array.mean(),
                               loss_array.std()) if loss_array.size > 0 else (
                                   np.nan, np.nan)
        reward_gap_list = list(
            map(compute_gap, cumulated_reward_list, reward_threshold_list))
        if oneline:
            # template = "W{:.1f}T{:.1f}E{:.1f} | Epoch {:5d} ({:7d} steps) | early {:4d} | exploration {:.8f} | reward {:.8f} | loss mean {:.8f} | loss std {:.8f} {}"
            delta_time = time.time() - self.times['t_ini']
            # steps_per_second = int(step//delta_time)
            self.ema = compute_ema_from_list(
                self.ema,
                self.times['t_step_delta_list'])  # Exponential moving average
            self.times['t_step_delta_list'] = list()
            template = (
                "{:.1f}s | Ech {:3d} (step {:5d} {:4.1f}/s) | ear {:4d} | ε {:.4f} | lmean {:7.4e} | lstd {:7.4e} |"
                + " |".join([" r {:.4f} (gap {:.2f})"] *
                            len(cumulated_reward_list)) + " {}")
            line = template.format(
                delta_time,  # times['t_tr_tot'], times['t_ev_tot'],
                epoch,
                step,
                self.ema,
                self.early_stop_max_iterations - self.early_stop_iterations,
                self.agent.explore(),
                loss_mean,
                loss_std,
                *chain.from_iterable([
                    (cumulated_reward, reward_gap)
                    for cumulated_reward, reward_gap in zip(
                        cumulated_reward_list, reward_gap_list)
                ]),
                self.agent.update_msg,
            )
            if self.early_stop_iterations == 0:
                if os.isatty(sys.stdout.fileno()):
                    # template = "\033[31m" + template + "\033[39m"
                    reinit()
                    print(Fore.GREEN + line + Style.RESET_ALL, flush=True)
                    deinit()
                else:
                    print("> " + line, flush=True)
                solution_array = np.array([
                    step.action for step in eval_trajectory_list[0]
                ]).ravel().tolist()
                if len(solution_array) <= 40:
                    print("Solution:", solution_array)
            elif time.time(
            ) - self.time_last_msg > 1.0 or self.agent.update_flag:
                print(line, flush=True)
                self.time_last_msg = time.time()
            if self.agent.update_flag:  # If update_flag is True then update_msg has text. After print, clean
                self.agent.update_msg = ""
                self.agent.update_flag = False  # To avoid reassing every time (cheaper check)
        else:
            print("Training summary of epoch {} ({} steps):".format(
                epoch, steps))
            print("  Training mean (std) loss: {} ({})".format(
                loss_mean, loss_std))
            print("  Evaluation reward: {}".format(cumulated_reward_list))
            print("  Early iter remaining: {}".format(
                self.early_stop_max_iterations - self.early_stop_iterations))
Exemple #32
0
def print_yellow(string):
    if find_client() == 2: reinit()
    print(Fore.YELLOW + Style.BRIGHT + string + Style.RESET_ALL)
    if find_client() == 2: deinit()
Exemple #33
0
 def __enter__(self):
     if self._has_initialized:
         reinit()
Exemple #34
0
def color_enable():
    global COLORS_ENABLED
    COLORS_ENABLED = True
    colorama.reinit()