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 |
|---|---|---|---|---|---|---|
import polars as pl
from asf_heat_pump_suitability.getters import get_datasets
def load_transform_df_n_households() -> pl.DataFrame:
"""
Load and process number of households per LSOA/DataZone in England, Scotland, and Wales.
Returns
pl.DataFrame: number of households per LSOA/DataZone
"""
... | nestauk/asf_heat_pump_suitability | asf_heat_pump_suitability/pipeline/transform/household_count.py | .py | c5ba94b20c0944c7 | 7.6 | 15 |
import pandas as pd
import geopandas as gpd
import regex as re
import logging
from tqdm import tqdm
import warnings
from asf_heat_pump_suitability.getters import base_getters, load_data, load_geodata
from asf_heat_pump_suitability.utils import geo_utils
def generate_gdf_file_bounds_s(path: str) -> gpd.GeoDataFrame:
... | nestauk/asf_heat_pump_suitability | asf_heat_pump_suitability/pipeline/transform/land_extent.py | .py | 2d0d1dc83c36a628 | 7.6 | 15 |
import polars as pl
import geopandas as gpd
from asf_heat_pump_suitability.getters import load_geodata
def transform_df_osopen_uprn_latlon() -> pl.DataFrame:
"""
Transform UPRN column in raw OS Open UPRN data to match format in EPC.
Returns:
pl.DataFrame: OS Open UPRN dataset with UPRN column in ... | nestauk/asf_heat_pump_suitability | asf_heat_pump_suitability/pipeline/transform/lat_lon.py | .py | 1d681be667b0ec05 | 7.6 | 15 |
import polars as pl
import geopandas as gpd
import pandas as pd
from tqdm import tqdm
import logging
from asf_heat_pump_suitability.getters import load_geodata
from asf_heat_pump_suitability.pipeline.transform import lat_lon
def generate_df_epc_listed_buildings(
epc_df: pl.DataFrame, nations: list = ["England", "... | nestauk/asf_heat_pump_suitability | asf_heat_pump_suitability/pipeline/transform/listed_buildings.py | .py | 8e2a61f8a54921c1 | 7.6 | 15 |
import geopandas as gpd
import logging
import pandas as pd
import polars as pl
import difflib
import regex as re
from asf_heat_pump_suitability.getters import load_geodata, load_boundaries
from asf_heat_pump_suitability.utils import geo_utils
from asf_heat_pump_suitability import config
def resolve_list_la_names(la_n... | nestauk/asf_heat_pump_suitability | asf_heat_pump_suitability/pipeline/transform/local_authority.py | .py | da435140f4ac9582 | 7.6 | 15 |
"""
Functions to transform data related to identifying non-domestic buildings.
"""
import geopandas as gpd
import pandas as pd
import numpy as np
# TODO these may need refinement for large cities where overlap with residential is possible
NO_RESIDENTIAL_OVERLAP_BUILDING_TYPES = [
"Port Consisting of Docks and Nau... | nestauk/asf_heat_pump_suitability | asf_heat_pump_suitability/pipeline/transform/non_residential_entities.py | .py | b619e7cfa7d4039d | 7.6 | 15 |
from typing import List
import polars as pl
import geopandas as gpd
from asf_heat_pump_suitability.getters import load_data
def process_off_gas_data() -> List[str]:
"""
This function processes the off-gas data by removing spaces from the postcodes and converting them to a list.
Returns:
List[st... | nestauk/asf_heat_pump_suitability | asf_heat_pump_suitability/pipeline/transform/off_gas.py | .py | 61052f1b0fe3d6b5 | 7.6 | 15 |
"""
Functions to calculate outdoor space estimates from building footprints and land extents.
"""
import geopandas as gpd
import logging
import pandas as pd
import polars as pl
from asf_heat_pump_suitability.getters import load_geodata
from asf_heat_pump_suitability.utils import geo_utils
def match_series_files_land... | nestauk/asf_heat_pump_suitability | asf_heat_pump_suitability/pipeline/transform/outdoor_space.py | .py | 09ad28bf18fccd63 | 7.6 | 15 |
"""
Functions to preprocess Points of Interest (POI) data for Great Britain.
"""
import geopandas as gpd
from typing import Iterable
import csv
import smart_open
from asf_heat_pump_suitability import config
def transform_gdf_poi(
poi: gpd.GeoDataFrame,
filter_categories: Iterable[str] = None,
target_crs... | nestauk/asf_heat_pump_suitability | asf_heat_pump_suitability/pipeline/transform/poi.py | .py | 6f54023deac61366 | 7.6 | 15 |
"""
Tests for asf_heat_pump_suitability.pipeline.transform.decision_tree.
Run:
pytest asf_heat_pump_suitability/pipeline/transform/tests/test_decision_tree.py
"""
import geopandas as gpd
import pytest
from shapely.geometry import Point, Polygon
from asf_heat_pump_suitability.pipeline.transform import decision_tree
... | nestauk/asf_heat_pump_suitability | asf_heat_pump_suitability/pipeline/transform/tests/test_decision_tree.py | .py | b660b4468b8d9e68 | 8.1 | 15 |
import pytest
import geopandas as gpd
from shapely.geometry import Polygon, Point
from asf_heat_pump_suitability.pipeline.transform.uprns import (
map_dict_uprns_to_building_id,
)
class TestMapDictUPRNsBuildingToID:
"""Tests for `map_dict_uprns_to_building_id`."""
@pytest.fixture(scope="class")
@clas... | nestauk/asf_heat_pump_suitability | asf_heat_pump_suitability/pipeline/transform/tests/test_uprns.py | .py | c81894277584758d | 7.1 | 15 |
"""
Preflight check that all S3 input paths configured under `config["data"]` exist.
Recursively collects every s3:// path in the nested `config["data"]` mapping,
expands paths with a "{square}" token into one path per grid square, truncates
any remaining tokens (e.g. "{layer}") to the prefix before the first "{", and... | nestauk/asf_heat_pump_suitability | asf_heat_pump_suitability/pipeline/validate/check_inputs.py | .py | c009395a0c8bdade | 7.6 | 15 |
"""Tests for the S3 input preflight check in `pipeline.validate.check_inputs`."""
import pytest
from asf_heat_pump_suitability.pipeline.validate.check_inputs import (
generate_list_expanded_square_paths,
get_list_missing_s3_paths,
get_list_s3_paths,
get_set_squares_absent_for_path,
get_str_common_... | nestauk/asf_heat_pump_suitability | asf_heat_pump_suitability/pipeline/validate/tests/test_check_inputs.py | .py | 62dd00bd92d00ea6 | 8.1 | 15 |
#
# Copyright 2023 ABSA Group Limited
#
# 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 required by applicable law or agreed to in ... | AbsaOSS/generate-release-notes | release_notes_generator/builder/builder.py | .py | 2aff33baa1a5aac3 | 7.57 | 13 |
#
# Copyright 2023 ABSA Group Limited
#
# 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 required by applicable law or agreed to in ... | AbsaOSS/generate-release-notes | release_notes_generator/chapters/base_chapters.py | .py | 36de4344ce08edb4 | 7.57 | 13 |
#
# Copyright 2023 ABSA Group Limited
#
# 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 required by applicable law or agreed to in ... | AbsaOSS/generate-release-notes | release_notes_generator/data/filter.py | .py | c740d394bb42460d | 7.57 | 13 |
#
# Copyright 2023 ABSA Group Limited
#
# 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 required by applicable law or agreed to in ... | AbsaOSS/generate-release-notes | release_notes_generator/generator.py | .py | 6ddbf9cffa2e326f | 7.57 | 13 |
#
# Copyright 2023 ABSA Group Limited
#
# 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 required by applicable law or agreed to in ... | AbsaOSS/generate-release-notes | release_notes_generator/model/chapter.py | .py | 0c0cab82c6bca4f3 | 7.57 | 13 |
#
# Copyright 2023 ABSA Group Limited
#
# 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 required by applicable law or agreed to in ... | AbsaOSS/generate-release-notes | release_notes_generator/model/mined_data.py | .py | bd4f07c74c0b4213 | 7.57 | 13 |
#
# Copyright 2023 ABSA Group Limited
#
# 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 required by applicable law or agreed to in ... | AbsaOSS/generate-release-notes | release_notes_generator/model/record/commit_record.py | .py | 03865b199ebf924c | 7.57 | 13 |
#
# Copyright 2023 ABSA Group Limited
#
# 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 required by applicable law or agreed to in ... | AbsaOSS/generate-release-notes | release_notes_generator/model/record/hierarchy_issue_record.py | .py | 05c002350d1101fc | 7.57 | 13 |
#
# Copyright 2023 ABSA Group Limited
#
# 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 required by applicable law or agreed to in ... | AbsaOSS/generate-release-notes | release_notes_generator/model/record/issue_record.py | .py | c79e658014b0ae95 | 7.57 | 13 |
#
# Copyright 2023 ABSA Group Limited
#
# 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 required by applicable law or agreed to in ... | AbsaOSS/generate-release-notes | release_notes_generator/model/record/pull_request_record.py | .py | 6b47748114915a14 | 7.57 | 13 |
#
# Copyright 2023 ABSA Group Limited
#
# 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 required by applicable law or agreed to in ... | AbsaOSS/generate-release-notes | release_notes_generator/record/factory/default_record_factory.py | .py | 25ec33751f6ed5a2 | 7.57 | 13 |
#
# Copyright 2023 ABSA Group Limited
#
# 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 required by applicable law or agreed to in ... | AbsaOSS/generate-release-notes | release_notes_generator/utils/decorators.py | .py | 4fc8fbd2c4620b36 | 7.57 | 13 |
#
# Copyright 2023 ABSA Group Limited
#
# 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 required by applicable law or agreed to in ... | AbsaOSS/generate-release-notes | release_notes_generator/utils/gh_action.py | .py | f8c9adcfb7ac6949 | 7.57 | 13 |
#
# Copyright 2023 ABSA Group Limited
#
# 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 required by applicable law or agreed to in ... | AbsaOSS/generate-release-notes | release_notes_generator/utils/github_rate_limiter.py | .py | 5e3cdfb088446797 | 7.57 | 13 |
#
# Copyright 2023 ABSA Group Limited
#
# 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 required by applicable law or agreed to in ... | AbsaOSS/generate-release-notes | release_notes_generator/utils/pull_request_utils.py | .py | 9d755afa4312db65 | 7.57 | 13 |
#
# Copyright 2023 ABSA Group Limited
#
# 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 required by applicable law or agreed to in ... | AbsaOSS/generate-release-notes | release_notes_generator/utils/utils.py | .py | 9336bb45fdea85ca | 7.57 | 13 |
#
# Copyright 2023 ABSA Group Limited
#
# 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 required by applicable law or agreed to in ... | AbsaOSS/generate-release-notes | tests/integration/helpers.py | .py | 64be7b1bdd5753da | 8.07 | 13 |
#
# Copyright 2023 ABSA Group Limited
#
# 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 required by applicable law or agreed to in ... | AbsaOSS/generate-release-notes | tests/integration/test_snapshot.py | .py | 26305e5d50b257bb | 8.07 | 13 |
import logging
import os
from copy import deepcopy
from functools import cached_property
import torch
from anemoi.utils.checkpoints import load_metadata
from anemoi.utils.config import DotDict
from torch_geometric.data import HeteroData
LOGGER = logging.getLogger(__name__)
try:
from anemoi.models.data_indices.co... | metno/bris-inference | bris/checkpoint.py | .py | dd36a81ec3e71603 | 7.63 | 17 |
"""This module converts anemoi variable names to CF-standard names"""
def get_metadata(anemoi_variable: str) -> dict:
"""Extract metadata about a variable
Args:
variable: Anemoi variable name (e.g. u_800)
Returns:
dict with:
ncname: Name of variable in NetCDF
cfname... | metno/bris-inference | bris/conventions/cf.py | .py | 43571ecca0a3dc81 | 7.63 | 17 |
"""Met-Norway's conventions for writing NetCDF files
In particular, the naming of variables (which cannot follow CF standard, since
these are not unique (e.g. air_temperature_pl vs air_temperature_2m).
Additionally, the names of some dimension-variables do not use CF-names
"""
from bris.utils import LOGGER
class M... | metno/bris-inference | bris/conventions/metno.py | .py | 6ab5beadf86c3e6f | 7.63 | 17 |
import logging
from functools import cached_property
from typing import Any
# Backward compatibility
try:
from anemoi.datasets.data.select import Select
except ImportError:
from anemoi.datasets.usage.gridded.select import Select
try:
from anemoi.datasets.data.subset import Subset
except ImportError:
f... | metno/bris-inference | bris/data/datamodule.py | .py | 71f7ae4cc9a54358 | 7.63 | 17 |
import logging
import random
from collections.abc import Callable, Iterator
from functools import cached_property
import numpy as np
import torch
from einops import rearrange
from torch.utils.data import IterableDataset
from bris.data.grid_indices import BaseGridIndices
from bris.utils import LOGGER, get_base_seed, g... | metno/bris-inference | bris/data/dataset/nativegrid.py | .py | ef4eebaaacfd9829 | 7.63 | 17 |
# (C) Copyright 2024 Anemoi contributors.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
#
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an ... | metno/bris-inference | bris/data/grid_indices.py | .py | 750502fddd23417d | 7.63 | 17 |
"""
This submodule includes legacy NativeGridDataset used in
aifs-mono.
"""
import os
import random
from functools import cached_property
from typing import Callable, Optional
import numpy as np
import torch
from einops import rearrange
from torch.utils.data import IterableDataset, get_worker_info
from bris.data.le... | metno/bris-inference | bris/data/legacy/dataset.py | .py | 9b2d0d284c85b794 | 7.63 | 17 |
import os
import numpy as np
import pytorch_lightning as pl
import torch
from lightning_fabric.utilities.optimizer import _optimizers_to_device
from pytorch_lightning.overrides.distributed import _sync_module_states
from pytorch_lightning.strategies.ddp import DDPStrategy
from pytorch_lightning.trainer.states import T... | metno/bris-inference | bris/data/legacy/distributed/strategy.py | .py | 900c9459a2687ab9 | 7.63 | 17 |
"""
This utils submodule contains legacy functions which
legacy dataset.py needs to run aifs-mono
"""
import logging
import os
import sys
import time
import numpy as np
from anemoi.utils.config import DotDict
LOGGER = logging.getLogger(__name__)
def get_code_logger(name: str, debug: bool = True) -> logging.Logger:... | metno/bris-inference | bris/data/legacy/utils.py | .py | 44cf4bd74bf3356e | 7.63 | 17 |
# (C) Copyright 2024 Anemoi contributors.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
#
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an ... | metno/bris-inference | bris/ddp_strategy.py | .py | abf47c928967e8eb | 7.63 | 17 |
import datetime
import numpy as np
from earthkit.data.utils.dates import to_datetime
# def phase_of_day(time) -> float:
# hour = time.astype(int)
# return hour * 2 * np.pi / 24
#
# def phase_of_year(time) -> float:
# return (phase_of_day(time) - np.pi/2)/365.25
#
# def cos_julian_day(time) -> float:
# ... | metno/bris-inference | bris/forcings.py | .py | 56d00be03870e61f | 7.63 | 17 |
import importlib
import json
import sys
from argparse import ArgumentParser
from .checkpoint import Checkpoint
from .forcings import anemoi_dynamic_forcings
from .utils import get_model_multistep_input
def clean_version_name(name: str) -> tuple[str, str]:
"""Filter out these weird version names that can't be com... | metno/bris-inference | bris/inspect.py | .py | c8e8a9d1b0584b52 | 8.13 | 17 |
import logging
import math
import os
from abc import abstractmethod
from collections.abc import Iterable
from typing import Any, Union
import numpy as np
import pytorch_lightning as pl
import torch
from anemoi.models.data_indices.index import DataIndex, ModelIndex
from torch.distributed.distributed_c10d import Process... | metno/bris-inference | bris/model/brispredictor.py | .py | 92f083b89c6295c5 | 7.63 | 17 |
import numpy as np
class Observations:
def __init__(self, locations, times, data):
"""
data: dict with key variable_name and value: 2D numpy array with dimensions (time, location)
"""
for _k, v in data.items():
assert len(times) == v.shape[0]
assert len(loca... | metno/bris-inference | bris/observations.py | .py | 8f68505c38732354 | 7.63 | 17 |
import copy
import time
from abc import abstractmethod
import numpy as np
from bris import sources
from bris.predict_metadata import PredictMetadata
from bris.utils import LOGGER
def instantiate(name: str, predict_metadata: PredictMetadata, workdir: str, init_args):
"""Creates an object of type name with config... | metno/bris-inference | bris/outputs/__init__.py | .py | 33c65a4c77efe50c | 7.63 | 17 |
from datetime import datetime
import eccodes as ecc
import numpy as np
from bris import projections, utils
from bris.conventions import cf
from bris.conventions.metno import Metno
from bris.conventions.variable_list import VariableList
from bris.outputs import Output
from bris.outputs.intermediate import Intermediate... | metno/bris-inference | bris/outputs/grib.py | .py | 1eb6354340a9ec59 | 7.63 | 17 |
import numpy as np
from numpy.typing import NDArray
class PredictMetadata:
"""This class stores metadata about each dimension of a batch
NOTE: altitudes can be None
"""
def __init__(
self, variables, lats, lons, altitudes, leadtimes, num_members, field_shape=None
):
# assert util... | metno/bris-inference | bris/predict_metadata.py | .py | 541f2a194bd8ad2c | 7.63 | 17 |
import netCDF4
import numpy as np
import pyproj
def get_proj4_str(name: str) -> str:
"""Returns a proj4 string based on a name"""
return {
"meps": "+proj=lcc +lat_0=63.3 +lon_0=15 +lat_1=63.3 +lat_2=63.3 +x_0=0 +y_0=0 +R=6371000 +units=m +no_defs +type=crs",
"arome_arctic": "+proj=lcc +lat_0=7... | metno/bris-inference | bris/projections.py | .py | 8e1ffa32448392e6 | 7.63 | 17 |
import os
from collections import defaultdict
from typing import Any, Literal
import numpy as np
import bris.outputs
from bris import utils
from bris.checkpoint import Checkpoint
from bris.data.datamodule import DataModule
from bris.predict_metadata import PredictMetadata
def get(
routing_config: dict,
lead... | metno/bris-inference | bris/routes.py | .py | 2acaaed72038a77e | 7.63 | 17 |
from bris import sources
def instantiate(name: str, init_args: dict):
"""Creates an object of type name with config
Args:
predict_metadata: Contains metadata about the bathc the output will recive
init_args: Arguments to pass to Output constructor
"""
if name == "frost":
retur... | metno/bris-inference | bris/sources/__init__.py | .py | 70226423bc3f4fa2 | 7.63 | 17 |
# python standard library
import logging
import os
from argparse import Namespace
from concurrent.futures import ThreadPoolExecutor, as_completed
from functools import cached_property
from typing import Optional
# PyPi packages
from dotenv import load_dotenv
from omegaconf import DictConfig
LOGGER = logging.getLogger... | metno/bris-inference | bris/sources/azurestorage.py | .py | 9e4bc0eec0f6feba | 7.63 | 17 |
from functools import cached_property
import numpy as np
from bris.sources import Source
class Frost(Source):
"""This class writes verification files in Verif format. See github.com/WFRT/verif."""
def __init__(
self,
filename: str,
frost_variable_name: str,
leadtimes: list,
... | metno/bris-inference | bris/sources/frost.py | .py | d410c46a8b767143 | 7.63 | 17 |
"""Unit conversion module
This module handles conversion between different units and provides a set of preferred units that
should be used internally in yrprod.
"""
import numbers
import numpy as np
default_units = ["K", "m/s", "1", "kg/m^2", "degree", "Pa", "text"]
"""Preferred units (must all be strings)"""
def... | metno/bris-inference | bris/units.py | .py | a9c1da57665505ab | 7.63 | 17 |
import json
import logging
import numbers
import os
import sys
import time
import uuid
from argparse import ArgumentParser
from collections.abc import Iterable
from typing import Any
import jsonschema
import numpy as np
import torch
import yaml
from anemoi.models.data_indices.index import DataIndex, ModelIndex
from an... | metno/bris-inference | bris/utils.py | .py | e875d8e8527b0c2d | 7.63 | 17 |
import pytest
from bris.conventions.anemoi import get_units
def test_get_units_with_known_variable():
variable_name = "2t"
expected_units = "K" # Kelvin
assert get_units(variable_name) == expected_units
def test_get_units_with_unknown_variable():
# Test with an unknown variable that does not have ... | metno/bris-inference | tests/test_conventions_anemoi.py | .py | 376f637d644db96d | 7.13 | 17 |
import pytest
import bris.checkpoint
import bris.inspect
def test_clean_version_name():
"""Very basic test of removing +... from version name"""
assert bris.inspect.clean_version_name("2.6.0+cu124") == ("2.6.0", "")
assert bris.inspect.clean_version_name("anemoi-models-0.1.dev92+g80c9fbf") == (
"... | metno/bris-inference | tests/test_inspect.py | .py | 9c11bcb0debb140f | 8.13 | 17 |
#!/usr/bin/python3
# Wrapper for `ydb debug latency`: runs the command and uploads results to the
# specified YDB database.
# For each `debug latency` kind we store max observed throughput (among all inflights)
# and latency percentiles for inflight 1.
# full cmd is `ydb -p perf1 debug latency --min-inflight 1 --max-... | ydb-platform/benchhelpers | debug_latency/wrapper.py | .py | 9f54ac5f459478b4 | 7.42 | 6 |
import numpy as np
from scipy.signal.windows import hamming
class AnalysisWindow:
def __init__(self, sample_rate=48000, overlap=0.5):
self.sample_rate = sample_rate
self.overlap = overlap
self.size = self.calc_window_size()
self.data = self.apply_hamming_window()
self.windo... | QxLabIreland/Ambiqual | analysis_window.py | .py | 230ad5f8d073aac8 | 7.56 | 12 |
import numpy as np
from gammatone.gtgram import gtgram
from gammatone.fftweight import fft_gtgram
from scipy.signal import stft
def build_gammatonegram(signal, sample_rate, filter_bank, time_spaces):
"""
Build a gammatonegram from an audio signal.
Args:
signal (numpy.ndarray): The audio signal.
... | QxLabIreland/Ambiqual | build_spectrogram.py | .py | 26415cbb2a14ebbb | 8.06 | 12 |
import numpy as np
from scipy.interpolate import interp1d
def iso226(phon):
"""
Calculate the equal-loudness contour for a given phon level based on ISO 226:2003 standard.
Args:
phon (float): The phon level for which the contour is calculated.
Returns:
tuple: (SPL values in dB, frequ... | QxLabIreland/Ambiqual | equal_loudness_correct.py | .py | c08220bc87ca22d6 | 7.56 | 12 |
# Copyright 2014 Jason Heeris, jason.heeris@gmail.com
#
# This file is part of the gammatone toolkit, and is licensed under the 3-clause
# BSD license: https://github.com/detly/gammatone/blob/master/COPYING
"""
This module contains functions for calculating weights to approximate a
gammatone filterbank-like "spectrogr... | QxLabIreland/Ambiqual | gammatone/fftweight.py | .py | ea6a9552ab2c320d | 7.56 | 12 |
# Copyright 2014 Jason Heeris, jason.heeris@gmail.com
#
# This file is part of the gammatone toolkit, and is licensed under the 3-clause
# BSD license: https://github.com/detly/gammatone/blob/master/COPYING
"""
This module contains functions for constructing sets of equivalent rectangular
bandwidth gammatone filters.
... | QxLabIreland/Ambiqual | gammatone/filters.py | .py | 6402671563567772 | 7.56 | 12 |
# Copyright 2014 Jason Heeris, jason.heeris@gmail.com
#
# This file is part of the gammatone toolkit, and is licensed under the 3-clause
# BSD license: https://github.com/detly/gammatone/blob/master/COPYING
from __future__ import division
import numpy as np
from .filters import make_erb_filters, centre_freqs, erb_fil... | QxLabIreland/Ambiqual | gammatone/gtgram.py | .py | 4de253833dc5893e | 7.56 | 12 |
# Copyright 2014 Jason Heeris, jason.heeris@gmail.com
#
# This file is part of the gammatone toolkit, and is licensed under the 3-clause
# BSD license: https://github.com/detly/gammatone/blob/master/COPYING
"""
Plotting utilities related to gammatone analysis, primarily for use with
``matplotlib``.
"""
from __future__ ... | QxLabIreland/Ambiqual | gammatone/plot.py | .py | df046fa6d8e82c09 | 7.56 | 12 |
# Copyright 2024 Hasan Sezer Taşan <hasansezertasan@gmail.com>
"""Flask CLI commands.
Commands are grouped under `flask seed ...` via ``flask.cli.AppGroup``.
Grouping keeps the CLI surface scannable as new fixtures are added —
``flask --help`` shows one ``seed`` entry instead of N flat commands.
"""
import json
from... | hasansezertasan/not-just-a-todo-app | src/app/commands.py | .py | e03250df1eb6c08a | 7.45 | 7 |
import logging
from logging.config import fileConfig
from alembic import context
from flask import current_app
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers ba... | hasansezertasan/not-just-a-todo-app | src/app/db/migrations/env.py | .py | 49361095a3259dac | 7.45 | 7 |
"""Add account-lockout columns to user
Revision ID: a1b2c3d4e5f6
Revises: d6b27a916acd
Create Date: 2026-05-10 00:00:00.000000
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "a1b2c3d4e5f6"
down_revision = "d6b27a916acd"
branch_labels = None
depends_on = None
... | hasansezertasan/not-just-a-todo-app | src/app/db/migrations/versions/a1b2c3d4e5f6_add_lockout_columns.py | .py | e8b638903472b7ac | 7.45 | 7 |
"""Add server_default=func.now() to StandardMixin timestamp columns
Revision ID: b2c3d4e5f6a7
Revises: a1b2c3d4e5f6
Create Date: 2026-05-10 00:50:00.000000
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "b2c3d4e5f6a7"
down_revision = "a1b2c3d4e5f6"
branch_labe... | hasansezertasan/not-just-a-todo-app | src/app/db/migrations/versions/b2c3d4e5f6a7_add_server_default_to_timestamps.py | .py | ff8c583532c89a38 | 7.45 | 7 |
# Copyright 2024 Hasan Sezer Taşan <hasansezertasan@gmail.com>
"""HTTP middleware: request IDs, security headers, error handlers.
Each function takes a ``Flask`` app and registers its hook(s); the factory
calls them in order. Keeping middleware out of the factory body lets us
unit-test each concern in isolation.
"""
... | hasansezertasan/not-just-a-todo-app | src/app/middleware.py | .py | 4270417973af8622 | 7.45 | 7 |
# Copyright 2024 Hasan Sezer Taşan <hasansezertasan@gmail.com>
"""Domain-specific Prometheus counters.
The auto-tracked Flask metrics (`flask_http_request_total`, latency
histograms) measure *endpoint hit rate*. These counters measure
*outcomes* — what mattered semantically. Login failure rate, lockout
rate, registrat... | hasansezertasan/not-just-a-todo-app | src/app/observability/metrics.py | .py | 897bbb985728c2e1 | 7.45 | 7 |
# Copyright 2024 Hasan Sezer Taşan <hasansezertasan@gmail.com>
"""Slow-query event listener.
Hooks SQLAlchemy's `before/after_cursor_execute` to time every statement;
warns on outliers. Catches N+1 patterns, missing indexes, accidental
table scans. Pairs with the JSON formatter — `duration_ms` and
`statement` land as ... | hasansezertasan/not-just-a-todo-app | src/app/observability/sql.py | .py | da985ec4d79d6fee | 7.45 | 7 |
# Copyright 2024 Hasan Sezer Taşan <hasansezertasan@gmail.com>
"""Account-lockout primitives.
Pairs with flask-limiter's per-IP rate limit. The IP limit slows brute-force
*attempts*; the per-account lockout slows credential-stuffing against a
specific username even when attempts come from rotating IPs.
"""
import dat... | hasansezertasan/not-just-a-todo-app | src/app/services/auth.py | .py | 6b5b71abc4199e7d | 7.45 | 7 |
# Copyright 2024 Hasan Sezer Taşan <hasansezertasan@gmail.com>
"""HaveIBeenPwned password-breach lookup.
Uses k-Anonymity: only the first 5 chars of the SHA-1 hash leave the
host; the API returns all suffixes that share that prefix and we match
locally. The plaintext password never crosses the wire.
Gated by `PASSWOR... | hasansezertasan/not-just-a-todo-app | src/app/services/password_breach.py | .py | 8a18ca1127595131 | 7.45 | 7 |
# Copyright 2024 Hasan Sezer Taşan <hasansezertasan@gmail.com>
"""Sequence + Task domain operations."""
import datetime
from app.db.models.sequences import Sequence, Task
from app.db.models.templates import SequenceTemplate
def instantiate_from_template(*, template_id: int, user_id: int) -> Sequence:
"""Materia... | hasansezertasan/not-just-a-todo-app | src/app/services/sequences.py | .py | c369e1925e863b27 | 7.45 | 7 |
# Copyright 2024 Hasan Sezer Taşan <hasansezertasan@gmail.com>
"""HMAC-signed, time-bounded tokens for sensitive URLs.
Wraps `itsdangerous.URLSafeTimedSerializer` with a per-purpose salt so
tokens issued for different flows (password-reset vs email-verify) can't
be cross-replayed. Backed by Flask's `SECRET_KEY` so sig... | hasansezertasan/not-just-a-todo-app | src/app/services/tokens.py | .py | f1229184d033c596 | 7.45 | 7 |
# Copyright 2024 Hasan Sezer Taşan <hasansezertasan@gmail.com>
from flask import flash, redirect, request, url_for
from flask_admin import AdminIndexView, expose
from flask_login import login_user, logout_user
from app.db.models.users import User
from app.forms import LoginForm, RegisterForm
from app.observability imp... | hasansezertasan/not-just-a-todo-app | src/app/views/index.py | .py | 0fa63d4251ca9f46 | 7.45 | 7 |
# Copyright 2024 Hasan Sezer Taşan <hasansezertasan@gmail.com>
"""Custom syrupy snapshot extensions."""
from syrupy.extensions.single_file import SingleFileSnapshotExtension
class PNGImageExtension(SingleFileSnapshotExtension):
_file_extension = "png"
class HTMLExtension(SingleFileSnapshotExtension):
_file... | hasansezertasan/not-just-a-todo-app | tests/extensions.py | .py | ef27fd282c965ef8 | 7.45 | 7 |
# Copyright 2024 Hasan Sezer Taşan <hasansezertasan@gmail.com>
"""Account-lockout service tests."""
import datetime
from typing import TYPE_CHECKING
from app.services import auth as auth_service
if TYPE_CHECKING:
from app.db.models.users import User
def test_fresh_user_is_not_locked(user: User) -> None:
as... | hasansezertasan/not-just-a-todo-app | tests/test_auth_service.py | .py | 6c0f4d38bfa3b3f4 | 7.95 | 7 |
# Copyright 2024 Hasan Sezer Taşan <hasansezertasan@gmail.com>
"""Factory invariants — verify create_app() honors Settings across env profiles."""
from datetime import timedelta
import pytest
from werkzeug.middleware.proxy_fix import ProxyFix
from app.config import DEFAULT_DEV_SECRET, Settings
from app.factory impor... | hasansezertasan/not-just-a-todo-app | tests/test_factory.py | .py | 010b28cf5fe414a8 | 7.95 | 7 |
# Copyright 2024 Hasan Sezer Taşan <hasansezertasan@gmail.com>
"""Smoke tests — verify the app boots and exposes its operational endpoints."""
from typing import TYPE_CHECKING
from flask import Flask
if TYPE_CHECKING:
from flask.testing import FlaskClient
def test_app_boots(app: Flask) -> None:
assert isin... | hasansezertasan/not-just-a-todo-app | tests/test_main.py | .py | 7e766755f998e409 | 7.95 | 7 |
# Copyright 2024 Hasan Sezer Taşan <hasansezertasan@gmail.com>
"""Cross-cutting HTTP behavior: readiness, request IDs, security headers, errors."""
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from flask import Flask
from flask.testing import FlaskClient
def test_readyz_reports_db_up(client: FlaskClie... | hasansezertasan/not-just-a-todo-app | tests/test_middleware.py | .py | 0bed893f5fa50afc | 7.95 | 7 |
# Copyright 2024 Hasan Sezer Taşan <hasansezertasan@gmail.com>
import datetime
from app.db.models.sequences import Sequence, Task
from app.db.models.templates import SequenceTemplate, TaskTemplate
from app.db.models.users import User
def test_user_full_name_column_property(user: User) -> None:
assert user.full_... | hasansezertasan/not-just-a-todo-app | tests/test_models.py | .py | 6a35c66a28f2b175 | 7.95 | 7 |
# Copyright 2024 Hasan Sezer Taşan <hasansezertasan@gmail.com>
"""HMAC-signed token service tests."""
import time
from typing import TYPE_CHECKING
import pytest
from app.services import tokens as token_service
from app.services.tokens import TokenError
if TYPE_CHECKING:
from flask import Flask
def test_sign_a... | hasansezertasan/not-just-a-todo-app | tests/test_token_service.py | .py | e72a372d064f4d0d | 7.95 | 7 |
from __future__ import annotations
from typing import Any, ClassVar, TYPE_CHECKING
from PyQt5 import QtGui, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QGraphicsView, QGraphicsSceneMouseEvent
from ..settings import settings
if TYPE_CHECKING:
from ..views.image_view import ImageView
class Ma... | senyai/gmc | gmc/markup_objects/__init__.py | .py | 3a44272454b48907 | 7.42 | 6 |
from __future__ import annotations
from typing import Any, Callable
from PyQt5.QtCore import QSettings, QByteArray, Qt
from PyQt5.QtGui import QColor, QFont
from PyQt5.QtWidgets import QMainWindow
default_font_label = QFont("Arial")
default_font_label.setPointSizeF(10.0)
default_font_label.setFixedPitch(False)
class... | senyai/gmc | gmc/settings/__init__.py | .py | c6aab672296859da | 7.42 | 6 |
"""
Convenient ways to get/set gmc objects from clipboard. Not sure where to hold
the "scheme". Nobody will likely to complain about the ability to paste
from one scheme to another.
"""
from typing import Any
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QMimeData
from json import dumps, loads
de... | senyai/gmc | gmc/utils/clipboard.py | .py | bd046756789a3fdc | 7.42 | 6 |
from __future__ import annotations
from typing import TYPE_CHECKING
from PyQt5.QtGui import QPixmap, QImage, QColor
from PyQt5.QtWidgets import QMessageBox as MB
from os.path import getmtime
if TYPE_CHECKING:
import numpy.typing as npt
from PIL.Image import Image
CONVERT: dict[int, QImage.Format] = {
4: ... | senyai/gmc | gmc/utils/image.py | .py | ccc8b0aa0f12ce54 | 7.42 | 6 |
from __future__ import annotations
import json
from typing import Any
from PyQt5.QtWidgets import QMessageBox, QWidget
from PyQt5.QtCore import QFileInfo
from . import CantOpenMarkup
# highly modified version of
# https://gist.github.com/jannismain/e96666ca4f059c3e5bc28abb711b5c92
# tip: available as `vsl-json`` pack... | senyai/gmc | gmc/utils/json.py | .py | 547952bd74ec3099 | 7.42 | 6 |
from __future__ import annotations
from typing import Any, Generic, TypeVar, Callable
from PyQt5 import QtCore, QtGui, QtWidgets
from ..utils import separator, new_action
from .image_view import ImageView
from ..markup_objects import MarkupSelect, MarkupObjectMeta
Qt = QtCore.Qt
T = TypeVar("T", bound=ImageView)
tr = ... | senyai/gmc | gmc/views/image_widget.py | .py | f3d250deeea40dca | 7.42 | 6 |
"""This script downloads the GSP location data from NESO and the PVLive genereration data from
the PVLive API for all GSPs in Great Britain.
The downloaded data is saved as a Zarr dataset.
This script takes around 40 mins to download 7 years of data for all GSPs.
"""
import fnmatch
import io
import logging
import o... | openclimatefix/solar-consumer | scripts/get_pvlive_uk_pv_generation.py | .py | c5f2abaa44f6cbe1 | 7.54 | 11 |
"""Get German solar generation and forecasts from the ENTSO-E.
Generation is published for each German TSO control area and Germany overall,
enabling both regional and national values to be saved to the data platform.
Forecasts are national, and ENTSO-E publishes three of them: day ahead, intraday and current.
"""
i... | openclimatefix/solar-consumer | solar_consumer/data/fetch_de_data.py | .py | f48c29768f129b5a | 7.54 | 11 |
import json
import os
import urllib.parse
import urllib.request
from datetime import UTC, datetime, timedelta
import pandas as pd
import yaml
from loguru import logger
from pvlive_api import PVLive
from pydantic import BaseModel, Field
from solar_consumer.constants import GB_NESO_FORECAST_URL, GB_PVLIVE_DOMAIN_URL
... | openclimatefix/solar-consumer | solar_consumer/data/fetch_gb_data.py | .py | 41dff69ef7563680 | 7.54 | 11 |
"""
Script to fetch NESO Solar Forecast Data
This script provides functions to fetch solar forecast data from the NESO API.
The data includes solar generation estimates for embedded solar farms and combines
date and time fields into a single timestamp for further analysis.
"""
import json
import urllib.parse
import ur... | openclimatefix/solar-consumer | solar_consumer/fetch_data.py | .py | 0b3d73e514658c0a | 7.54 | 11 |
import pandas as pd
from loguru import logger
from pvsite_datamodel.pydantic_models import PVSiteEditMetadata as PVSite
from pvsite_datamodel.read.site import get_site_by_client_site_name
from pvsite_datamodel.write.forecast import insert_forecast_values
from pvsite_datamodel.write.generation import insert_generation_... | openclimatefix/solar-consumer | solar_consumer/save/save_site_database.py | .py | 9007d46319ee95b8 | 7.54 | 11 |
from collections.abc import Generator
from datetime import UTC, datetime, timedelta
import pytest
from pvsite_datamodel.sqlmodels import Base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from testcontainers.postgres import PostgresContainer
# Shared Test Configuration Constants
RESOURC... | openclimatefix/solar-consumer | tests/conftest.py | .py | 5c5121c480dd7aa0 | 8.04 | 11 |
# integration test
from datetime import UTC, datetime, timedelta
import pytest
from solar_consumer.data.fetch_be_data import fetch_be_data_forecast, fetch_be_data_generation
@pytest.mark.integration
@pytest.mark.skip(
reason="Elia BE API may not return data within the expected time window due to upstream delays... | openclimatefix/solar-consumer | tests/integration/test_fetch_be_forecast.py | .py | f6fb93e5fe79310a | 7.04 | 11 |
# integration test
from datetime import UTC, datetime, timedelta
import pytest
from solar_consumer.data.fetch_ind_rajasthan_data import fetch_ind_rajasthan_data
@pytest.mark.skip(reason="Live RUVNL API is unstable and only accessible in India")
@pytest.mark.integration
def test_ind_rajasthan_data():
"""
Int... | openclimatefix/solar-consumer | tests/integration/test_fetch_ind_rajasthan_data.py | .py | cb40f08fa937adc1 | 7.04 | 11 |
import datetime
import numpy as np
import pandas as pd
import pytest
from betterproto.lib.google.protobuf import Struct, Value
from ocf import dp
from solar_consumer.save.save_data_platform import (
get_update_capacity_df,
save_forecasts_to_data_platform,
save_generation_to_data_platform,
)
@pytest.mark... | openclimatefix/solar-consumer | tests/integration/test_save_to_data_platform.py | .py | d5fb77fb9858ef7a | 7.04 | 11 |
"""
Test Suite for `fetch_data` and `fetch_data_using_sql` Functions
This script validates the functionality and consistency of two data-fetching functions:
- `fetch_data`: Fetches data via API (mocked).
- `fetch_data_using_sql`: Fetches data via SQL query (mocked).
### How to Run the Tests:
Run the entire test suit... | openclimatefix/solar-consumer | tests/unit/test_fetch_data.py | .py | 9f7a669aac6ef9cb | 8.04 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.