Esempio n. 1
0
def init_prettyprinter() -> Formatter:
    """Initialize prettyprinter and add all IMPLICIT_MODULES."""
    prettyprinter.install_extras(include={"python", "dataclasses"})
    for filepath in Path("wolfbot").rglob("*.py"):
        module_name = filepath.stem
        if "__" not in module_name:
            prefix = ".".join(filepath.parts[:-1] + (module_name, ))
            IMPLICIT_MODULES.add(prefix)
    return Formatter(prettyprinter)
Esempio n. 2
0
def _setup_logger(console_log_level):
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        prettyprinter.install_extras()
    verboselogs.install()
    if sys.platform == "win32":
        # In Windows the default black is black, which is invisible on the default terminal.
        coloredlogs.DEFAULT_FIELD_STYLES["levelname"] = {"color": "blue"}

    root_logger = logging.getLogger()
    root_logger.setLevel(min(console_log_level, logging.DEBUG))

    console_log_handler = ConsoleLogHandler()
    console_log_handler.setLevel(console_log_level)
    root_logger.addHandler(console_log_handler)

    sys.excepthook = _exception_handler
    logging.captureWarnings(True)
Esempio n. 3
0
    | num
    | ( expr )
id -> [a-zA-Z]\w*
num -> [0-9]+
type -> float int

"""
import dataclasses
import enum
import functools
import unittest
from typing import List

import prettyprinter

prettyprinter.install_extras()


class TokenType(str, enum.Enum):
    EOF = ''
    NUM = 'num'
    ID = 'id'
    MUL = 'mul'
    ADD = 'add'
    DOT = 'dot'
    COMMA = 'comma'
    LBRACK = 'lrback'
    RBRACK = 'rrback'
    EQ = 'eq'
    PRINT = 'print'
    SEMI = 'semicolon'
import pytest
from prettyprinter import install_extras, pformat

from coreapp.models import MyModel

install_extras(['django'])


@pytest.mark.django_db
def test_simple_case():
    instance = MyModel.objects.create(name='John', slug='john', version=2)
    expected = "coreapp.models.MyModel(id={}, slug='john', version=2, name='John')".format(
        instance.id)
    assert pformat(instance, width=999) == expected


@pytest.mark.django_db
def test_blank_field():
    instance = MyModel.objects.create(name='', slug=None, version=2)
    expected = """\
coreapp.models.MyModel(
    id={},
    version=2,
    # Null fields: slug
    # Blank fields: name
)""".format(instance.id)
    assert pformat(instance, width=999) == expected


@pytest.mark.django_db
def test_default_field():
Esempio n. 5
0
#!/usr/bin/env python3
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from prettyprinter import pprint, install_extras
from secrets import token_hex
from typing import List, Any

from sly import Lexer, Parser

# Pretty printer dataclasses support
install_extras(include=['dataclasses'], warn_on_error=True)


@contextmanager
def next_token(state):
    token = "r" + token_hex(4)
    state['tokens'].append(token)
    try:
        yield token
    finally:
        state['tokens'].pop()


def indent(s, amount=1):
    return str(s).replace('\n', '\n' + '  ' * amount)


def mdc_compile(source, verbose=False):
    lexer = MindusLexer()
    parser = MindusParser()
Esempio n. 6
0
import numpy as np
import pytest

from prettyprinter import install_extras, pformat

install_extras(["numpy"])


@pytest.mark.parametrize(
    'nptype', (np.sctypes["uint"] + np.sctypes["int"] + np.sctypes["float"]))
def test_numpy_numeric_types(nptype):
    val = nptype(1)
    py_val = val.item()

    if type(py_val) in (int, float):
        inner_printed = pformat(py_val)
    else:
        # numpy renders types such as float128,
        # that are not representable in native Python
        # types, with Python syntax
        inner_printed = repr(py_val)

    expected = "numpy.{}({})".format(nptype.__name__, inner_printed)
    assert pformat(val) == expected


def test_numpy_bool_type():
    assert pformat(np.bool_(False)) == "numpy.bool_(False)"
    assert pformat(np.bool_(True)) == "numpy.bool_(True)"

Esempio n. 7
0
import logging
import sys

import prettyprinter

import uvicore

# Enable extras like @dataclass
prettyprinter.install_extras(exclude=[
    # Not using django, no need to print django models
    'django',

    # Maybe when I get a shell ?
    'ipython_repr_pretty',
    'ipython',
    'attrs',
])


def dump(*args):
    """Dump variables using prettyprinter"""

    # Detect if running in pytest
    if "pytest" in sys.modules: level = None

    for arg in args:
        if type(arg) == str:
            # I don't want string printed with dump because it adds quotes to the string
            # which seems confusing at times.
            #prettyprinter.cpprint(arg, width=10000, ribbon_width=10000)
            print(arg)
import logging
from statistics import mean

import pandas as pd
import prettyprinter
import wandb
from prettyprinter import pprint
from sklearn.metrics import accuracy_score

from simpletransformers.classification import ClassificationArgs, ClassificationModel
from utils import load_rte_data_file

prettyprinter.install_extras(
    include=[
        "dataclasses",
    ],
    warn_on_error=True,
)

logging.basicConfig(level=logging.INFO)
transformers_logger = logging.getLogger("transformers")
transformers_logger.setLevel(logging.WARNING)

# Preparing train data
train_df = load_rte_data_file("data/train.jsonl")
eval_df = pd.read_json("data/eval_df.jsonl", lines=True, orient="records")
test_df = pd.read_json("data/test_df.jsonl", lines=True, orient="records")

sweep_result = pd.read_csv("sweep_results/deep-sweep.csv")

best_params = sweep_result.to_dict()
Esempio n. 9
0
import click
import egpt.processing as proc
import prettyprinter  # type: ignore
from distributed import Client  # type: ignore
prettyprinter.install_extras(
    # Comment out any packages you are not using.
    include=[
        'dataclasses',
    ],
    warn_on_error=True)


@click.group()
def jobgroup():
    pass


@jobgroup.group("job")
def job():
    pass


@job.command("run")
@click.argument("jobfile")
@click.option("--scheduler")
def run(jobfile: str, scheduler: str):
    if scheduler is not None:
        Client(scheduler)
    else:
        Client()
    res = proc.submit(jobfile)
Esempio n. 10
0
from attr import attrs, attrib, Factory

from prettyprinter import install_extras, pformat

install_extras(['attrs'])


@attrs
class MyClass:
    one = attrib()
    optional = attrib(default=1)
    optional2 = attrib(default=Factory(list))


def test_simple_case():
    value = MyClass(1)
    expected = "tests.test_attrs.MyClass(one=1)"
    assert pformat(value, width=999) == expected


def test_different_from_default():
    value = MyClass(1, optional=2, optional2=[1])
    expected = "tests.test_attrs.MyClass(one=1, optional=2, optional2=[1])"
    assert pformat(value, width=999) == expected


@attrs
class MyOtherClass:
    one = attrib(repr=False)

Esempio n. 11
0
    AssocNodeOr,
    PlusNode,
    BarNode,
    walk,
    AssocNode,
    map_contents,
    WordType,
    OptionalNode,
    EmptyNode,
    tree_has_gram,
)
from itertools import chain
from typing import Callable, Optional, List, Tuple, Iterable, Iterator
from prettyprinter import pprint, install_extras

install_extras(exclude=["django", "ipython", "ipython_repr_pretty"])


def intersect_none(s1, s2):
    if s1 is None:
        return s2
    if s2 is None:
        return s1
    return s1.intersection(s2)


def uni(dl1, dl2):
    all_keys = {*dl1.keys(), *dl2.keys()}
    res = {}
    for key in all_keys:
        res[key] = dl1.get(key, []) + dl2.get(key, [])
Esempio n. 12
0
DEBUG = False

DNS_HEADER = '!HBBHHHH'
DNS_HEADER_SIZE = struct.calcsize(DNS_HEADER)
DNS_DOMAIN_PATTERN = re.compile('^[A-Za-z0-9\-\.\_]+$')

NEW_ACCOUNT_URL = None
NONCE_URL = None
NEW_ORDER_URL = None
REVOKE_CERT_URL = None

ACME_SERVER_CERT = './pebble_https_ca.pem'

if DEBUG:
    import prettyprinter
    prettyprinter.install_extras(['requests'])


def read_answer(name):
    ans = ''
    try:
        apath = FILE_PATH + name
        if DEBUG:
            print('Trying to open file ', apath)
        afile = open(apath, 'r')
        ans = afile.read().strip()
        afile.close()
    except:
        pass
    return ans
Esempio n. 13
0
import prettyprinter

prettyprinter.install_extras(exclude=['django'])
Esempio n. 14
0
import time
import prettyprinter
import numpy as np

from geode.dispatcher import Dispatcher

prettyprinter.install_extras(include=['dataclasses'])

DESTS = np.array([[37.55799625, -97.78447195], [37.55799625, -97.78447195],
                  [34.821800, -92.052100], [31.419600, -83.230200],
                  [33.213000, -87.331800], [31.529500, -88.531600]])

ORIGS = np.array([[31.782000, -83.508600], [32.766200, -83.763700],
                  [37.755600, -96.773100], [35.393400, -95.272200],
                  [35.219700, -84.235400], [31.252500, -81.308500],
                  [31.646600, -91.954300], [30.384600, -97.415300],
                  [31.492100, -98.697900], [38.339300, -84.797900],
                  [31.719300, -96.396000], [39.113700, -96.249100],
                  [30.203000, -98.977700], [39.179000, -90.797400],
                  [39.707000, -81.610200], [38.978100, -87.091100],
                  [35.412000, -93.640600], [34.440900, -82.486700],
                  [32.529100, -95.140700], [36.434000, -86.271000],
                  [36.367600, -95.154600], [33.436000, -84.739100],
                  [36.499200, -91.634700], [39.323800, -88.615600],
                  [31.106400, -89.572400], [33.930700, -92.971900],
                  [36.977800, -84.871600], [35.019000, -85.219900],
                  [38.368600, -94.349600], [37.914100, -94.475800],
                  [31.318100, -91.481100], [33.983800, -98.433300],
                  [30.322100, -94.631500], [30.643200, -82.238600],
                  [36.893800, -98.801000], [33.035600, -99.468700],
                  [33.331600, -91.767900], [32.907600, -87.142700],
Esempio n. 15
0
Snyk Shell provides a convenient shell interface to the Snyk API. You can
use any valid Python expression as well as make calls to the Snyk API using
the pre-configured Snyk API client. When you load the the shell it will
pre-load a list of your organizations and projects so you have some data to explore.
"""

import os
import sys

import prettyprinter
import snyk
from IPython.terminal.embed import InteractiveShellEmbed
from prettyprinter import cpprint as pprint
from termcolor import colored, cprint

prettyprinter.install_extras(include=["requests", "dataclasses"])


def run():
    try:
        token = os.environ["SNYK_TOKEN"]
    except KeyError:
        sys.exit("You must provide a SNYK_TOKEN to run Snyk Shell")
    client = snyk.SnykClient(token)
    organizations = client.organizations.all()
    projects = client.projects.all()

    shell = InteractiveShellEmbed(
        banner1=colored("Welcome to Snyk Shell", "blue"))

    shell(
Esempio n. 16
0
import builtins

import prettyprinter

prettyprinter.install_extras(include=['attrs'])
prettyprinter.set_default_style("light")

builtins.pretty = prettyprinter.cpprint


@prettyprinter.register_pretty('regulator.location.Location')
def pretty_location(value, ctx):
    return "Location({})".format(value)


@prettyprinter.register_pretty('regulator.decode.Type')
def pretty_decoder_type(value, ctx):
    return prettyprinter.pretty_call_alt(ctx,
                                         type(value),
                                         kwargs=(
                                             ('name', value.name),
                                             ('kind', value.kind),
                                             ('fields',
                                              list(reversed(value.fields))),
                                         ))


@prettyprinter.register_pretty('regulator.decode.Cluster')
def pretty_decoder_type(value, ctx):
    return prettyprinter.pretty_call_alt(ctx,
                                         type(value),
Esempio n. 17
0
from dataclasses import (
    dataclass,
    fields,
    field,
)
from typing import Any

from prettyprinter import install_extras, pformat

install_extras(['dataclasses'])


@dataclass
class MyClass:
    one: Any
    optional: Any = field(default=1)
    optional2: Any = field(default_factory=list)


def test_simple_case():
    value = MyClass(1)
    expected = "tests.test_dataclasses.MyClass(one=1)"
    assert pformat(value, width=999) == expected


def test_different_from_default():
    value = MyClass(1, optional=2, optional2=[1])
    expected = "tests.test_dataclasses.MyClass(one=1, optional=2, optional2=[1])"
    assert pformat(value, width=999) == expected

Esempio n. 18
0
from datetime import timedelta
from io import BytesIO
from requests import (
    Request,
    Response,
    Session,
)
from requests.structures import CaseInsensitiveDict

from prettyprinter import (
    install_extras,
    pformat,
    pprint,
)

install_extras(['requests'])


def test_session():
    sess = Session()
    sess.auth = ('user', 'pass')
    assert pformat(sess, width=999) == """\
requests.Session(
    headers=requests.structures.CaseInsensitiveDict({
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate',
        'Connection': 'keep-alive',
        'User-Agent': 'python-requests/2.18.4'
    }),
    auth=('user', 'pass')
)"""
Esempio n. 19
0
import dataclasses
import logging
import os
import sys

# Use prettyprinter for dataclass formatting
try:
    import prettyprinter as pprint

    # NOTE ipython extra has issue, throwing a warning if installed and log a DF
    # 'ZMQInteractiveShell' object has no attribute 'highlighting_style'
    pprint.install_extras(exclude=["django", "ipython"], warn_on_error=False)

    # Set a fairly aggressive limit to sequence by default
    # This makes printing more similar to pandas truncation, which is nice
    # NOTE However, this doesn't seem to work for big nested structures, so we
    # might still have to apply a limit on total formatted string lines
    # TODO Add a way to bypass sequence length when needed
    pprint.set_default_config(
        style="dark",
        max_seq_len=20,
        width=79,
        ribbon_width=71,
        depth=None,
    )
except ImportError:
    import pprint

# ANSI codes that will generate colored text
def_color_map = {
    # reset should suffix any use of the other following prefixes
Esempio n. 20
0
from pathlib import Path
from tempfile import NamedTemporaryFile

import click
from prettyprinter import install_extras

from . import commands
from . import exceptions
from .cache import purge
from .uri_handlers.base import URIHandler

from . import __version__
from . import config


install_extras(include=("dataclasses",))
LOGGER = config.get_logger(__name__)
CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])


def scan_help_text():
    help_text = """
    Perform a security audit for a given package/data
    """

    help_text = textwrap.dedent(help_text)

    for uri_handler in URIHandler.__subclasses__():
        if hasattr(uri_handler, "help"):
            uhelp = textwrap.dedent(uri_handler.help).strip()
            help_text += f"\n{uhelp}\n"
Esempio n. 21
0
import yaml
import parglare
from parglare.actions import collect_sep
import prettyprinter
from prettyprinter import pprint
import dataclasses
import json

import sys

from parglare_adapter import to_parglare_grammar
from facts import Fact, Judgement, Variable, Name, ComplexTerm, List

prettyprinter.install_extras(['dataclasses'])

with open('semantics.bnf.yml', 'rt') as f:
    grammar = yaml.load(f, Loader=yaml.Loader)
    for s in grammar['string_terminals']:
        assert s not in grammar['terminals']
        grammar['terminals'][s] = ('string', s)


def pass_many(indexes):
    def action(_, nodes):
        return [nodes[i] for i in indexes]

    return action


def pass_single(i):
    def action(_, nodes):
Esempio n. 22
0
import icdiff
from prettyprinter import install_extras, pformat

install_extras()


def pretty_compare(config, op, left, right):
    very_verbose = config.option.verbose >= 2
    if not very_verbose:
        return None

    if op != "==":
        return None

    try:
        if abs(left + right) < 100:
            return None
    except TypeError:
        pass

    try:
        pretty_left = pformat(left, indent=4, width=80,
                              sort_dict_keys=True).splitlines()
        pretty_right = pformat(right, indent=4, width=80,
                               sort_dict_keys=True).splitlines()
        differ = icdiff.ConsoleDiff(cols=160, tabsize=4)
        icdiff_lines = list(
            differ.make_table(pretty_left, pretty_right, context=False))

        return (["equals failed"] +
                ["<left>".center(79) + "|" + "<right>".center(80)] +
Esempio n. 23
0
    # 3rd party
    import prettyprinter  # type: ignore  # nodep
    from prettyprinter.prettyprinter import _BASE_DISPATCH, pretty_dispatch  # type: ignore  # nodep
except ImportError as e:  # pragma: no cover
    exc = type(
        e
    )(f"Could not import 'prettyprinter'. Perhaps you need to install 'attr_utils[pprint]'?\n\n{e}"
      )
    raise exc.with_traceback(e.__traceback__) from None

__all__ = ["pretty_repr", "register_pretty", "PrettyFormatter", "_PF"]

_T = TypeVar("_T")
_PF = TypeVar("_PF", bound="PrettyFormatter")

prettyprinter.install_extras(["attrs"])


@runtime_checkable
class PrettyFormatter(Protocol):
    """
	:class:`typing.Protocol` representing the pretty formatting functions decorated by :func:`register_pretty`.

	.. versionadded:: 0.6.0
	.. latex:vspace:: 10px
	"""
    def __call__(self, value: Any, ctx: Any) -> str:
        """
		Call the function.

		:param value: The value to pretty print.