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 |
|---|---|---|---|---|---|---|
"""This module contains the tests for the NVIDIA GPU container."""
import pytest
from pytest_container import DerivedContainer
from pytest_container import container_and_marks_from_pytest_param
from pytest_container.container import ContainerData
from bci_tester.data import NVIDIA_CONTAINERS
CONTAINER_IMAGES = NVIDI... | SUSE/BCI-tests | tests/test_nvidia.py | .py | 5357b8898df207c0 | 7.04 | 11 |
"""Tests of the OpenJDK base container."""
import os.path
import re
import time
from dataclasses import dataclass
from dataclasses import field
import pytest
from pytest_container import DerivedContainer
from pytest_container import Version
from pytest_container.container import ContainerData
from pytest_container.co... | SUSE/BCI-tests | tests/test_openjdk.py | .py | 2f6bd4e20269ad98 | 8.04 | 11 |
"""Tests for the OpenJDK development container (the container including JDK and
JRE).
"""
import pytest
from pytest_container import DerivedContainer
from pytest_container import container_and_marks_from_pytest_param
from pytest_container.container import ContainerData
from pytest_container.runtime import LOCALHOST
... | SUSE/BCI-tests | tests/test_openjdk_devel.py | .py | b791aa44bb0e010d | 8.04 | 11 |
"""This module contains the tests for the pcp container"""
import time
import requests
from bci_tester.data import PCP_CONTAINERS
CONTAINER_IMAGES = PCP_CONTAINERS
def test_systemd_status(auto_container):
"""Verify that :command:`systemctl` is present and works and that
:file:`/etc/machine-id` exists.
... | SUSE/BCI-tests | tests/test_pcp.py | .py | a3466be1b98673b2 | 8.04 | 11 |
"""Tests for the PHP-cli, -apache and -fpm containers."""
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
import pytest
import requests
import tenacity
from pytest_container import DerivedContainer
from pytest_container import OciRuntimeBase
from pytest_container impo... | SUSE/BCI-tests | tests/test_php.py | .py | 80f116d526267945 | 8.04 | 11 |
"""Tests for the PostgreSQL related application container images."""
from datetime import timedelta
from itertools import product
from typing import List
from typing import Optional
import pg8000.dbapi
import pytest
from _pytest.mark import ParameterSet
from pytest_container.container import ContainerData
from pytest... | SUSE/BCI-tests | tests/test_postgres.py | .py | 12140c8fb308d73e | 8.04 | 11 |
"""Tests for the Prometheus containers."""
import pytest
import requests
from pytest_container.container import ContainerData
from bci_tester.data import ALERTMANAGER_CONTAINERS
from bci_tester.data import BLACKBOX_CONTAINERS
from bci_tester.data import PROMETHEUS_CONTAINERS
PROMETHEUS_STACK_CONTAINERS = PROMETHEUS_... | SUSE/BCI-tests | tests/test_prometheus.py | .py | fbf832141329df1b | 8.04 | 11 |
"""Basic tests for the Python base container images."""
import hashlib
import packaging.version
import pytest
import requests
from pytest_container import DerivedContainer
from pytest_container import PortForwarding
from pytest_container.container import ContainerData
from pytest_container.container import ImageForma... | SUSE/BCI-tests | tests/test_python.py | .py | 5c817d0a65c857aa | 7.04 | 11 |
"""Tests for the SLE_BCI repository itself: can all packages in the repository
be installed and ensure that we do not accidentally ship forbidden packages.
"""
import xml.etree.ElementTree as ET
from typing import Callable
from typing import List
import pytest
from bci_tester.data import ALLOWED_BCI_REPO_OS_VERSION... | SUSE/BCI-tests | tests/test_repository.py | .py | 887471654ff40e02 | 8.04 | 11 |
"""Basic tests for the Ruby base container images."""
import pytest
from bci_tester.data import OS_VERSION
from bci_tester.data import RUBY_CONTAINERS
CONTAINER_IMAGES = RUBY_CONTAINERS
def test_ruby_version(auto_container):
"""Verify that the environment variable ``RUBY_VERSION`` and ``RUBY_MAJOR``
match ... | SUSE/BCI-tests | tests/test_ruby.py | .py | beeac9bbfa8cb970 | 8.04 | 11 |
"""Tests for the Rust development container.
Rust development containers include rust and cargo.
"""
import pytest
from pytest_container import GitRepositoryBuild
from bci_tester.data import RUST_CONTAINERS
CONTAINER_IMAGES = RUST_CONTAINERS
def test_rust_version(auto_container):
"""Check that the environment... | SUSE/BCI-tests | tests/test_rust.py | .py | 884b065eac39682c | 8.04 | 11 |
import typing
from abc import ABC
from abc import abstractmethod
a = typing.TypeVar("a")
b = typing.TypeVar("b")
class Atomic:
def __init__(self, value: typing.Any) -> None:
self.value = value
def __repr__(self) -> str:
return f"{self.__class__.__name__}({type(self.value)})"
def __eq__(... | finsberg/category-theory-python | src/category_theory/core.py | .py | 11b6c8a13880cb94 | 7.63 | 17 |
import functools
import typing
from itertools import zip_longest
import dask
from .core import Monoid
def chunkify(
chunk_size: int,
iterable: typing.Iterable[typing.Any],
fillvalue: typing.Any = None,
) -> typing.Iterable[typing.Iterable[typing.Any]]:
"""Split iterable into chunks of size `chunk_si... | finsberg/category-theory-python | src/category_theory/par_operations.py | .py | d93723d3afe87569 | 7.63 | 17 |
"""
Command line interface for pygscholar. You can also set the environment variable
`PYSCHOLAR_CACHE_DIR` to change the default cache directory.
"""
import json
from pathlib import Path
from typing import Optional
import typer
from rich.console import Console
from rich.table import Table
from scholarly import MaxTr... | finsberg/pygscholar | src/pygscholar/cli.py | .py | b2f2a19304da6c38 | 7.56 | 12 |
from ctypes import c_char_p
from ctypes import c_double
from ctypes import c_int
from typing import Dict
from typing import List
from typing import NamedTuple
from typing import Optional
import numpy as np
class CModel:
def __init__(self, lib, ode):
self.lib = lib
# Get number of states and para... | finsberg/gotranx | examples/compile-c-extension/cmodel.py | .py | 213ab5f2fef46182 | 7.57 | 13 |
from enum import Enum, EnumMeta
# https://stackoverflow.com/questions/62299740/how-do-i-detect-and-invoke-a-function-when-a-python-enum-member-is-accessed
class OnAccess(EnumMeta):
"""
runs a user-specified function whenever member is accessed
"""
#
def __getattribute__(cls, name):
obj =... | finsberg/gotranx | src/gotranx/_enum.py | .py | f1d99c4826f6205d | 7.57 | 13 |
from __future__ import annotations
from typing import Any
from pathlib import Path
import typer
from ..codegen import CodeGenerator
from ..schemes import Scheme, get_scheme
def add_schemes(
codegen: CodeGenerator,
scheme: list[Scheme] | None = None,
delta: float = 1e-8,
stiff_states: list[str] | Non... | finsberg/gotranx | src/gotranx/cli/utils.py | .py | 89663e79def0997e | 7.57 | 13 |
from __future__ import annotations
import lark
import sympy as sp
from . import sympytools
from .exceptions import InvalidTreeError, MissingSymbolError
def relational_to_piecewise(expr: sp.Expr) -> sp.Piecewise:
"""Convert a relational expression to a piecewise expression
Parameters
----------
expr ... | finsberg/gotranx | src/gotranx/expressions.py | .py | 09e7c69cba1f4ad5 | 7.57 | 13 |
from __future__ import annotations
from pathlib import Path
from structlog import get_logger
from . import exceptions
from .ode import make_ode, ODE
from .parser import Parser
from .transformer import TreeToODE, LarkODE
logger = get_logger()
def ode_from_string(text: str, name="ode") -> ODE:
"""Create an ODE ... | finsberg/gotranx | src/gotranx/load.py | .py | 6136efbcd360857a | 7.57 | 13 |
from __future__ import annotations
from collections import defaultdict
import warnings
from pathlib import Path
from typing import overload
import sympy as sp
try:
import myokit
import myokit.formats.sympy
import myokit.lib.guess
import myokit.formats.cellml
except ImportError:
myokit = None
from... | finsberg/gotranx | src/gotranx/myokit.py | .py | 69e741e1e60bea63 | 7.57 | 13 |
from __future__ import annotations
from collections import defaultdict
from functools import cached_property
from pathlib import Path
from graphlib import TopologicalSorter
from collections.abc import Iterable
from collections.abc import Sequence
from typing import TypeVar
from typing import cast
from typing import An... | finsberg/gotranx | src/gotranx/ode.py | .py | 940d5abc2b236bf5 | 7.57 | 13 |
from pathlib import Path
from lark import Lark
_here = Path(__file__).absolute().parent
def load_grammar() -> str:
"""Load the grammar
Returns
-------
str
The grammar
"""
return (_here / "ode.lark").read_text()
class Parser(Lark):
def __init__(self, *args, **kwargs) -> None:... | finsberg/gotranx | src/gotranx/parser.py | .py | 3ba28d8df43dbfc5 | 7.07 | 13 |
""" Gets the ALMA telescope configuration files for an observation cycle.
The files are downloaded as an archive from the ALMA server. See
constant CONFIG_FILE_URL for the URL. It converts the configuration
files to an OSKAR telescope model directory. The folder are created
in the current working direct... | i4Ds/Karabo-Pipeline | karabo/data/_add_oskar_alma_layouts/alma_config_to_oskar_tm.py | .py | 893197830e438e42 | 7.65 | 19 |
"""Module to access CASA Measurement Set metadata.
Details see MS v2.0: https://casacore.github.io/casacore-notes/229.html
"""
from __future__ import annotations
import os
from abc import ABC, abstractmethod
from contextlib import redirect_stdout
from dataclasses import dataclass, fields
from pathlib import Path
fro... | i4Ds/Karabo-Pipeline | karabo/data/casa.py | .py | d6da1ca235c38ddf | 7.65 | 19 |
import functools
import os
import re
import shutil
import warnings
from typing import Final, List
import requests
from tqdm import tqdm
from karabo.util._types import FilePathType
from karabo.util.file_handler import FileHandler
cscs_base_url = "https://rgw.cscs.ch/ska" # S3 object storage
cscs_karabo_public_base_u... | i4Ds/Karabo-Pipeline | karabo/data/external_data.py | .py | b5c49a211f45de83 | 7.65 | 19 |
from __future__ import annotations
import json
from copy import deepcopy
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any, Dict, Optional, Union, cast
from warnings import warn
from karabo.data.obscore import ObsCoreMeta
from karabo.util._types import FilePathType, TFilePathTy... | i4Ds/Karabo-Pipeline | karabo/data/src.py | .py | 1d538763246a4037 | 7.65 | 19 |
from __future__ import annotations
import math
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Tuple
from karabo.imaging.image import Image
from karabo.simulation.visibility import Visibility
@dataclass(frozen=True)
class ImageSpec:
"""Minimal imaging parameters shared a... | i4Ds/Karabo-Pipeline | karabo/imaging/imager_interface.py | .py | cf7d4b008c7db065 | 7.65 | 19 |
from __future__ import annotations
import os
from dataclasses import dataclass
from typing import Optional
import numpy as np
import oskar
from astropy.coordinates import SkyCoord
from typing_extensions import override
from karabo.imaging.image import Image
from karabo.imaging.imager_base import DirtyImager, DirtyIm... | i4Ds/Karabo-Pipeline | karabo/imaging/imager_oskar.py | .py | 172b5f6880e729d5 | 7.65 | 19 |
from __future__ import annotations
import math
import os
import shutil
import subprocess
from dataclasses import dataclass
from typing import List, Optional, Union
from typing_extensions import override
from karabo.imaging.image import Image
from karabo.imaging.imager_base import (
DirtyImager,
DirtyImagerCo... | i4Ds/Karabo-Pipeline | karabo/imaging/imager_wsclean.py | .py | 12d17879961dc981 | 7.65 | 19 |
from __future__ import annotations
import warnings
from typing import List, Tuple, Union
import numpy as np
from astropy.modeling import fitting, models
from astropy.wcs import WCS
from numpy.typing import NDArray
from scipy.optimize import minpack
from ska_sdp_datamodels.image.image_model import Image as SkaSdpImage... | i4Ds/Karabo-Pipeline | karabo/imaging/util.py | .py | 7b47982be0fdc566 | 7.65 | 19 |
import re
from dataclasses import dataclass
from pathlib import Path
from typing import List, Tuple
import matplotlib.pyplot as plt
import numpy as np
"""
Assumes that several perfomance runs have been made
Author: andreas.wassmer@fhnw.ch
"""
@dataclass
class LogfileInfo:
filename: str
freq_channels: int
... | i4Ds/Karabo-Pipeline | karabo/performance_test/paper/process_results.py | .py | dfe5981a9018c25d | 8.15 | 19 |
import subprocess
from typing import cast
import numpy as np
from astropy.convolution import Gaussian2DKernel
from numpy.typing import NDArray
from scipy.special import j1
# Reference values below were obtained for a MeerKAT-like beam
REFERENCE_FWHM_DEGREES = 1.8
REFERENCE_FREQUENCY_HZ = 8e8
def gaussian_beam_fwhm_... | i4Ds/Karabo-Pipeline | karabo/simulation/beam.py | .py | dd088674f47aa625 | 7.65 | 19 |
from typing import Tuple, Union
import astropy.units as u
import numpy as np
from astropy.coordinates import EarthLocation
from numpy.typing import NDArray
def east_north_to_long_lat(
east_relative: float,
north_relative: float,
long: float,
lat: float,
alt: float = 0.0,
up: float = 0.0,
) ->... | i4Ds/Karabo-Pipeline | karabo/simulation/coordinate_helper.py | .py | d79b44aec89716e0 | 7.65 | 19 |
class EastNorthCoordinate:
"""
Class defining an east-north-(up) coordinate.
Args:
x: east coordinate in meters
y: north coordinate in meters
z: up coordinate in meters
x_error: east coordinate error in meters
y_error: north coordinate error in meters
z_error... | i4Ds/Karabo-Pipeline | karabo/simulation/east_north_coordinate.py | .py | f138c1c6be1f7c23 | 7.65 | 19 |
from typing import Tuple, TypeVar, cast
import numpy as np
import xarray as xr
from astropy.constants import c
from numpy.typing import NDArray
from karabo.util._types import IntFloat
_T = TypeVar("_T", NDArray[np.float_], xr.DataArray, IntFloat)
def convert_z_to_frequency(z: _T) -> _T:
"""Turn given redshift ... | i4Ds/Karabo-Pipeline | karabo/simulation/line_emission_helpers.py | .py | 0490cfe96263c5a4 | 7.65 | 19 |
from django.http import JsonResponse
from rest_framework import generics, viewsets
from rest_framework.response import Response
from studio.system_version import SystemVersion
from studio.utils import get_logger
logger = get_logger(__name__)
class OpenAPI(generics.GenericAPIView):
"""
The Open API basic API... | ScilifelabDataCentre/serve | api/openapi/common_api.py | .py | 05b5052b0ab59bb2 | 7.6 | 15 |
import json
from django.conf import settings
from django.http import JsonResponse
from rest_framework import viewsets
from rest_framework.exceptions import (
APIException,
MethodNotAllowed,
NotFound,
ValidationError,
)
from studio.utils import get_logger
logger = get_logger(__name__)
class Universi... | ScilifelabDataCentre/serve | api/openapi/lookups_api.py | .py | 98336b2e53ab9b75 | 7.6 | 15 |
from typing import Any
from django.conf import settings
from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from rest_framework import viewsets
from rest_framework.exceptions import NotFound
from rest_framework.request import Request
from apps.app_re... | ScilifelabDataCentre/serve | api/openapi/public_apps_api.py | .py | 6714f82257fc9473 | 7.6 | 15 |
from django.conf import settings
from django.http import JsonResponse
def get_studio_settings(request):
"""
This view should return a list of settings
needed to set up the CLI client.
"""
studio_settings = []
studio_url = {"name": "studio_host", "value": settings.STUDIO_HOST}
studio_setti... | ScilifelabDataCentre/serve | api/public_views.py | .py | 77570de40978799d | 7.6 | 15 |
from typing import Any, Dict, Set
import requests
from django.conf import settings
from studio.utils import get_logger
logger = get_logger(__name__)
def process_loki_response(response_json: dict[str, Any]) -> set[str]:
"""
Extract unique IP addresses from the Loki JSON response.
Args:
response... | ScilifelabDataCentre/serve | api/services/loki.py | .py | 3306a6d3828c09d3 | 7.6 | 15 |
import json
import os
from rest_framework import status
from rest_framework.test import APITestCase
from studio.utils import get_logger
logger = get_logger(__name__)
class OpenApiTests(APITestCase):
"""Tests for the Open API generic base endpoints"""
BASE_API_URL = "/openapi/v1/"
def test_get_are_you... | ScilifelabDataCentre/serve | api/tests/test_openapi.py | .py | a6806baff1468343 | 8.1 | 15 |
import json
import os
from datetime import date, datetime
from django.contrib.auth import get_user_model
from rest_framework import status
from rest_framework.test import APITestCase
from apps.models import Apps, CustomAppInstance, K8sUserAppStatus, Subdomain
from projects.models import Project
from studio.utils impo... | ScilifelabDataCentre/serve | api/tests/test_openapi_public_apps.py | .py | 88d79c6f61f3f959 | 8.1 | 15 |
"""
DOI provisioning background task.
This task sends app metadata to Invenio and reserves a DOI + publishes it
if needed (e.g. public access, new image version).
"""
import json
from typing import Any
from django.utils.dateparse import parse_datetime
from apps.background_tasks.base import BaseBackgroundTask
from ... | ScilifelabDataCentre/serve | apps/background_tasks/tasks/doi_provisioning.py | .py | 29ea5db95931f7dc | 7.6 | 15 |
"""
Example validation tasks.
These tasks validate various aspects of app instances before deployment.
"""
from typing import Any, Dict
import requests
from apps.app_registry import APP_REGISTRY
from apps.background_tasks.base import BaseBackgroundTask
from apps.background_tasks.registry import TASK_REGISTRY
from a... | ScilifelabDataCentre/serve | apps/background_tasks/tasks/validation.py | .py | 3468606cc1eb770f | 7.6 | 15 |
"""
Shared utilities for background tasks.
Use these from task modules to avoid duplicating logic across different task types.
"""
def select_latest_task_records(task_records):
"""
Keep only the latest record for each logical task name.
Background tasks may be retried or re-run across updates, so the UI... | ScilifelabDataCentre/serve | apps/background_tasks/utils.py | .py | d4065090c665af72 | 7.6 | 15 |
from crispy_bootstrap5.bootstrap5 import BS5Accordion
from crispy_forms.bootstrap import Accordion, AccordionGroup, PrependedText
from crispy_forms.layout import HTML, Div, Layout
from django import forms
from django.urls import reverse
from django.utils.safestring import mark_safe
from apps.forms.base import AppBaseF... | ScilifelabDataCentre/serve | apps/forms/custom.py | .py | 1c213d368eae4b5d | 7.6 | 15 |
from crispy_bootstrap5.bootstrap5 import BS5Accordion
from crispy_forms.bootstrap import Accordion, AccordionGroup, PrependedText
from crispy_forms.layout import HTML, Div, Layout
from django import forms
from django.core.exceptions import ValidationError
from django.urls import reverse
from django.utils.safestring imp... | ScilifelabDataCentre/serve | apps/forms/dash.py | .py | fa6568e2ca4b990e | 7.6 | 15 |
from crispy_forms.layout import Div
from apps.constants import HELP_MESSAGE_MAP
from apps.forms.field.custom import CustomField
class SRVCommonDivField(Div):
"""
This class is the most common field used in the apps creation forms.
Resulting field has a question_mark with tooltip next to the label. So "Na... | ScilifelabDataCentre/serve | apps/forms/field/common.py | .py | 83ef7d82fd44df3a | 7.6 | 15 |
from crispy_bootstrap5.bootstrap5 import BS5Accordion
from crispy_forms.bootstrap import Accordion, AccordionGroup, PrependedText
from crispy_forms.layout import HTML, Div, Layout
from django import forms
from django.utils.safestring import mark_safe
from apps.forms.base import AppBaseForm
from apps.forms.field.common... | ScilifelabDataCentre/serve | apps/forms/gradio.py | .py | dd69e81ac9febc4a | 7.6 | 15 |
from crispy_bootstrap5.bootstrap5 import BS5Accordion
from crispy_forms.bootstrap import Accordion, AccordionGroup, Field, PrependedText
from crispy_forms.layout import HTML, Div, Layout
from django import forms
from django.forms.widgets import HiddenInput
from django.utils.safestring import mark_safe
from apps.forms.... | ScilifelabDataCentre/serve | apps/forms/shiny.py | .py | 4485a32f401630da | 7.6 | 15 |
from crispy_bootstrap5.bootstrap5 import BS5Accordion
from crispy_forms.bootstrap import Accordion, AccordionGroup, PrependedText
from crispy_forms.layout import HTML, Div, Layout
from django import forms
from django.utils.safestring import mark_safe
from apps.forms.base import AppBaseForm
from apps.forms.field.common... | ScilifelabDataCentre/serve | apps/forms/streamlit.py | .py | 6529cdd7a401dcd7 | 7.6 | 15 |
"""_summary_
"""
import json
from behave import Given, When, Then
import sys
import os
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(SCRIPT_DIR))
from src.utils.validate import Workout
@Given("A JSON file with test data")
def given_combo(context):
context.file = "fea... | TheNewThinkTank/fitness-tracker | features/steps/validate.py | .py | 47fd7c8ef2e4d40e | 7.66 | 20 |
"""
Detect anomalies in user data to identify potential overtraining,
injury risks, or inconsistencies in workout logs.
"""
from loguru import logger # type: ignore
import numpy as np
from sklearn.ensemble import IsolationForest # type: ignore
def train_anomaly_detector(data):
"""Trains an Isolation Forest mod... | TheNewThinkTank/fitness-tracker | src/anomaly_detection.py | .py | 2c95fd5a097e21ef | 7.66 | 20 |
"""
Read workout data and calculate combined metrics.
"""
from __future__ import annotations
from datetime import datetime as dt
from pathlib import Path
from pprint import pformat
from typing import Any, cast
import matplotlib.cm as cm
import matplotlib.colors as mcolors
import matplotlib.dates as mdates
import mat... | TheNewThinkTank/fitness-tracker | src/combined_metrics/combined_metrics.py | .py | fd677695efd329cb | 7.66 | 20 |
"""Visualizations for annual training frequency
"""
from src.utils.config import settings # type: ignore
import numpy as np
import pandas as pd # type: ignore
import matplotlib.pyplot as plt
import seaborn as sns # type: ignore
def add_labels(ax, x, y):
for i in range(len(x)):
ax.text(i, y[i] + 0.2, s... | TheNewThinkTank/fitness-tracker | src/combined_metrics/plot_frequency.py | .py | 6e7a7efa1862a0ca | 7.66 | 20 |
"""Common parameter data classes for various operations.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Optional
@dataclass
class PlotParams:
table: Any
year: str
month: Optional[str] = None
img_path: Optional[str] = None # fallback to settings if N... | TheNewThinkTank/fitness-tracker | src/common/params.py | .py | 95e3c574e707500e | 7.66 | 20 |
"""Shared workout typing helpers for the fitness tracker domain."""
from __future__ import annotations
from typing import Any, TypedDict
class ExerciseSet(TypedDict, total=False):
"""Represents a single exercise set inside a workout record."""
set_number: int
reps: int
weight: str
class WorkoutRe... | TheNewThinkTank/fitness-tracker | src/common/workout_types.py | .py | d9557217a865d516 | 7.66 | 20 |
"""Delete data from the database.
"""
from src.utils.set_db_and_table import set_db_and_table # type: ignore
def remove_from_table(table) -> None:
"""Remove from table.
:param table: TinyDB table
:type table: TinyDB.table
"""
raise NotImplementedError
def truncate_table(table) -> None:
""... | TheNewThinkTank/fitness-tracker | src/crud/delete.py | .py | dc87e83d283a98b1 | 7.66 | 20 |
"""
Store weight-training data.
Docs: https://tinydb.readthedocs.io/en/latest/getting-started.html
"""
import json
import os
from pathlib import Path
from typing import NewType
from src.utils.config import settings # type: ignore
import yaml # type: ignore
from tinydb import table # type: ignore
from loguru import... | TheNewThinkTank/fitness-tracker | src/crud/insert.py | .py | 4638fbc213705aee | 7.66 | 20 |
"""
Update or delete weight-training data.
"""
import re
from pprint import pformat # type: ignore
from loguru import logger # type: ignore
from src.utils.set_db_and_table import set_db_and_table # type: ignore
def filter_exercises_with_whitespace(workout_data: list) -> list[dict]:
"""Find exercises with whit... | TheNewThinkTank/fitness-tracker | src/crud/update.py | .py | adc81b4469685949 | 7.66 | 20 |
"""
Expose API for training data.
Docs: https://fastapi.tiangolo.com/tutorial/first-steps/
To run, execute following command from CLI:
cd src && uvicorn main:app --reload
visit URL: http://127.0.0.1:8000/docs
"""
import datetime
from contextlib import asynccontextmanager
from typing import Any, cast
import yaml # ... | TheNewThinkTank/fitness-tracker | src/main.py | .py | 441acc8944eb78d4 | 7.66 | 20 |
"""
Read workout data and calculate 1RM and training volume.
"""
from datetime import datetime
import re
from typing import Any, Final, cast
import pandas as pd # type: ignore
from loguru import logger # type: ignore
from src.common.workout_types import WorkoutRecord, is_workout_record
from src.utils.set_db_and_tabl... | TheNewThinkTank/fitness-tracker | src/model/model.py | .py | a98e0bee696b0f1e | 7.66 | 20 |
"""
Plot weight-training data with fit.
"""
import argparse
from datetime import datetime
from src.utils.config import settings # type: ignore
from src.utils.get_program import get_pgm_from_date # type: ignore
import matplotlib.pyplot as plt # type: ignore
import seaborn as sns # type: ignore
from src.model.model ... | TheNewThinkTank/fitness-tracker | src/model/plot_model.py | .py | e88e034a27e59ee0 | 7.66 | 20 |
"""acsm_1rm, epley or brzycki formulas
are used to implement the 1RM estimation.
ACSM 1RM formula
.. math::
\\frac{w}{\\frac{100 - r \\cdot 2.5}{100}}
Epley 1RM formula
.. math::
w \\cdot \\frac{1 + r}{30}
Brzycki 1RM formula
.. math::
w \\cdot \\frac{36}{37 - r}
"""
from abc import ABC, abstractmet... | TheNewThinkTank/fitness-tracker | src/one_rep_max.py | .py | ebdca2644b99cf97 | 7.66 | 20 |
"""
Plots of popular 1-repetition-maximum formulas.
"""
import matplotlib.pyplot as plt # type: ignore
import numpy as np # type: ignore
import pandas as pd # type: ignore
import seaborn as sns # type: ignore
from src.one_rep_max import EpleyStrategy, BrzyckiStrategy # type: ignore
from src.one_rep_max_calc impor... | TheNewThinkTank/fitness-tracker | src/one_rep_max_plot.py | .py | 2484208b762f78b0 | 7.66 | 20 |
"""
Plot weight-training data.
"""
from src.utils.config import settings # type: ignore
from typing import Any
import matplotlib.pyplot as plt # type: ignore
import numpy as np # type: ignore
import pandas as pd # type: ignore
import seaborn as sns # type: ignore
from src.crud.read import show_exercise # type: i... | TheNewThinkTank/fitness-tracker | src/plot.py | .py | 9d1713a786052ee9 | 7.66 | 20 |
"""Simulate weight training workouts.
"""
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
import json
from pathlib import Path
import random
from loguru import logger # type: ignore
import numpy as np
from src.utils.file_conversions.load_yaml import load_yaml_file # type: ignore
class ... | TheNewThinkTank/fitness-tracker | src/simulations/workout_simulator.py | .py | 15742d59956465ac | 7.66 | 20 |
"""Loads configuration from environment and files.
"""
from dynaconf import Dynaconf # type: ignore
settings = Dynaconf(
settings_files=[".config/settings.toml"],
# envvar_prefix="DYNACONF", # False # Optional: Prefix for environment variables
environments=True, # Enable environments (defaul... | TheNewThinkTank/fitness-tracker | src/utils/config.py | .py | 607aa8b6b1270fb4 | 7.66 | 20 |
"""Extend TinyDB to use YAML as storage.
"""
from pprint import pformat # type: ignore
from loguru import logger # type: ignore
from tinydb import TinyDB # type: ignore
from tinydb.storages import Storage, touch # type: ignore
import yaml # type: ignore
from src.utils.config import settings # type: ignore
clas... | TheNewThinkTank/fitness-tracker | src/utils/custom_storage.py | .py | 55b36fd131fe3225 | 7.66 | 20 |
"""
Flatten nested JSON data into csv format,
e.g. for the great expectations framework to process.
"""
import json
from pathlib import Path
import pandas as pd # type: ignore
def get_exercise_data(infile: str) -> pd.DataFrame:
"""Read nested JSON file into dataframe.
:param infile: Filepath to JSON file
... | TheNewThinkTank/fitness-tracker | src/utils/file_conversions/json_to_csv.py | .py | 3cf8ccef19d8481b | 7.66 | 20 |
"""Get the bodyweight from the google sheet.
"""
from __future__ import annotations
from pprint import pformat
import pandas as pd # type: ignore[import-untyped]
from loguru import logger
from src.utils.config import settings
from src.utils.google_sheet import get_sheet
def get_bw(url: str | None = None) -> floa... | TheNewThinkTank/fitness-tracker | src/utils/get_bodyweight.py | .py | 5586fcc71e54bc0f | 7.66 | 20 |
"""
Get breath holding data from Google Sheet
and plot min, max, and mean duration.
"""
from datetime import datetime as dt # type: ignore
import pandas as pd # type: ignore
import seaborn as sns # type: ignore
import matplotlib.pyplot as plt # type: ignore
import matplotlib.colors as mcolors # type: ignore
from ... | TheNewThinkTank/fitness-tracker | src/utils/get_breath_holding.py | .py | 15398edfcb2ad8a4 | 7.66 | 20 |
"""
Get all exercises available for a given musclegroup.
"""
from __future__ import annotations
from functools import lru_cache
from pprint import pformat # type: ignore
from typing import Any
from loguru import logger # type: ignore
from src.utils.file_conversions.load_yaml import load_yaml_file # type: ignore
... | TheNewThinkTank/fitness-tracker | src/utils/get_exercises.py | .py | 429dc508607f2df3 | 7.66 | 20 |
"""Get the number of workouts in a given year."""
from __future__ import annotations
from pprint import pformat # type: ignore
from loguru import logger # type: ignore
from src.utils.get_data import get_data # type: ignore
def get_number_of_workouts(year: int | str) -> int:
"""Get the number of workouts in... | TheNewThinkTank/fitness-tracker | src/utils/get_number_of_workouts.py | .py | 1e9838b87a301b67 | 7.66 | 20 |
"""Get the workout program based on the workout date.
"""
from __future__ import annotations
import datetime
from functools import lru_cache
from pathlib import Path
from pprint import pformat # type: ignore
from typing import Any
from loguru import logger # type: ignore
from src.utils.config import settings # t... | TheNewThinkTank/fitness-tracker | src/utils/get_program.py | .py | f511525ce85b1e63 | 7.66 | 20 |
# Copyright INRIM (https://www.inrim.eu)
# See LICENSE file for full licensing details.
import json
from typing import (
AbstractSet,
Any,
Callable,
Dict,
List,
Mapping,
Optional,
Tuple,
Union,
no_type_check,
)
from pathlib import Path
from pydantic import BaseSettings, PrivateAt... | INRIM/service-app | backend/config.py | .py | c8b6433e13c46091 | 7.52 | 10 |
# Copyright INRIM (https://www.inrim.eu)
# See LICENSE file for full licensing details.
import ujson
import httpx
import logging
logger = logging.getLogger(__name__)
class PluginBase:
plugins = []
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if cls not in cls.pl... | INRIM/service-app | backend/ozon/core/BaseClass.py | .py | bcba3e9aea7b9ddf | 7.52 | 10 |
# Copyright INRIM (https://www.inrim.eu)
# See LICENSE file for full licensing details.
import sys
import os
import logging
import ujson
from .BaseClass import PluginBase
from fastapi.exceptions import HTTPException
from .DateEngine import DateEngine, datetime, date, time, DateTimeEncoder
from .database.mongo_core impo... | INRIM/service-app | backend/ozon/core/QueryEngine.py | .py | 86c6e0a30ba61279 | 7.52 | 10 |
# SPDX-FileCopyrightText: 2022-2026 Ginkgoty
# SPDX-License-Identifier: MIT
"""Lazy loading and indexing of the bundled administrative dataset."""
from __future__ import annotations
import json
from collections.abc import Mapping
from copy import deepcopy
from dataclasses import dataclass
from functools import lru_c... | Ginkgoty/chinese-address-generator | chinese_address_generator/_data.py | .py | dedac78cfab944ce | 7.42 | 6 |
# SPDX-FileCopyrightText: 2022-2026 Ginkgoty
# SPDX-License-Identifier: MIT
"""Command-line interface for chinese-address-generator."""
from __future__ import annotations
import argparse
import json
from collections.abc import Sequence
from ._version import __version__
from .generator import AddressGenerator
def ... | Ginkgoty/chinese-address-generator | chinese_address_generator/cli.py | .py | b90c70a1771c457f | 7.42 | 6 |
# SPDX-FileCopyrightText: 2022-2026 Ginkgoty
# SPDX-License-Identifier: MIT
"""Random address generation backed by the bundled official dataset."""
import functools
import random
import warnings
from typing import Callable, Optional, TypeVar, cast
from ._data import get_dataset
from .models import Address
Function ... | Ginkgoty/chinese-address-generator | chinese_address_generator/generator.py | .py | 0ddf1bd2d319a5ea | 7.42 | 6 |
# SPDX-FileCopyrightText: 2022-2026 Ginkgoty
# SPDX-License-Identifier: MIT
"""Public immutable models returned by the generator."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Union
JsonValue = Union[str, int, None]
@dataclass(frozen=True)
class Division:
"""Repres... | Ginkgoty/chinese-address-generator | chinese_address_generator/models.py | .py | 0819f78c878de98f | 7.42 | 6 |
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2022-2026 Ginkgoty
# SPDX-License-Identifier: MIT
"""Build the bundled dataset from the Ministry of Civil Affairs API."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import tempfile
import time
import urllib.error
import url... | Ginkgoty/chinese-address-generator | tools/update_data.py | .py | c2fea821e861356f | 7.42 | 6 |
"""Module that handles sending the requests to API"""
import requests
from .errors import InvalidRequestError
class RequestHandler:
"""
Object that handles sending the requests to API
Attributes
----------
session : requests.sessions.Session
A session object to send the requests. This ca... | Meteosource/pymeteosource | pymeteosource/request_handler.py | .py | 49646d5031a19abb | 7.57 | 13 |
"""Generate core.pyi stub file from mintalib.core using inspect.signature."""
import inspect
from pathlib import Path
from mintalib import core
from mintalib.utils import get_metadata
OUTPUT = Path(__file__).parent.parent / "src/mintalib/core.pyi"
IMPORTS = """\
import numpy as np
"""
class Literal(str):
"""S... | furechan/mintalib | scripts/make-stubs.py | .py | 5b3e4fb76b6cc58d | 7.6 | 15 |
"""Download and update bundled sample prices (AAPL OHLCV via yfinance)."""
from pathlib import Path
from functools import lru_cache
import pandas as pd
import yfinance as yf
ROOTDIR = Path(__file__).parent.parent
PKGDIR = ROOTDIR.joinpath("src/mintalib").resolve(strict=True)
SAMPLES = PKGDIR / "samples"
SYMBOL = "A... | furechan/mintalib | scripts/update-samples.py | .py | 444b632e55dbe9ea | 7.6 | 15 |
"""Function Model"""
import sys
import inspect
import numpy as np
from typing import ParamSpec, Callable, Any
P = ParamSpec("P")
def _get_prices(data):
"""Get prices data frame, raises on error
Accepts a pandas or polars data frame, or a structured numpy ndarray.
"""
if isinstance(data, np.n... | furechan/mintalib | src/mintalib/model/function.py | .py | bffe98b08b14163f | 7.6 | 15 |
"""Indicator Model"""
import inspect
import numpy as np
import pandas as pd
from typing import TYPE_CHECKING, Callable, ParamSpec, Any, cast, overload
from types import MappingProxyType
from functools import cached_property
from abc import ABCMeta, abstractmethod
from ..utils import format_partial, lazy_repr
if TY... | furechan/mintalib | src/mintalib/model/indicator.py | .py | 8c38091dd1958a43 | 7.6 | 15 |
"""
Pandas `ts` Accessor (Experimental)
Registers a `ts` accessor on pandas DataFrame and Series,
providing access to mintalib indicators via `df.ts.SMA(20)`.
This module is **experimental** — consider using `mintalib.indicators` for pandas workflows.
Importing this module is sufficient to register the accessor.
"""
... | furechan/mintalib | src/mintalib/pandas.py | .py | 829023557e2da428 | 7.6 | 15 |
""" helper utilities """
from typing import Callable
from inspect import Signature, Parameter
def first_param(func: Callable):
"""Name of function's first parameter if any"""
params = Signature.from_callable(func).parameters
return next(params.__iter__(), None)
def sample_param(param: Parameter):
... | furechan/mintalib | src/mintalib/testing.py | .py | 7a01f7e9e4f204db | 8.1 | 15 |
"""Mintalib Utils"""
from inspect import Signature, Parameter
def detect_backend(data) -> str:
"""Detect the backend of a data object ('pandas', 'polars', or '')."""
return (getattr(data, '__module__', None) or '').partition('.')[0]
def normalize_prices(prices):
"""Normalize prices dataframe with lower ... | furechan/mintalib | src/mintalib/utils.py | .py | 47b5595b826dc2d7 | 7.6 | 15 |
# noinspection PyUnresolvedReferences
import os
import re
import json
import subprocess
import urllib.error
import urllib.request
from pathlib import Path
from invoke.exceptions import Exit
from invoke.tasks import task
PACKAGE = "mintalib"
ROOT = Path(__file__).parent
def load_direnv(path: str | Path = ROOT):
... | furechan/mintalib | tasks.py | .py | 89db8c4de5ba1f55 | 7.6 | 15 |
"""Concurrency / free-threading safety checks for the core kernels.
The ``calc_*`` kernels release the GIL (``with nogil``), so threads run their
C loops concurrently even on a standard build. Computing every kernel from many
threads at once and comparing against a single-threaded reference exercises those
concurrent ... | furechan/mintalib | tests/test_concurrency.py | .py | c453da3f6a6e62ef | 8.1 | 15 |
"""
Connector for Azure Service Bus.
"""
# Copyright (c) 2023-2026. ECCO Data & AI and other project contributors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.a... | SneaksAndData/adapta | adapta/connectors/service_bus/_connector.py | .py | 9a4bc36a0f597763 | 7.54 | 11 |
"""
Abstract Data Class
"""
from copy import deepcopy
from typing import Any
import polars as pl
from adapta.dataclass_validation.dataclass.dataclass_core import CoreDataClass
from adapta.dataclass_validation.validation.validation_utils import (
raise_failed_validations,
ValidationResponse,
)
from adapta.data... | SneaksAndData/adapta | adapta/dataclass_validation/dataclass/dataclass_abstract.py | .py | 4fd05ae60af45d05 | 7.54 | 11 |
"""
Core data class implementation for the adapta library
"""
from enum import Enum
from typing import final
@final
class Checks:
"""
Check class to perform additional checks on fields.
1. ge_value: Greater than or equal to constraint for the field (default is None).
2. le_value: Less than or equal to... | SneaksAndData/adapta | adapta/dataclass_validation/dataclass/dataclass_core.py | .py | 0546a5f330701bd2 | 7.54 | 11 |
"""
Validation Class for validating data against a schema defined as an AbstractDataClass.
"""
from adapta.dataclass_validation.dataclass.dataclass_abstract import AbstractDataClass
from adapta.dataclass_validation.validation.validation_utils import (
ValidationResponse,
raise_failed_validations,
)
class Vali... | SneaksAndData/adapta | adapta/dataclass_validation/validation/validation.py | .py | 5990a3e8be38b737 | 7.54 | 11 |
"""
Validation class for Polars DataFrames.
"""
import datetime
from typing import Any
import polars as pl
from adapta.dataclass_validation.validation.validation_abstract import AbstractValidationClass
class PolarsValidationClass(AbstractValidationClass):
"""
Polars Validation Class for validating data agai... | SneaksAndData/adapta | adapta/dataclass_validation/validation/validation_polars.py | .py | ba30a171370a8179 | 7.54 | 11 |
"""
Validation utilities for the adapta dataclass validation framework
"""
from dataclasses import dataclass
import polars as pl
from adapta.dataclass_validation.dataclass.dataclass_core import CoreDataClass
@dataclass
class ValidationResponse:
"""
Class to hold validation response.
"""
schema_name:... | SneaksAndData/adapta | adapta/dataclass_validation/validation/validation_utils.py | .py | 00e6f21cb2ffa84c | 7.54 | 11 |
"""
Asyncio-safe implementation of a Semantic Logger.
"""
import asyncio
# Copyright (c) 2023-2026. ECCO Data & AI and other project contributors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the L... | SneaksAndData/adapta | adapta/logs/_async_logger.py | .py | d93fc805dca6eda6 | 7.54 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.