Ejemplo n.º 1
0
def get_data(name):
    filename = resource_filename(  # noqa: not-callable
        'envrpt',
        'data/html_fancy/%s' % (name, ),
    )
    with open(filename) as res:
        return res.read()
Ejemplo n.º 2
0
def make_session() -> requests.Session:
    headers_path = Path(pkg_resources.resource_filename(__name__, 'headers.json'))
    if not headers_path.exists():
        raise ValueError(f'headers file {headers_path} is missing')
    with headers_path.open('r', encoding='utf-8') as f1:
        headers = json.load(f1)
    session = requests.Session()
    session.headers.update(headers)
    return session
def main():
    default_config_path = Path(pkg_resources.resource_filename('dnevnik2', 'app_config.toml')).resolve()
    default_output_dir = Path('.').resolve()
    arg_parser = argparse.ArgumentParser()
    arg_parser.add_argument('cookies_path', type=Path)
    arg_parser.add_argument('--config_path', type=Path, default=default_config_path)
    arg_parser.add_argument('--output_dir', type=Path, default=default_output_dir)
    args = arg_parser.parse_args()

    cookies_path: Path = args.cookies_path
    config_path: Path = args.config_path
    base_dir: Path = args.output_dir

    with config_path.open('r', encoding='utf-8') as f1:
        config = toml.load(f1)

    dnevnik = Dnevnik2.make_from_cookies_file(cookies_path)

    data = dnevnik.fetch_marks_for_current_quarter()

    with (base_dir / 'last_res.txt').open('w', encoding='utf-8') as f1:
        print(json.dumps(data, ensure_ascii=False, indent=2), file=f1)

    out_lines = []
    grouped = defaultdict(list)
    for item in sorted(data['data']['items'], key=lambda x: (to_date(x['date']), x['estimate_value_name'])):
        s_name = item['subject_name'] = get_subject(item, config['subjects'])
        mark = item['estimate_value_name']
        if mark.isdigit():
            grouped[s_name].append(int(mark))
        comment = ('# ' + item['estimate_comment']) if item['estimate_comment'] else ''
        out_lines.append((
            to_date(item['date']),
            "{subject_name:25s} {estimate_value_code:5s} {estimate_value_name:9s} {estimate_type_name:20s}".format(
                **item),
            comment
        ))

    if not out_lines:
        exit(1)

    with (base_dir / f'marks.{dt.date.today()}.txt').open('w', encoding='utf-8') as f1:
        for date, mark, comment in sorted(out_lines):
            print(f'{date}  {mark} {comment}', file=f1)

        f1.write('\n\n')
        for s_name in sorted(grouped):
            avg = sum(grouped[s_name]) / len(grouped[s_name])
            s_marks = ' '.join(str(mark) for mark in grouped[s_name])
            print(f'{s_name:25s} : {avg:0.3f}    {s_marks}', file=f1)
Ejemplo n.º 4
0
    def __init__(self):
        pygame.init()
        screen = pygame.display.set_mode(self.screen_size)
        self._done = False
        clock = pygame.time.Clock()
        img = resource_filename('bulbutil', 'resources/img/bulb-384-600.png')
        bulb_image = pygame.image.load(img)

        while not self._done:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self._done = True
                elif event.type == self.event_set_rgb:
                    screen.fill(event.rgb)
            screen.blit(bulb_image, bulb_image.get_rect())
            pygame.display.flip()

            clock.tick(60)
Ejemplo n.º 5
0
def config_logging():
    global configured
    if configured:
        logging.info(f"Logging already configured.")
        return
    configured = True

    log_conf_file = os.getenv('LOG_CONFIG')  # None

    if not log_conf_file:
        log_conf_file = resource_filename(Requirement.parse('eam_core'),
                                          "logconf.yml")
        if not os.path.exists(log_conf_file):
            import pathlib
            log_conf_file = pathlib.Path(__file__).parent.absolute().joinpath(
                "logconf.yml")

    with open(log_conf_file, 'r') as f:
        log_config = yaml.safe_load(f.read())
    dictConfig(log_config)
    logging.info(f"Configured logging from {log_conf_file}")
Ejemplo n.º 6
0
from typing import (
    List,
    Optional,
    NamedTuple,
    Generic,
    TypeVar,
    Dict,
    Callable,
    Set,
    Iterable,
)
from jinja2 import Template
from io import StringIO
import inspect

with open(resource_filename(__name__, "template.jinja2"),
          encoding="utf-8") as fp:
    template = Template(fp.read())

# Note: ideally this would be a dataclass, but we're supporting Python 3.5+ so we can't do this yet
NamedDiagram = NamedTuple(
    "NamedDiagram",
    [("name", str), ("diagram", Optional[railroad.DiagramItem]),
     ("index", int)],
)
"""
A simple structure for associating a name with a railroad diagram
"""

T = TypeVar("T")