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
""" A set of constants used within the glambie software """ from enum import Enum DENSITY_OF_WATER_KG_PER_M3 = 997 DENSITY_OF_ICE_KG_PER_M3 = 850 # Huss et al. (2013) OCEAN_AREA_IN_KM2 = 3.625e8 # Cogley et al. (2012) # Ratio of relative error for seasonal correction. for more info see the GlaMBIE Assessment Algori...
earthwave/glambie
glambie/const/constants.py
.py
6e523088a3916f1b
7.52
10
""" Interface to the GlaMBIE data submission system. The submission system standardises the data recieved by GlaMBIE in a number of different ways and presents the output within a Google Bucket. This module provides access functions for that bucket. """ from io import BytesIO import json import os import re from typ...
earthwave/glambie
glambie/data/submission_system_interface.py
.py
5979d836abfd94f4
7.52
10
import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt from glambie.util.timeseries_helpers import resample_1d_array, timeseries_as_months from glambie.data.timeseries import Timeseries """ Handy functions to help making plots """ COLOURS = ["red", "blue", "gold", "green", "or...
earthwave/glambie
glambie/plot/plot_helpers.py
.py
453edd5d9690e9be
7.52
10
import logging from glambie.config.config_classes import GlambieRunConfig from glambie.data.data_catalogue import DataCatalogue from glambie.processing.process_regional_results import ( run_one_region, combine_within_one_region, ) from glambie.processing.process_regional_results import ( convert_and_save_on...
earthwave/glambie
glambie/processing/main.py
.py
02a7f40a40591dc0
7.52
10
import logging from glambie.config.config_classes import GlambieRunConfig from glambie.const.regions import REGIONS from glambie.data.data_catalogue import DataCatalogue from glambie.data.timeseries import Timeseries, TimeseriesData from glambie.const.constants import YearType from glambie.processing.path_handling impo...
earthwave/glambie
glambie/processing/process_global_results.py
.py
1a385c15d8a95b07
7.52
10
from datetime import datetime from datetime import timedelta import numpy as np import pandas as pd import math def fractional_years_to_datetime_dates(fractional_year_list: list) -> list: """Function to convert a list of fractional years to datetime dates Parameters ---------- fractional_year_list : ...
earthwave/glambie
glambie/util/date_helpers.py
.py
85f78b3cfd523b26
7.52
10
import warnings import numpy as np import pandas as pd def calibrate_timeseries_with_trends( trends: pd.DataFrame, calibration_timeseries: pd.DataFrame ): """ This function calibrates a higher resolution calibration timeseries with the trends from a trend DataFrame. The 'calibration_timeseries' is adj...
earthwave/glambie
glambie/util/timeseries_combination_helpers.py
.py
2e30ae7b8f9a054b
7.52
10
import os from glambie.config.config_classes import GlambieRunConfig from glambie.config.config_classes import RegionRunConfig from glambie.const.constants import ( ExtractTrendsMethod, YearType, SeasonalCorrectionMethod, ) from glambie.const.data_groups import GlambieDataGroup import pytest import yaml ...
earthwave/glambie
tests/config/test_config_classes.py
.py
a8e8c3710ac38058
7.02
10
from glambie.const.regions import REGIONS, REGIONS_BY_ID, REGIONS_BY_SHORT_NAME import numpy as np import pytest def test_get_region_by_short_name(): region = REGIONS_BY_SHORT_NAME["ISL"] assert region.name == "iceland" def test_get_region_by_id(): region = REGIONS_BY_ID[6] assert region.name == "ic...
earthwave/glambie
tests/const/test_regions.py
.py
1ea98237c359256a
7.02
10
import os from unittest.mock import MagicMock from google.cloud.storage import Blob from google.cloud.storage import Client import numpy as np import pandas as pd import pytest from glambie.data.submission_cleaning_script import check_glambie_submission_for_errors from glambie.data.submission_cleaning_script import d...
earthwave/glambie
tests/data/test_submission_cleaning_script.py
.py
a446e1dd8aab46c5
8.02
10
"""Methods for running the NHP model in a Docker container.""" import argparse import logging import uuid from datetime import datetime from nhp.docker.config import Config from nhp.docker.run import RunWithAzureStorage, RunWithLocalStorage from nhp.model.data import Local from nhp.model.run import run_all def pars...
The-Strategy-Unit/nhp_model
src/nhp/docker/__main__.py
.py
6cfc70d3ea781713
7.64
18
"""config values for docker container.""" import os import dotenv class Config: """Configuration class for Docker container.""" def __init__(self): """Configuration settings for the Docker container.""" dotenv.load_dotenv() self._app_version = os.environ.get("APP_VERSION", "dev") ...
The-Strategy-Unit/nhp_model
src/nhp/docker/config.py
.py
a9ad7f47105cee0f
7.64
18
"""Run the model inside of the docker container.""" import gzip import json import logging import os import re from pathlib import Path from typing import Any, Callable from uuid import UUID import pandas as pd from azure.data.tables import TableServiceClient, UpdateMode from azure.identity import DefaultAzureCredent...
The-Strategy-Unit/nhp_model
src/nhp/docker/run.py
.py
e8e19ec0a82eb457
7.64
18
"""Functions to run the model. This module allows you to run the various models. It allows you to run a single model run of one of the different types of models for debugging purposes, or it allows you to run all of the models in parallel saving the results to disk. There are existing launch profiles for vscode that ...
The-Strategy-Unit/nhp_model
src/nhp/model/__main__.py
.py
efcda74e57630612
7.64
18
"""Accident and Emergency Module. Implements the A&E model. """ from typing import Any, Callable, Tuple import numpy as np import pandas as pd from nhp.model.data import Data from nhp.model.model import Model from nhp.model.model_iteration import ModelIteration class AaEModel(Model): """Accident and Emergency...
The-Strategy-Unit/nhp_model
src/nhp/model/aae.py
.py
ce8f48cdd1da274c
7.64
18
"""Inpatient Row Resampling. Methods for handling row resampling """ from typing import TYPE_CHECKING import numpy as np import pandas as pd if TYPE_CHECKING: from nhp.model.model_iteration import ModelIteration class ActivityResampling: """Activity Resampling. Class for handling the activity resampl...
The-Strategy-Unit/nhp_model
src/nhp/model/activity_resampling.py
.py
bf6226d6e7e63fea
7.64
18
"""Reference Data. Any reference data needed for the model should be stored in this folder. Helper methods for loading the reference data should be created here. """ import json import pathlib import pandas as pd from metalog_jax.base import MetalogParameters from metalog_jax.metalog import Metalog def _ref_path(...
The-Strategy-Unit/nhp_model
src/nhp/model/data/reference/__init__.py
.py
38e2c0a82507456c
7.64
18
"""Helper methods for the model package.""" import json import numpy as np import pandas as pd def inrange(value: float, low: float = 0, high: float = 1) -> float: """Force a value to be in the interval [low, high]. Args: value: The value we want to constrain to the interval. l...
The-Strategy-Unit/nhp_model
src/nhp/model/helpers.py
.py
9ae56f045c30993a
7.64
18
"""Inpatients Module. Implements the inpatients model. """ from collections import defaultdict from typing import Any, Callable, Self, cast import numpy as np import pandas as pd from nhp.model.data import Data from nhp.model.model import Model from nhp.model.model_iteration import ModelIteration class Inpatients...
The-Strategy-Unit/nhp_model
src/nhp/model/inpatients.py
.py
05ea7b9e1836f8e5
7.64
18
"""Model Module. Implements the generic class for all other model types. This should not be directly instantiated, instead you should use one of the concrete classes (e.g. [`AaEModel`][nhp.model.aae.AaEModel], [`InpatientsModel`][nhp.model.inpatients.InpatientsModel], [`OutpatientsModel`][nhp.model.outpatients.Outpati...
The-Strategy-Unit/nhp_model
src/nhp/model/model.py
.py
060931b5d041391e
7.64
18
"""Model Iteration. Provides a simple class which holds all of the data required for a model iteration """ from typing import TYPE_CHECKING import numpy as np import pandas as pd from nhp.model.activity_resampling import ActivityResampling ModelRunResult = dict[str, pd.Series] if TYPE_CHECKING: from nhp.model...
The-Strategy-Unit/nhp_model
src/nhp/model/model_iteration.py
.py
2b9d61759a42f94d
7.64
18
"""Outpatients Module. Implements the Outpatients model. """ from typing import Any, Callable, Tuple import numpy as np import pandas as pd from nhp.model.data import Data from nhp.model.model import Model from nhp.model.model_iteration import ModelIteration class OutpatientsModel(Model): """Outpatients Model...
The-Strategy-Unit/nhp_model
src/nhp/model/outpatients.py
.py
219ebcc75e55484d
7.64
18
"""Methods to work with results of the model. This module allows you to work with the results of the model. Namely, combining the monte-carlo runs into a single panda's dataframe, and helping with saving the results files. """ import json import logging import os from typing import Dict, List import pandas as pd fr...
The-Strategy-Unit/nhp_model
src/nhp/model/results.py
.py
c0afe90bba14f558
7.64
18
"""Run the model.""" import logging import multiprocessing import os import time from typing import Any, Callable, Tuple, Type import pandas as pd from tqdm.auto import tqdm as base_tqdm from nhp.model.aae import AaEModel from nhp.model.data import Data, Local from nhp.model.health_status_adjustment import HealthSta...
The-Strategy-Unit/nhp_model
src/nhp/model/run.py
.py
6a9bf7a8c8def755
7.64
18
"""Test single model runs for the NHP model.""" import pandas as pd import pytest from nhp.model import ( AaEModel, HealthStatusAdjustmentInterpolated, InpatientsModel, Model, ModelIteration, OutpatientsModel, load_sample_params, ) from nhp.model.data import Local from nhp.model.results im...
The-Strategy-Unit/nhp_model
tests/e2e/test_run_model_snapshot.py
.py
838b45cf5f4468d7
8.14
18
"""Test params-sample.""" import pytest from nhp.model.params import load_sample_params @pytest.mark.integration def test_sample_params_are_valid(): load_sample_params(dataset="dev", scenario="unit-test") # assert: no exception raised @pytest.mark.integration def test_load_sample_params_validation_fails()...
The-Strategy-Unit/nhp_model
tests/integration/nhp/model/test_params_validation.py
.py
7d783c628bca161e
7.64
18
"""Test single model runs for the NHP model.""" import pytest from nhp.model import ( AaEModel, InpatientsModel, ModelIteration, OutpatientsModel, load_sample_params, ) from nhp.model.data import Local @pytest.fixture(scope="session") def model_single_run_results(data_dir): params = load_sam...
The-Strategy-Unit/nhp_model
tests/integration/nhp/model/test_single_model_run.py
.py
36febe57af310811
8.14
18
"""test docker run.""" import uuid from datetime import datetime from unittest.mock import Mock, patch import pytest from nhp.docker.__main__ import main, parse_args @pytest.mark.unit @pytest.mark.parametrize( ", ".join( [ "args", "expected_file", "expected_model_run...
The-Strategy-Unit/nhp_model
tests/unit/nhp/docker/test___main__.py
.py
a099d0aa7fd0cb93
7.14
18
"""test docker run.""" import uuid from unittest.mock import Mock, call, mock_open, patch import pytest from azure.data.tables import UpdateMode from nhp.docker.run import RunWithAzureStorage, RunWithLocalStorage # RunWithLocalStorage @pytest.mark.unit def test_RunWithLocalStorage(mocker): # arrange m = m...
The-Strategy-Unit/nhp_model
tests/unit/nhp/docker/test_run.py
.py
d292afb8895ff330
7.14
18
"""test nhp data (local).""" from unittest.mock import call, mock_open, patch import pandas as pd import pytest from nhp.model.data import Local @pytest.mark.unit def test_init_sets_values(): # arrange # act d = Local("data", 2019, "synthetic") # assert assert d._data_path == "data" @pytest...
The-Strategy-Unit/nhp_model
tests/unit/nhp/model/data/test_local.py
.py
d42447b6153b5a43
7.14
18
"""test nhp data (reference).""" from unittest.mock import call import pytest from nhp.model.data import reference expected_hsa_variants = {"lle", "hle", "ppp"} @pytest.mark.unit def test_variants(): # arrange # act vl = reference.variant_lookup() # assert assert len(vl) == 17 assert set...
The-Strategy-Unit/nhp_model
tests/unit/nhp/model/data/test_reference.py
.py
61a4d2b09eeac71f
8.14
18
"""Test run_model.py.""" from unittest.mock import Mock, patch import pytest from nhp.model.__main__ import main from nhp.model.aae import AaEModel from nhp.model.inpatients import InpatientsModel from nhp.model.outpatients import OutpatientsModel @pytest.mark.unit @pytest.mark.parametrize( "acti...
The-Strategy-Unit/nhp_model
tests/unit/nhp/model/test__main__.py
.py
2d2a04e5178a5798
7.14
18
"""Test a&e model.""" from unittest.mock import Mock, call, patch import numpy as np import pandas as pd import pytest from nhp.model.aae import AaEModel # fixtures @pytest.fixture def mock_model(): """Create a mock Model instance.""" with patch.object(AaEModel, "__init__", lambda s, p, d, h, r: None): ...
The-Strategy-Unit/nhp_model
tests/unit/nhp/model/test_aae.py
.py
558218bef768225a
8.14
18
"""test activity avoidance.""" from unittest.mock import Mock, patch import numpy as np import pandas as pd import pytest from nhp.model.activity_resampling import ActivityResampling # fixtures @pytest.fixture def mock_activity_resampling(): """Create a mock Model instance.""" with patch.obj...
The-Strategy-Unit/nhp_model
tests/unit/nhp/model/test_activity_resampling.py
.py
bb4c76c060f10266
7.14
18
"""Test health status adjustmente.""" from unittest.mock import Mock, patch import numpy as np import pandas as pd import pytest from nhp.model.health_status_adjustment import ( HealthStatusAdjustment, HealthStatusAdjustmentGAM, HealthStatusAdjustmentInterpolated, ) # Health Status Adjustment @pytest....
The-Strategy-Unit/nhp_model
tests/unit/nhp/model/test_health_status_adjustment.py
.py
fe23b6597fb28b63
7.14
18
"""Test helper methods.""" from unittest.mock import Mock import pytest from nhp.model.helpers import inrange, rnorm @pytest.mark.unit @pytest.mark.parametrize("value, expected", [(-1.1, 0), (1.1, 1), (0, 0), (1, 1), (0.5, 0.5)]) def test_inrange(value, expected): """Test that the inrange function returns expe...
The-Strategy-Unit/nhp_model
tests/unit/nhp/model/test_helpers.py
.py
7dddee5ede7a2dec
8.14
18
"""Test inpatient efficiencies.""" from unittest.mock import Mock, patch import numpy as np import pandas as pd import pytest from nhp.model.inpatients import InpatientEfficiencies @pytest.fixture def mock_ipe(): """Create a mock Model instance.""" with patch.object(InpatientEfficiencies, "__init__", lambd...
The-Strategy-Unit/nhp_model
tests/unit/nhp/model/test_inpatient_efficiencies.py
.py
f107187d0c1fa371
7.14
18
"""Test inpatients model.""" from unittest.mock import Mock, call, patch import numpy as np import pandas as pd import pytest from nhp.model.inpatients import InpatientsModel # fixtures @pytest.fixture def mock_model(): """Create a mock Model instance.""" with patch.object(InpatientsModel, "__init__", lamb...
The-Strategy-Unit/nhp_model
tests/unit/nhp/model/test_inpatients.py
.py
d0e991d3b48a5c75
7.14
18
"""Test run_model.""" from unittest.mock import Mock, patch import numpy as np import pandas as pd import pytest from nhp.model.model_iteration import ModelIteration # fixtures @pytest.fixture def mock_model_iteration(): """Create a mock Model instance.""" with patch.object(ModelIteration, "...
The-Strategy-Unit/nhp_model
tests/unit/nhp/model/test_model_iteration.py
.py
31409be4d5b55a1a
7.14
18
"""Test outpatients model.""" from unittest.mock import Mock, call, patch import numpy as np import pandas as pd import pytest from nhp.model.outpatients import OutpatientsModel # fixtures @pytest.fixture def mock_model(): """Create a mock Model instance.""" with patch.object(OutpatientsModel, "__init__", ...
The-Strategy-Unit/nhp_model
tests/unit/nhp/model/test_outpatients.py
.py
0b8bf377ee0a122f
8.14
18
"""Test params-sample.""" from unittest.mock import mock_open, patch import pytest from nhp.model.params import load_params, load_sample_params, validate_params @pytest.mark.unit def test_validate_params(mocker): # arrange m_validate = mocker.patch("jsonschema.validate") m_json_load = mocker.patch("jso...
The-Strategy-Unit/nhp_model
tests/unit/nhp/model/test_params.py
.py
e48c6273183392ed
7.14
18
"""Test results.py.""" from unittest.mock import Mock, call, mock_open, patch import pandas as pd import pytest from nhp.model.results import ( _add_metadata_to_dataframe, _check_for_duplicates, _combine_model_results, _complete_model_runs, _patch_converted_sdec_activity, _save_params_file, ...
The-Strategy-Unit/nhp_model
tests/unit/nhp/model/test_results.py
.py
6f6060c4e3b1de35
7.14
18
"""Test run_model.py.""" from unittest.mock import Mock, call import pandas as pd import pytest from nhp.model.aae import AaEModel from nhp.model.data import Data from nhp.model.inpatients import InpatientsModel from nhp.model.outpatients import OutpatientsModel from nhp.model.run import ( _run_model...
The-Strategy-Unit/nhp_model
tests/unit/nhp/model/test_run.py
.py
5f5db6ef85070e0d
7.14
18
"""sqlalchemy infrastructure serving this package (and other sqlalchemy applications).""" from pathlib import Path from typing import Optional, Type from sqlalchemy.ext.asyncio import AsyncConnection, AsyncEngine, AsyncSession, create_async_engine from sqlalchemy.ext.asyncio import async_sessionmaker as sessionmaker ...
aioqzone/QzEmoji
src/qzemoji/base.py
.py
6968a4428201647c
7.42
6
import re import shutil from pathlib import Path from typing import Optional, Union from aiofiles import open as aopen from aiohttp import ClientSession as AsyncClient from yarl import URL from qzemoji.base import AsyncEngineFactory from qzemoji.orm import EmojiTable FALLBACK_DB = "https://github.com/aioqzone/QzEmoj...
aioqzone/QzEmoji
src/qzemoji/finddb.py
.py
400967e79e3fa83d
7.42
6
import re from pathlib import Path from typing import Optional, Union from yarl import URL import qzemoji as qe def resolve(*, url: Union[URL, str, None] = None, tag: Optional[str] = None): """ The resolve function takes either a URL or a tag as an argument, and returns the emoji ID. If the argument is...
aioqzone/QzEmoji
src/qzemoji/utils.py
.py
e675cc919b73a827
7.42
6
"""Shared pytest configuration. Channels' ``RedisChannelLayer`` keeps a connection pool whose asyncio locks are bound to the event loop of the first test that uses them; reusing it across the fresh event loops that ``TransactionTestCase`` creates per test leads to non-deterministic "bound to a different event loop" er...
d-party/backend
conftest.py
.py
8ce31804c4dcacb5
7.95
7
"""django-unfold の管理画面ダッシュボード用コールバック。 ``settings.UNFOLD`` の ``DASHBOARD_CALLBACK`` / ``ENVIRONMENT`` から参照される。 同時視聴サービスの状態を一目で把握できる KPI カードとリアクション内訳を、 トップページ(``admin:index``)へ差し込む。 """ from __future__ import annotations from django.conf import settings from django.db.models import Count, Sum from django.utils.timezon...
d-party/backend
d_party/dashboard.py
.py
f406eb1bfb9cf8bb
7.45
7
from django.contrib import admin from django.contrib.auth.admin import GroupAdmin as BaseGroupAdmin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import Group, User from django.utils.timezone import now from django.utils.translation import gettext_lazy as _ from unfold...
d-party/backend
streamer/admin.py
.py
66e93dc11e2d475d
7.45
7
"""Transparent application-level encryption for model fields. Replaces the unmaintained ``django-cryptography`` ``encrypt()`` wrapper with a small, dependency-light ``EncryptedCharField`` built on top of the maintained ``cryptography`` package (Fernet / AES-128-CBC + HMAC). The encryption key is derived from ``settin...
d-party/backend
streamer/fields.py
.py
57f2e4e36af12f0e
7.45
7
"""Reap stale "alive" rooms / users left behind by an ungraceful shutdown. Channels WebSocket session state lives only in the Django process (`AnimePartyConsumer`). On a graceful shutdown each connection's ``disconnect`` fires and ``leave_party`` cleans up the rows, but on a hard crash (OOMKill / node loss / SIGKILL) ...
d-party/backend
streamer/management/commands/close_active_sessions.py
.py
63661342ab51ae58
7.45
7
"""Logical (soft) deletion support. This module is a self-contained replacement for the now-unmaintained ``django_boost`` ``LogicalDeletionMixin``. The public behaviour is kept identical so the streamer core logic does not have to change: * ``Model.objects.alive()`` / ``.dead()`` filter by the ``deleted_at`` flag. * ...
d-party/backend
streamer/mixins.py
.py
8eb7593e582954df
7.45
7
import uuid from django.db import models from .fields import EncryptedCharField from .mixins import LogicalDeletionMixin class AnimeRoom(LogicalDeletionMixin): room_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) num_people = models.PositiveSmallIntegerField(default=1) sum_pe...
d-party/backend
streamer/models.py
.py
56c3db6cb044a52e
7.45
7
"""Tests for the startup ghost-session reaper (``close_active_sessions``). Only rooms/users whose ``updated_at`` is older than ``STALE_AFTER`` should be closed; sessions touched recently (i.e. still being served) must be left alive so that running on a fresh replica never wipes another replica's live sessions. """ im...
d-party/backend
streamer/test_close_active_sessions.py
.py
d21dd6e473fe4343
7.95
7
"""Tests for reaction folding into ``ReactionStat`` on room end.""" import datetime import pytest from django.utils import timezone from .cron import fold_room_reactions from .factories import AnimeRoomFactory from .models import AnimeReaction, ReactionStat def _make_reaction(room, reaction_type: str, when: dateti...
d-party/backend
streamer/test_stats_folding.py
.py
b4a1f1e68348fffd
7.95
7
import json import numpy as np from napari_organoid_counter import get_reader, settings # tmp_path is a pytest fixture def test_reader(tmp_path): """Testing the reader part of the plugin""" settings.init() # write some fake data using your supported file format my_test_file = str(tmp_path / 'myfile.js...
HelmholtzAI-Consultants-Munich/napari-organoid-counter
napari_organoid_counter/_tests/test_reader.py
.py
5fcc1f5ca163e0eb
8.1
15
#!/usr/bin/env python3 """ Timing Analysis Script for Organoid Counter Experiments Analyzes JSON timing logs and computes mean ± std for different configurations. Groups results by model name and (window_sizes, downsampling) pairs. Usage: python analyze_timings.py <directory_path> python analyze_timings.py /p...
HelmholtzAI-Consultants-Munich/napari-organoid-counter
napari_organoid_counter/analyze_timings.py
.py
c4a87cfb5ac4c283
7.6
15
""" 数据提取模块 处理markdown文件并提取论文数据 """ import os import re import warnings warnings.filterwarnings('ignore', category=UserWarning, module='jieba') import numpy as np import pandas as pd import jieba import jieba.posseg as pseg from collections import Counter def _print_parse_error(md_file, date_text, item_index, reason...
SukiYume/APOD
Status/data_extractor.py
.py
b163f91103e5df63
7.42
6
""" 主函数模块 控制程序流程,决定生成哪些图表 """ import os from data_extractor import get_markdown_path, extract_data, get_keyword_counter, content_count from plot_generator import plot_new_count, plot_word_cloud, plot_word_max, plot_counter_graph def ensure_figure_dir(): """确保Figure目录存在""" if not os.path.exists('Figure'): ...
SukiYume/APOD
Status/status.py
.py
29f9c93003a441ae
7.42
6
import random from .items import ( DungeonItem, DungeonWeapon, DungeonPotion, DungeonScroll, DungeonThrowable, DungeonArmour, DungeonSpell, DungeonSpellBook, ) from .people import DungeonPeople, DungeonTrader, DungeonHealer from .decoder import DungeonJSONDecoder class DungeonDatabase: """Root database t...
mime-r/Dungeon.py
Dungeon/Application/classes/database.py
.py
b05ede8ca81b7ba4
7.48
8
from enum import Enum from .weapons import WeaponType, DungeonWeaponTexts class ItemUseType(str, Enum): EQUIP = "equip" USE = "use" class DungeonItem: """Base class for all dungeon items.""" symbol = "(" # default ground glyph; subclasses override def __init__(self, name: str, description: s...
mime-r/Dungeon.py
Dungeon/Application/classes/items.py
.py
f5d5b4b1f9bcf826
7.48
8
import copy import json import random from pathlib import Path DATA_DIR = Path(__file__).parent.parent.parent / "data" _NAME_POOL: dict | None = None # Brand tier multiplier for price calculation (applied to base cost). _BRAND_PRICE_MULT: dict[int, float] = { 1: 0.3, # venom, protection 2: 0.5, # flaming...
mime-r/Dungeon.py
Dungeon/Application/classes/people.py
.py
5c1bd3b982e392c0
7.48
8
from enum import Enum class SkillState(str, Enum): DISABLED = "-" ENABLED = "+" FOCUSED = "*" # Weapon name -> skill category mapping _WEAPON_SKILL_MAP = { # Maces & Flails "Club": "Maces & Flails", "Whip": "Maces & Flails", "Mace": "Maces & Flails", "Flail": "Maces & Flails", "M...
mime-r/Dungeon.py
Dungeon/Application/classes/skills.py
.py
77f73fdb9909888e
7.48
8
"""Status effects shared by the player and monsters. A :class:`StatusSet` hangs off each actor as ``.status``. Most effects are passive flags read elsewhere (might at attack time, haste/slow by the energy scheduler, confusion at move time); only poison and regeneration do something on each game-tick via :meth:`tick`. ...
mime-r/Dungeon.py
Dungeon/Application/classes/status.py
.py
9158611c82acc636
7.48
8
"""Central game configuration: colours, symbols, terrain, map size, depth and spawns.""" class StyleConfig: """Rich markup styles. Each attribute name is usable as ``[name]...[/name]``.""" # --- terrain / map tiles --- wall: str = "bold #5a5a5a" floor: str = "#3a3a3a" unknown: str = "#0C0C0C" ...
mime-r/Dungeon.py
Dungeon/Application/config.py
.py
78a183b9677f4704
7.48
8
"""Cross-platform, turn-based single-key input. Replaces the old ``keyboard`` global-hook library. Reads one logical keypress at a time from the controlling terminal: * Windows -> ``msvcrt`` * Unix/mac -> ``termios`` + ``tty`` raw mode Arrow keys, Enter, Escape and friends are normalised to stable logical tokens ("...
mime-r/Dungeon.py
Dungeon/Application/input.py
.py
dd0d61f0dcf69685
7.48
8
# https://github.com/The-Duck-Syndicate/encry-duck/blob/master/encry-duck.py import importlib import os import platform import subprocess import sys from importlib import import_module def _clear(): os.system("cls" if platform.system() == "Windows" else "clear") def _pip_install(module, logger) -> bool: """...
mime-r/Dungeon.py
Dungeon/Application/modules.py
.py
8a08789d0a96de7c
7.48
8
"""Main module for Dolphin Central. Initializes and registers the required components then starts the main event loop of the process. """ from . import ( admin, buildbot, config, discord, events, git, github, ircclient, notifications, redmine, webserver, wiki, ) import...
dolphin-emu/central
central/__main__.py
.py
b3fc16549c83234d
7.45
7
"""Admin module that handles some central management and administration related commands.""" from . import events import os import os.path import sys import time class RebootListener(events.EventTarget): def accept_event(self, evt): return evt.type == events.CommandMessage.TYPE def push_event(self,...
dolphin-emu/central
central/admin.py
.py
b120c6462fb16d73
7.45
7
"""Configuration system for Dolphin Central. Loads a single configuration file at initialization time and provides access to the configuration as a global 'cfg' object. """ from . import utils import yaml cfg = utils.ObjectLike({}) def file_include_constructor(loader, node): value = str(loader.construct_scala...
dolphin-emu/central
central/config.py
.py
0cb36e3596b8dc33
7.45
7
from . import app, authz, build_status, fifoci_reporter, webhooks from .. import utils from ..config import cfg import json import requests def get_pull_request(owner, repo, pr_id): return requests.get( "https://api.github.com/repos/%s/%s/pulls/%s" % (owner, repo, pr_id) ).json() def get_pull_requ...
dolphin-emu/central
central/github/__init__.py
.py
d3edefd17db8bdc3
7.45
7
"""Transforms raw Redmine issue events into higher level ones. Will potentially also have more complex processing in the future. """ from . import events from .config import cfg class Reactor(events.EventTarget): def accept_event(self, evt): return evt.type == events.RawRedmineHook.TYPE def push_ev...
dolphin-emu/central
central/redmine.py
.py
add22aff1d962433
7.45
7
from __future__ import annotations from collections.abc import Iterable, Iterator import pynbs def sorted_notes(notes: Iterable[Note]) -> list[Note]: """Return a list of notes sorted by pitch, instrument, velocity, and panning.""" return sorted(notes, key=lambda x: (x.pitch, x.instrument, x.velocity, x....
OpenNBS/nbswave
nbswave/nbs.py
.py
6cafec1b35754745
7.56
12
from __future__ import annotations import ast from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from collections.abc import Iterator # The code FA is required in order for errors to appear. ERROR_MESSAGE_100 = "FA100 Missing from __future__ import annotations but imports: {}" ERROR_MESSAGE_101 = "FA101 Mis...
TylerYep/flake8-future-annotations
flake8_future_annotations/checker.py
.py
05585105dfd70d47
7.6
15
# Copyright 2015 Adriana Supady # # This file is part of fafoom. # # Fafoom is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later...
inter-info-lab/chem_laqa
laqa_fafoom/pyff.py
.py
96239dec891ea7fe
7.42
6
#!/usr/bin/env python3 import aiofiles import argparse import asyncio import io import mmap import os import pcpp import re import CppHeaderParser import pathlib from typing import List, Optional import locale locale.setlocale(locale.LC_ALL, "") # Use '' for auto, or force e.g. to 'en_US.UTF-8' HEADER_TYPES = (".h",...
alandtse/vr_address_tools
extractStruct.py
.py
09698d03995df2f3
7.63
17
import pandas as pd import csv BASE = 0x140000000 def merge_skyrim(): # read address id SSE offsets df1 = pd.read_table("offsets-1-5-97-0.csv", sep=",") # read address id AE offsets df2 = pd.read_table("offsets-1-6-318-0.csv", sep=",") # read meh's attempted match table. https://www.nexusmods.com/...
alandtse/vr_address_tools
merge.py
.py
6a18e73d24483096
7.63
17
import re import argparse import os from typing import Dict, Tuple, Union # Define a type alias for offsets OffsetsType = Dict[str, Union[int, Tuple[int, Union[int, Tuple]]]] CommonLibOffsets = r".*REL::ID (\w+)\(static_cast<std::uint64_t>\((\d+)\)\);" CommonLibNGOffsets = r".*constexpr auto (\w+) = RELOCATION_ID\((\...
alandtse/vr_address_tools
replaceOffsetsNamespace.py
.py
7ed998346848fa8c
7.63
17
"""Example demonstrating how to create an LLM project and add tests to it. This script shows: - Creating an LLM project - Adding various types of tests suitable for LLM monitoring: - LLM Rubric tests (evaluating quality criteria) - Character length tests (checking response length) - PII detection tests (ensuring...
openlayer-ai/openlayer-python
examples/rest-api/create_llm_project_with_tests.py
.py
d3400f3899dc53c1
7.13
17
""" Example: Configuring the Openlayer Tracer Demonstrates the three ways to configure the tracer and how they compose: 1. Environment variables (canonical for deployments) 2. init() — programmatic, idempotent, merges on repeated calls 3. Per-decorator override via @trace(inference_pipeline_id=...) Precedence (...
openlayer-ai/openlayer-python
examples/tracing/programmatic_configuration.py
.py
af383c576f8c04b8
7.63
17
#!/usr/bin/env python3 """ Comprehensive example showing how to use Openlayer's trace metadata update functionality. This example demonstrates how to set user_id, metadata, and other context information dynamically during trace execution without having to pass them as function arguments. """ import os import time fro...
openlayer-ai/openlayer-python
examples/tracing/trace_metadata_updates.py
.py
f558fe1ece348d08
7.63
17
# Note: initially copied from https://github.com/florimondmanca/httpx-sse/blob/master/src/httpx_sse/_decoders.py from __future__ import annotations import json import inspect from types import TracebackType from typing import TYPE_CHECKING, Any, Generic, TypeVar, Iterator, Optional, AsyncIterator, cast from typing_ext...
openlayer-ai/openlayer-python
src/openlayer/_streaming.py
.py
5ac10cdf74cdffaa
7.63
17
from __future__ import annotations from os import PathLike from typing import ( IO, TYPE_CHECKING, Any, Dict, List, Type, Tuple, Union, Mapping, TypeVar, Callable, Iterable, Iterator, Optional, Sequence, AsyncIterable, ) from typing_extensions import ( ...
openlayer-ai/openlayer-python
src/openlayer/_types.py
.py
3b7520f95be13246
7.63
17
from __future__ import annotations from typing import Any from typing_extensions import override from ._proxy import LazyProxy class ResourcesProxy(LazyProxy[Any]): """A proxy for the `openlayer.resources` module. This is used so that we can lazily import `openlayer.resources` only when needed *and* so...
openlayer-ai/openlayer-python
src/openlayer/_utils/_resources_proxy.py
.py
6e29386060d28433
7.63
17
"""Base class for an Openlayer model.""" import os import abc import json import time import inspect import argparse from typing import Any, Dict, Tuple from dataclasses import field, dataclass import pandas as pd from ..tracing import tracer @dataclass class RunReturn: """The return type of the `run` method i...
openlayer-ai/openlayer-python
src/openlayer/lib/core/base_model.py
.py
2fc7bb4f3c2dbbfd
7.63
17
"""Module containing the BaseMetric definition for Openlayer.""" from __future__ import annotations import os import abc import json import argparse import traceback from typing import Any, Set, Dict, List, Union, Optional from dataclasses import field, asdict, dataclass import pandas as pd @dataclass class Metric...
openlayer-ai/openlayer-python
src/openlayer/lib/core/metrics.py
.py
407f9307f768c3cf
7.63
17
"""Module containing convenience functions for the tests API.""" from typing import Optional, List from openlayer import Openlayer def copy_tests( client: Openlayer, origin_project_id: str, target_project_id: str, verbose: bool = False, test_ids: Optional[List[str]] = None, ) -> None: """Copy...
openlayer-ai/openlayer-python
src/openlayer/lib/core/tests.py
.py
cd634462774cf19c
8.13
17
"""Upload a batch of inferences to the Openlayer platform.""" import time import logging import tempfile from typing import Optional import httpx import pandas as pd import pyarrow as pa from . import StorageType, _upload from ... import Openlayer from ..._utils import maybe_transform from ...types.inference_pipelin...
openlayer-ai/openlayer-python
src/openlayer/lib/data/batch_inferences.py
.py
1f7291ed09304b4f
7.63
17
"""Pushes a commit to the Openlayer platform.""" import os import tarfile import tempfile import time from typing import Optional from ... import Openlayer from . import StorageType, _upload from ...types.commit_retrieve_response import CommitRetrieveResponse def push( client: Openlayer, directory: str, ...
openlayer-ai/openlayer-python
src/openlayer/lib/data/commit.py
.py
013884d2456fa2bc
7.63
17
""" Copyright 2020 ETH Zurich, Secure, Reliable, and Intelligent Systems Lab 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.apache.org/licenses/LICENSE-2.0 Unless requi...
uiuc-arc/FANC
tf_verify/config.py
.py
653816e8981b0e06
7.57
13
""" Copyright 2020 ETH Zurich, Secure, Reliable, and Intelligent Systems Lab 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.apache.org/licenses/LICENSE-2.0 Unless requi...
uiuc-arc/FANC
tf_verify/constraint_utils.py
.py
be60b76695f52263
7.57
13
import sys from typing import Any from unittest.mock import DEFAULT, patch import structlog def import_without_structlog_sentry(package: str, *args: Any, **kwargs: Any) -> Any: """ :param package: Name of package :return: None if `structlog_sentry` is part of package name, else default import """ ...
kolonialno/troncos
tests/structlog/test_configuration.py
.py
50e61a79f37bbae5
8.07
13
import time from typing import Any, Awaitable, Callable, Iterator, Mapping, MutableMapping, cast from ddtrace.trace import tracer from python_ipware.python_ipware import IpWare try: from structlog import get_logger except ImportError as exc: raise RuntimeError( "Structlog must be installed to use th...
kolonialno/troncos
troncos/contrib/asgi/logging/middleware.py
.py
0b8f03a8c07e0a96
7.57
13
import time from typing import Any from celery import signals try: from structlog import get_logger except ImportError as exc: raise RuntimeError( "Structlog must be installed to use the celery logging signals." ) from exc logger = get_logger("troncos.celery.task") def connect_troncos_logging_c...
kolonialno/troncos
troncos/contrib/celery/logging/signals.py
.py
9e66d287ae9eb7c3
7.57
13
import logging def print_loggers(verbose: bool = True) -> None: """ Function that prints out initialized loggers. This is helpful for you to visualize exactly how loggers have been set up in your project (and your dependencies). By default, all loggers will be printed. If you want to filter out loggin...
kolonialno/troncos
troncos/contrib/logging/tools/__init__.py
.py
440702931e57fe3b
7.57
13
from ddtrace.trace import tracer from structlog.processors import LogfmtRenderer as LogFmt from structlog.types import EventDict, WrappedLogger def trace_injection_processor( _logger: WrappedLogger, _log_method: str, event_dict: EventDict ) -> EventDict: """ Simple logging processor that adds a trace_id ...
kolonialno/troncos
troncos/contrib/structlog/processors.py
.py
dfd3bb245c84dba3
7.57
13
from typing import Any from ddtrace.trace import tracer, Tracer from ddtrace.internal.service import ServiceStatusError from ._exporter import Exporter, ExporterType from ._writer import OTELWriter __all__ = ["Exporter", "ExporterType", "configure_tracer", "create_trace_writer"] def create_trace_writer( *, ...
kolonialno/troncos
troncos/tracing/__init__.py
.py
d20be53fc1221cc0
7.57
13
import os import sys from opentelemetry.exporter.otlp.proto.http.trace_exporter import ( OTLPSpanExporter as HTTPSpanExporter, ) from opentelemetry.sdk.trace import SpanProcessor from opentelemetry.sdk.trace.export import ( BatchSpanProcessor, ConsoleSpanExporter, SimpleSpanProcessor, SpanExporter,...
kolonialno/troncos
troncos/tracing/_otel.py
.py
f0fe44bff1736dc0
7.57
13
#!/usr/bin/env python3 import os import json import tempfile import textwrap from pathlib import Path import requests from tqdm import tqdm from prompt_toolkit import prompt from prompt_toolkit import print_formatted_text as print HERE = Path(__file__).parent.resolve() CACHE_FILE = HERE / "uploaded_photos_cache.jso...
lubianat/inat2wiki
batch_upload/batch_upload.py
.py
f3861eef69c1cfe4
7.5
9
"""A flask app to connect iNaturalist to Wikidata.""" from dataclasses import dataclass from flask_bootstrap import Bootstrap5 from flask_wtf import FlaskForm from taxon2wikipedia.render_page import run_pipeline_for_wikipage from wdcuration import get_statement_values, lookup_id from wtforms import BooleanField, Integ...
lubianat/inat2wiki
www/python/src/app.py
.py
a3f5ba9edc7b976d
7.5
9