Ejemplo n.º 1
0
    def test_text_spinner_color(self):
        """Test basic spinner with available colors color (both spinner and text)
        """
        for color, color_int in COLORS.items():
            self._stream_file = os.path.join(self.TEST_FOLDER, 'test.txt')
            self._stream = io.open(self._stream_file, 'w+')

            spinner = Halo(
                text='foo',
                text_color=color,
                color=color,
                spinner='dots',
                stream=self._stream
            )

            spinner.start()
            time.sleep(1)
            spinner.stop()
            output = self._get_test_output()['colors']

            # check if spinner colors match
            self.assertEqual(color_int, int(output[0][0]))
            self.assertEqual(color_int, int(output[1][0]))
            self.assertEqual(color_int, int(output[2][0]))

            # check if text colors match
            self.assertEqual(color_int, int(output[0][1]))
            self.assertEqual(color_int, int(output[1][1]))
            self.assertEqual(color_int, int(output[2][1]))
Ejemplo n.º 2
0
def apply_formatting(pargs: Namespace, formatting: int, s: str) -> str:
    if not use_colour(pargs):
        return s

    formatting_codes: str = ''
    formats_to_apply: [str]
    if type(formatting) == list:
        formats_to_apply = formatting
    else:
        formats_to_apply = [formatting]
    colour: str = None
    on_colour: str = None
    attrs: str = []
    for format_to_apply in formats_to_apply:
        if format_to_apply in COLOURS:
            colour = format_to_apply
        elif format_to_apply in HIGHLIGHTS:
            on_colour = format_to_apply
        elif format_to_apply in ATTRIBUTES:
            attrs.append(format_to_apply)
        elif format_to_apply is None:
            pass
        else:
            print('Unknown format "%s" acceptible values %s' %
                  (format_to_apply,
                   str([None] + list(COLOURS.keys()) +
                       list(HIGHLIGHTS.keys()) + list(ATTRIBUTES.keys()))),
                  file=stderr)
            exit(1)

    return coloured(s, color=colour, on_color=on_colour, attrs=attrs)
Ejemplo n.º 3
0
    def test_spinner_color(self):
        """Test ANSI escape characters are present
        """

        for color, color_int in COLORS.items():
            spinner = HaloNotebook(color=color)
            spinner.start()
            output = self._get_test_output(spinner, no_ansi=False)
            spinner.stop()

            output_merged = [arr for c in output['colors'] for arr in c]

            self.assertEquals(str(color_int) in output_merged, True)
Ejemplo n.º 4
0
 def get_colored_style(self, spec):
     c, s = spec, None
     try:
         c, s = spec.split("|")
         s = s.split(",")
     except Exception:
         pass
     # assuming correct colors are given, if _col_ is not in colors
     # we assume it's one (or list of) styling, especially if none are given
     if c not in COLORS.keys() and not s:
         s = c.split(',')
         c = None
     return (c, s)
Ejemplo n.º 5
0
def color_picker(color_list=None):
    import itertools

    if not color_list:
        for color_list in itertools.repeat(COLORS.keys()):
            for list_elem in color_list:
                yield list_elem
    else:
        for color in color_list:
            yield color

        while True:
            yield color_list[0]
Ejemplo n.º 6
0
    def test_spinner_color(self):
        """Test ANSI escape characters are present
        """

        for color, color_int in COLORS.items():
            self._stream = io.open(self._stream_file, 'w+')  # reset stream
            spinner = Halo(color=color, stream=self._stream)
            spinner.start()
            spinner.stop()

            output = self._get_test_output(no_ansi=False)
            output_merged = [arr for c in output['colors'] for arr in c]

            self.assertEquals(str(color_int) in output_merged, True)
Ejemplo n.º 7
0
 def _new_tree(self):
     self.boughs = (['*'] +
                       sum([self._bough(n)
                            for n in range(1, (self.height - 1) // 2)], []) +
                       self._bough((self.height - 1) // 2, True) + ['| |'])
     self.tree = '\n'.join([s.center(self.center)
                            for s in self.boughs])
     if self.blink:
         for i in self.ornament:
             self.tree = self.tree.replace(i, colored(i, choice(COLORS.keys()), attrs=['blink', 'bold']))
             if randint(0, 99) > 50:
                 self.tree = self.tree.replace(i, colored(choice(self.ornament), choice(COLORS.keys()), attrs=['blink', 'bold']))
         self.tree = self.tree.replace('/', colored('/', 'green', attrs=['bold'])).replace('\\', colored('\\', 'green', attrs=['bold']))
         self.tree = self.tree.replace('*', colored('*', 'green', attrs=['bold'])).replace('_', colored('_', 'green', attrs=['bold']))
         self.tree = self.tree.replace('|', colored('|', 'green', attrs=['bold']))
Ejemplo n.º 8
0
def main():
    import sys
    from docopt import docopt

    arguments = docopt(__doc__)

    try:
        if len(arguments['<cmd>']):
            color_iterator = None
            auto_colorize = arguments.get('-c')
            if auto_colorize:
                avoid = arguments['-a']
                if avoid:
                    avoid_list = ':'.join(avoid).split(':')
                    validate_color_list(avoid_list)
                    for e in avoid_list:
                        if COLORS.has_key(e):
                            del(COLORS[e])
                    if len(COLORS) < 1:
                        print colored('No colors left - exiting.')
                        sys.exit(1)

                color_iterator = color_picker()
            else:
                cmd_line_colors = arguments['-s']
                if len(cmd_line_colors):
                    # may be multiple -s on cli, so join them with a :, then create a list
                    color_list = ':'.join(cmd_line_colors).split(':')
                    validate_color_list(color_list)
                    color_iterator = color_picker(color_list)

            mcat = Mcat(arguments['<cmd>'], color_iterator)

            timeout = arguments.get('-t')
            if timeout is not None:
                timeout = float(timeout)
            else:
                timeout = 1.0

            mcat.run(timeout)

    except Exception as e:
        print 'Fatal problem encountered: ', type(e)
        print '\t', e
        print 'mcat will now exit...\n'
    except KeyboardInterrupt:
        pass
Ejemplo n.º 9
0
    def showKanban(self):
        """
        render kanban
        https://beautifultable.readthedocs.io/en/latest/quickstart.html
        """
        table = BeautifulTable()
        table.set_style(BeautifulTable.STYLE_COMPACT)
        project = self.config.get("project")

        rows_qnt = 0

        groups_list = {}
        for group in self.statuses_groups.getKeys():
            groups_list[group] = []

        for group in self.statuses_groups.getKeys():
            status_list = self.statuses_groups[group]
            statuses_str = ','.join(str(e) for e in status_list)
            jql = "project = " + project + " and assignee=currentUser() and status in (" + statuses_str + ")"
            tasks_list = []
            for task in self.searchIssues(jql)['issues']:
                task_color = task['fields']['status']['statusCategory'][
                    'colorName']
                if task_color not in COLORS.keys():
                    task_color = 'white'
                tasks_list.append(
                    colored(task['key'], task_color, attrs=['bold']))

            groups_list[group] = tasks_list
            if len(tasks_list) > rows_qnt:
                rows_qnt = len(tasks_list)

        for index, group in enumerate(self.statuses_groups.getKeys()):
            tasks_list = groups_list[group]
            rows = []
            r = 0
            while r <= rows_qnt:
                task = tasks_list[r] if r < len(tasks_list) else ''
                rows.append(task)
                r += 1

            group = colored(group, 'white', attrs=['bold'])

            table.insert_column(index, group, rows)

        print(table)
Ejemplo n.º 10
0
    def test_text_spinner_color(self):
        """Test basic spinner with available colors color (both spinner and text)
        """
        for color, color_int in COLORS.items():
            spinner = HaloNotebook(text='foo', text_color=color, color=color, spinner='dots')

            spinner.start()
            time.sleep(1)
            output = self._get_test_output(spinner)['colors']
            spinner.stop()

            # check if spinner colors match
            self.assertEqual(color_int, int(output[0][0]))
            self.assertEqual(color_int, int(output[1][0]))
            self.assertEqual(color_int, int(output[2][0]))

            # check if text colors match
            self.assertEqual(color_int, int(output[0][1]))
            self.assertEqual(color_int, int(output[1][1]))
            self.assertEqual(color_int, int(output[2][1]))
Ejemplo n.º 11
0
#!/usr/bin/env python
"""
Console output colorizator
Author: Alexander Artemenko <*****@*****.**>
Usage: tail -f some.log | colorize 'one.*pattern' 'another'
"""

import sys
import re

from termcolor import colored, COLORS
from itertools import starmap


COLORS = sorted([c for c in COLORS.keys() if c not in ('grey', 'white')])
COLORS = zip(COLORS, [[]] * len(COLORS)) + zip(COLORS, [['reverse']] * len(COLORS))

class Colorer:
    def __init__(self, regex, color):
        self.regex = re.compile(regex)
        self.color = color

    def __call__(self, line):
        return self.regex.sub(lambda x: colored(x.group(0), self.color[0], attrs = self.color[1]), line)

COLORERS = list(starmap(Colorer, zip(sys.argv[1:], COLORS)))

def process(line):
    for colorer in COLORERS:
        line = colorer(line)
    return line
Ejemplo n.º 12
0
        elif choice == '2':
            standing = True
            while value_of_card(dealer) <= 16:
                dealer.append(cards.pop())


##################

import random
import time
from termcolor import colored, COLORS

CARD_RANK = ("A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3", "2")
CARD_SUIT = ("♡", "♢", "♧", "♤")
SYSTEM_COLORS = ['grey', 'white']
PLAYER_COLORS = list(c for c in COLORS.keys() if c not in SYSTEM_COLORS)


class Card(object):
    """Represents an individual playing card"""
    def __init__(self, rank, suit):
        assert rank in CARD_RANK
        self.rank = rank
        assert suit in CARD_SUIT
        self.suit = suit

    def __repr__(self):
        return "{:>2}{}".format(self.rank, self.suit)

    def value(self):
        """Computes the value of a card according to Blackjack rules"""
Ejemplo n.º 13
0
import json
import click
from termcolor import colored, COLORS
from urllib.parse import urlencode
import webbrowser
import numpy as np
from config import *

os.system('color')

TWITCH_CLIENT_ID = 'e0fm2z7ufk73k2jnkm21y0gp1h9q2o'
COLORS.update({
    'light_grey': 90,
    'light_red': 91,
    'light_green': 92,
    'light_yellow': 93,
    'light_blue': 94,
    'light_magenta': 95,
    'light_cyan': 96,
    'light_white': 97
})


@click.group(invoke_without_command=True)
@click.pass_context
@click.option('--config', help='Configuration file location')
def main(ctx, config):
    """List or play Twitch streams"""
    if config is not None:
        set_config_path(config)

    load_config()
Ejemplo n.º 14
0
def show_colors():
    """Displays available text colors."""
    all_colors = " ".join([colored(name, name) for name in COLORS.keys()])
    cprint(all_colors)
Ejemplo n.º 15
0
import re
import curses
from termcolor import COLORS, RESET, ATTRIBUTES, HIGHLIGHTS
from .log import log

C_R = {'\x1b[%dm' % v: 'COLOR_%s' % k.upper() for k, v in COLORS.items()}
A_R = {'\x1b[%dm' % v: 'A_%s' % k.upper() for k, v in ATTRIBUTES.items()}
A_R['\x1b[3m'] = 'A_ITALIC'
H_R = {
    '\x1b[%dm' % v: 'COLOR_%s' % k[3:].upper()
    for k, v in HIGHLIGHTS.items()
}
COLORS_R = {'\x1b[%dm' % v: k for k, v in COLORS.items()}
COLOR_SCAN = re.compile(r'(\x1b\[\d+m)')
delete_sub = re.compile(r'(\x1b\[\d+\w)')
COLOR_SCAN2 = re.compile(r'(\x1b\[(\d+)\;?\d*m)')


def ascii2filter(words):
    if isinstance(words, list):
        strings = COLOR_SCAN2.sub('', ' '.join(words)).split()
    else:
        strings = COLOR_SCAN2.sub('', words)
    return strings


def fgascii2curses(context,
                   row,
                   col,
                   string,
                   colors=None,
Ejemplo n.º 16
0
def get_colors() -> List[str]:
    return [c for c in COLORS.keys()]
Ejemplo n.º 17
0
 def __init__(self):
     from termcolor import COLORS
     self.colors = sorted(list(COLORS.keys()))
     self.colors = [x for x in self.colors if x != 'white']
     self.n_colors = len(self.colors)
Ejemplo n.º 18
0
#!/usr/bin/env python

import itertools
import math
import pprint
import sys

try:
    from termcolor import colored, COLORS
    color_names = COLORS.keys()
    def print_depth(z):
        print colored("X", color_names[z % len(color_names)], attrs=["bold"]),
    print "Color key:"
    for i in range(len(color_names)):
        print i,
        print_depth(i)
        print ""
except ImportError:
    def print_depth(z):
        print chr(ord("A") + z),

if len(sys.argv) < 2:
    print "Usage: %s <circle|torus|sphere> <size>" % sys.argv[0]
    sys.exit()

if sys.argv[1] == "circle":
    if len(sys.argv) < 3:
        print "Circles need a size."
        sys.exit()

    size = int(sys.argv[2])
Ejemplo n.º 19
0
from pyfiglet import Figlet
from termcolor import colored, COLORS

text = input("What message do you want to print? ")
color = input("What color? ")

if color not in COLORS.keys():
    color = 'white'

# this is a really long comment that probably should be set over a couple
# of lines and cleaned up.
print(colored(Figlet().renderText(text), color))
Ejemplo n.º 20
0
from pyfiglet import Figlet
from termcolor import cprint, COLORS
import enquiries

allowed_colors = list(COLORS.keys())
msg = input('Text you wanna print? ')
choice = enquiries.choose('Choose one of these colors: ', allowed_colors)

cprint(Figlet().renderText(msg), choice)
Ejemplo n.º 21
0
3.Explicit is better than impliciplicit is better than plicit is better than t.
Simple is better than complex.   le is one two three four five six seven eight night ten
Complex is better than complicatelex is better than comlex is better than comd.
Flat is better than nested.       is better than nested is better than nested
Sparse is better than dense.     se is better than densse is better than dens
Readability counts.              ability counts.       ability counts.
Now is better than never.        is better than never. is better than never.
Although never is often better though never is often beough never is often bean *right* now.
If the implementation is hard to he implementation is hhe implementation is hexplain, it's a bad idea.
If the implementation is easy to he implementation is ehe implementation is eexplain, it may be a good idea.
Namespaces are one honking great spaces are one honkingspaces are one honkingidea -- let's do more of those!""".split(
    '\n')
T = [
    str(i) +
    termcolor.colored(v,
                      list(COLORS.keys())[i % len(COLORS)],
                      attrs=[list(ATTRIBUTES.keys())[i % len(ATTRIBUTES)]])
    for i, v in enumerate(T)
]
T = '\n'.join(T)


class Test(Stack):
    @listener(10)
    def enter(self):
        # res = Test.Popup(["hello", "world","more power","awsl", "这个是什么时代的啊啊啊啊","exit"], context=self, exit_key=147)

        res = TextPanel.Popup(T, context=self)
        msgBox(msg=res)

    @listener('i')
Ejemplo n.º 22
0
def build_regression_model(model_names: List[str], x_train: DataFrame, y_train: DataFrame,
                           max_cardinality: int, estimators: List[int], svr_kernel: List[str], poly_degree: List[int],
                           max_depth: List[int], random_state: int) -> \
        Dict[str, regression.AbstractRegression]:
    """
    Creates a dictionary based on a list of desired regression models

    Args:
        model_names (List[str]): List of regression models names.
        x_train (pandas.DataFrame): Independent variables from the training data.
        y_train (pandas.DataFrame): Dependent variable from the training data.
        max_cardinality (int): Maximum cardinality to apply OneHotEncoder
        estimators (List[int]): List of estimators for Random Forest Regression
        svr_kernel (List[str]): Kernel list names for Support Vector Regression
        poly_degree (List[int]): List of degrees for  Polynomial Regression
        max_depth (List[int]): Array of max_depth for Random Forest and Gradient Boosting
        random_state (int): Number used for initializing the internal random number generator

    Returns:
        Dict[str, AbstractRegression]: Dictionary containing the models specified in the models_names list
    """
    model_dict: Dict[str, regression.AbstractRegression] = dict()
    num_models = len(model_names)
    color_list = list(COLORS.keys())[1:]
    num_colors = len(color_list)
    circular_colors = [color_list[i % num_colors] for i in range(0, num_models)]

    for idx, model_name in enumerate(model_names):
        color = circular_colors[idx]
        if model_name == "MultipleLinearRegression":
            key_model = model_name
            model_dict[key_model] = regression.MultipleLinearRegression(max_cardinality=max_cardinality,
                                                                        print_color=color)
        elif model_name == "SupportVectorRegression":
            for kernel in svr_kernel:
                key_model = f'{model_name}_{kernel}Kernel'
                model_dict[key_model] = regression.SupportVectorRegression(max_cardinality=max_cardinality,
                                                                           kernel=kernel,
                                                                           print_color=color)
        elif model_name == "PolynomialRegression":
            for degree in poly_degree:
                key_model = f'{model_name}_{degree}Degree'
                model_dict[key_model] = regression.PolynomialRegression(max_cardinality=max_cardinality, degree=degree,
                                                                        print_color=color)
        elif model_name == "DecisionTreeRegression":
            key_model = model_name
            model_dict[key_model] = regression.DecisionTreeRegression(max_cardinality=max_cardinality,
                                                                      random_state=random_state,
                                                                      print_color=color)
        elif model_name == "RandomForestRegression":
            for depth in max_depth:
                for num_estimators in estimators:
                    key_model = f'{model_name}_{num_estimators}Estimators_{depth}MaxDepth'
                    model_dict[key_model] = regression.RandomForestRegression(max_cardinality=max_cardinality,
                                                                              random_state=random_state,
                                                                              num_estimators=num_estimators,
                                                                              max_depth=depth,
                                                                              print_color=color)
        elif model_name == 'GradientBoostingRegressor':
            for depth in max_depth:
                for num_estimators in estimators:
                    key_model = f'{model_name}_{num_estimators}Estimators_{depth}MaxDepth'
                    model_dict[key_model] = regression.GradientBoostedDecisionTrees(max_cardinality=max_cardinality,
                                                                                    random_state=random_state,
                                                                                    num_estimators=num_estimators,
                                                                                    max_depth=depth,
                                                                                    print_color=color)
    for _, model in model_dict.items():
        model.train_model(x_train=x_train, y_train=y_train)
    return model_dict
Ejemplo n.º 23
0
def validate_color_list(color_list):
    unknown_colors = set(color_list)-set(COLORS.keys())
    if len(unknown_colors) > 0:
        raise Exception('Unknown colors: %s' % ', '.join(list(unknown_colors)))
Ejemplo n.º 24
0
import re

from termcolor import cprint, colored, COLORS

mobile = '06 09-00-15-45'

# raw string
pattern1 = r'\d\d-\d\d-\d\d-\d\d-\d\d'
# add end of line $ ans start of line ^
pattern2 = r'\A\d\d-\d\d-\d\d-\d\d-\d\d$'
pattern3 = r'\A[0-9]{2}[ -]\d\d-\d\d-\d\d-\d\d$'
pattern4 = r'\A[0-9]{2}[ -]\d{2}-\d{2}-\d{2}-\d{2}'

for k, v in COLORS.items():
    print(f'{k}', end='  ')
print('\n')

if re.fullmatch(pattern4, mobile):
    cprint(f'{mobile} is accepted',
           'green',
           on_color='on_white',
           attrs=['bold'])
else:
    print(f'{mobile} is {colored("rejected", "grey", "on_red")}')

a_str = 'this is'


def test_exp(p):
    global a_str
    if re.match(p, a_str):
Ejemplo n.º 25
0
 def show_available_text_colors():
     print(COLORS.keys())