Python colorama.Fore.LIGHTYELLOW_EX Examples

The following are 18 code examples of colorama.Fore.LIGHTYELLOW_EX(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module colorama.Fore , or try the search function .
Example #1
Source File: cmd2.py    From WebPocket with GNU General Public License v3.0 7 votes vote down vote up
def perror(self, err: Union[str, Exception], traceback_war: bool=True, err_color: str=Fore.LIGHTRED_EX,
               war_color: str=Fore.LIGHTYELLOW_EX) -> None:
        """ Print error message to sys.stderr and if debug is true, print an exception Traceback if one exists.

        :param err: an Exception or error message to print out
        :param traceback_war: (optional) if True, print a message to let user know they can enable debug
        :param err_color: (optional) color escape to output error with
        :param war_color: (optional) color escape to output warning with
        """
        if self.debug:
            import traceback
            traceback.print_exc()

        if isinstance(err, Exception):
            err_msg = "EXCEPTION of type '{}' occurred with message: '{}'\n".format(type(err).__name__, err)
        else:
            err_msg = "{}\n".format(err)
        err_msg = err_color + err_msg + Fore.RESET
        self.decolorized_write(sys.stderr, err_msg)

        if traceback_war and not self.debug:
            war = "To enable full traceback, run the following command:  'set debug true'\n"
            war = war_color + war + Fore.RESET
            self.decolorized_write(sys.stderr, war) 
Example #2
Source File: settings.py    From evo_slam with GNU General Public License v3.0 6 votes vote down vote up
def update_if_outdated():
    """
    Update user settings to a new version if needed.
    """
    if open(USER_ASSETS_VERSION_PATH).read() == PACKAGE_VERSION:
        return
    from evo.tools.settings_template import DEFAULT_SETTINGS_DICT
    old_settings = json.loads(open(DEFAULT_PATH).read())
    updated_settings = merge_dicts(old_settings, DEFAULT_SETTINGS_DICT,
                                   soft=True)
    write_to_json_file(DEFAULT_PATH, updated_settings)
    open(USER_ASSETS_VERSION_PATH, 'w').write(PACKAGE_VERSION)
    print("{}Updated outdated {}{}".format(Fore.LIGHTYELLOW_EX, DEFAULT_PATH,
                                           Fore.RESET))


# Load the user settings into this container. 
Example #3
Source File: settings.py    From evo_slam with GNU General Public License v3.0 6 votes vote down vote up
def initialize_if_needed():
    """
    Initialize evo user folder after first installation
    (or if it was deleted).
    """
    if not os.path.isdir(USER_ASSETS_PATH):
        os.makedirs(USER_ASSETS_PATH)

    if not os.path.exists(USER_ASSETS_VERSION_PATH):
        open(USER_ASSETS_VERSION_PATH, 'w').write(PACKAGE_VERSION)

    if not os.path.exists(DEFAULT_PATH):
        try:
            reset(dest=DEFAULT_PATH)
            print("{}Initialized new {}{}".format(Fore.LIGHTYELLOW_EX,
                                                  DEFAULT_PATH, Fore.RESET))
        except:
            logger.error("Fatal: failed to write package settings file {}".
                         format(DEFAULT_PATH))
            raise 
Example #4
Source File: settings.py    From evo with GNU General Public License v3.0 6 votes vote down vote up
def update_if_outdated():
    """
    Update user settings to a new version if needed.
    """
    if open(USER_ASSETS_VERSION_PATH).read() == PACKAGE_VERSION:
        return
    from evo.tools.settings_template import DEFAULT_SETTINGS_DICT
    old_settings = json.loads(open(DEFAULT_PATH).read())
    updated_settings = merge_dicts(old_settings, DEFAULT_SETTINGS_DICT,
                                   soft=True)
    write_to_json_file(DEFAULT_PATH, updated_settings)
    open(USER_ASSETS_VERSION_PATH, 'w').write(PACKAGE_VERSION)
    print("{}Updated outdated {}{}".format(Fore.LIGHTYELLOW_EX, DEFAULT_PATH,
                                           Fore.RESET))


# Load the user settings into this container. 
Example #5
Source File: settings.py    From evo with GNU General Public License v3.0 6 votes vote down vote up
def initialize_if_needed():
    """
    Initialize evo user folder after first installation
    (or if it was deleted).
    """
    if not os.path.isdir(USER_ASSETS_PATH):
        os.makedirs(USER_ASSETS_PATH)

    if not os.path.exists(USER_ASSETS_VERSION_PATH):
        open(USER_ASSETS_VERSION_PATH, 'w').write(PACKAGE_VERSION)

    if not os.path.exists(DEFAULT_PATH):
        try:
            reset(dest=DEFAULT_PATH)
            print("{}Initialized new {}{}".format(Fore.LIGHTYELLOW_EX,
                                                  DEFAULT_PATH, Fore.RESET))
        except:
            logger.error("Fatal: failed to write package settings file {}".
                         format(DEFAULT_PATH))
            raise 
Example #6
Source File: save.py    From Lyndor with MIT License 6 votes vote down vote up
def chapters(url, course_folder_path):
    ''' create chapters folder '''
    soup = create_soup(url)
    heading4 = soup.find_all('h4', {"class": "ga"})
    chapter_no = 0

    message.colored_message(Fore.LIGHTYELLOW_EX, "Creating Chapters:\n") # Print message

    
    for h in heading4:
        chapter = format_chapter(h.text, chapter_no)
        chapter_no += 1
        message.print_line(chapter)

        new_chapter = course_folder_path + "/" + chapter
        new_chapter = new_chapter.strip()
        os.mkdir(new_chapter) # create folders (chapters)
            
    message.colored_message(Fore.LIGHTGREEN_EX, '\n✅  '+str(chapter_no)+' chapters created!!\n') 
Example #7
Source File: prox.py    From proxy-checker with MIT License 5 votes vote down vote up
def check_proxy(proxy):
    '''
        Function for check proxy return ERROR
        if proxy is Bad else
        Function return None
    '''
    try:
        session = requests.Session()
        session.headers['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36'
        session.max_redirects = 300
        proxy = proxy.split('\n',1)[0]
        print(Fore.LIGHTYELLOW_EX + 'Checking ' + proxy)
        session.get(URL, proxies={'http':'http://' + proxy}, timeout=TIMEOUT,allow_redirects=True)
    except requests.exceptions.ConnectionError as e:
        print(Fore.LIGHTRED_EX + 'Error!')
        return e
    except requests.exceptions.ConnectTimeout as e:
        print(Fore.LIGHTRED_EX + 'Error,Timeout!')
        return e
    except requests.exceptions.HTTPError as e:
        print(Fore.LIGHTRED_EX + 'HTTP ERROR!')
        return e
    except requests.exceptions.Timeout as e:
        print(Fore.LIGHTRED_EX + 'Error! Connection Timeout!')
        return e
    except urllib3.exceptions.ProxySchemeUnknown as e:
        print(Fore.LIGHTRED_EX + 'ERROR unkown Proxy Scheme!')
        return e
    except requests.exceptions.TooManyRedirects as e:
        print(Fore.LIGHTRED_EX + 'ERROR! Too many redirects!')
        return e 
Example #8
Source File: shell.py    From unipacker with GNU General Public License v2.0 5 votes vote down vote up
def address_updated(self, address):
        self.address = address
        self.prompt = f"{Fore.LIGHTYELLOW_EX}[0x{address:02x}]> {Fore.RESET}" 
Example #9
Source File: shell.py    From unipacker with GNU General Public License v2.0 5 votes vote down vote up
def get_path_from_user(self, known_samples):
        print("Your options for today:\n")
        lines = []
        for i, s in enumerate(known_samples):
            if s == "New sample...":
                lines += [(f"\t[{i}]", f"{Fore.LIGHTYELLOW_EX}New sample...{Fore.RESET}", "")]
            else:
                label, name = s.split(";")
                lines += [(f"\t[{i}]", f"{Fore.LIGHTBLUE_EX}{label}:{Fore.RESET}", name)]
        print_cols(lines)
        print()

        while True:
            try:
                id = int(input("Enter the option ID: "))
            except ValueError:
                print("Error parsing ID")
                continue
            if 0 <= id < len(known_samples) - 1:
                path = known_samples[id].split(";")[1]
            elif id == len(known_samples) - 1:
                path = input("Please enter the sample path (single file or directory): ").rstrip()
            else:
                print(f"Invalid ID. Allowed range: 0 - {len(known_samples) - 1}")
                continue
            if os.path.exists(path):
                return path
            else:
                print("Path does not exist")
                continue 
Example #10
Source File: headers.py    From unipacker with GNU General Public License v2.0 5 votes vote down vote up
def print_iat(uc, base_addr):
    imp = parse_memory_to_header(uc, base_addr, "IMPORTS")
    print(f"{Fore.LIGHTYELLOW_EX}IMPORT ADDRESS TABLE:{Fore.RESET}")
    for i in imp:
        indent = '\t'
        if i.Name == 0:
            return
        print(f"{indent} Name: {Fore.LIGHTRED_EX}{get_string(base_addr + i.Name, uc)}{Fore.RESET}")
        print(f"{indent} Characteristics (Hint/Name): {Fore.LIGHTRED_EX}{hex(i.Characteristics)}{Fore.RESET}")
        print(f"{indent} TimeDateStamp: {Fore.LIGHTRED_EX}{hex(i.TimeDateStamp)}{Fore.RESET}")
        print(f"{indent} ForwarderChain: {Fore.LIGHTRED_EX}{hex(i.ForwarderChain)}{Fore.RESET}")
        print(f"{indent} FirstThunk: {Fore.LIGHTRED_EX}{hex(i.FirstThunk)}{Fore.RESET}")
        indent = '\t\t'

        if i.Characteristics == 0:
            print(f"{indent} Hint/Name Array is not set")
        else:
            curr_pos = 0
            imp_array_element = struct.unpack("<I", uc.mem_read(base_addr + i.Characteristics, 4))[0]
            if (imp_array_element >> 20) == 0x1 and ((imp_array_element & 0xFFEFFFFF) >> 14) == 0x1:
                print(f"{indent}No resolving of imports as hookaddr values are set")
                continue
            while imp_array_element != 0:
                if imp_array_element >> 0x1f == 1:
                    print(f"{indent} Import by Ordinal: "
                          f"{Fore.LIGHTRED_EX}{hex(imp_array_element - 0x80000000)}{Fore.RESET}")
                else:
                    print(f"{indent} Import by Name: "
                          f"{Fore.LIGHTRED_EX}{get_string(base_addr + imp_array_element + 0x2, uc)}{Fore.RESET}")
                curr_pos += 0x4
                imp_array_element = struct.unpack("<I", uc.mem_read(base_addr + i.Characteristics + curr_pos, 4))[0]

            print() 
Example #11
Source File: headers.py    From unipacker with GNU General Public License v2.0 5 votes vote down vote up
def print_struc_rec(s, offset, name, indent='\t', array_dict=None):
    if name is not None:
        print(f"{Fore.LIGHTYELLOW_EX}{name}:{Fore.RESET}")
    for field_name, field_type in s._fields_:
        if isinstance(getattr(s, field_name), Array):
            print(indent + f" +0x{offset:02x} {field_name}:")
            new_indent = indent
            for i in range(len(getattr(s, field_name))):
                if array_dict is not None:
                    new_indent = '\t' + new_indent
                    print(new_indent + f" +0x{offset:02x} {array_dict[i]}:")
                if hasattr(getattr(s, field_name)[i], "_fields_"):
                    offset = print_struc_rec(getattr(s, field_name)[i], offset, None, '\t' + new_indent)
                else:
                    print(indent + f" +0x{offset:02x} {field_name}: {getattr(s, field_name)}")
                new_indent = indent
        else:
            if isinstance(getattr(s, field_name), int):
                if "TimeDateStamp" in field_name:
                    print(f"{indent} +0x{offset:02x} {field_name}: "
                          f"{Fore.LIGHTRED_EX}"
                          f"{datetime.utcfromtimestamp(getattr(s, field_name)).strftime('%Y-%m-%d %H:%M:%S')}"
                          f"{Fore.RESET}")
                else:
                    print(f"{indent} +0x{offset:02x} {field_name}: "
                          f"{Fore.LIGHTRED_EX}{hex(getattr(s, field_name))}{Fore.RESET}")
            else:
                print(f"\t +0x{offset:02x} {field_name}: {getattr(s, field_name)}")
            offset += len(bytes(field_type()))
    return offset 
Example #12
Source File: rpsgame.py    From python-for-absolute-beginners-course with MIT License 5 votes vote down vote up
def get_roll(player_name, roll_names):
    if os.environ.get('PYCHARM_HOSTED') == "1":
        print(Fore.LIGHTRED_EX + "Warning: Cannot use fancy prompt dialog in PyCharm.")
        print(Fore.LIGHTRED_EX + "Run this app outside of PyCharm to see it in action.")
        val = input(Fore.LIGHTYELLOW_EX + "What is your roll: ")
        print(Fore.WHITE)
        return val

    print(f"Available rolls: {', '.join(roll_names)}.")

    # word_comp = WordCompleter(roll_names)
    word_comp = PlayComplete()

    roll = prompt(f"{player_name}, what is your roll: ", completer=word_comp)

    if not roll or roll not in roll_names:
        print(f"Sorry {player_name}, {roll} not valid!")
        return None

    return roll


# def get_roll(player_name, roll_names):
#     print("Available rolls:")
#     for index, r in enumerate(roll_names, start=1):
#         print(f"{index}. {r}")
#
#     text = input(f"{player_name}, what is your roll? ")
#     selected_index = int(text) - 1
#
#     if selected_index < 0 or selected_index >= len(rolls):
#         print(f"Sorry {player_name}, {text} is out of bounds!")
#         return None
#
#     return roll_names[selected_index]
# 
Example #13
Source File: exercise_file.py    From Lyndor with MIT License 5 votes vote down vote up
def use_aria2(url, course_folder, cookie_path, driver):
    ''' user aria2 to download exercise files '''
    # jump to course_folder
    os.chdir(course_folder)

    # To be filled with all exercise file links /ajax/....
    exercise_file_urls = []
    files = driver.find_elements_by_css_selector('.course-file')

    for file in files:
        url = file.get_attribute('href')
        exercise_file_urls.append(url)

    driver.find_element_by_css_selector('#exercise-tab').click()
    exercises = driver.find_elements_by_css_selector('a > .exercise-name')

    for exercise in exercises:
        exercise_message = message.return_colored_message(Fore.LIGHTYELLOW_EX, exercise.text)
        print(f"To be Downloaded: {exercise_message}")


    total_ex_files = len(exercise_file_urls)
    counter = 1
    for url in exercise_file_urls:
        print(message.return_colored_message(Fore.LIGHTYELLOW_EX, f"\nDownloading {counter} of {total_ex_files}"))
        counter += 1
        os.system("aria2c --load-cookie='{}' {}".format(cookie_path, url)) 
Example #14
Source File: run.py    From Lyndor with MIT License 5 votes vote down vote up
def main():
    ''' Main function '''
    init()
    message.animate_characters(Fore.LIGHTYELLOW_EX, draw.ROCKET, 0.02)
    message.spinning_cursor()
    message.print_line('\r1. Paste course url or\n' +
    '2. Press enter for Bulk Download')
    
    url = input()
    
    print('')
    start_time = time.time() #start time counter begins
    if url == "":
        # If user press Enter (i.e. url empty), get urls from Bulkdownload.txt
        urls = read.bulk_download()
        if not urls:
            sys.exit(message.colored_message(Fore.LIGHTRED_EX, 'Please paste urls in Bulk Download.txt\n'))
        for url in urls:
            schedule_download(url)
    else:
        # begin regular download
        schedule_download(url)
    try:
        end_time = time.time()
        message.animate_characters(Fore.LIGHTGREEN_EX, draw.COW, 0.02)
        message.colored_message(Fore.LIGHTGREEN_EX, "\nThe whole process took {}\n".format(move.hms_string(end_time - start_time)))
    except KeyboardInterrupt:
        sys.exit(message.colored_message(Fore.LIGHTRED_EX, "\n- Program Interrupted!!\n")) 
Example #15
Source File: cricket.py    From Jarvis with MIT License 5 votes vote down vote up
def scorecard(self, index):
        selected_match = self.all_match_data[index]
        data = self.c.scorecard(self.matches[index]['id'])
        card = {}
        card['matchinfo'] = "{}, {}".format(
            selected_match['srs'], selected_match['mnum'])
        card['status'] = "{}".format(selected_match['status'])
        card['scorecard'] = data['scorecard']
        text = ''
        text += Fore.LIGHTYELLOW_EX + \
            card['matchinfo'] + '\n' + card['status'] + '\n\n'
        text += Fore.BLACK + '*' * 35 + '\n\n'

        for scr in reversed(card['scorecard']):
            text += Fore.LIGHTYELLOW_EX + "{}\nInnings: {}\n{}/{} in {} overs\n\n".format(
                scr['batteam'], scr['inng_num'], scr['runs'], scr['wickets'], scr['overs'])
            text += Fore.BLUE + "Batting\n"
            text += Fore.RED + \
                "{:<17} {:<3} {:<3} {:<3} {}\n\n".format('Name', 'R', 'B', '4', '6')
            for b in scr['batcard']:
                text += Fore.BLACK + "{:<17} {:<3} {:<3} {:<3} {}\n{}\n\n".format(
                    b['name'], b['runs'], b['balls'], b['fours'], b['six'], b['dismissal'])
            text += Fore.LIGHTYELLOW_EX + "-" * 35 + "\n\n"
            text += Fore.BLUE + "Bowling\n"
            text += Fore.RED + \
                "{:<17} {:<5} {:<3} {:<3} {}\n\n".format('Name', 'O', 'M', 'R', 'W')
            for b in scr['bowlcard']:
                text += Fore.BLACK + "{:<17} {:<5} {:<3} {:<3} {}\n\n".format(
                    b['name'], b['overs'], b['maidens'], b['runs'], b['wickets'])
            text += Fore.BLUE + '*' * 35 + '\n\n'
        return text 
Example #16
Source File: cricket.py    From Jarvis with MIT License 5 votes vote down vote up
def commentary(self, index):
        selected_match = self.all_match_data[index]
        data = self.c.commentary(self.matches[index]['id'])
        comm = {}
        comm['matchinfo'] = "{}, {}".format(
            selected_match['srs'], selected_match['mnum'])
        comm['status'] = "{}".format(selected_match['status'])
        comm['commentary'] = data['commentary']
        text = []
        for com in comm['commentary']:
            line = ''
            if com['over']:
                line += com['over'] + ' : '
            line += "{}\n\n".format(com['comm'])
            # doing bold breaklines and italics looks good in terminal
            text.append(
                line.replace(
                    '<b>',
                    '\033[1m').replace(
                    '</b>',
                    '\033[0m') .replace(
                    '<br/>',
                    '\n').replace(
                    '<i>',
                    '\x1B[3m').replace(
                        '</i>',
                    '\x1B[23m'))

        text.reverse()

        commentary = Fore.LIGHTYELLOW_EX + \
            comm['matchinfo'] + '\n' + comm['status'] + '\n\n' + Fore.RESET
        for line in text:
            commentary += line

        return commentary 
Example #17
Source File: cricket.py    From Jarvis with MIT License 5 votes vote down vote up
def live_score(self, index):
        if self.all_match_data[index]['mchstate'] == 'preview':
            return(Fore.RED + "MATCH YET TO BEGIN")
        selected_match = self.all_match_data[index]
        data = self.c.livescore(self.matches[index]['id'])
        score = {}
        score['matchinfo'] = "{}, {}".format(
            selected_match['srs'], selected_match['mnum'])
        score['status'] = "{}".format(selected_match['status'])
        score['bowling'] = data['bowling']
        score['batting'] = data['batting']

        text = ''
        text += Fore.LIGHTYELLOW_EX + \
            score['matchinfo'] + '\n' + score['status'] + '\n\n'

        text += Fore.BLUE + score['batting']['team'] + Fore.BLACK
        for scr in reversed(score['batting']['score']):
            text += " :- {}/{} in {} overs\n".format(
                scr['runs'], scr['wickets'], scr['overs'])
        for b in reversed(score['batting']['batsman']):
            text += "{} : {}({}) \n".format(
                b['name'].strip('*'), b['runs'], b['balls'])

        text += Fore.BLUE + '\n' + score['bowling']['team'] + Fore.BLACK
        for scr in reversed(score['bowling']['score']):
            text += " :- {}/{} in {} overs\n".format(
                scr['runs'], scr['wickets'], scr['overs'])
        for b in reversed(score['bowling']['bowler']):
            text += "{} : {}/{} \n".format(b['name'].strip('*'),
                                           b['wickets'], b['runs'])
        text += Fore.RESET

        return text 
Example #18
Source File: exercise_file.py    From Lyndor with MIT License 4 votes vote down vote up
def use_selenium(url, course_folder, driver):
    ''' use just selenium to download files '''

    # injecting jquery
    jquery = requests.get(url="https://code.jquery.com/jquery-3.3.1.min.js")
    driver.execute_script(jquery.text)
    
    # delete .exercise-tab max-height:320px so that all the ex_files can be seen
    driver.execute_script("$('.exercise-tab .content').css('max-height', 'none');")

    # Maximize Window if exercise-tab element not visible
    WebDriverWait(driver, 15).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "#exercise-tab")))
    driver.find_element_by_css_selector('#exercise-tab').click()

    # Make sure page is more fully loaded before finding the element
    WebDriverWait(driver, 15).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "html.no-touch.member.loaded")))

    exercises = driver.find_elements_by_css_selector('a > .exercise-name')

    try:
        for exercise in exercises:
                print(f"Downloading: {exercise.text}")
                exercise.click()
    except Exception as e:
        sys.exit(e)

    time.sleep(4)                                       # Give some heads up time to downloads

    downloads_folder = install.get_path("Downloads")
    os.chdir(downloads_folder)

    message.spinning_cursor()    
    while len(exercises) > 0:                           # until exercises[] gets empty
        sys.stdout.write('\033[F\033[F')
        sys.stdout.flush()                              # Force Python to write data into terminal.
        
        for folder in os.listdir(downloads_folder):
            sys.stdout.write("\033[K")                  # Clear to the end of line
            sys.stdout.write(f"\rFinding Ex_file in Downloads folder --->  {message.return_colored_message(Fore.LIGHTYELLOW_EX, folder)}")
            sys.stdout.flush()                          # Force Python to write data into terminal

            for exercise in exercises:
                if folder == exercise.text:
                    if os.path.getsize(folder) > 0:     # if file downloaded completely.
                        try:
                            shutil.move(exercise.text, course_folder)
                            print(f'\nMoved to course folder: {exercise.text}')
                        except:
                            print('\nMoving error: File already exists.')
                        
                        exercises.remove(exercise)      # pop out moved exercise file from exercises list
                        break                           # break inner for-loop when ex-file downloaded
            
            if(len(exercises) == 0):                    # if all exercises downloaded successfully
                break                                   # break outer for-loop and stop scanning Downloads folder

            # time.sleep(0.02)                            # delay to print which file is being scanned

    driver.close()                                      # close web browser