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 |
|---|---|---|---|---|---|---|
"""File I/O helpers supporting CSV and Stata (.dta) formats.
Format is auto-detected from file extensions:
.dta → Stata
anything else → CSV (the default)
"""
import pandas as pd
from pathlib import Path
from typing import Union
STATA_EXTENSIONS = {".dta"}
def _is_stata(path: Union[str, Path]) -> bool:
ret... | PolicyEngine/policyengine-taxsim | policyengine_taxsim/core/io.py | .py | 929a8b7303a67bf2 | 7.63 | 17 |
"""
Format a single PE-Microsim result row in TAXSIM-35's labeled-section
text output (idtl=5). Reads values from the result DataFrame row plus
the input row; does not run a fresh Simulation. Mirrors the legacy
output from `generate_text_description_output` so the cli stdin/stdout
flow can emit idtl=5 output without fa... | PolicyEngine/policyengine-taxsim | policyengine_taxsim/core/text_formatter.py | .py | 476646cc57ec0358 | 7.63 | 17 |
import functools
import numpy as np
import yaml
from pathlib import Path
@functools.lru_cache(maxsize=1)
def load_variable_mappings():
"""Load variable mappings from YAML file (cached after first call)."""
config_path = Path(__file__).parent.parent / "config" / "variable_mappings.yaml"
with open(config_pa... | PolicyEngine/policyengine-taxsim | policyengine_taxsim/core/utils.py | .py | a59c6d9055b70abc | 7.63 | 17 |
import yaml
import numpy as np
from typing import Dict, Any, Optional, List
class PETestsYAMLGenerator:
def __init__(self):
pass
def _get_year(self, household_data: Dict[str, Any]) -> int:
"""Extract the year from household data."""
state_name_data = (
household_data.get("... | PolicyEngine/policyengine-taxsim | policyengine_taxsim/core/yaml_generator.py | .py | ddc73190b90c1f27 | 7.63 | 17 |
import sys
import pandas as pd
from abc import ABC, abstractmethod
from typing import Optional, Union
from pathlib import Path
try:
from ..core.io import write_output
except ImportError:
from policyengine_taxsim.core.io import write_output
class BaseTaxRunner(ABC):
"""Abstract base class for tax calcula... | PolicyEngine/policyengine-taxsim | policyengine_taxsim/runners/base_runner.py | .py | 0fb7b248e0e006aa | 7.63 | 17 |
"""Runner that submits CSV to NBER's hosted TAXSIM-35 web service."""
import logging
import pandas as pd
from io import StringIO
from .base_runner import BaseTaxRunner
from ..core.utils import convert_taxsim32_dependents
logger = logging.getLogger(__name__)
TAXSIM_URL = "https://taxsim.nber.org/taxsim35/redirect.cg... | PolicyEngine/policyengine-taxsim | policyengine_taxsim/runners/remote_taxsim_runner.py | .py | 4e791781dc2ce715 | 7.63 | 17 |
"""Runner that stitches PolicyEngine (2021+) and TAXSIM (pre-2021) results."""
import logging
import pandas as pd
from .base_runner import BaseTaxRunner
from .policyengine_runner import PolicyEngineRunner
logger = logging.getLogger(__name__)
class StitchedRunner(BaseTaxRunner):
"""Routes rows to PolicyEngine o... | PolicyEngine/policyengine-taxsim | policyengine_taxsim/runners/stitched_runner.py | .py | a3f6fc2054bb9800 | 7.63 | 17 |
import os
import platform
import subprocess
import tempfile
from pathlib import Path
import pandas as pd
from .base_runner import BaseTaxRunner
from ..core.utils import convert_taxsim32_dependents
class TaxsimRunner(BaseTaxRunner):
"""Clean TAXSIMTEST executable runner"""
# TAXSIM column definitions based on... | PolicyEngine/policyengine-taxsim | policyengine_taxsim/runners/taxsim_runner.py | .py | f13ed562f948f133 | 7.63 | 17 |
"""Convert a PolicyEngine H5 dataset to TAXSIM CSV format.
Usage:
python scripts/convert_h5_to_taxsim.py [--dataset small_enhanced_cps_2024] [--year 2024] [--output dashboard/public/sample_ecps_2024.csv]
Requires: policyengine-us, huggingface_hub
"""
import argparse
import numpy as np
import pandas as pd
# FIPS... | PolicyEngine/policyengine-taxsim | scripts/convert_h5_to_taxsim.py | .py | 54ede242893cf3c0 | 7.63 | 17 |
"""
Test that PE's `fiitax` output does NOT include the Additional
Medicare Tax (Form 8959, IRC § 3101(b)(2) / § 1401(b)(2)).
NBER TAXSIM-35 (`taxsimtest`) reports AddMed in a separate `addmed`
column rather than rolling it into `fiitax`. This matches Form 1040
Line 23 / Schedule 2 Line 11: Additional Medicare Tax is ... | PolicyEngine/policyengine-taxsim | tests/test_addmed_excluded_from_fiitax.py | .py | 33c8d959d8b2481b | 8.13 | 17 |
"""
Tests for the --assume-w2-wages flag.
This flag sets w2_wages_from_qualified_business to a large value so that
the W-2 wage cap in the QBID calculation never binds, aligning PE's
Section 199A implementation with TAXSIM's simplified approach for S-Corp income.
"""
import pytest
import numpy as np
import pandas as ... | PolicyEngine/policyengine-taxsim | tests/test_assume_w2_wages.py | .py | 15d88d455c9cd2cb | 7.13 | 17 |
"""
Regression test for issue #702: CLI entry point must resolve to a callable.
The Aug 2025 click group refactor renamed `main` to `cli` in cli.py but
forgot to update pyproject.toml, breaking every `policyengine-taxsim`
command for new installs. This test ensures the entry point stays valid.
"""
from importlib.met... | PolicyEngine/policyengine-taxsim | tests/test_cli_entry_point.py | .py | 4aca16bc4f0106a8 | 7.13 | 17 |
"""
Tests for idtl=5 (human-readable full-text) output in the cli stdin/stdout
flow. The legacy `exe.py` PyInstaller entry point supported idtl=5; the
current Microsim-based cli.py used to always emit CSV. This restores the
idtl=5 path by rendering result-DataFrame rows in TAXSIM's labeled
section format (Input Data / ... | PolicyEngine/policyengine-taxsim | tests/test_cli_idtl5.py | .py | 4387f9c15d5079c4 | 8.13 | 17 |
"""
Regression test for the `fica` output column.
TAXSIM's `fica` column is the *combined* employee + employer FICA (OASDI +
HI, including Additional Medicare Tax); `tfica` is the employee-only half.
The `fica` column was mapped to the `na_pe` sentinel (always 0.0) even after
the PolicyEngine-US `taxsim_fica` variable... | PolicyEngine/policyengine-taxsim | tests/test_fica_output.py | .py | 26eb241eb2fb264e | 8.13 | 17 |
"""
Regression test for zeroing PE-imputed means-tested transfers.
TAXSIM has no input columns for SSI, SNAP, TANF, WIC or state SSI
supplements. PolicyEngine imputes these for low-income records, and they
leak into state calculations that count cash public assistance as income —
most visibly the Massachusetts Senior ... | PolicyEngine/policyengine-taxsim | tests/test_imputed_transfers_zeroed.py | .py | f9d8c28ce27d8fbb | 8.13 | 17 |
"""
Tests for the income-scaled match tolerance in the comparator.
The flat $15 absolute tolerance flags negligible differences on
extreme-magnitude records (e.g. large S-corp income/losses), where PE and
TAXSIM agree to a tiny fraction of income. `relative_tolerance` lets a record
match within max($15, relative_toler... | PolicyEngine/policyengine-taxsim | tests/test_income_scaled_tolerance.py | .py | 483d71ff12fc8ac2 | 8.13 | 17 |
"""
MA's COVID-19 Essential Employee Premium Pay Program must stay out of siitax.
Chapter 102 of the Acts of 2021 funded $500-per-worker premium pay checks
mailed during 2022 to low-income essential workers (earnings above a minimum,
AGI under 300% of poverty). They were direct payments, never a Form 1 line,
so neithe... | PolicyEngine/policyengine-taxsim | tests/test_ma_premium_pay.py | .py | 352eb769a3369d3c | 8.13 | 17 |
"""
Maryland county/local income tax parity with TAXSIM.
TAXSIM's Maryland `siitax` is state-only: it applies no county tax when the
input carries no locality. PolicyEngine applies MD's residence-based county
tax (~2.25-3.20%) to every MD resident, over-stating MD siitax vs TAXSIM.
Since the TAXSIM input has no county... | PolicyEngine/policyengine-taxsim | tests/test_md_local_tax_parity.py | .py | ab64590663078eda | 8.13 | 17 |
"""
Maine's 2025 affordability payment must stay out of siitax.
H.P. 1491 (132nd Leg.), Part T creates a one-time $300-per-adult payment
for TY2025 filers under FAGI limits, paid by the State Tax Assessor from a
Special Revenue Fund in 2026-27. It is not a 1040ME line item, so neither
TAXSIM nor commercial software re... | PolicyEngine/policyengine-taxsim | tests/test_me_affordability_payment.py | .py | bd15bb10f142ee02 | 8.13 | 17 |
"""
Multi-state batch tests to guard against StateGroup enum regressions.
The state_group variable in policyengine-us must correctly map all state
codes to their StateGroup (CONTIGUOUS_US, AK, HI, etc.). A previous bug
(fixed in policyengine-us 1.449.1) called StateGroup.encode() on raw
state codes like 'AL' and 'KY'... | PolicyEngine/policyengine-taxsim | tests/test_multi_state.py | .py | be28cc79e1ead23f | 7.13 | 17 |
"""
Tests for rebate-aware state tax comparison (--net-of-rebates).
TAXSIM includes one-time state rebates in `siitax` in the payout year and
reports them in the `srebate` output column; PolicyEngine books them to the
liability year inside `state_income_tax`. Scoring `siitax + srebate` on both
sides removes this timin... | PolicyEngine/policyengine-taxsim | tests/test_net_of_rebates.py | .py | 367d0d47092bf22a | 8.13 | 17 |
"""
Wraps open_source/common/run_experiment.py to enable running experiments in AML.
Check open_source/common/run_experiment.py for details what arguments to use to run an expeirment.
"""
import argparse
import os
import sys
from typing import List
from evaluation_pipeline.aml_run_context import setup_run_context_in_a... | microsoft/Project-BayesDAG | run_experiment.py | .py | 318f17342cf40ab9 | 7.62 | 16 |
from typing import Callable, Dict, List, Optional
import jax
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from jax import nn, random
# pylint: disable=wrong-import-position
jax.config.update("jax_platform_name", "cpu")
from numpyro import plate
from numpyro.handlers imp... | microsoft/Project-BayesDAG | src/causica/data_generation/csuite/pyro_utils.py | .py | bbed27d8aa6a98c4 | 7.62 | 16 |
import os
import pickle as pkl
import random
import graphviz
import igraph as ig
import numpy as np
import pyro.distributions as dist
import torch
from scipy.special import softmax
from ...utils.nri_utils import BGe, enum_all_graphs
from ...utils.torch_utils import generate_fully_connected
def save_data(
datase... | microsoft/Project-BayesDAG | src/causica/data_generation/large_synthetic/data_utils.py | .py | 341f853c82b77b1e | 7.62 | 16 |
import logging
import os
from typing import List, Optional, Tuple, TypedDict, Union
import numpy as np
from ..utils.io_utils import read_json_as
from .csv_dataset_loader import CSVDatasetLoader
from .dataset import CausalDataset
from .intervention_data import InterventionData, InterventionDataContainer
class Option... | microsoft/Project-BayesDAG | src/causica/datasets/causal_csv_dataset_loader.py | .py | f4c0f30c73bca132 | 7.62 | 16 |
import io
import logging
import os
import warnings
from typing import List, Optional, Tuple, Union
import numpy as np
import pandas as pd
import pickle as pkl
from ..datasets.dataset import Dataset
from ..datasets.dataset_loader import DatasetLoader
from ..datasets.variables import Variables
logger = logging.getLogg... | microsoft/Project-BayesDAG | src/causica/datasets/csv_dataset_loader.py | .py | d313bc98c543efc5 | 7.62 | 16 |
import os
import warnings
from typing import Any, Dict, List, Optional, Tuple, Union, cast
import numpy as np
from scipy.sparse import csr_matrix, issparse
from ..utils.io_utils import save_json
from .intervention_data import InterventionData
from .variables import Variables
T = Union[csr_matrix, np.ndarray]
class... | microsoft/Project-BayesDAG | src/causica/datasets/dataset.py | .py | 449b08c6ca63a5f4 | 7.62 | 16 |
import logging
import os
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Tuple, Union, cast
import numpy as np
import pandas as pd
from scipy.sparse import issparse
from sklearn.model_selection import train_test_split
from tqdm import tqdm
from ..datasets.dataset import Dataset, Spar... | microsoft/Project-BayesDAG | src/causica/datasets/dataset_loader.py | .py | 43b31ba0c5413e48 | 7.62 | 16 |
from typing import List, NamedTuple, Optional
import numpy as np
class InterventionMetadata(NamedTuple):
columns_to_nodes: List[int]
def to_dict(self):
return self._asdict()
class InterventionData(NamedTuple):
"""Class that acts as a container for observational (rank-1), interventional (rank-... | microsoft/Project-BayesDAG | src/causica/datasets/intervention_data.py | .py | 5d859c5ebcd05d1e | 7.62 | 16 |
from typing import Callable
def mock_download_dataset(dataset_name: str, data_dir: str):
raise NotImplementedError("No download_dataset functionality provided")
def aml_step(func: Callable, _: bool) -> Callable:
return func
class RunContext:
"""
Run context which carries information about the comp... | microsoft/Project-BayesDAG | src/causica/experiment/run_context.py | .py | f4efe625a9fcc1ef | 7.62 | 16 |
"""
Aggregate results from multiple models.
See parallel_random_seeds_and_aggregate.py for example usage with AzureML.
"""
import copy
import glob
import logging
import os
from typing import Any, Dict, List
import mlflow
import pandas as pd
from ...datasets.variables import Variables
from ...utils.io_utils import f... | microsoft/Project-BayesDAG | src/causica/experiment/steps/aggregation_step.py | .py | 7a40100e73250a75 | 7.62 | 16 |
from __future__ import annotations
import torch
from ...datasets.variables import Variables
from .bayesdag_nonlinear import BayesDAGNonLinear
class BayesDAGLinear(BayesDAGNonLinear):
"""
Approximate Bayesian inference over the graph in a Gaussian linear ANM based on the BayesDAG result. Any DAG G is represen... | microsoft/Project-BayesDAG | src/causica/models/bayesdag/bayesdag_linear.py | .py | d2cfd41be0361966 | 7.62 | 16 |
import copy
from typing import Dict, List, Optional, Tuple, Type
import torch
from functorch import FunctionalModuleWithBuffers
from functorch._src.make_functional import _swap_state, extract_weights, transpose_stack, extract_buffers
from torch import nn
from ...utils.torch_utils import generate_fully_connected
cla... | microsoft/Project-BayesDAG | src/causica/models/bayesdag/generation_functions.py | .py | 984ec3f238b6d6d9 | 7.62 | 16 |
# This is required in python 3 to allow return types of the same class.
from __future__ import annotations
import os
from typing import Tuple
import numpy as np
from ..datasets.variables import Variables
from ..utils.helper_functions import write_git_info
from .imodel import IModel
class Model(IModel):
"""
... | microsoft/Project-BayesDAG | src/causica/models/model.py | .py | bc92ec328d428111 | 7.62 | 16 |
import os
from typing import Optional
import torch
from torch.nn import Linear, ReLU, Sequential
from .feature_embedder import FeatureEmbedder, SparseFeatureEmbedder
from .set_encoder_base_model import SetEncoderBaseModel
from .torch_model import ONNXNotImplemented
class PointNet(SetEncoderBaseModel):
"""
E... | microsoft/Project-BayesDAG | src/causica/models/point_net.py | .py | 8b62853ae72a50b4 | 7.62 | 16 |
from __future__ import annotations
import copy
import logging
import os
from time import gmtime, strftime
from typing import Any, Dict, Tuple, Type, TypeVar, Union
import torch
from ..datasets.variables import Variables
from ..utils.helper_functions import maintain_random_state
from ..utils.io_utils import read_json... | microsoft/Project-BayesDAG | src/causica/models/torch_model.py | .py | e1d72eb4aa696808 | 7.62 | 16 |
import os
import sys
import json
import uuid
import random
import asyncio
import logging
import argparse
import aiohttp
from vastai import Serverless
# ---------------------- Config ----------------------
DEFAULT_PROMPT = "a beautiful sunset over mountains, digital art, highly detailed"
ENDPOINT_NAME = "my-comfyui-en... | vast-ai/pyworker | workers/comfyui-json/client.py | .py | 6e9c9bd644580b7d | 7.65 | 19 |
"""Shared core for the OpenAI-compatible workers (vllm/sglang/llama/openai).
They all proxy the same /v1/completions + /v1/chat/completions API, so the logic lives
here and the per-engine adapters just pass an EngineDefaults. Every default is
env-overridable: the image is version-locked to the engine, so it owns the
e... | vast-ai/pyworker | workers/openai/core.py | .py | 159aab545ec40b49 | 7.65 | 19 |
import logging
import json
import os
import sys
import argparse
from vastai import Serverless
import asyncio
# ---------------------- Logging ----------------------
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s[%(levelname)-5s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
log = logging.get... | vast-ai/pyworker | workers/tgi/client.py | .py | 534077b5972e8758 | 7.65 | 19 |
"""Configuration models and schedule helpers for Carrier systems."""
from datetime import UTC, datetime
from logging import getLogger
from typing import TYPE_CHECKING, Any
from .const import ActivityTypes, FanModes
from .util import safely_get_json_value
if TYPE_CHECKING:
from .status import StatusZone
_LOGGER ... | dahlb/carrier_api | src/carrier_api/config.py | .py | 9731c906594a8fa7 | 7.5 | 9 |
"""Constants and enumerations used by the Carrier API models and mutations."""
from enum import Enum
VERSION: str = "3.4.1"
class SystemModes(Enum):
"""Operating modes accepted or reported by Carrier systems."""
OFF = "off"
COOL = "cool"
HEAT = "heat"
AUTO = "auto"
FAN_ONLY = "fanonly"
cl... | dahlb/carrier_api | src/carrier_api/const.py | .py | fef4df5cafd4323b | 7.5 | 9 |
"""Energy configuration and usage models for Carrier systems."""
from dataclasses import dataclass
from enum import StrEnum
from math import isfinite
from typing import Any
from .util import safely_get_json_value
EnergyUsageValue = int | float | None
class EnergyPeriod(StrEnum):
"""Carrier energy reporting per... | dahlb/carrier_api | src/carrier_api/energy.py | .py | 280f53075995ad70 | 7.5 | 9 |
"""Models for Carrier "entry level" (Smart Thermostat) systems and zones.
These cover the non-Infinity Carrier Smart Thermostat line (e.g. TSTATCCEEF-01)
exposed by the cloud as ``entryLevelSystems``. They are a separate object type
from Infinity ``System``: single-zone, addressed by serial and zone index, with
cool/h... | dahlb/carrier_api | src/carrier_api/entry_level.py | .py | caac04549661644b | 7.5 | 9 |
"""Carrier API exception types."""
from typing import Any
from aiohttp import ClientError
class CarrierApiError(Exception):
"""Base exception for Carrier API failures."""
def __init__(self, message: object, payload: Any | None = None) -> None:
"""Initialize a Carrier API exception.
Args:
... | dahlb/carrier_api | src/carrier_api/errors.py | .py | 9d8e7c33b69ff7b8 | 7.5 | 9 |
"""Carrier system profile model."""
from logging import getLogger
from typing import Any
from .util import safely_get_json_value
_LOGGER = getLogger(__name__)
class Profile:
"""Static identity and equipment metadata for a Carrier system."""
model: str | None = None
brand: str | None = None
firmwar... | dahlb/carrier_api | src/carrier_api/profile.py | .py | 1d1d39e3aca64e29 | 7.5 | 9 |
"""Current operational status models for Carrier systems and zones."""
from datetime import datetime
from typing import Any
from dateutil.parser import isoparse
from .const import ActivityTypes, FanModes, SystemModes, TemperatureUnits
from .util import safely_get_json_value
class StatusUnit:
"""Runtime status ... | dahlb/carrier_api | src/carrier_api/status.py | .py | 18db6297a8208873 | 7.5 | 9 |
"""Aggregate model for a Carrier system and its related state."""
from logging import getLogger
from typing import Any
from .config import Config
from .energy import Energy
from .profile import Profile
from .status import Status
_LOGGER = getLogger(__name__)
HEAT_CAPABILITY_FIELDS = ("electric_heat", "gas", "hp_hea... | dahlb/carrier_api | src/carrier_api/system.py | .py | 70b8352cf7aaf510 | 7.5 | 9 |
"""Shared pytest fixtures for Carrier API tests."""
import json
from pathlib import Path
from typing import Any
import pytest
from carrier_api import Config, Energy, Profile, Status, System
FIXTURE_ROOT = Path(__file__).parent
@pytest.fixture
def system_response() -> dict[str, Any]:
"""Load the GraphQL system... | dahlb/carrier_api | tests/conftest.py | .py | 0df750883d860efa | 8 | 9 |
"""Tests for websocket connection state isolation."""
from collections.abc import AsyncIterator
from types import SimpleNamespace
from typing import cast
from aiohttp import ClientConnectionError, ClientError, ClientSession, WSMsgType
import pytest
from carrier_api import ApiConnectionGraphql, ApiWebsocket, CarrierA... | dahlb/carrier_api | tests/test_api_websocket.py | .py | 4a403cc9a883d799 | 7 | 9 |
"""Tests for configuration schedule behavior."""
from datetime import datetime, tzinfo
from typing import Self
import pytest
from carrier_api import config as config_module
from carrier_api.config import ConfigZone
from carrier_api.const import ActivityTypes
class FixedDateTime(datetime):
"""Fixed datetime pro... | dahlb/carrier_api | tests/test_config.py | .py | 0404ad122fea6e9d | 8 | 9 |
"""Tests for entry-level (Smart Thermostat) model parsing and serialization."""
from copy import deepcopy
from typing import Any
from carrier_api import EntryLevelSystem, EntryLevelZone
SAMPLE_SYSTEM: dict[str, Any] = {
"serial": "SERIALXXX",
"name": "Basement",
"location_id": "LOCATIONXXX",
"model":... | dahlb/carrier_api | tests/test_entry_level.py | .py | b95a7b2700f46a7c | 8 | 9 |
"""Contract tests for stored GraphQL and websocket fixtures."""
from asyncio import to_thread
import json
from pathlib import Path
from typing import Any
import pytest
from carrier_api import Config, Energy, Profile, Status, WebsocketDataUpdater
from carrier_api.system import System
FIXTURE_ROOT = Path(__file__).pa... | dahlb/carrier_api | tests/test_fixture_contracts.py | .py | 40321975d5bbda0b | 8 | 9 |
"""Tests for merging Carrier websocket updates into loaded system models."""
import json
from pathlib import Path
from typing import Any
import pytest
from carrier_api import (
ActivityTypes,
Config,
Energy,
FanModes,
Profile,
Status,
System,
WebsocketDataUpdater,
)
from carrier_api.a... | dahlb/carrier_api | tests/test_websocket_data_updater.py | .py | 708257a4aa291631 | 7 | 9 |
"""Workflow-level tests for Carrier API model, websocket, and mutation paths."""
from collections.abc import AsyncIterator
from copy import deepcopy
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from aiohttp import ClientWebSocketResponse, WSMsgType
from gql import GraphQLRequest
i... | dahlb/carrier_api | tests/test_workflows.py | .py | 9e2de09d9f7eca78 | 8 | 9 |
# pylint: disable=broad-exception-caught
"""The core Python module."""
import asyncio
from pynintendoauth.exceptions import HttpException
from .api import Api
from .authenticator import Authenticator
from .const import _LOGGER
from .device import Device
from .exceptions import NoDevicesFoundException
class Nintend... | pantherale0/pynintendoparental | pynintendoparental/__init__.py | .py | 82a7e18f652ea56c | 7.57 | 13 |
"""API handler."""
import aiohttp
from pynintendoauth.exceptions import HttpException
from .authenticator import Authenticator
from .const import (
_LOGGER,
BASE_URL,
DEVICE_MODEL,
ENDPOINTS,
MOBILE_APP_BUILD,
MOBILE_APP_PKG,
MOBILE_APP_VERSION,
OS_NAME,
OS_VERSION,
USER_AGENT,... | pantherale0/pynintendoparental | pynintendoparental/api.py | .py | b66492734fc0842c | 7.57 | 13 |
"""A Nintendo application."""
import copy
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from typing import TYPE_CHECKING
from .api import Api
from .const import _LOGGER
from .enum import SafeLaunchSetting
from .utils import current_datetime, is_awaitable
if TYPE... | pantherale0/pynintendoparental | pynintendoparental/application.py | .py | 4070b57ac7326964 | 7.57 | 13 |
"""Nintendo Authentication."""
from __future__ import annotations
from pynintendoauth import NintendoAuth
from .const import CLIENT_ID
class Authenticator(NintendoAuth):
"""Nintendo authentication handler.
Handles authentication with Nintendo's servers for accessing Parental Controls API.
Supports bot... | pantherale0/pynintendoparental | pynintendoparental/authenticator.py | .py | 058c7f1f0940a648 | 7.57 | 13 |
"""Callback registry and API update orchestration for Device."""
from __future__ import annotations
from collections.abc import Callable
from typing import TYPE_CHECKING
from ..utils import current_datetime, is_awaitable
if TYPE_CHECKING: # pragma: no cover
from ._core import Device
class DeviceCallbacksMixi... | pantherale0/pynintendoparental | pynintendoparental/device/_callbacks.py | .py | 643ecef5eae3d33d | 7.57 | 13 |
# pylint: disable=line-too-long
"""Defines a single Nintendo Switch device."""
from __future__ import annotations
import asyncio
from collections.abc import Callable
from datetime import datetime, time, timedelta
from pynintendoauth.exceptions import (
HttpException,
)
from ..api import Api
from ..application i... | pantherale0/pynintendoparental | pynintendoparental/device/_core.py | .py | d1cd40fe48116d57 | 7.57 | 13 |
"""Pure helpers for Device parental-control mutations and parsing."""
from __future__ import annotations
from datetime import time
from ..exceptions import BedtimeOutOfRangeError, DailyPlaytimeOutOfRangeError
_DISABLED_BEDTIME = time(0, 0)
_DEFAULT_STARTING_TIME = {"hour": 6, "minute": 0}
def time_to_api_dict(val... | pantherale0/pynintendoparental | pynintendoparental/device/_helpers.py | .py | bbcc40996b6bda8d | 7.57 | 13 |
"""Parental control setting parsing for Device."""
from __future__ import annotations
from datetime import datetime, time
from typing import TYPE_CHECKING
from ..const import _LOGGER
from ..enum import DeviceTimerMode, RestrictionMode
from ._helpers import api_dict_to_time, disabled_bedtime, time_to_minutes
if TYPE... | pantherale0/pynintendoparental | pynintendoparental/device/_parsing.py | .py | fdf77e92ae9fdc87 | 7.57 | 13 |
"""Parental control setting mutators for Device."""
from __future__ import annotations
from datetime import time
from typing import TYPE_CHECKING
from ..api import Api
from ..const import _LOGGER, DAYS_OF_WEEK
from ..enum import DeviceTimerMode, FunctionalRestrictionLevel, RestrictionMode
from ..exceptions import Be... | pantherale0/pynintendoparental | pynintendoparental/device/_settings.py | .py | 187480f314631062 | 7.57 | 13 |
"""Playtime / remaining-time calculations for Device."""
from __future__ import annotations
from datetime import datetime, time, timedelta
from typing import TYPE_CHECKING
from ..const import _LOGGER
from ..exceptions import ExtraPlayingTimeActiveError
from ._helpers import is_bedtime_disabled, minutes_until_end_of_... | pantherale0/pynintendoparental | pynintendoparental/device/_times.py | .py | 5212d303333450a1 | 7.57 | 13 |
"""Enums"""
from enum import Enum, StrEnum
class NintendoEnum(Enum):
"""Base enum for Nintendo-related enums."""
def __str__(self) -> str:
return self.name
@classmethod
def options(cls) -> list[str]:
"""Return a list of string representations of the enum members."""
return [... | pantherale0/pynintendoparental | pynintendoparental/enum.py | .py | a2b62ca5862e8817 | 7.57 | 13 |
"""Nintendo Parental exceptions."""
from enum import StrEnum
class RangeErrorKeys(StrEnum):
"""Keys for range errors."""
DAILY_PLAYTIME = "daily_playtime_out_of_range"
BEDTIME = "bedtime_alarm_out_of_range"
INVALID_DEVICE_STATE = "invalid_device_state"
EXTRA_PLAYING_TIME_ACTIVE = "extra_playing_... | pantherale0/pynintendoparental | pynintendoparental/exceptions.py | .py | ef33dd44c4a014b9 | 7.57 | 13 |
"""Nintendo Player."""
from collections.abc import Iterator
from datetime import date, datetime, timezone
from .application import ApplicationRegistry, PlayedAppUsage
from .const import _LOGGER
def _is_stale_daily_summary(summary: dict, now: datetime | None = None) -> bool:
"""Return True when the summary date ... | pantherale0/pynintendoparental | pynintendoparental/player.py | .py | 07a36143f1ff1656 | 7.57 | 13 |
"""Generic utilities."""
import inspect
from datetime import datetime
from zoneinfo import ZoneInfo
def is_awaitable(func):
"""Check if a function is awaitable or not."""
return inspect.iscoroutinefunction(func) or inspect.isasyncgenfunction(func)
def current_datetime(tz: str) -> datetime:
"""Return th... | pantherale0/pynintendoparental | pynintendoparental/utils.py | .py | 87fa7481ce8c411e | 7.07 | 13 |
"""Generates fixture files for pytest."""
import asyncio
import json
import logging
import os
from datetime import datetime
from pathlib import Path
from dotenv import load_dotenv
from faker import Faker
from pynintendoauth.exceptions import InvalidSessionTokenException
from pynintendoparental import Authenticator
f... | pantherale0/pynintendoparental | scripts/generate_fixtures.py | .py | 3db0904c3a89fa19 | 7.57 | 13 |
"""Pytest fixtures."""
from datetime import datetime
from unittest.mock import AsyncMock, PropertyMock, create_autospec
import pytest
from freezegun import freeze_time
from pynintendoparental import NintendoParental
from pynintendoparental.api import Api
from pynintendoparental.application import ApplicationRegistry... | pantherale0/pynintendoparental | tests/conftest.py | .py | 5a2d95331f9a62a6 | 8.07 | 13 |
"""Test helpers."""
from __future__ import annotations
import copy
import json
from datetime import datetime, time
from pathlib import Path
from typing import TYPE_CHECKING
import aiofiles
from pynintendoparental.application import ApplicationRegistry
from pynintendoparental.device import Device
from pynintendopare... | pantherale0/pynintendoparental | tests/helpers.py | .py | a630b2cc18680a77 | 8.07 | 13 |
"""Tests for the API class."""
from unittest.mock import AsyncMock, MagicMock, Mock, PropertyMock
import pytest
from aiohttp import ContentTypeError
from pynintendoauth.exceptions import HttpException
from pynintendoparental.api import Api, _check_http_success
from pynintendoparental.authenticator import Authenticat... | pantherale0/pynintendoparental | tests/test_api.py | .py | f68363d866e3c027 | 7.07 | 13 |
"""Test enum methods."""
import pytest
from pynintendoparental.enum import (
AlarmSettingState,
DeviceTimerMode,
FunctionalRestrictionLevel,
RestrictionMode,
)
@pytest.mark.parametrize(
"enum_member, expected_str",
[
(AlarmSettingState.SUCCESS, "SUCCESS"),
(RestrictionMode.AL... | pantherale0/pynintendoparental | tests/test_enum.py | .py | 4579e0f0e7257fbb | 8.07 | 13 |
"""Tests for the pynintendoparental package."""
from unittest.mock import AsyncMock, patch
import pytest
from pynintendoauth.exceptions import HttpException
from pynintendoparental import NintendoParental, NoDevicesFoundException
from pynintendoparental.authenticator import Authenticator
from .helpers import load_f... | pantherale0/pynintendoparental | tests/test_init.py | .py | 59e8a8f48d116720 | 8.07 | 13 |
"""Tests that parse the multi-device dump into Device / Player / Application dataclasses."""
import pytest
from pynintendoparental.api import Api
from pynintendoparental.application import Application, PlayedAppUsage
from pynintendoparental.device import Device
from pynintendoparental.player import Player
from .help... | pantherale0/pynintendoparental | tests/test_multiple_devices.py | .py | 071dc1fc195f398f | 8.07 | 13 |
"""Tests for the Player class."""
import copy
import logging
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
import pytest
from syrupy.assertion import SnapshotAssertion
from pynintendoparental.application import ApplicationRegistry
from pynintendoparental.player import Player, PlayerRegistry,... | pantherale0/pynintendoparental | tests/test_player.py | .py | d8d4d6c7c8bd9d0b | 7.07 | 13 |
"""Tests for generic utilities."""
from datetime import datetime, timezone
from freezegun import freeze_time
from pynintendoparental.utils import current_datetime
def test_current_datetime_uses_iana_zone():
"""current_datetime returns the civil date in the requested zone."""
with freeze_time(datetime(2025,... | pantherale0/pynintendoparental | tests/test_utils.py | .py | 6cdd71ef4ea013af | 7.07 | 13 |
import pytest
import json
from model.deepdives import Anomaly, Biome, DeepDives, Stage, Type, Variant, Warning
from model.salutes import Salutes
from model.trivia import Trivia
from service.drg import DRGService
@pytest.fixture
def requests_mock(mocker):
return mocker.patch("requests.get")
@pytest.fixture
def lo... | MoritzHayden/bosco | src/tests/service/test_drg.py | .py | ed00944fe77e6ac4 | 7 | 9 |
"""
File that defines the ACL class, which is used to manage access control lists
for allowing or restricting domains for emails and urls
"""
import re
class ACL:
"""
An ACL is a structure composed by :
- a compiled regex pattern that is used for matching a domain
- a boolean that indicates if the AC... | backo-stricto/stricto | stricto/acl.py | .py | 6526c3567364b845 | 7.42 | 6 |
"""
List acl that search
"""
from .acl import ACL
class ACLS:
"""init list acl and default"""
def __init__(self, acls: list[ACL], default: bool):
self.acls = acls
self.default = default
def authorize(self, value_to_verify: str) -> bool:
"""
verify an authorization
... | backo-stricto/stricto | stricto/acls.py | .py | eaf1cce016eff41f | 7.42 | 6 |
"""Module providing the Bool() Class"""
from typing import Any
from .generic import GenericType
from .error import STypeError
class Bool(GenericType):
"""Boolean type
:param ``**kwargs``:
See :py:class:`GenericType`
"""
def __init__(self, **kwargs):
"""Constructor method"""
... | backo-stricto/stricto | stricto/bool.py | .py | 24613d466657613e | 7.42 | 6 |
"""
Module providing Event management
"""
import copy
from typing import Callable, Any
from .error import SSyntaxError
class SingletonEventManager:
"""
Event manager object
"""
_events_per_object = {}
def __init__(self):
"""
Generator
"""
self._events_per_object ... | backo-stricto/stricto | stricto/event.py | .py | 64242be485d3af1d | 7.42 | 6 |
"""Module providing the Int() Class"""
from .generic import GenericType
from .error import STypeError, SError
class Extend(GenericType):
"""
A Extent type for any types type
"""
def __init__(self, type_for_extend, **kwargs):
"""
available arguments
"""
self._type = ty... | backo-stricto/stricto | stricto/extend.py | .py | 07bc97cc2a7ecbf1 | 7.42 | 6 |
"""
Module for bytes
"""
import base64
import binascii
from stricto.extend import Extend, STypeError
class Bytes(Extend):
"""
A specific class to play with datetime
"""
def __init__(self, **kwargs):
"""
initialisation. Myst pass the type (datetime)
"""
super().__init_... | backo-stricto/stricto | stricto/extended/bytes.py | .py | 7b8832440f67c6a9 | 7.42 | 6 |
"""
Module for complex
(just for fun)
"""
from stricto.dict import Dict
from stricto.float import Float
from stricto.error import STypeError
class Complex(Dict):
"""
A specific class to play with Dict
"""
def __init__(self, **kwargs):
"""
initialisation. Must define the struct
... | backo-stricto/stricto | stricto/extended/complex.py | .py | 59ff38a17cc3b29c | 7.42 | 6 |
# pylint: disable=duplicate-code
"""
Module for datetime
"""
from datetime import datetime
from stricto.extend import Extend
from stricto import STypeError, SConstraintError
from ..kparse import Kparse # pylint: disable=relative-beyond-top-level
def trunk_microseconds(value, o): # pylint: disable=unused-argument
... | backo-stricto/stricto | stricto/extended/date_time.py | .py | 564090ae67289736 | 7.42 | 6 |
# pylint: disable=duplicate-code
"""
Module for ip adresses
"""
import ipaddress
from stricto.extend import Extend
from stricto import STypeError
class Ipaddress(Extend):
"""
A specific class to play with ipadsress
"""
def __init__(self, **kwargs):
"""
initialisation. Must pass the t... | backo-stricto/stricto | stricto/extended/ip_address.py | .py | b645643fccf1fab5 | 7.42 | 6 |
# pylint: disable=duplicate-code
"""
Module for ip network addresses in CIDR notation
"""
import ipaddress
from stricto.extend import Extend
from stricto import STypeError
class Ipnetwork(Extend):
"""
A specific class to play with ipnetwork
"""
def __init__(self, **kwargs):
"""
initi... | backo-stricto/stricto | stricto/extended/ip_network.py | .py | 2f2a2cea63114840 | 7.42 | 6 |
# pylint: disable=duplicate-code
"""
Module for URL validation and parsing.
"""
from urllib.parse import urlsplit, SplitResult
from stricto.extend import Extend
from stricto import STypeError
class Url(Extend):
"""
A specific class to play with URLs
"""
def __init__(self, **kwargs):
"""
... | backo-stricto/stricto | stricto/extended/url.py | .py | 59eeb0beec00ac44 | 7.42 | 6 |
"""Module for kwargs parser"""
import re
from enum import Enum
from typing import Self, Any
from .generic import GenericType
from .list_and_tuple import ListAndTuple
type SFilterArgs = tuple[str, Operator, Any]
class Operator(Enum):
"""List of Operators
:param Enum: Enum
:type Enum: Enum
"""
E... | backo-stricto/stricto | stricto/filter.py | .py | 25bc1a87c8520350 | 7.42 | 6 |
"""Module providing the Float() Class"""
from typing import Any
from .generic import GenericType
from .error import STypeError, SConstraintError
from .kparse import Kparse
from .toolbox import get_content
KPARSE_MODEL = {
"min|minimum": float,
"max|maximum": float,
}
class Float(GenericType):
"""Float t... | backo-stricto/stricto | stricto/float.py | .py | 745ed16fedf2e4c2 | 7.42 | 6 |
"""Module providing the In() sur-Class"""
from .generic import GenericType
from .error import STypeError, SAttributeError
from .toolbox import validation_parameters
class In(GenericType):
"""
A kind of "one of"
"""
@validation_parameters
def __init__(self, models: list[GenericType | None], **kwa... | backo-stricto/stricto | stricto/in_type.py | .py | c0f1fffbc929da26 | 7.42 | 6 |
# pylint: disable=duplicate-code
"""
Module providing the Int() Class
"""
from .generic import GenericType
from .error import STypeError, SConstraintError
from .kparse import Kparse
from .toolbox import get_content
KPARSE_MODEL = {
"min|minimum": int,
"max|maximum": int,
}
class Int(GenericType):
"""
... | backo-stricto/stricto | stricto/int.py | .py | c66688b30e9f6aaf | 7.42 | 6 |
"""
JSON Encoder for complex object
"""
from json import JSONEncoder
class StrictoEncoder(JSONEncoder):
"""
Overwrite of the defaule JSONEncoder
to pick up the __json_encode__ for a complex objects if needed.
"""
def default(self, o):
"""
Overwrite the default encoder function de... | backo-stricto/stricto | stricto/json_encoder.py | .py | a1b91d96643fd6c7 | 7.42 | 6 |
"""Module for kwargs parser"""
import re
from typing import Dict, Any
from .toolbox import check_value_type
class Kparse: # pylint: disable=too-few-public-methods
"""Parser for kwargs.
:raises TypeError: error if obj is not compliant to the parser model
:return: an Object Kparser
:rtype: Kparse
... | backo-stricto/stricto | stricto/kparse.py | .py | e0c5bbbbe6028ca9 | 7.42 | 6 |
"""Module providing the Permission( Class)"""
import copy
class Permissions:
"""
To manage permissions
"""
def __init__(self, **kwargs):
"""
available arguments
"""
# Tell if we take care about permission or not
self._enabled = False
# All kwargs ar k... | backo-stricto/stricto | stricto/permissions.py | .py | c8f729c78eda0c29 | 7.42 | 6 |
"""Module providing the String() Class"""
import re
from typing import Callable
from .generic import GenericType
from .error import STypeError, SConstraintError
from .kparse import Kparse
from .toolbox import get_content
KPARSE_MODEL = {
"regexp|pattern|patterns|reg": {"type": str | list[str] | Callable, "default... | backo-stricto/stricto | stricto/string.py | .py | 277eb82c740eceae | 7.42 | 6 |
"""
Toolbox is a set of functions
usable everywhere
"""
import inspect
from types import UnionType
from typing import Callable, Any, Self, Union, get_origin
from functools import wraps
from .error import SSyntaxError
def get_content(value: Any) -> Any:
"""Return the value but if the value is Callable (a function... | backo-stricto/stricto | stricto/toolbox.py | .py | 8127e3dcafd5780f | 7.42 | 6 |
# pylint: disable=duplicate-code, no-member
"""
test for ACL()
"""
import unittest
from stricto import ACL
class TestACL(unittest.TestCase): # pylint: disable=too-many-public-methods
"""
Test on ACL
"""
def __init__(self, *args, **kwargs):
"""init this tests"""
super().__init__(*ar... | backo-stricto/stricto | tests/test_acl.py | .py | 2f9d8db27ece9ded | 7.92 | 6 |
# pylint: disable=duplicate-code
"""
test for Bool()
"""
import unittest
import hashlib
import json
from stricto import Int, Dict, Bool, Tuple, Float, In, List, String
def check_pair(value, o): # pylint: disable=unused-argument
"""
return true if pair
"""
return not value % 2
class TestDiff(unitte... | backo-stricto/stricto | tests/test_diff.py | .py | 40fe9d8c4b2cb47e | 7.92 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.