Ejemplo n.º 1
0
def test_custom_tablefmt():
    "Regression: allow custom TableFormat that specifies with_header_hide (github issue #20)"
    tablefmt = TableFormat(
        lineabove=Line("", "-", "  ", ""),
        linebelowheader=Line("", "-", "  ", ""),
        linebetweenrows=None,
        linebelow=Line("", "-", "  ", ""),
        headerrow=DataRow("", "  ", ""),
        datarow=DataRow("", "  ", ""),
        padding=0,
        with_header_hide=["lineabove", "linebelow"],
    )
    rows = [["foo", "bar"], ["baz", "qux"]]
    expected = "\n".join(["A    B", "---  ---", "foo  bar", "baz  qux"])
    result = tabulate(rows, headers=["A", "B"], tablefmt=tablefmt)
    assert_equal(result, expected)
Ejemplo n.º 2
0
    def plain_table_format(cls, *, sep: str = " ", **kwargs) -> TableFormat:
        """
        Creates a simple tabulate style using a column-delimiter ``sep``.

        Returns:
            A tabulate ``TableFormat``, which can be passed as a style
        """
        defaults = dict(
            lineabove=None,
            linebelowheader=None,
            linebetweenrows=None,
            linebelow=None,
            headerrow=DataRow("", sep, ""),
            datarow=DataRow("", sep, ""),
            padding=0,
            with_header_hide=None,
        )
        kwargs = {**defaults, **kwargs}
        return TableFormat(**kwargs)
    def _latex_row(cell_values,
                   colwidths,
                   colaligns,
                   escrules=LATEX_ESCAPE_RULES):
        def escape_char(c):
            return escrules.get(c, c)

        escaped_values = [
            "".join(map(escape_char, cell)) for cell in cell_values
        ]
        escaped_values = [
            "\\multicolumn{1}{r}{" + e + "}" if "%" in e else e
            for e in escaped_values
        ]
        escaped_values = [
            "\\multicolumn{1}{r}{" + e + "}" if e == "Yes" or e == "No" else e
            for e in escaped_values
        ]

        rowfmt = DataRow("", "&", "\\\\")
        return _build_simple_row(escaped_values, rowfmt)
Ejemplo n.º 4
0
def _styled_datarow(begin, sep, end, cls, cell_values, colwidths, colaligns):
    ''' Function that add a HTML style <cls> to each even cell value.
        The rest of the parameters follows the tabulate's definition.
        '''
    values = (c if i % 2 else ('<%s>%s</%s>' % (cls, c, cls))
              for i, c in enumerate(cell_values))
    return (begin + sep.join(values) + end).rstrip()


# Table format for the registers based on tabulate's 'simple' format
_registers_table_fmt = TableFormat(
    lineabove=Line("", "-", "  ", ""),
    linebelowheader=Line("", "-", "  ", ""),
    linebetweenrows=None,
    linebelow=Line("", "-", "  ", ""),
    headerrow=DataRow("", "  ", ""),
    datarow=partial(_styled_datarow, "", "  ", "", "pygments.name"),
    padding=0,
    with_header_hide=["lineabove", "linebelow"],
)


class Shell:
    def __init__(self, style, regs, pc, mem, mu, columns, doc, simple_prompt,
                 no_history, visible_regs):
        self.dirs = AppDirs("iasm", "badaddr")
        self.session = self._create_shell_session(style, no_history)

        self.regs = regs
        self.pc = pc
        self.mem = mem
Ejemplo n.º 5
0
import colorlog
import pandas as pd
import ujson as json

format = '%(log_color)s%(asctime)15s %(name)15s %(levelname)10s - %(message)s'
handler = colorlog.StreamHandler()
handler.setFormatter(
    colorlog.ColoredFormatter(format, datefmt="%y%m%d %H:%M:%S"))

logging.getLogger("cflib.crazyflie.log").addHandler(handler)

myfmt = TableFormat(lineabove=Line("", "-", "  ", ""),
                    linebelowheader=Line("| ", "-", " | ", " |"),
                    linebetweenrows=None,
                    linebelow=None,
                    headerrow=DataRow("| ", " | ", " |"),
                    datarow=DataRow("| ", " | ", " |"),
                    padding=0,
                    with_header_hide=["lineabove", "linebelow"])


def get_logger(name, level=logging.DEBUG):
    """
    This function returns a logger object
    """

    logger = colorlog.getLogger(name)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(handler)

    return logger
Ejemplo n.º 6
0
class Session:
    odd_even = cycle((
        DataRow('', '  ', ''),
        # set background to dark gray, reset background at end of line
        DataRow('\x1b[100m', '  ', '\x1b[49m'),
    ))
    # TableFormat copied from tabulate's 'simple' format, datarow being the exception
    alternating_format = TableFormat(
        lineabove=Line('', '-', '  ', ''),
        linebelowheader=Line('', '-', '  ', ''),
        linebetweenrows=None,
        linebelow=Line('', '-', '  ', ''),
        headerrow=DataRow('', '  ', ''),
        # alternate between the definitions in odd_even
        datarow=lambda values, *_: _build_simple_row(values,
                                                     next(Session.odd_even)),
        padding=0,
        with_header_hide=('lineabove', 'linebelow'))

    def __init__(self, config, today=None):
        self.config = config
        self._database = None
        self.today = today or date.today()

        self.week_start = self.today - timedelta(days=self.today.weekday())
        self.days = {
            day: self.week_start + timedelta(days=week_index)
            for week_index, day in enumerate(('monday', 'tuesday', 'wednesday',
                                              'thursday', 'friday', 'saturday',
                                              'sunday'))
        }
        self.days.update(today=self.today,
                         yesterday=self.today - timedelta(days=1),
                         tomorrow=self.today + timedelta(days=1))

    @property
    def database(self):
        if not self._database:
            self._database = sqlite3.connect(
                path.expanduser(self.config.database.path or '~/.hours.db'))

        return self._database

    def select_day(self, argument):
        if argument in self.days:
            return self.days[argument]

        if DATE_PATTERN.match(argument):
            year, month, day = argument.split('-')
            return date(int(year), int(month), int(day))

        raise ValueError('not a day: {}'.format(argument))

    def to_name(self, argument):
        cursor = self.database.execute(
            """
                SELECT name FROM aliases WHERE alias = ?
            """, (argument, ))
        name = cursor.fetchone()
        if name:
            return name[0]
        else:
            return argument

    def log_hours(self, name, day, hours):
        self.database.execute(
            """
                INSERT INTO hours (name, day, hours) VALUES (?, ?, ?)
            """, (name, day, hours))

    def run_log(self, arguments):
        assert 2 <= len(arguments) <= 3

        day = self.today
        name = hours = None

        for argument in arguments:
            if argument in self.days or DATE_PATTERN.match(argument):
                day = self.select_day(argument)
            elif HOURS_PATTERN.match(argument):
                hours = float(argument.replace(',', '.'))
            else:
                name = self.to_name(argument)

        assert None not in (name, day, hours)

        return self.log_hours(name, day, hours)

    def show_day(self, day):
        cursor = self.database.execute(
            """
                SELECT name, SUM(hours) FROM hours WHERE day = ? GROUP BY name ORDER BY name
            """, (day, ))

        print(
            tabulate(cursor.fetchall(),
                     headers=('', day.isoformat()),
                     tablefmt=self.alternating_format))

    def show_range(self, start, end):
        def hilight_today(headers):
            today = self.today.isoformat()
            for header in headers:
                if header == today:
                    yield '\x1b[1m{}\x1b[21m'.format(header)
                else:
                    yield header

        days = [(start + timedelta(days=offset)).isoformat()
                for offset in range((end - start).days + 1)]

        cursor = self.database.execute(
            """
                SELECT name, day, SUM(hours) 
                FROM hours 
                WHERE day >= ? AND day <= ? 
                GROUP BY name, day 
                ORDER BY name, day
            """, (start, end))

        data = {(name, day): hours for (name, day, hours) in cursor.fetchall()}
        names = sorted({name for (name, day) in data.keys()})

        print(
            tabulate([[name] + [data.get((name, day)) for day in days]
                      for name in names],
                     headers=[''] + list(hilight_today(days)),
                     tablefmt=self.alternating_format))

    def run_show(self, arguments):
        assert 0 <= len(arguments) <= 2

        if len(arguments) == 2:
            if arguments == ['last', 'week']:
                start = self.week_start - timedelta(days=7)
                end = self.week_start - timedelta(days=1)
            else:
                start = self.select_day(arguments[0])
                end = self.select_day(arguments[1])
        elif len(arguments) == 1 and arguments[0] != 'week':
            start = end = self.select_day(arguments[0])
        else:
            start = self.week_start
            end = self.week_start + timedelta(days=6)

        if start == end:
            return self.show_day(start)
        else:
            return self.show_range(*sorted((start, end)))

    def show_aliases(self):
        cursor = self.database.execute("""
                SELECT alias, name FROM aliases ORDER BY alias
            """)

        print(tabulate(cursor.fetchall(), tablefmt=self.alternating_format))

    def create_alias(self, alias, name):
        self.database.execute(
            """
                INSERT OR REPLACE INTO aliases (alias, name) VALUES (?, ?)
            """, (alias, name))
        # apply alias to currently logged hours
        self.database.execute(
            """
                UPDATE hours SET name = ? WHERE name = ?
            """, (name, alias))

    def run_alias(self, arguments):
        assert len(arguments) in (0, 2)

        if len(arguments) == 0:
            return self.show_aliases()

        if len(arguments) == 2:
            return self.create_alias(*arguments)

    def run(self, arguments):
        actions = {
            'log': self.run_log,
            'show': self.run_show,
            'alias': self.run_alias,
        }

        # determine default action: no arguments at all = show, any arguments = log or explicit action
        if arguments:
            action = 'log'
            if arguments[0] in actions:
                action = arguments.pop(0)
        else:
            action = 'show'

        with self.database:
            ensure_db(self.database)

            actions[action](arguments)
args_pattern = re.compile('\([^\)]*\)')
template_pattern = re.compile('<[^>]*>')
dll_pattern = re.compile('([^@]+)@0x[a-fA-F0-9]+')
extra_pattern = re.compile('[0-9]+|\.|-')
jsbugmon_pattern = re.compile(
    'The first bad revision is:\nchangeset:[ \t]*([^\n]*)\nuser:[ \t]*[^\n]*\ndate:[ \t]*[^\n]*\nsummary:[ \t]*[^\n]*'
)
hg_rev_pattern = re.compile(
    '://hg.mozilla.org/(?:releases/)?mozilla-([^/]+)/rev/([0-9a-z]+)')

global_tablefmt = TableFormat(lineabove=None,
                              linebelowheader=None,
                              linebetweenrows=None,
                              linebelow=None,
                              headerrow=DataRow(' ', ' ', ''),
                              datarow=DataRow(' ', ' ', ''),
                              padding=0,
                              with_header_hide=None)
byweek_tablefmt = TableFormat(lineabove=None,
                              linebelowheader=None,
                              linebetweenrows=None,
                              linebelow=None,
                              headerrow=DataRow(' ', '', ''),
                              datarow=DataRow(' ', '', ''),
                              padding=0,
                              with_header_hide=None)
rank_tablefmt = TableFormat(lineabove=None,
                            linebelowheader=None,
                            linebetweenrows=None,
                            linebelow=None,