text
stringlengths
185
73.3k
repo
stringlengths
7
100
path
stringlengths
4
146
language
stringclasses
7 values
hash
stringlengths
16
16
score
float64
7
8.5
stars
int64
0
237k
"""Testing CLI command convert.""" import os import subprocess def test_unordered(tmp_path): """Tests for converting unordered SWC file.""" os.chdir(os.path.dirname(__file__) + '/data') proc = subprocess.Popen(['swc', 'convert', 'fail_unordered.swc', '-o', tmp_path / 'test_tr...
a1eko/treem
tests/test_cmd_convert.py
.py
df9dc91342a01f56
7.8
3
"""Testing CLI command measure.""" import os import subprocess def test_measure(): """Tests for morphometric mesurements.""" os.chdir(os.path.dirname(__file__) + '/data') proc = subprocess.Popen(['swc', 'measure', 'pass_simple_branch.swc', '-a', 'path', 'sholl'], ...
a1eko/treem
tests/test_cmd_measure.py
.py
85512abae61e045b
7.8
3
"""Import tests of the main module treem and it's submodules.""" # ruff: noqa: F401 def test_import_treem(): """Tests importing treem.""" import treem def test_import_node(): """Tests importing Node from treem.""" from treem import Node def test_import_morph(): """Tests importing Morph from t...
a1eko/treem
tests/test_import.py
.py
d6b37782940c3da6
7.8
3
"""Testing module io.""" import json import numpy as np import pytest from treem.io import TreemEncoder, load_swc, save_swc class MyObject: def __init__(self, value): self.value = value def test_io_encoder_success(): """Tests JSON encoder for successful serialization.""" data = [[1, 2, 3], np....
a1eko/treem
tests/test_io.py
.py
d0eb8f992b245305
7.8
3
"""Implementation of CLI find command.""" import numpy as np from treem.io import SWC from treem.morph import Morph from treem.utils.geom import fibonacci_sphere, rotation, rotation_matrix def _filter_by_comparison(nodes, getter_func, target_val, compare_op): """Encapsulates the repetitive comparison filtering ...
a1eko/treem
treem/commands/find.py
.py
a407305c97bdfb20
7.3
3
"""Implementation of CLI measure command.""" import json import math import multiprocessing as mp import os import numpy as np from treem import SWC, Morph from treem.io import TreemEncoder from treem.morph import SEG, get_segdata from treem.utils.geom import norm def _measure_neurites(morph, morphometry, name, ty...
a1eko/treem
treem/commands/measure.py
.py
68f23c95ae188c70
7.3
3
"""Implementation of CLI modify command.""" import math from itertools import chain import numpy as np from treem.io import SWC from treem.morph import Morph from treem.utils.geom import rotation def _scale_radii(morph, nodes, scale_radius): """Scales radii.""" scale = np.abs(scale_radius) for node in ...
a1eko/treem
treem/commands/modify.py
.py
39c938291e031cbf
7.3
3
"""Implementation of CLI render command.""" import numpy as np import OpenGL.GL as GL import OpenGL.GLU as GLU import OpenGL.GLUT as GLUT from PIL import Image, ImageOps from treem import SWC, Morph from treem.utils.geom import rotation _HELP = """ interactive commands: mouse left drag rotate mouse r...
a1eko/treem
treem/commands/render.py
.py
91535137db6de885
7.3
3
"""SWC data format defintion and services.""" import json import numpy as np class SWC(): """Definitions of the data format.""" TYPES = (SOMA, AXON, DEND, APIC) = range(1, 5) COLS = (I, T, X, Y, Z, R, P) = range(7) # noqa: E741 XY = slice(2, 4) XZ = slice(2, 5, 2) YZ = slice(3, 5) XYZ =...
a1eko/treem
treem/io.py
.py
c641d5c2aa2b3c1c
7.3
3
"""Basic tree data structure.""" from collections import deque class Tree(): """Recursive tree data structure.""" def __init__(self): """Constructor of empty tree.""" self.parent = None self.siblings = [] def add(self, tree): """Appends tree as continuation.""" t...
a1eko/treem
treem/tree.py
.py
894324dfbf5f566a
7.3
3
"""Utilities for manipulating geometry of morphology reconstructions.""" import math import numpy as np from treem.io import SWC def rotation_matrix(axis, angle): """Computes rotation matrix for 3D manipulations. Args: axis (float[3]): rotation axis. angle (float): rotation angle in radian...
a1eko/treem
treem/utils/geom.py
.py
ef5009c4ec80a077
7.3
3
"""Plotting utilities.""" import numpy as np from treem.io import SWC def plot_tree(ax, tree, data, **kwargs): """Plots entire branch. Args: ax: matplotlib axes object. tree (treem.Node): branch start node. data (NumPy ndarray): raw data of morphology Morph. kwargs: argument...
a1eko/treem
treem/utils/plot.py
.py
e69eed5e290e0902
7.3
3
"""MkDocs hook to merge sub-project configurations into the parent. The monorepo plugin only merges nav and docs from !include'd sub-projects. This hook merges theme features, markdown_extensions, extra_css, and extra_javascript from sub-project mkdocs.yml files into the parent config at build time. Note: plugins can...
workfloworchestrator/workfloworchestrator.github.io
hooks/merge_subproject_configs.py
.py
dab0f1da48144a5f
7.15
1
#!/usr/bin/env python # -*- coding: utf-8 -*- """The setup script.""" from setuptools import setup, find_packages import re def get_property(prop, project): result = re.search(r'{}\s*=\s*[\'"]([^\'"]*)[\'"]'.format(prop), open(project + '/__init__.py').read()) return result.group(1) ...
adellej/beans
setup.py
.py
84a60f25c3cdfb28
7.39
5
""" test to check if settle has been compiled correctly """ # from pySettle import settler as se import pySettle import numpy as np def test_settle_location(): # se.Settle() pySettle.settler.Settle() return def test_settle_output(): settle_version = pySettle.__version__ # initialize settle inter...
adellej/beans
tests/test_settle.py
.py
d052a9c2d5f92125
7.89
5
"""Geographic data functions and court classes.""" from __future__ import annotations from typing import Dict, List, Optional, Union import pandas as pd import numpy as np import re from copy import copy from diarios.clean.text import clean_text, get_data, get_estado_mapping, title, transform from diarios.clean.num...
hsigstad/diarios
diarios/clean/geo.py
.py
0c5fee3e1e66c5c6
7
0
"""Core text cleaning and data utility functions.""" from __future__ import annotations from typing import Any, Dict, List, Optional, Union import pandas as pd import numpy as np import glob from unidecode import unidecode import os import re from copy import copy import warnings warnings.filterwarnings("ignore", "T...
hsigstad/diarios
diarios/clean/text.py
.py
af8449e75f5f1107
7
0
"""Parser for STF (Supremo Tribunal Federal) scraped case data.""" from __future__ import annotations from typing import List, Optional, Tuple import pandas as pd from diarios.clean import clean_text from diarios.clean import clean_oab from diarios.clean import map_regex from diarios.io import read_files def parse...
hsigstad/diarios
diarios/consulta/STF.py
.py
7e5bb479ae24972c
7
0
"""Parser for STJ (Superior Tribunal de Justiça) scraped case data.""" from __future__ import annotations from typing import List, Tuple import pandas as pd from diarios.clean import clean_text from diarios.clean import map_regex from diarios.io import read_files def parse_consulta_stj( infiles: List[str], ) -...
hsigstad/diarios
diarios/consulta/STJ.py
.py
e71c1a8701617c38
7
0
"""Parser for TJSP (Tribunal de Justiça de São Paulo) scraped case data.""" from __future__ import annotations from typing import Callable, Dict, List, Optional, Tuple, Union import pandas as pd from diarios.clean import clean_text from diarios.clean import map_regex import zipfile import gc def parse_consulta_tjs...
hsigstad/diarios
diarios/consulta/TJSP.py
.py
4791ebcc33bd8c99
7
0
"""Parser for TRF1 (Tribunal Regional Federal da 1a Região) scraped case data.""" from __future__ import annotations from typing import List, Tuple import pandas as pd from diarios.clean import clean_text from diarios.clean import map_regex from diarios.clean import split_series def parse_consulta_trf1( infile...
hsigstad/diarios
diarios/consulta/TRF1.py
.py
13a7931a9910b26f
7
0
"""Database connection and query utilities for SQLite, MySQL, and PostgreSQL.""" from __future__ import annotations from typing import Any, Dict, List, Optional, Union import pandas as pd from time import time import sqlite3 import os from re import sub __all__ = [ "query", "insert", "create_index", ...
hsigstad/diarios
diarios/database.py
.py
44f1f5a377583c9d
7
0
"""Regex patterns, configuration, and utilities for decision parsing.""" from __future__ import annotations from typing import Any, Callable, Dict, List, Optional, Tuple, Union import pandas as pd from diarios.clean import get_cardinal_number_regex __all__ = [ "get_main_sentence_regexes", "get_dispositivo_r...
hsigstad/diarios
diarios/decision/config.py
.py
eee8ace852b5103b
7
0
"""Regex-based text extraction from files using pcre2grep.""" from __future__ import annotations from typing import Any, List, Optional import subprocess import os from glob import glob __all__ = [ "Extractor", ] class Extractor: """Extract text matching regex patterns from files using pcre2grep. Arg...
hsigstad/diarios
diarios/extract.py
.py
756278feffc4f437
7
0
"""File reading and OCR utilities for PDF, DOCX, and DOC files.""" from __future__ import annotations from typing import List, Optional, Union from pathlib import Path import pandas as pd import pytesseract from pdf2image import convert_from_path from tempfile import TemporaryDirectory from PIL import Image from sub...
hsigstad/diarios
diarios/io.py
.py
08116084b514bc64
7
0
"""Political data utilities for elections and party coalitions.""" from __future__ import annotations from typing import Union import pandas as pd import numpy as np from .clean import get_data def split_coalition(coalition: pd.Series, name: str = "party") -> pd.Series: """Split coalition strings into individu...
hsigstad/diarios
diarios/politica.py
.py
09d82d0dc1376142
7
0
"""DataJud (CNJ) public API client. INTENT: shared infrastructure for any project that needs raw DataJud JSONL on disk. ``download_datajud()`` writes one JSONL per (tribunal, classes) query; helpers (``iter_search_after``, ``post_search``, ``build_classe_query``) are exposed for projects with non-standard query shapes...
hsigstad/diarios
diarios/scrape/datajud.py
.py
6b824e106f7e844d
7
0
"""diarios.scrape.proxy — optional Decodo residential proxy egress (shared across repos). INTENT Several BR gov portals only yield to a Brazilian RESIDENTIAL IP; a datacenter / commercial-VPN egress (e.g. PIA) is geoblocked or its reCAPTCHA score is bot-penalized (bllcompras invisible reCAPTCHA → "Captcha ...
hsigstad/diarios
diarios/scrape/proxy.py
.py
a26444fed0b7af32
7
0
"""diarios.secrets — the one resolver for the shared cross-cutting secrets file. INTENT Cross-repo API keys (TWOCAPTCHA_API_KEY, DECODO_*) live in ONE file outside every git repo: <workspace-root>/.secrets/research.env (see research/rules/secrets.md). Consumers used to hardcode `Path.home() / ".config/rese...
hsigstad/diarios
diarios/secrets.py
.py
9e8ed902d77fb800
7
0
"""Hierarchical text parser using regex-based structure definitions.""" from __future__ import annotations from typing import Any, List, Optional import re import warnings import pandas as pd import os import copy __all__ = [ "Structure", "bold", "parse", "parse_structure_string", ] class Structur...
hsigstad/diarios
diarios/structure.py
.py
297d0fc5ce50d3e6
7
0
"""Generate assunto.org by building a tree of legal subject categories from CNJ data.""" import os from typing import Any, Dict, List import pandas as pd from diarios.clean import clean_text def read(infile: str) -> pd.DataFrame: """Read a CSV from the tabelas_unificadas dump directory. Args: infi...
hsigstad/diarios
scripts/assunto.py
.py
2f927b6a67888407
7
0
"""Generate classe.csv and classe_dispositivo.csv from CNJ unified tables.""" import os from typing import Dict, Tuple import pandas as pd from diarios.clean import clean_text def read(infile: str) -> pd.DataFrame: """Read a CSV from the tabelas_unificadas dump directory. Args: infile: Filename re...
hsigstad/diarios
scripts/classe.py
.py
625a2dbfc40823dc
7
0
"""Generate foro.csv by combining foro data with tribunal and municipality info.""" from glob import glob import numpy as np import pandas as pd import path from diarios.clean import transform # TODO: Add trabalhista (use varas/vara_year_TRT) def read_csv(infile: str) -> pd.DataFrame: """Read a single foro CSV ...
hsigstad/diarios
scripts/foro.py
.py
2ef1f68f96a5a297
7
0
"""Generate municipio_id.csv and municipio_correction_tse.csv from TSE election data.""" import os import re from glob import glob from typing import List, Tuple import pandas as pd import path from diarios.clean import clean_text def clean_municipio() -> Tuple[pd.DataFrame, pd.DataFrame]: """Build municipality...
hsigstad/diarios
scripts/municipio_id.py
.py
fda4bd8f1f9cffe9
7
0
"""Generate tribunal.csv by enriching tribunal_manual.csv with diary date ranges.""" import os from typing import Optional import pandas as pd def main() -> pd.DataFrame: """Read tribunal_manual.csv and add diary start/end dates. Returns: Enriched tribunal DataFrame. """ df = pd.read_csv( ...
hsigstad/diarios
scripts/tribunal.py
.py
4724c5ee74b79acd
7
0
#!/usr/bin/env python import os from glob import glob from setuptools import Extension, setup # type: ignore[import] def module_name_from_src_path(path: str) -> str: """Derive a fully-qualified module name from a file path under ./src. Cython's default path-to-module logic relies on finding __init__.py fi...
akornatskyy/wheezy.validation
setup.py
.py
41134c84e14f036b
7
0
class Checker(object): """Intended to be used by unittest/doctest for validation rules. It is recommended to use test case per validator, test method per attribute, split by success check first than fails. """ def __init__(self, stop=True, translations=None, gettext=None): """Initial...
akornatskyy/wheezy.validation
src/wheezy/validation/checker.py
.py
cb3bcec682f0f4ff
7
0
from datetime import date, datetime, time from decimal import Decimal from gettext import NullTranslations from time import strptime from wheezy.validation.i18n import ( decimal_separator, default_date_input_format, default_datetime_input_format, default_time_input_format, fallback_date_i...
akornatskyy/wheezy.validation
src/wheezy/validation/model.py
.py
6286057bf95fb0b1
7
0
def patch_strptime_cache_size(max_size=100): """Patch for strptime regex cache max size.""" try: # pragma: nocover import _strptime if not hasattr(_strptime, "_CACHE_MAX_SIZE"): return False if not hasattr(_strptime, "_cache_lock"): return False exc...
akornatskyy/wheezy.validation
src/wheezy/validation/patches.py
.py
326229a8bf1f0f31
7
0
import unittest from datetime import date, datetime, time from decimal import Decimal from wheezy.validation.model import ( bool_value_provider, boolean_true_values, bytes_value_provider, date_value_provider, datetime_value_provider, float_value_provider, int_value_provider, str_value_p...
akornatskyy/wheezy.validation
src/wheezy/validation/tests/test_model.py
.py
4e9cb6e3f0c602e0
7.5
0
from gettext import NullTranslations from wheezy.validation.comp import ref_getter null_translations = NullTranslations() class Validator(object): """Container of validation rules that all together provide object validation. """ __slots__ = ("rules", "inner") def __init__(self, m...
akornatskyy/wheezy.validation
src/wheezy/validation/validator.py
.py
b359073c5f628a26
7
0
#!/usr/bin/env python import os from glob import glob from setuptools import Extension, setup # type: ignore[import] def module_name_from_src_path(path: str) -> str: """Derive a fully-qualified module name from a file path under ./src. Cython's default path-to-module logic relies on finding __init__.py fi...
akornatskyy/wheezy.security
setup.py
.py
646492c2df9fe50c
7
0
# flake8: noqa: F811 from hashlib import md5, sha1, sha224, sha256, sha384, sha512 from os import urandom from warnings import warn def digest_size(d): return d().digest_size try: from hashlib import new as openssl_hash def ripemd160(): return openssl_hash("ripemd160") # pragma: nocover ...
akornatskyy/wheezy.security
src/wheezy/security/crypto/comp.py
.py
a75c64dd375e5ff8
7
0
def pad(s, block_size): """Pad with zeros except make the last byte equal to the number of padding bytes. The convention with this method is usually always to add a padding string, even if the original plaintext was already an exact multiple of `block_size` bytes. ``s`` - byte string. """ ...
akornatskyy/wheezy.security
src/wheezy/security/crypto/padding.py
.py
c59700f32e3bcb75
7
0
import unittest from binascii import hexlify, unhexlify from wheezy.security.crypto.padding import pad, unpad class PaddingTestCase(unittest.TestCase): def test_pad(self): """Test pad.""" s = hexlify(pad(b"workbook", 8)).decode() assert "776f726b626f6f6b0000000000000008" == s s = ...
akornatskyy/wheezy.security
src/wheezy/security/crypto/tests/test_padding.py
.py
b44d7288c8b65b0a
7.5
0
import unittest import warnings from base64 import b64encode from wheezy.security.crypto.comp import ( aes128, aes128iv, aes192, aes192iv, aes256, aes256iv, sha1, ) from wheezy.security.crypto.ticket import Ticket, ensure_strong_key class TicketTestCase(unittest.TestCase): def test_en...
akornatskyy/wheezy.security
src/wheezy/security/crypto/tests/test_ticket.py
.py
1eb8a6a8fceafa1f
7.5
0
from base64 import b64decode, b64encode from binascii import Error as BinError from hmac import new as hmac_new from os import urandom from struct import pack, unpack from time import time from warnings import warn from wheezy.security.crypto.comp import ( aes128, block_size, decrypt, digest_size, ...
akornatskyy/wheezy.security
src/wheezy/security/crypto/ticket.py
.py
ee2affe6f9c4a064
7
0
class Principal(object): """Container of user specific security information""" def __init__(self, id="", roles=(), alias="", extra=""): self.id = id self.roles = roles self.alias = alias self.extra = extra def dump(self): """Dump principal object.""" return ...
akornatskyy/wheezy.security
src/wheezy/security/principal.py
.py
af4e7b8f88d7f87a
7
0
import unittest from wheezy.security.authorization import authorized from wheezy.security.errors import SecurityError from wheezy.security.principal import Principal class MyService(object): principal = None @authorized def op_a(self): return True @authorized(roles=("operator",)) def op...
akornatskyy/wheezy.security
src/wheezy/security/tests/test_authorization.py
.py
7154e7e5cfaf39e4
7.5
0
import unittest from wheezy.security.principal import Principal class PrincipalTestCase(unittest.TestCase): def test_dump(self): """Ensure the principal object is dumped correctly with delimiters. """ p = Principal() s = p.dump() assert 3 == len(s) assert "...
akornatskyy/wheezy.security
src/wheezy/security/tests/test_principal.py
.py
e6f6a0b8f1aeec2c
7.5
0
import unittest class MainTestCase(unittest.TestCase): """Test the ``main`` funcation call.""" def test_hello_match(self): """""" from helloworld import main def start_response(status, response_headers): self.assertEqual("200 OK", status) environ = {"PATH_INFO": ...
akornatskyy/wheezy.routing
demos/hello/test_helloworld.py
.py
30f72fd17ed21f0f
7.74
2
import unittest class FunctionalTestCase(unittest.TestCase): """Functional tests for ``time`` application.""" def go(self, path, expected_status="200 OK"): """Make a call to ``main`` function setting wsgi ``environ['PATH_INFO']`` to ``path`` and validating expected http response ...
akornatskyy/wheezy.routing
demos/time/test_functional.py
.py
24f0cfc7dde22336
7.74
2
#!/usr/bin/env python import os from glob import glob from setuptools import Extension, setup # type: ignore[import] def module_name_from_src_path(path: str) -> str: """Derive a fully-qualified module name from a file path under ./src. Cython's default path-to-module logic relies on finding __init__.py fi...
akornatskyy/wheezy.routing
setup.py
.py
ff5c2044c2924047
7.24
2
import re RE_CHOICE_ROUTE = re.compile( r"^(?P<p>[\w/]*)" r"\{(?P<n>\w+):\((?P<c>[\w|]+)\)\}" r"(?P<s>[\w/]*)$" ) def try_build_choice_route(pattern, finishing=True, kwargs=None, name=None): """If the choince route regular expression match the pattern than create a ChoiceRoute instance. """...
akornatskyy/wheezy.routing
src/wheezy/routing/choice.py
.py
2589dc1bc9517c09
7.24
2
import re from wheezy.routing.regex import RegexRoute from wheezy.routing.utils import outer_split RE_SPLIT = re.compile(r"(?P<n>{[\w:]+.*?})") def try_build_curly_route(pattern, finishing=True, kwargs=None, name=None): """Convert pattern expression into regex with named groups and create regex ro...
akornatskyy/wheezy.routing
src/wheezy/routing/curly.py
.py
64b663307cc1b791
7.24
2
import re RE_PLAIN_ROUTE = re.compile(r"^[\w\./-]+$") def try_build_plain_route(pattern, finishing=True, kwargs=None, name=None): """If the plain route regular expression match the pattern than create a PlainRoute instance. """ if isinstance(pattern, PlainRoute): return pattern ...
akornatskyy/wheezy.routing
src/wheezy/routing/plain.py
.py
84d612a136af52dc
7.24
2
# flake8: noqa: W605 import re from wheezy.routing.utils import outer_split def try_build_regex_route(pattern, finishing=True, kwargs=None, name=None): """There is no special tests to match regex selection strategy. """ if isinstance(pattern, RegexRoute): return pattern return RegexRoute...
akornatskyy/wheezy.routing
src/wheezy/routing/regex.py
.py
b217c44a4f7d0f21
7.24
2
import unittest from unittest.mock import Mock from wheezy.routing.builders import build_route class BuildersTestCase(unittest.TestCase): def test_name_raises_error(self): """Name for intermediate route has no sense.""" self.assertRaises( AssertionError, lambda: build_rout...
akornatskyy/wheezy.routing
src/wheezy/routing/tests/test_builders.py
.py
208ac2c69f535896
7.74
2
import unittest from wheezy.routing.choice import ChoiceRoute, try_build_choice_route class TryChoiceRouteTestCase(unittest.TestCase): def test_build(self): """Ensure choice route is built.""" route = try_build_choice_route("{locale:(en|ru)}") assert route assert route == try_buil...
akornatskyy/wheezy.routing
src/wheezy/routing/tests/test_choice.py
.py
0e651230aa93a94d
7.74
2
import inspect import unittest from wheezy.routing import config def callable(obj): return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) class RouteBuildersTestCase(unittest.TestCase): """Test the ``config.route_builders`` setting.""" def test_builder_callable(self): """Ensu...
akornatskyy/wheezy.routing
src/wheezy/routing/tests/test_config.py
.py
ffab28fa094bdc9f
7.74
2
import re import unittest from wheezy.routing import config from wheezy.routing.curly import ( convert, default_pattern, parse, patterns, replace, try_build_curly_route, ) class TryBuildCurlyRouteTestCase(unittest.TestCase): def test_build(self): """Ensure curly route is built."""...
akornatskyy/wheezy.routing
src/wheezy/routing/tests/test_curly.py
.py
3e44c9b281451f99
7.74
2
import unittest from wheezy.routing.plain import PlainRoute, try_build_plain_route class TryPlainRouteTestCase(unittest.TestCase): def test_build(self): """Ensure plain route is built.""" route = try_build_plain_route("favicon.ico") assert route assert route == try_build_plain_rou...
akornatskyy/wheezy.routing
src/wheezy/routing/tests/test_plain.py
.py
d2ca4dd17fc9d432
7.74
2
import unittest from wheezy.routing.route import Route class RouteTestCase(unittest.TestCase): def test_raises_errors(self): """Ensure Route raises errors.""" r = Route() assert not r.exact_matches self.assertRaises(NotImplementedError, lambda: r.match("")) self.assertRais...
akornatskyy/wheezy.routing
src/wheezy/routing/tests/test_route.py
.py
47026adfe248c2d0
7.24
2
import re RE_STRIP_NAME = re.compile(r"(Handler|Controller|Page|View)$") RE_CAMELCASE_TO_UNDERSCOPE_1 = re.compile("(.)([A-Z][a-z]+)") RE_CAMELCASE_TO_UNDERSCOPE_2 = re.compile("([a-z0-9])([A-Z])") def route_name(handler): """Return a name for the given handler. ``handler`` can be an object, class o...
akornatskyy/wheezy.routing
src/wheezy/routing/utils.py
.py
d3bf40dcf07926f5
7.24
2
#!/usr/bin/env python import os from glob import glob from setuptools import Extension, setup # type: ignore[import] def module_name_from_src_path(path: str) -> str: """Derive a fully-qualified module name from a file path under ./src. Cython's default path-to-module logic relies on finding __init__.py fi...
akornatskyy/wheezy.caching
setup.py
.py
a9ef36ad9a137aba
7
0
class CacheClient(object): """CacheClient serves mediator purpose between a single entry point that implements Cache and one or many namespaces targeted to concrete cache implementations. CacheClient let partition application cache by namespaces effectively hiding details from client code. ...
akornatskyy/wheezy.caching
src/wheezy/caching/client.py
.py
ba3ebd6914d6e459
7
0
from wheezy.caching.utils import total_seconds class CacheDependency(object): """CacheDependency introduces a `wire` between cache items so they can be invalidated via a single operation, thus simplifing code necessary to manage dependencies in cache. """ def __init__(self, cache, time=0...
akornatskyy/wheezy.caching
src/wheezy/caching/dependency.py
.py
1fa207ee71248c60
7
0
from base64 import b64encode BASE64_ALTCHARS = "-_".encode("latin1") def encode_keys(mapping, key_encode): """Encodes all keys in mapping with ``key_encode`` callable. Returns tuple of: key mapping (encoded key => key) and value mapping (encoded key => value). >>> mapping = {'k1': 1, 'k2':...
akornatskyy/wheezy.caching
src/wheezy/caching/encoding.py
.py
ae18c584ab1149ae
7
0
from warnings import warn from wheezy.caching.utils import total_seconds class Locker(object): """Used to define lockout terms.""" def __init__( self, cache, forbid_action, namespace=None, key_prefix="c", **terms ): self.cache = cache self.forbid_action = forbid_actio...
akornatskyy/wheezy.caching
src/wheezy/caching/lockout.py
.py
26cff81d3338fafd
7
0
from hashlib import sha1 from logging import Handler from wheezy.caching.encoding import hash_encode from wheezy.caching.utils import total_seconds class OnePassHandler(Handler): """One pass logging handler is used to proxy a message to inner handler once per one pass duration. """ def _...
akornatskyy/wheezy.caching
src/wheezy/caching/logging.py
.py
6acbcffe4d5d573b
7
0
from wheezy.caching.encoding import encode_keys, string_encode try: from memcache import Client except ImportError: # pragma: nocover Client = None import warnings warnings.warn("No module named 'memcache'", stacklevel=2) class MemcachedClient(object): """A wrapper around python-mem...
akornatskyy/wheezy.caching
src/wheezy/caching/memcache.py
.py
79220fad1db35e72
7
0
from inspect import getfullargspec from time import sleep, time from wheezy.caching.dependency import CacheDependency from wheezy.caching.utils import total_seconds class Cached(object): """Specializes access to cache by using a number of common settings for various cache operations and patterns. ...
akornatskyy/wheezy.caching
src/wheezy/caching/patterns.py
.py
dd00a58d6f626bbe
7
0
import unittest from unittest.mock import Mock from wheezy.caching.logging import OnePassHandler class OnePassHandlerTestCase(unittest.TestCase): def setUp(self): self.mock_inner = Mock() self.mock_cache = Mock() self.h = OnePassHandler(self.mock_inner, self.mock_cache, 60) def test_...
akornatskyy/wheezy.caching
src/wheezy/caching/tests/test_logging.py
.py
6e49902e208ec4a1
7.5
0
import re known_functions = ["format"] RE_ARGS = re.compile(r'\s*(?P<expr>(([\'"]).*?\3|.+?))\s*\,') RE_KWARGS = re.compile( r'\s*(?P<name>\w+)\s*=\s*(?P<expr>([\'"].*?[\'"]|.+?))\s*\,' ) RE_STR_VALUE = re.compile(r'^[\'"](?P<value>.+)[\'"]$') RE_INT_VALUE = re.compile(r"^(?P<value>(\d+))$") RE_FUNCTION...
akornatskyy/wheezy.html
src/wheezy/html/ext/parser.py
.py
359ad70f960991ae
7.15
1
import unittest from wheezy.html.ext.tests.test_lexer import PreprocessorMixin class Jinja2PreprocessorTestCase(PreprocessorMixin, unittest.TestCase): """Test the ``Jinja2Preprocessor``.""" WHITE_SPACE_PATTERNS = ["%(w)s", " %(w)s", "%(w)s ", " %(w)s "] def assert_render_equal(self, template, expected,...
akornatskyy/wheezy.html
src/wheezy/html/ext/tests/test_jinja2.py
.py
da39038ad2838488
7.65
1
import unittest from wheezy.html.ext.tests.test_lexer import PreprocessorMixin class MakoPreprocessorTestCase(PreprocessorMixin, unittest.TestCase): """Test the ``MakoPreprocessor``.""" WHITE_SPACE_PATTERNS = ["%(w)s", " %(w)s", "%(w)s ", " %(w)s "] def assert_render_equal(self, template, expected, **k...
akornatskyy/wheezy.html
src/wheezy/html/ext/tests/test_mako.py
.py
9d2a56c581163884
7.65
1
import unittest from wheezy.html.ext.tests.test_lexer import PreprocessorMixin class TenjinPreprocessorTestCase(PreprocessorMixin, unittest.TestCase): """Test the ``TenjinPreprocessor``.""" WHITE_SPACE_PATTERNS = ["%(w)s", "[ %(w)s", "%(w)s ", "[ %(w)s "] def assert_render_equal(self, template, expecte...
akornatskyy/wheezy.html
src/wheezy/html/ext/tests/test_tenjin.py
.py
f523dbbbfab157a8
7.65
1
from datetime import date, datetime def escape_html(s): """Escapes a string so it is valid within HTML. Converts `None` to an empty string. Raises TypeError is `s` is not a string or unicode object. >>> html_escape(None) '' >>> escape_html('&<>"\\'') "&amp;&lt;&gt;&quot;\'" ...
akornatskyy/wheezy.html
src/wheezy/html/utils.py
.py
d7ee95a13eb1404a
7.15
1
import unittest from wheezy.http.functional import WSGIClient class MainFunctionalTestCase(unittest.TestCase): """Functional tests for ``guestbook`` application.""" def setUp(self): from guestbook import main self.client = WSGIClient(main) def tearDown(self): del self.client ...
akornatskyy/wheezy.http
demos/guestbook/test_guestbook.py
.py
93354745742a7f5c
7.65
1
import unittest from wheezy.http.functional import WSGIClient class HelloWorldTestCase(unittest.TestCase): def setUp(self): from helloworld import main self.client = WSGIClient(main) def tearDown(self): del self.client self.client = None def test_welcome(self): ...
akornatskyy/wheezy.http
demos/hello/test_helloworld.py
.py
f5ffb59fe9140000
7.65
1
#!/usr/bin/env python import os from glob import glob from setuptools import Extension, setup # type: ignore[import] def module_name_from_src_path(path: str) -> str: """Derive a fully-qualified module name from a file path under ./src. Cython's default path-to-module logic relies on finding __init__.py fi...
akornatskyy/wheezy.http
setup.py
.py
f759806b909c95ff
7.15
1
from functools import reduce from wheezy.http.request import HTTPRequest from wheezy.http.response import not_found def wrap_middleware(following, func): """Helper function to wrap middleware, adapts middleware contract to:: def handler(request): return response ``following`` - next...
akornatskyy/wheezy.http
src/wheezy/http/application.py
.py
cc83574219314c99
7.15
1
from wheezy.core.datetime import format_http_datetime, total_seconds SUPPORTED = ["no-cache", "private", "public"] class HTTPCachePolicy(object): """Controls cache specific http headers.""" modified = None http_last_modified = None http_etag = None is_no_store = False is_must_revalidate = Fa...
akornatskyy/wheezy.http
src/wheezy/http/cachepolicy.py
.py
d8cff2146bec04a0
7.15
1
from datetime import datetime, timezone from time import time from wheezy.core.datetime import format_http_datetime, total_seconds from wheezy.http.cachepolicy import HTTPCachePolicy UTC = timezone.utc CACHEABILITY = { "none": "no-cache", "server": "no-cache", "client": "private", "both": "private", ...
akornatskyy/wheezy.http
src/wheezy/http/cacheprofile.py
.py
77000fcd4ccd9176
7.15
1
import re from http.cookies import SimpleCookie from io import BytesIO from json import loads as json_loads from urllib.parse import urlencode, urlsplit from wheezy.core.benchmark import Benchmark, Timer from wheezy.core.collections import attrdict, defaultdict RE_FORMS = re.compile(r"<form.*?</form>", re.DOTALL) DEF...
akornatskyy/wheezy.http
src/wheezy/http/functional.py
.py
4652cfcf96476c18
7.15
1
from urllib.parse import unquote try: from cgi import FieldStorage except ImportError: from wheezy.http._cgi import FieldStorage MULTIPART_ENVIRON = {"REQUEST_METHOD": "POST"} def parse_qs(qs): params = {} for field in qs.split("&"): r = field.partition("=") k = r[0] v = r[2]...
akornatskyy/wheezy.http
src/wheezy/http/parse.py
.py
74a94bae9f7a8edf
7.15
1
from json import loads as json_loads from wheezy.core.descriptors import attribute from wheezy.core.url import UrlParts from wheezy.http.parse import parse_cookie, parse_multipart, parse_qs class HTTPRequest(object): """Represent HTTP request. ``environ`` variables are accessable via attributes. """ ...
akornatskyy/wheezy.http
src/wheezy/http/request.py
.py
d228e395da40a287
7.15
1
from wheezy.core.json import json_encode # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html # see http://en.wikipedia.org/wiki/List_of_HTTP_status_codes HTTP_STATUS = { # Informational 100: "100 Continue", 101: "101 Switching Protocols", # Successful 200: "200 OK", 201: "201 Created",...
akornatskyy/wheezy.http
src/wheezy/http/response.py
.py
a8d97ab5f1996f46
7.15
1
from io import BytesIO def multipart(environ): # pragma: nocover """Setup multipart/form-data request.""" body = """----A Content-Disposition: form-data; name="name" test ----A Content-Disposition: form-data; name="file"; filename="f.txt" Content-Type: text/plain hello ----A--""" environ["wsgi.input"] ...
akornatskyy/wheezy.http
src/wheezy/http/tests/sample.py
.py
27e365c62ab38070
7.65
1
import inspect import unittest from unittest.mock import Mock from wheezy.http.application import WSGIApplication, wrap_middleware class WrapMiddlewareTestCase(unittest.TestCase): """Test the ``wrap_middleware``.""" def test_callable(self): """Ensure ``wrap_middleware`` returns a valid calla...
akornatskyy/wheezy.http
src/wheezy/http/tests/test_application.py
.py
63fdf31e9878c5e1
7.65
1
import unittest from unittest.mock import Mock from wheezy.http.authorization import secure class SecureTestCase(unittest.TestCase): """Test the ``secure``.""" def test_check_not_secure(self): """Check if request is not secure. @secure def my_view(request): ... "...
akornatskyy/wheezy.http
src/wheezy/http/tests/test_authorization.py
.py
422bcd4fb8a49029
7.65
1
import unittest from datetime import datetime, timedelta, timezone from unittest.mock import Mock, patch from wheezy.core.datetime import parse_http_datetime from wheezy.http.cacheprofile import ( # isort:skip CACHEABILITY, CacheProfile, RequestVary, SUPPORTED, ) UTC = timezone.utc class Supported...
akornatskyy/wheezy.http
src/wheezy/http/tests/test_cacheprofile.py
.py
51a2c56b791021a1
7.65
1
import unittest from wheezy.http.config import bootstrap_http_defaults class BootstrapHTTPDefaultsTestCase(unittest.TestCase): """Test the ``bootstrap_http_defaults``.""" def test_default_options(self): """Ensure required keys exist.""" options = {} assert bootstrap_http_defaults(op...
akornatskyy/wheezy.http
src/wheezy/http/tests/test_config.py
.py
eb9bd401083b44a9
7.65
1
import re import unittest from datetime import datetime, timedelta, timezone from wheezy.core.datetime import parse_http_datetime from wheezy.http.config import bootstrap_http_defaults from wheezy.http.cookie import HTTPCookie UTC = timezone.utc class HTTPCookieTestCase(unittest.TestCase): """Test the ``HTTPCo...
akornatskyy/wheezy.http
src/wheezy/http/tests/test_cookie.py
.py
d4afd6e6ae4226fc
7.65
1
import unittest from wheezy.http.parse import parse_cookie, parse_multipart, parse_qs from wheezy.http.tests import sample class ParseQSTestCase(unittest.TestCase): """Test the ``parse_qs``.""" def test_parse(self): """Ensure query string is parsed correctly.""" for s, e in ( (""...
akornatskyy/wheezy.http
src/wheezy/http/tests/test_parse.py
.py
85a0f11127383ae2
7.65
1
import unittest from unittest.mock import patch from wheezy.http import request from wheezy.http.request import HTTPRequest from wheezy.http.tests import sample class HTTPRequestTestCase(unittest.TestCase): """Test the ``HTTPRequest`` class.""" def setUp(self): self.options = {"MAX_CONTENT_LENGTH": ...
akornatskyy/wheezy.http
src/wheezy/http/tests/test_request.py
.py
231ccede4524b0e9
7.65
1
import unittest from unittest.mock import patch from wheezy.http import response from wheezy.http.response import json_response class ShortcutsTestCase(unittest.TestCase): """Test various response shortcuts.""" def test_json_response(self): """json_response""" patcher = patch.object(response...
akornatskyy/wheezy.http
src/wheezy/http/tests/test_response.py
.py
4a6a67ff306dbff2
7.65
1
#!/usr/bin/env python import os from glob import glob from setuptools import Extension, setup # type: ignore[import] def module_name_from_src_path(path: str) -> str: """Derive a fully-qualified module name from a file path under ./src. Cython's default path-to-module logic relies on finding __init__.py fi...
akornatskyy/wheezy.core
setup.py
.py
f98a3b9ccd64cb91
7
0
from timeit import default_timer # noqa from timeit import timeit class Benchmark(object): """Measure execution time of your code.""" def __init__(self, targets, number, warmup_number=None, timer=None): """ ``targets`` - a list of targets (callables) to be tested. ``numbe...
akornatskyy/wheezy.core
src/wheezy/core/benchmark.py
.py
b9109862757e0fa5
7
0
from datetime import datetime, timedelta, timezone, tzinfo from email.utils import parsedate from time import localtime, mktime UTC = timezone.utc ZERO = timedelta(0) WEEKDAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") MONTHS = ( None, "Jan", "Feb", "Mar", "Apr", "May", ...
akornatskyy/wheezy.core
src/wheezy/core/datetime.py
.py
6f2effb0fda6f0a3
7
0