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 |
|---|---|---|---|---|---|---|
# (c) Kevin Dunn, 2010-2026. MIT License.
"""Prediction intervals and confirmation-run testing (ENG-02)."""
from __future__ import annotations
from typing import Any
import pandas as pd
from statsmodels.regression.linear_model import RegressionResultsWrapper
def _run_prediction(
ols_result: RegressionResultsWr... | kgdunn/process-improve | src/process_improve/experiments/_analyses/prediction.py | .py | 3ef405cb14af4a74 | 7.63 | 17 |
# (c) Kevin Dunn, 2010-2026. MIT License.
"""Derringer-Suich desirability functions, shared by the optimizer and the plots.
Two quantities in this module are easy to confuse, so they are named apart:
*weight*
The exponent that shapes an *individual* desirability ramp, per response.
A weight of 1 gives a linea... | kgdunn/process-improve | src/process_improve/experiments/_desirability.py | .py | 43cda487906e6091 | 7.63 | 17 |
# (c) Kevin Dunn, 2010-2026. MIT License.
r"""Minimum moment aberration for two-level designs (Xu, 2003).
The classical minimum aberration criterion ranks two-level fractional
factorial designs by their word-length pattern, which is read off the
defining relation. That works only for *regular* designs, and only when ... | kgdunn/process-improve | src/process_improve/experiments/_moment_aberration.py | .py | aa825dadd10d28f4 | 7.63 | 17 |
# (c) Kevin Dunn, 2010-2026. MIT License.
"""MCP tool wrapper: ``analyze_experiment`` (ENG-02)."""
from __future__ import annotations
from typing import Any, Literal
import pandas as pd
from pydantic import BaseModel, ConfigDict, Field
from process_improve.experiments._tools import _TOOL_EXPECTED_EXCEPTIONS, _regis... | kgdunn/process-improve | src/process_improve/experiments/_tools/analyze_experiment.py | .py | fbe37ffdd98272a0 | 7.63 | 17 |
# (c) Kevin Dunn, 2010-2026. MIT License.
"""MCP tool wrapper: ``augment_design`` (ENG-02)."""
from __future__ import annotations
from typing import Any, Literal
import pandas as pd
from pydantic import BaseModel, ConfigDict, Field
from process_improve.experiments._tools import _TOOL_EXPECTED_EXCEPTIONS, _register,... | kgdunn/process-improve | src/process_improve/experiments/_tools/augment_design.py | .py | f58067dc41e09fa5 | 7.63 | 17 |
# (c) Kevin Dunn, 2010-2026. MIT License.
"""MCP tool wrapper: ``create_factorial_design`` (ENG-02)."""
from __future__ import annotations
from typing import Any
import pandas as pd
from pydantic import BaseModel, ConfigDict, Field
from process_improve.experiments._tools import _TOOL_EXPECTED_EXCEPTIONS, _register,... | kgdunn/process-improve | src/process_improve/experiments/_tools/create_factorial_design.py | .py | 2525d277ed5ac63a | 7.63 | 17 |
# (c) Kevin Dunn, 2010-2026. MIT License.
"""MCP tool wrapper: ``doe_knowledge`` (ENG-02)."""
from __future__ import annotations
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
from process_improve.experiments._tools import _TOOL_EXPECTED_EXCEPTIONS, _register, logger
from process_... | kgdunn/process-improve | src/process_improve/experiments/_tools/doe_knowledge.py | .py | 58f3fac27bb13f3b | 7.63 | 17 |
# (c) Kevin Dunn, 2010-2026. MIT License.
"""MCP tool wrapper: ``evaluate_design`` (ENG-02)."""
from __future__ import annotations
from typing import Any, Literal
import pandas as pd
from pydantic import BaseModel, ConfigDict, Field
from process_improve.experiments._tools import _TOOL_EXPECTED_EXCEPTIONS, _register... | kgdunn/process-improve | src/process_improve/experiments/_tools/evaluate_design.py | .py | 7fac14f997ea0511 | 7.63 | 17 |
# (c) Kevin Dunn, 2010-2026. MIT License.
"""MCP tool wrapper: ``fit_linear_model`` (ENG-02)."""
from __future__ import annotations
from typing import Any
import pandas as pd
from pydantic import BaseModel, ConfigDict, Field
from process_improve.experiments._tools import _TOOL_EXPECTED_EXCEPTIONS, _register, logger... | kgdunn/process-improve | src/process_improve/experiments/_tools/fit_linear_model.py | .py | f430ebc9e503e7b0 | 7.63 | 17 |
# (c) Kevin Dunn, 2010-2026. MIT License.
"""MCP tool wrapper: ``optimize_responses`` (ENG-02)."""
from __future__ import annotations
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
from process_improve.experiments._tools import _TOOL_EXPECTED_EXCEPTIONS, _register, logger
from pro... | kgdunn/process-improve | src/process_improve/experiments/_tools/optimize_responses.py | .py | 5f1fe0f424d83a6b | 7.63 | 17 |
# cloudwatch_rich_stream.py
import sys
import time
import threading
from io import IOBase
from typing import List, Dict, Optional
import boto3
from botocore.exceptions import ClientError
class CloudWatchLogStream(IOBase):
"""
File-like stream that batches writes and sends to CloudWatch Logs.
Use one insta... | DemocracyClub/LGSF | lgsf/aws_lambda/cloudwatch.py | .py | 20761cfd66ee2c06 | 7.52 | 10 |
"""
Mixin for adding AWS Step Function invocation capability to commands.
This module provides a mixin class that can be added to command classes
to enable AWS Step Function invocation via the --aws flag.
The Step Function ARN is automatically discovered based on the environment
and CDK naming convention, so no manua... | DemocracyClub/LGSF | lgsf/commands/aws_mixin.py | .py | 986c12eafbd377d3 | 7.52 | 10 |
from pathlib import Path
from typing import Type
class BaseSettings(object):
"""
Django like global settings object.
Use the class to store global settings for the project.
Read the settings by calling `from lgsf.conf import settings`.
"""
def __init__(self):
"Default settings"
... | DemocracyClub/LGSF | lgsf/conf/__init__.py | .py | a1e5a6bdcb5f4e94 | 7.52 | 10 |
from rich.table import Table
from lgsf.commands.aws_mixin import AWSInvokableMixin
from lgsf.commands.base import PerCouncilCommandBase
class Command(AWSInvokableMixin, PerCouncilCommandBase):
command_name = "councillors"
# The scheduled production job behind this dashboard runs councillors
# scrapers.
... | DemocracyClub/LGSF | lgsf/councillors/commands.py | .py | 3f0936f7764897a1 | 7.52 | 10 |
class SkipDecisionException(Exception):
"""Raised by a scraper to drop a decision from the run entirely."""
class DecisionNotModifiedException(Exception):
"""
Raised when the server answered 304 to a conditional request for a
decision, meaning what we already have stored is still current and there
... | DemocracyClub/LGSF | lgsf/decisions/exceptions.py | .py | 9248418fef0c7e74 | 7.02 | 10 |
import json
from dataclasses import dataclass, field
from pathlib import Path
from slugify import slugify
@dataclass
class DecisionBase:
url: str
identifier: str
title: str
date: str
decision_maker: str = None
# Fields the scraper fills in after construction. Kept out of hash and
# equali... | DemocracyClub/LGSF | lgsf/decisions/models.py | .py | 520b00237bf9a4df | 7.52 | 10 |
import pytest
from lgsf.decisions.scrapers import BaseDecisionsScraper, CustomHTMLDecisionsScraper
def test_abc_raises():
with pytest.raises(TypeError) as excinfo:
BaseDecisionsScraper(options={})
assert "Can't instantiate abstract class BaseDecisionsScraper" in str(excinfo.value)
def test_custom_h... | DemocracyClub/LGSF | lgsf/decisions/tests/test_base_class.py | .py | d3479867209e42bc | 8.02 | 10 |
"""
The decision record: what lands in JSON, and what comes back out.
`from_storage` is the mirror of `as_dict`, so a field added to one and not
the other is lost on the next run without anything failing.
"""
import json
from lgsf.decisions import DecisionBase
class FakeSession:
def __init__(self, payload):
... | DemocracyClub/LGSF | lgsf/decisions/tests/test_models.py | .py | 6a3c95b29c4f50b0 | 8.02 | 10 |
"""
Parsing a ModernGov decision, from the list page to the record.
Fixtures are real responses from democracy.kirklees.gov.uk, trimmed to the
relevant markup.
"""
import datetime
from pathlib import Path
import pytest
from bs4 import BeautifulSoup
from lgsf.decisions.exceptions import DecisionNotModifiedException
... | DemocracyClub/LGSF | lgsf/decisions/tests/test_modgov_scraper.py | .py | 3ad0eb91aa61e4c3 | 7.02 | 10 |
"""
Not re-fetching decisions that have settled.
A decision is amended, if at all, in the months just after publication, so
one older than that which we already hold is left alone. Everything here is
about not skipping something we would still want.
"""
import datetime
from pathlib import Path
import pytest
from lg... | DemocracyClub/LGSF | lgsf/decisions/tests/test_settled_decisions.py | .py | 552da9933c09a2ae | 7.02 | 10 |
import json
from abc import ABC
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Dict, Any, Optional
from lgsf.path_utils import scraper_abs_path
class SerializableDataclass(ABC):
"""Base class for dataclasses with common serialization methods."""... | DemocracyClub/LGSF | lgsf/metadata/models.py | .py | 4b8f6f994ffde4fc | 7.52 | 10 |
"""
Scraper validation across services.
Validation takes a service name, so a whole data type can be checked in
one pass: that a council declaring a service has a matching scraper file,
that base_url is set, and that the scraper's base class agrees with the
recorded cms_type.
"""
import json
import pytest
from lgsf... | DemocracyClub/LGSF | lgsf/metadata/tests/test_validation_services.py | .py | e71053aa613f900f | 7.02 | 10 |
"""
Simple runtime utilities for scrapers to access their metadata.
"""
from typing import Optional
from .models import CouncilMetadata, ServiceData
def get_council_metadata(council_id: str) -> Optional[CouncilMetadata]:
"""Get metadata for a council, return None if not found."""
try:
return Council... | DemocracyClub/LGSF | lgsf/metadata/utils.py | .py | 0c5b9f47c1d195db | 7.52 | 10 |
class SkipMeetingException(Exception):
"""Raised by a scraper to drop a meeting from the run entirely."""
class MeetingNotModifiedException(Exception):
"""
Raised when the server answered 304 to a conditional request for a
meeting, meaning what we already have stored is still current and there
is ... | DemocracyClub/LGSF | lgsf/minutes/exceptions.py | .py | 3b5f8e1cf81c3089 | 7.02 | 10 |
import pytest
from lgsf.minutes.scrapers import BaseMinutesScraper, CustomHTMLMinutesScraper
def test_abc_raises():
with pytest.raises(TypeError) as excinfo:
BaseMinutesScraper(options={})
assert "Can't instantiate abstract class BaseMinutesScraper" in str(excinfo.value)
def test_custom_html_scrape... | DemocracyClub/LGSF | lgsf/minutes/tests/test_base_class.py | .py | 84ff73aec9fe6990 | 8.02 | 10 |
"""
How the minutes scraper handles document files: what it downloads, what it
skips because it already has it, and what it records in the metadata.
No network: every HTTP call is served by a fake client that records what it
was asked for.
"""
import json
from pathlib import Path
import pytest
from lgsf.conf import... | DemocracyClub/LGSF | lgsf/minutes/tests/test_document_scraping.py | .py | 1af588f29bee89ed | 7.02 | 10 |
from statefun_tasks.messages_pb2 import TaskRequest, TaskResult, ArgsAndKwargs, ValueArgsAndKwargs
from statefun_tasks.protobuf import pack_any, convert_from_proto, convert_to_proto, ObjectProtobufConverter, DEFAULT_CONVERTERS
from statefun_tasks.utils import is_tuple
from google.protobuf.any_pb2 import Any
from google... | fransking/flink-statefun-tasks | statefun_tasks/default_serialiser.py | .py | 421b9b2ef04d2170 | 7.57 | 13 |
from statefun_tasks.messages_pb2 import TaskRequest, TaskResult, TaskException
from statefun_tasks.types import TasksException
from asyncio import iscoroutine
class EventHandlers(object):
def __init__(self):
self._on_task_received_handlers = []
self._on_task_started_handlers = []
... | fransking/flink-statefun-tasks | statefun_tasks/events/event_handlers.py | .py | e035b10f8817bbef | 7.57 | 13 |
from statefun_tasks import FlinkTasks
import inspect
import cloudpickle
import logging
_log = logging.getLogger('FlinkTasks')
__defaults = None
def enable_inline_tasks(tasks: FlinkTasks):
"""
Enables inline tasks support. Inline tasks work by sending pickled code as well as data
to a gene... | fransking/flink-statefun-tasks | statefun_tasks/extensions/inline_tasks/inline_tasks_impl.py | .py | 23639ee7916ab051 | 7.57 | 13 |
from statefun_tasks.task_context import TaskContext
from statefun_tasks.events.event_handlers import EventHandlers
from statefun_tasks.pipeline_builder import PipelineBuilder
from statefun_tasks.utils import is_tuple, type_name, annotated_protos_for
from statefun_tasks.messages_pb2 import TaskRequest
from statefun... | fransking/flink-statefun-tasks | statefun_tasks/flink_task.py | .py | a6964f715842e4eb | 7.57 | 13 |
class Source:
"""Base class for all sources.
A source knows where the data comes from (local file, CMA HPC archive,
CMADaaS service, memory object, ...). Sources are created through
``reki.from_source()`` and are transformed by the ``mutate()`` loop
into the most concrete source before being parsed... | cemc-oper/reki | reki/core/source.py | .py | 90c9251d34e531da | 7.65 | 19 |
from pathlib import Path
from typing import Union, Optional
def find_config(
config_dir: Union[str, Path],
data_type: str,
data_class: str = "od"
) -> Optional[Path]:
"""
Find config YAML for some data type by combine ``config_dir``, ``data_type`` and ".yaml".
Parameters
-----... | cemc-oper/reki | reki/data_finder/_config.py | .py | 5cec0ea97fc30212 | 7.65 | 19 |
import datetime
from typing import Union, Optional, Iterable
from pathlib import Path
import pandas as pd
from reki.data_finder._config import (
find_config, load_config, get_default_local_config_path,
)
from reki.data_finder._util import find_files, render_file_name
from reki.sources.local import LocalSource
d... | cemc-oper/reki | reki/data_finder/local.py | .py | fa90008a3e52b5b1 | 7.65 | 19 |
from typing import Union, Optional
import xarray as xr
import numpy as np
from .._dispatch import as_data_array
def extract_region(
data: xr.DataArray,
start_longitude: Union[float, int],
end_longitude: Union[float, int],
start_latitude: Union[float, int],
end_latitude: Union... | cemc-oper/reki | reki/operator/area/__init__.py | .py | 183ab4f7070ff6b1 | 7.65 | 19 |
from typing import Union, Literal
import xarray as xr
from .._dispatch import as_data_array
from ._interpolator import _get_interpolator
def interpolate_grid(
data: xr.DataArray,
target: xr.DataArray,
scheme: str = "linear",
engine: Literal["scipy", "xarray"] = "xarray",
**kw... | cemc-oper/reki | reki/operator/regrid/__init__.py | .py | 0562940f2c07cb57 | 7.65 | 19 |
"""Format readers and the ``reader()`` dispatch.
A *reader* knows how to parse the data a source provides into a unified
data object. Each reader module (or subpackage) under ``reki/readers/``
may export a ``READER`` factory function with the signature::
READER(source, path, magic=None, deeper_check=False, **kwar... | cemc-oper/reki | reki/readers/__init__.py | .py | 0d25f490283070f0 | 7.65 | 19 |
"""Reader for CMADaaS MUSIC response objects (Grid*2D / Array2D).
This reader converts the in-memory response classes of ``nuwe-cmadaas``
into xarray/pandas objects. It never imports ``nuwe_cmadaas`` at module
level: ``nuwe-cmadaas`` is an optional dependency, and the reader
directory scan imports every reader module ... | cemc-oper/reki | reki/readers/cmadaas.py | .py | 693c31cd491faf59 | 7.65 | 19 |
"""Lazy backend arrays for GrADS binary records.
GrADS data files are raw float32 binaries, so laziness is built on
``np.memmap``: a record's values are read from disk on demand, when
the data is actually accessed. The arrays implement xarray's explicit
indexing protocol and only hold the file path, byte offset and sc... | cemc-oper/reki | reki/readers/grads/_lazy.py | .py | fe2423d5240e32ae | 7.65 | 19 |
from typing import Union, Optional, Literal
from pathlib import Path
import numpy as np
import pandas as pd
import xarray as xr
from .grads_ctl import GradsCtlParser
from .grads_data_handler import GradsDataHandler, GradsRecordHandler
from ._lazy import lazy_record_values, concat_lazy_arrays
def load_field_from_fi... | cemc-oper/reki | reki/readers/grads/field.py | .py | f7db844b4337c4a6 | 7.65 | 19 |
import sys
import re
from pathlib import Path
import logging
from typing import Optional, Union
import pandas as pd
logger = logging.getLogger(__name__)
class GradsCtl(object):
def __init__(self):
self.dset = None # data file path
self.dset_template = False
self.title = ''
sel... | cemc-oper/reki | reki/readers/grads/grads_ctl.py | .py | a0fb1e3910a9d837 | 7.65 | 19 |
import pandas as pd
from typing import Optional
from .grads_ctl import GradsCtl
from .grads_record_handler import GradsRecordHandler
class GradsDataHandler(object):
"""
Parse GrADS binary data file with a ctl file.
Get record from GrADS binary data file.
"""
def __init__(self, a_grads_ctl: Grads... | cemc-oper/reki | reki/readers/grads/grads_data_handler.py | .py | a2d2db0f305961c8 | 7.65 | 19 |
from typing import BinaryIO
import numpy as np
from .grads_ctl import GradsCtl
class GradsRecordHandler(object):
"""
Load record data from binary file.
"""
def __init__(self, grads_ctl: GradsCtl, record_index: int, offset: int, var_index: int = -1, level_index: int = -1):
self.grads_ctl = gr... | cemc-oper/reki | reki/readers/grads/grads_record_handler.py | .py | a0482f21dc680ce5 | 7.65 | 19 |
"""GrADS reader bound to the ``reader()`` dispatch.
A GrADS dataset is a ``.ctl`` description file plus a raw binary data
file; the reader wraps the ctl path and delegates decoding to the
``reki.readers.grads.field`` kernel.
"""
import os
from typing import Dict, Optional
from reki.readers import Reader
from .field... | cemc-oper/reki | reki/readers/grads/reader.py | .py | 132150565cf7cad4 | 7.65 | 19 |
"""
GRIB2 要素注册表查询接口。
数据文件为同目录 ``param_registry.yaml``,约束规范见 ``param_registry_spec.md``。
匹配语义(规范 §5):
1. 变体命中:``when`` 中每个键都等于实际值;缺省键 = 通配;实际值缺失不命中。
2. 最具体匹配:命中变体中 ``when`` 键数最多者胜出,并列时 ``params`` 中靠后者胜出。
3. 无变体命中时回退到条目级通用名 ``name``。
4. ``wgrib2_name`` 层次无关,由 :func:`find_wgrib2_name` 单独返回。
"""
from dataclasses import ... | cemc-oper/reki | reki/readers/grib/config/__init__.py | .py | 4219619ed8747d7a | 7.65 | 19 |
"""Lazy backend arrays for GRIB messages (eccodes engine).
The arrays implement xarray's explicit indexing protocol
(``xarray.backends.BackendArray``): they only hold the file path, the
message offset and scalar metadata — never an ecCodes handle — so they
stay picklable (dask distributed safe). Values are decoded fro... | cemc-oper/reki | reki/readers/grib/eccodes/_lazy.py | .py | d7d461f24f1cd750 | 7.65 | 19 |
"""
Given a voxel in a brain volume, find the FreeSurfer region it lies in (or the closest one if it is not in any region).
"""
import numpy as np
import brainload as bl
import brainload.freesurferdata as blfsd
import brainload.spatial as blsp
class BrainVoxLocate:
"""
Voxel segmentation label locator. This cl... | dfsp-spirit/brainload | src/brainload/brainvoxlocate.py | .py | fe8fad70fb631e0d | 7.52 | 10 |
#!/usr/bin/env python
from __future__ import print_function
import os
import sys
import errno
import numpy as np
import scipy
import argparse
import brainload as bl
from numpy.linalg import norm
import brainload.surfacegraph as sg
import brainload.freesurferdata as fsd
import networkx
from scipy.spatial import ConvexHu... | dfsp-spirit/brainload | src/brainload/clients/intersurface.py | .py | 14a55812c10e843e | 7.52 | 10 |
"""
Export functions for brainload. In contrast to the brainview functions, these do not support color.
These functions allow one to export brain meshes, e.g., for loading into standard 3D modeling software.
"""
import brainload as bl
import os
import brainload.meshexport as me
import numpy as np
def export_mesh_no... | dfsp-spirit/brainload | src/brainload/export.py | .py | 4daa978375ca82f6 | 7.52 | 10 |
# -*- coding: utf-8 -*-
"""
Turn a surface mesh into a networkx graph. Useful for asking questions that can be answered using graph algorithms. An example would be to find, for a given source vertex, all vertices which are connected to it by a certain number of hops. Requires networkx.
"""
import numpy as np
import br... | dfsp-spirit/brainload | src/brainload/surfacegraph.py | .py | c61347952a825a9e | 7.52 | 10 |
# Tests for the brain_mesh_info script.
#
# These tests require the package `pytest-console-scripts`.
import os
import pytest
import tempfile
import shutil
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
TEST_DATA_DIR = os.path.join(THIS_DIR, os.pardir, 'test_data')
TEST_VOL_FILE = os.path.join(TEST_DATA_DIR, '... | dfsp-spirit/brainload | tests/clients/test_brain_vol_info.py | .py | bc33b99fa588d41e | 7.02 | 10 |
"""Configuration file for sniffer."""
import time
import subprocess
from sniffer.api import select_runnable, file_validator, runnable
try:
from pync import Notifier
except ImportError:
notify = None
else:
notify = Notifier.notify
watch_paths = ["skydance", "tests"]
class Options:
group = int(time.... | tomasbedrich/skydance | scent.py | .py | eaa9ca5724d3ae67 | 7.42 | 6 |
from collections import deque
from typing import Sequence
# TODO is this reimplementing https://docs.python.org/3/library/asyncio-protocol.html#asyncio.BufferedProtocol.buffer_updated ?
class Buffer:
"""
A buffer which allows feeding chunks of messages and reading them out complete.
It is specificaly t... | tomasbedrich/skydance | skydance/network/buffer.py | .py | 96dfbb70c0aad896 | 7.42 | 6 |
import asyncio
import ipaddress
import logging
from collections import defaultdict
from typing import DefaultDict, Iterable, Mapping, Optional, cast
log = logging.getLogger(__name__)
# type aliases
MacAddress = bytes
DiscoveryResult = Mapping[MacAddress, Iterable[ipaddress.IPv4Address]]
class DiscoveryProtocol(asy... | tomasbedrich/skydance | skydance/network/discovery.py | .py | 4e9b229a3ed90cc6 | 7.42 | 6 |
import asyncio
import contextlib
import logging
from typing import Tuple
log = logging.getLogger(__name__)
class Session:
"""A session object handling connection re-creation in case of its failure."""
def __init__(self, host, port):
self.host = host
self.port = port
self._connection... | tomasbedrich/skydance | skydance/network/session.py | .py | 1f12c3b3b98677d1 | 7.42 | 6 |
"""
Django settings for fundraiser project.
Generated by 'django-admin startproject' using Django 2.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
Meant to be i... | dominikszopa/fundraising-website | fundraiser/settings/base.py | .py | d57131c860f03898 | 7.64 | 18 |
from django.contrib import admin
from django.db.models import Case, CharField, Count, F, Max, Sum, When
from django.http import HttpResponse
from django.template import loader
from django.views import View
from .models import Campaign, Fundraiser, Donation, Donor
class CampaignAdmin(admin.ModelAdmin):
pass
# Re... | dominikszopa/fundraising-website | team_fundraising/admin.py | .py | 94e1edc81dbbd0cb | 7.64 | 18 |
"""
Custom Django email backend that delegates to AWS SES via send_email().
"""
from django.core.mail.backends.base import BaseEmailBackend
from .email_utils import send_email
class SESEmailBackend(BaseEmailBackend):
"""Routes Django's built-in email sending (e.g. password reset) through SES."""
def send_me... | dominikszopa/fundraising-website | team_fundraising/email_backend.py | .py | b5531fa11a5a7a7b | 7.64 | 18 |
"""
Email sending utilities using AWS SES
"""
import boto3
from botocore.exceptions import ClientError
import logging
from django.conf import settings
from .text import Donation_text
logger = logging.getLogger(__name__)
def send_email(subject, text_content, from_email, to_emails, html_content=None):
"""
Sen... | dominikszopa/fundraising-website | team_fundraising/email_utils.py | .py | 07e02bf7225850f4 | 7.64 | 18 |
""" The forms for the team_fundraiser app
"""
from django import forms
from django.conf import settings
from django.utils import timezone
from django_recaptcha.fields import ReCaptchaField
from django_recaptcha.widgets import ReCaptchaV2Checkbox
from .models import Fundraiser
from django.contrib.auth.models import Use... | dominikszopa/fundraising-website | team_fundraising/forms.py | .py | d453d51c748b3517 | 7.64 | 18 |
"""
One-time management command to copy existing fundraiser/campaign media files
from the local filesystem (e.g. the Railway volume at MEDIA_ROOT) into the
configured default storage backend (S3 via django-storages).
Run this once after switching the default storage to S3 so that photos
uploaded before the migration k... | dominikszopa/fundraising-website | team_fundraising/management/commands/migrate_media_to_s3.py | .py | 877d6093e421d56c | 7.64 | 18 |
""" Database models for the team_fundraising app
This module contains the models for the team_fundraising app, including a
parent Campaign, with individual Fundraisers, and Donations that can be raised
by the Fundraisers, or applied to the general Campaign.
"""
import io
import logging
import os
from django.utils impo... | dominikszopa/fundraising-website | team_fundraising/models.py | .py | 11915242624c031f | 7.64 | 18 |
import os
from io import BytesIO
import cv2
import pydicom
import tensorflow as tf
from keras_unet.metrics import iou
import numpy as np
from preprocess import preprocess_image
class MDAIModel:
def __init__(self):
modelpath = os.path.join(os.path.dirname(__file__), "../lung-segmentation-model.h5")
... | mdai/model-deploy | examples/lung-segmentation/model/.mdai/mdai_deploy.py | .py | db77f87867585429 | 7.45 | 7 |
import os
from io import BytesIO
import pydicom
import json
import cv2
import subprocess
import pandas
class MDAIModel:
def __init__(self):
self.root_path = "/workspace/classificationfl_chexpert_v4"
self.data_path = "/workspace/data"
def predict(self, data):
"""
See https://gi... | mdai/model-deploy | examples/nvidia-mmar-chexpert/model/.mdai/mdai_deploy.py | .py | 70dcf8053f4b5625 | 7.45 | 7 |
import os
from io import BytesIO
import pydicom
import json
import subprocess
import dicom2nifti
import nibabel
import numpy as np
class MDAIModel:
def __init__(self):
# Set MMAR root folder name
self.root_path = os.path.join("/workspace")
self.config_path = os.path.join(self.root_path, "c... | mdai/model-deploy | examples/nvidia-mmar-spleen-segmentation/model/.mdai/mdai_deploy.py | .py | 2bd34022eca4a664 | 7.45 | 7 |
import sys
import os
import logging
import asyncio
import shutil
import threading
import traceback
import msgpack
from fastapi import FastAPI, HTTPException, Request, Response
from uvicorn import Config, Server
from validation import OutputValidator
# To handle compressed DICOM image data
import pylibjpeg # noqa: F4... | mdai/model-deploy | mdai/server.py | .py | 9318c4f71873a523 | 7.45 | 7 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Manager of channel configurations.
The ChannelConfigHandler manages only channel configurations and not
the global decision-engine configuration. It is responsible for
loading channel configuration files and validat... | HEPCloud/decisionengine | src/decisionengine/framework/config/ChannelConfigHandler.py | .py | d0faea63857e0fd2 | 7.48 | 8 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
ValidConfig represents a valid JSON document.
The decision engine requires each of its configuration files to be
valid JSON. This is achieved by either supplying a valid Jsonnet or
JSON document upfront.
Vetting of... | HEPCloud/decisionengine | src/decisionengine/framework/config/ValidConfig.py | .py | 4880577eca28020e | 7.48 | 8 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Decision-engine default configuration policies.
For the decision-engine process, the configuration policies are:
- The global configuration file must be named 'decision_engine.jsonnet'
and it must reside in (a) a ... | HEPCloud/decisionengine | src/decisionengine/framework/config/policies.py | .py | ca7040764adf8c5b | 7.48 | 8 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
import decisionengine.framework.dataspace.datasource as ds
class NullDataSource(ds.DataSource): # pragma: no cover
"""
Implementation of data source ABC that does nothing
"""
def __init__(self, config_... | HEPCloud/decisionengine | src/decisionengine/framework/dataspace/datasources/null.py | .py | f0ce559db56272b1 | 7.48 | 8 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Code not written by us
"""
import os
import sqlalchemy
import structlog
from decisionengine.framework.modules.logging_configDict import LOGGERNAME
__all__ = ["orm_as_dict", "clone_model", "add_engine_pidguard"]
d... | HEPCloud/decisionengine | src/decisionengine/framework/dataspace/datasources/sqlalchemy_ds/utils.py | .py | d2139ccbaea37002 | 7.48 | 8 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""pytest fixtures/constants"""
import datetime
import gc
import logging
import platform
import sys
import threading
from collections import UserDict
from unittest import mock
import pytest
from pytest_postgresql impor... | HEPCloud/decisionengine | src/decisionengine/framework/dataspace/datasources/tests/fixtures.py | .py | 07c497d1e8e4be95 | 7.98 | 8 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
import importlib
import structlog
from decisionengine.framework.modules.logging_configDict import DELOGGER_CHANNEL_NAME, LOGGERNAME
from decisionengine.framework.util.singleton import ScopedSingleton
__all__ = [
"D... | HEPCloud/decisionengine | src/decisionengine/framework/dataspace/dataspace.py | .py | 6ffc79c60ef7f938 | 7.48 | 8 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
import threading
import structlog
import decisionengine.framework.dataspace.dataspace as dataspace
from decisionengine.framework.modules.logging_configDict import DELOGGER_CHANNEL_NAME, LOGGERNAME
from decisionengine.f... | HEPCloud/decisionengine | src/decisionengine/framework/dataspace/maintain.py | .py | 45146aac060a72bc | 7.48 | 8 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
import logging
import multiprocessing
import os
import threading
import structlog
import decisionengine.framework.modules.de_logger as de_logger
import decisionengine.framework.modules.logging_configDict as logconf
impo... | HEPCloud/decisionengine | src/decisionengine/framework/engine/ChannelWorkers.py | .py | 5ec177d5d59e7bc3 | 7.48 | 8 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
import contextlib
import logging
import multiprocessing
import os
import pickle
import time
import uuid
import psutil
import structlog
from kombu import Connection, Queue
from kombu.pools import producers
import decisi... | HEPCloud/decisionengine | src/decisionengine/framework/engine/SourceWorkers.py | .py | 9466f02afd5b85d0 | 7.48 | 8 |
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
import argparse
import xmlrpc.client
from functools import partial
from decisionengine.framework.engine.ClientMessageReceiver import ClientMessageReceiver
def create_parser():
parser = argp... | HEPCloud/decisionengine | src/decisionengine/framework/engine/de_client.py | .py | eb8a728148204cee | 7.48 | 8 |
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
import argparse
import xmlrpc.client
from functools import partial
from decisionengine.framework.engine.ClientMessageReceiver import ClientMessageReceiver
def create_parser():
parser = argp... | HEPCloud/decisionengine | src/decisionengine/framework/engine/de_query_tool.py | .py | d570e0b483f6cc6b | 7.48 | 8 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""pytest defaults"""
import gc
import logging
import os
import random
import re
import tempfile
import threading
import pytest
import decisionengine.framework.engine.de_client as de_client
import decisionengine.framewo... | HEPCloud/decisionengine | src/decisionengine/framework/engine/tests/fixtures.py | .py | 5136b895690ac816 | 7.98 | 8 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
import os
import re
import subprocess
import decisionengine.framework.engine.de_client as de_client
# Unfortunately, because argparse short-circuits the '-h' process, we
# need to run the -h option as a separate proces... | HEPCloud/decisionengine | src/decisionengine/framework/engine/tests/test_client_only.py | .py | 5479072cb5613241 | 7.98 | 8 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
import re
import subprocess
import decisionengine.framework.engine.de_query_tool as de_query_tool
# Unfortunately, because argparse short-circuits the '-h' process, we
# need to run the -h option as a separate process,... | HEPCloud/decisionengine | src/decisionengine/framework/engine/tests/test_query_tool_only.py | .py | 6bcaff93ae8f647e | 7.98 | 8 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
import tempfile
import pytest
from decisionengine.framework.engine.DecisionEngine import _check_metrics_env, _get_global_config, parse_program_options
# Because we just want to ensure correct behavior of program option... | HEPCloud/decisionengine | src/decisionengine/framework/engine/tests/test_startup.py | .py | b1586637aad6c019 | 7.98 | 8 |
class FullyKioskError(Exception):
"""Raised when Fully Kiosk Browser API request ended in error.
Attributes:
status_code - error code returned by Fully Kiosk Browser
status - more detailed description
"""
def __init__(self, status_code, status):
self.status_code = status_code
... | cgarwood/python-fullykiosk | fullykiosk/exceptions.py | .py | 0540e500360c672c | 7.1 | 15 |
import logging
import re
from pathlib import Path
from typing import IO
from lxml import etree
from rapidfuzz.distance import Levenshtein
from .util import NS
norm_alto_ns_re = re.compile(rb'alto/ns-v.#')
XML_PARSER = etree.XMLParser(remove_blank_text=True)
XPATH_TEXTBLOCK = etree.XPath('//alto:TextBlock', namespac... | slub/mets-mods2tei | mets_mods2tei/api/alto.py | .py | 6f61198e277b6e0d | 7.52 | 10 |
"""
multi-purpose METS editing and file handling tool purposed for DFG Viewer
"""
import sys
from datetime import datetime
from pathlib import Path
import click
# from lxml.isoschematron import Schematron
from lxml import etree as ET
from ocrd import Resolver, Workspace, WorkspaceValidator
from ocrd.decorators impor... | slub/mets-mods2tei | mets_mods2tei/scripts/update.py | .py | 8a1a3b739bb1b86a | 7.52 | 10 |
# -*- coding: utf-8 -*-
from pathlib import Path
import pytest
from mets_mods2tei import Alto
@pytest.fixture
def datadir(tmpdir, request):
"""
Fixture responsible for searching a folder with the same name of test
module and, if available, moving all contents to a temporary directory so
tests can us... | slub/mets-mods2tei | tests/test_alto.py | .py | 67b2853b7e28263b | 7.02 | 10 |
# -*- coding: utf-8 -*-
from mets_mods2tei import Iso15924
def test_constructor():
"""
Test the creation of an Iso15924 instance
"""
iso = Iso15924()
assert(iso.map != {})
def test_existing_script():
"""
Test requesting the script name for an existing code.
"""
iso = Iso15924()
... | slub/mets-mods2tei | tests/test_iso15924.py | .py | 78d1212eed06d5e0 | 7.02 | 10 |
import itertools
import unicodedata
import pygtrie
from . import _map
# Special characters that need their own references to rewrite with
_FINAL_LC_SIGMA = '\u03c2'
_MEDIAL_LC_SIGMA = '\u03c3'
# Punctuation marks in the betacode map
_BETA_PUNCTUATION = frozenset('\':-_')
_BETA_APOSTROPHE = '\u2019'
def _create_un... | matgrioni/betacode | betacode/conv.py | .py | e51670957d3a2d40 | 7.66 | 20 |
"""Private helpers for validating and encoding side-information covariates."""
import numpy as np
from sklearn.base import clone
from sklearn.preprocessing import OneHotEncoder
def to_dense_covariates(covariates):
"""Return dense covariates for downstream NumPy matrix operations."""
if hasattr(covariates, "t... | pykale/linear | kalelinear/_covariates.py | .py | d590b09aa4e694b4 | 7.42 | 6 |
"""Private helpers for source/target domain bookkeeping."""
from dataclasses import dataclass
import numpy as np
@dataclass
class DomainSplit:
"""Source/target partition derived from binary domain covariates."""
source_idx: np.ndarray
target_idx: np.ndarray
target_covariate: object
def check_bina... | pykale/linear | kalelinear/_domain.py | .py | 04bc7e82fd00cebb | 7.42 | 6 |
from time import time
import numpy as np
from scipy.special import expit
from sklearn.exceptions import NotFittedError
from sklearn.utils.validation import check_is_fitted
from kalelinear._covariates import check_numeric_covariates, fit_covariate_encoder
from kalelinear.estimator.base import BaseKaleEstimator
from ka... | pykale/linear | kalelinear/estimator/_gsda.py | .py | b3c504319ff84647 | 7.42 | 6 |
import inspect
import logging
import sys
from loguru import logger as loggr
try:
from rich.console import Console
from rich.traceback import Traceback
RICH_ENABLED = True
import io
except ModuleNotFoundError:
import traceback
RICH_ENABLED = False
FORMAT_ = "<d>|</d>".join(
[
"<... | jdanbot/jdanbot | bot/config/logger.py | .py | b6c5d2192c9a9a6c | 7.45 | 7 |
#!/usr/bin/env python3
import argparse
import csv
import sys
from pathlib import Path
def main():
parser = argparse.ArgumentParser(
description="""
Use the "--tsv_in"/"--tsv_out" options to strip invisible characters from TSVs.
"""
)
mutex = parser.add_mutually_exclusive_group(required=True)
... | hubmapconsortium/ingest-validation-tools | _deprecated/_src/cleanup_whitespace.py | .py | 3830b6f8f23dc169 | 7.5 | 9 |
#!/usr/bin/env python3
import argparse
import fileinput
import sys
from collections import defaultdict
from pathlib import Path
def main():
parser = argparse.ArgumentParser(
description="""
Factor out all variants of a given field.
"""
)
parser.add_argument("--field", metavar="NAME", requ... | hubmapconsortium/ingest-validation-tools | _deprecated/_src/factor_field_deprecated.py | .py | 2cc4b2de25437c8e | 7.5 | 9 |
#!/usr/bin/env python3
import argparse
import sys
from yaml import dump as dump_yaml
from ingest_validation_tools.schema_loader import (
get_is_assay,
get_table_schema,
list_table_schema_versions,
)
def main():
parser = argparse.ArgumentParser(
description="Outputs a YAML dict listing fields... | hubmapconsortium/ingest-validation-tools | _deprecated/_src/generate_field_yaml_deprecated.py | .py | e5c2ba829657f468 | 7.5 | 9 |
#!/usr/bin/env python3
import argparse
import csv
import hashlib
import io
import os
import re
import sys
import zipfile
from pathlib import Path
import requests
from tableschema_to_template.create_xlsx import create_xlsx
from yaml import dump as dump_yaml
from ingest_validation_tools.cli_utils import dir_path
from ... | hubmapconsortium/ingest-validation-tools | src/generate_docs.py | .py | 5adb01f7abea21cd | 7.5 | 9 |
import os
import re
from fnmatch import fnmatch
from pathlib import Path
class DirectoryValidationErrors(Exception):
def __init__(self, errors):
self.errors = errors
def validate_directory(
paths: list[Path], schema_files: list[dict], dataset_ignore_globs: list[str] = []
) -> None:
"""
Given... | hubmapconsortium/ingest-validation-tools | src/ingest_validation_tools/directory_validator.py | .py | 0b2b9b0933415832 | 7.5 | 9 |
from collections.abc import Iterator
from pathlib import Path
from typing import TypeVar
from ingest_validation_tools.schema_loader import SchemaVersion
from ingest_validation_tools.validation_utils import add_path
# KeyValuePair type hint is robust, but Validator is not available here; use generic
ValidatorGeneric =... | hubmapconsortium/ingest-validation-tools | src/ingest_validation_tools/plugin_validator.py | .py | 6ef7560f881cff2c | 7.5 | 9 |
import atexit
import traitlets
from traitlets.config.configurable import Configurable
from pseudopwm import *
class Motor(Configurable):
value = traitlets.Float()
pwm = PseudoPWM()
def __init__(self, driver, side, *args, **kwargs):
super(Motor, self).__init__(*args, **kwargs) # initializes t... | downingbots/ALSET | motor.py | .py | 73a34265fa679eab | 7.56 | 12 |
from collections import OrderedDict
from rocketreach.resource import Resource
class Person(Resource):
"""
A class representing a Person Profile, returned in lookups, check status and search.
Example attributes:
{
"id": 123456,
"status": "complete",
"name": "John Done",
... | rocketreach/rocketreach_python | rocketreach/person.py | .py | 86be262e9241490f | 7.64 | 18 |
#!/usr/bin/env python
"""BaseballSerialParserCOM.py: Collects data from a Daktronics All Sport 5000 connected via port J2 to a
Daktronics All Sport CG connected to a computer on COM port (defined on line 58), then parses data to
a .csv readable by broadcasting programs. This file has only been tested using game code... | BristolTNCitySchools/DaktronicsCGSerialParser | Baseball-5501/BaseballSerialParserCOM.py | .py | 12af51b0da69b635 | 7.5 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.