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 |
|---|---|---|---|---|---|---|
"""Tests for documentation assets included in built distributions."""
from pathlib import Path
import pytest
from GoogleCloudPlatformAPI.assets import read_text_resource, resource_path
ROOT = Path(__file__).resolve().parents[1]
def test_packaged_assets_are_readable() -> None:
"""Expose the machine-readable in... | fatmambot33/GoogleCloudPlatformAPI | tests/test_assets.py | .py | dcb30ffdc4ac2d32 | 7.65 | 1 |
"""
Scrapes a headline from The Daily Pennsylvanian website and saves it to a
JSON file that tracks headlines over time.
"""
import os
import sys
import daily_event_monitor
import bs4
import requests
import loguru
def scrape_data_point():
"""
Scrapes the main headline from The Daily Pennsylvanian home pag... | Tianyi-Wu2003/daily-pennsylvanian-headline-scraper | script.py | .py | aafd7fe462c244b7 | 7 | 0 |
"""
Fitbit API client for retrieving fitness data.
"""
import sys
from datetime import UTC, date, datetime
import requests
from .oauth_manager import OAuthManager, create_oauth_manager
class FitbitClient:
"""Client for interacting with Fitbit API."""
def __init__(self, oauth_manager: OAuthManager):
... | o6uoq/o6uoq | app/fitbit_client.py | .py | aa3c464838725c23 | 7 | 0 |
"""
OAuth Manager for fitness APIs.
"""
import base64
import json
import logging
import os
import sys
import time
from datetime import UTC, datetime
import requests
from dotenv import load_dotenv
# Configure logging - RFC5424 compatible, minimalist
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(leveln... | o6uoq/o6uoq | app/oauth_manager.py | .py | 1f2f54426bee6af2 | 7 | 0 |
"""
Strava API client for retrieving fitness data.
"""
import sys
import requests
from .oauth_manager import OAuthManager, create_oauth_manager
class StravaClient:
"""Client for interacting with Strava API."""
def __init__(self, oauth_manager: OAuthManager):
self.oauth = oauth_manager
@static... | o6uoq/o6uoq | app/strava_client.py | .py | e5bba6392d923aad | 7 | 0 |
"""
Scrapes a headline from The Daily Pennsylvanian website and saves it to a
JSON file that tracks headlines over time.
"""
import os
import sys
import daily_event_monitor
import bs4
import requests
import loguru
def scrape_data_point():
"""
Scrapes the main headline from The Daily Pennsylvanian home pag... | RuthTilahun/daily-pennsylvanian-headline-scraper | script.py | .py | c35a61ff6ae03684 | 7 | 0 |
"""
Scrapes a headline from The Daily Pennsylvanian website and saves it to a
JSON file that tracks headlines over time.
"""
import os
import sys
import daily_event_monitor
import bs4
import requests
import loguru
def get_latest_crossword_url():
response = requests.get("https://www.thedp.com/section/crosswords... | Jdoubleuotto/daily-pennsylvanian-headline-scraper | script.py | .py | 326dcb9e14e18772 | 7 | 0 |
"""
Scrapes a headline from The Daily Pennsylvanian Opinion website and saves it to a
JSON file that tracks headlines over time.
"""
import os
import sys
import daily_event_monitor
import bs4
import loguru
import requests
# def scrape_data_point():
# """
# Scrapes the main headline from The Daily Pennsylv... | panchel/daily-pennsylvanian-headline-scraper | script.py | .py | 1ef9a87269e035d8 | 7 | 0 |
"""
Scrapes a headline from The Under the Button website and saves it to a
JSON file that tracks headlines over time.
"""
import os
import sys
import daily_event_monitor
import bs4
import requests
import loguru
def scrape_data_point():
"""
Scrapes the featured headline from the Under the Button Homepage.
... | marcvaz1/daily-pennsylvanian-headline-scraper | script.py | .py | 708d8764f475c655 | 7 | 0 |
"""
Scrapes a headline from The Daily Pennsylvanian website and saves it to a
JSON file that tracks headlines over time.
"""
import os
import sys
import daily_event_monitor
import bs4
import requests
import loguru
def scrape_data_point():
"""
Scrapes the title of the latest crossword from The Daily Pen... | JudahNour/daily-pennsylvanian-headline-scraper | script.py | .py | 79d20238371086f0 | 7 | 0 |
import copy
import datetime
import json
import os
import pathlib
import typing
import requests
import pytz
TIMEZONE = pytz.timezone("US/Eastern")
DailyEventValueType = str
def time_now() -> str:
"""
Gets the current time in the "US/Eastern" timezone formatted as "YYYY-MM-DD HH:MMAM/PM".
... | AniPetrosyan/daily-pennsylvanian-headline-scraper | daily_event_monitor.py | .py | c494660a333a3ff2 | 7 | 0 |
"""
Scrapes the latest editorial headline from The Daily Pennsylvanian website and saves it to a JSON file.
This file tracks the editorial headlines over time, allowing for historical headline data accumulation.
"""
import os
import sys
import daily_event_monitor
from bs4 import BeautifulSoup
import reque... | AniPetrosyan/daily-pennsylvanian-headline-scraper | script.py | .py | 862f8085d3fb705e | 7 | 0 |
import os
from datetime import datetime
import alpaca_trade_api as tradeapi
import pandas as pd
import pandas_market_calendars as mcal
from pytz import timezone
TRADES_MORNING_FILE = "data/trades_morning.csv"
TRADES_AFTERNOON_FILE = "data/trades_afternoon.csv"
TRADES_TEST_FILE = "data/trades_morning_test.csv"
BUYING... | jolie-mcdonnell/llm_trader | src/execute_trades.py | .py | d59afbddb6bd000c | 7.24 | 2 |
import os
import re
import pandas as pd
import yfinance as yf
from alpaca.trading.client import TradingClient
# Read stock symbols from local CSV files
NYSE_SYMBOLS = pd.read_csv("data/nyse_stocks.csv")
NASDAQ_SYMBOLS = pd.read_csv("data/nasdaq_stocks.csv")
AMEX_SYMBOLS = pd.read_csv("data/amex_stocks.csv")
TRAILING... | jolie-mcdonnell/llm_trader | src/generate_stock_list.py | .py | 4b97fd726c379523 | 7.24 | 2 |
from datetime import datetime, timedelta
import time
import pandas as pd
from pytz import timezone
from headline_scraper import scrape_all_headlines
from llm_call import generate_stock_recommendation
# 1 is pre-market, 2 is during market hours, 3 is after hours
TRADING_CATEGORIES = {
1: {
"start": dateti... | jolie-mcdonnell/llm_trader | src/generate_trades.py | .py | a9b67aef482d3140 | 7.24 | 2 |
import json
from datetime import datetime
from typing import Any, Dict, Mapping
from types import MappingProxyType
import logging
import backoff
import requests
from hotglue_etl_exceptions import InvalidCredentialsError
from hotglue_singer_sdk.exceptions import RetriableAPIError
class SalesforceV3Authenticator:
"... | hotgluexyz/target-salesforce-v3 | target_salesforce_v3/auth.py | .py | 7616aa8443dcf878 | 7.15 | 1 |
"""Tests standard target features using the built-in SDK tests library."""
from __future__ import annotations
import typing as t
import pytest
from hotglue_singer_sdk.testing import get_standard_target_tests
from target_salesforce_v3.target import TargetSalesforceV3
SAMPLE_CONFIG: dict[str, t.Any] = {}
standard_t... | hotgluexyz/target-salesforce-v3 | tests/test_core.py | .py | daaf094b7b9b084b | 7.65 | 1 |
"""Base class for stage-specific system builders."""
from __future__ import annotations
from pathlib import Path
from typing import Optional, Dict, Any
from abc import ABC, abstractmethod
from loguru import logger
from batter.config.simulation import SimulationConfig, MEMBRANE_EXEMPT_COMPONENTS
from batter._interna... | yuxuanzhuang/batter | batter/_internal/builders/base.py | .py | f9095abbd5d304df | 7.15 | 1 |
from __future__ import annotations
from loguru import logger
from pathlib import Path
from typing import Any, Dict, Optional
from batter._internal.builders.base import BaseBuilder
from .fe_registry import BUILD_COMPLEX_REGISTRY, CREATE_SIMULATION_REGISTRY, CREATE_BOX_REGISTRY, RESTRAINT_REGISTRY, SIM_FILES_REGISTRY
... | yuxuanzhuang/batter | batter/_internal/builders/fe_alchemical.py | .py | b66b3e7e709eda87 | 7.15 | 1 |
"""AMBER template handling for builder workflows."""
from __future__ import annotations
from pathlib import Path
from loguru import logger
import shutil
import os
from batter.config.simulation import SimulationConfig
from batter._internal.templates import AMBER_FILES_DIR as amber_files_orig # type: ignore
def _r... | yuxuanzhuang/batter | batter/_internal/ops/amber.py | .py | 3628beff46697ec2 | 7.15 | 1 |
from __future__ import annotations
from pathlib import Path
from typing import Iterable, List
import re
from loguru import logger
from batter.config.simulation import SimulationConfig
from batter._internal.ops.helpers import rewrite_prmtop_reference
from batter.utils.components import COMPONENTS_DICT
from batter.uti... | yuxuanzhuang/batter | batter/_internal/ops/remd.py | .py | 8ca03c6eb146b446 | 7.15 | 1 |
from __future__ import annotations
import shutil
import os
from typing import Sequence
import numpy as np
from pathlib import Path
from loguru import logger
from batter._internal.builders.interfaces import BuildContext
from batter._internal.ops.fe_defaults import DEFAULT_FE_SEED_LAMBDA_STATES
from batter._internal.o... | yuxuanzhuang/batter | batter/_internal/ops/runfiles.py | .py | ffb7817fc1be4cab | 7.15 | 1 |
from __future__ import annotations
import importlib
import sys
from pathlib import Path
from types import ModuleType
def bundled_parmed_path() -> Path:
"""Return the bundled ParmEd source checkout path."""
return Path(__file__).resolve().parents[2] / "extern" / "ParmEd"
def import_parmed() -> ModuleType:
... | yuxuanzhuang/batter | batter/_internal/parmed_compat.py | .py | e59d20a4a3d45ef1 | 7.15 | 1 |
"""
Convert list of trajectories into a single trajecotry and strip e.g. water molecules
"""
import numpy as np
import MDAnalysis as mda
import os
from loguru import logger
import glob
import click
import tempfile
from batter.utils import natural_keys
from MDAnalysis.analysis import align
from MDAnalysis.transformatio... | yuxuanzhuang/batter | batter/analysis/preprocessing.py | .py | 7b5f13651ca5f191 | 7.15 | 1 |
"""Utilities for inspecting replica-exchange simulations."""
from __future__ import annotations
# Copy from Amber FETools (refactored into a single class)
import os
from typing import Dict, List, Optional, Tuple
import numpy as np
from loguru import logger
__all__ = ["RemdLog", "plot_trajectory"]
class RemdLog:
... | yuxuanzhuang/batter | batter/analysis/remd.py | .py | 3dae082c9cdd6454 | 7.15 | 1 |
import MDAnalysis as mda
import numpy as np
import rocklinc
import shutil
import subprocess
import os
from contextlib import contextmanager
import tempfile
from pathlib import Path
from loguru import logger
@contextmanager
def suppress_output_fds(stderr=False):
"""
Silence OS-level stdout (and optionally stder... | yuxuanzhuang/batter | batter/analysis/rocklin.py | .py | 0199d01977fe5325 | 7.15 | 1 |
"""Small numerical helpers used across :mod:`batter.analysis`."""
from __future__ import annotations
from typing import Generator, Iterable, List
import numpy as np
import pandas as pd
from loguru import logger
__all__ = [
"SizedChunks",
"MakeChunksWithSize",
"MakeGroupedChunks",
"exclude_outliers",... | yuxuanzhuang/batter | batter/analysis/utils.py | .py | 7fa53afc29e3fa54 | 7.15 | 1 |
"""Root CLI group and shared top-level commands."""
from __future__ import annotations
from pathlib import Path
import click
from batter.api import __version__
from batter.utils.slurm_templates import seed_default_headers
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
@click.version_option... | yuxuanzhuang/batter | batter/cli/root.py | .py | 1ea779f7fc4ec417 | 7.15 | 1 |
from deepforest import main
import pandas as pd
import os
from pytorch_lightning.loggers import CometLogger
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
from pytorch_lightning import Callback
import torch
import argparse
import tempfile
from contextlib import nullcontext
from deepforest import... | weecology/BOEM | scripts/USGS_backbone.py | .py | 846c1f8c5dbab5d5 | 7.24 | 2 |
#!/usr/bin/env python3
"""Mirror Label Studio annotation CSVs into the repo so git history is their backup.
The CSVs under /blue/ewhite/b.weinstein/BOEM/annotations are the only surviving copy
of every human annotation: `src/label_studio.check_for_new_annotations` deletes
completed tasks from the Label Studio server a... | weecology/BOEM | scripts/backup_annotations.py | .py | 4f670b1127fe0af1 | 7.24 | 2 |
#!/usr/bin/env python3
"""DeepForest precision/recall for Camera B.
Uses deepforest.evaluate.evaluate_boxes on the already-saved tiled predictions
(predictions.csv) versus the VIAME ground truth. Box metrics are class-agnostic,
so both sides are labeled 'Object' to match the detector's single class.
"""
import os
imp... | weecology/BOEM | scripts/camera_b_evaluate.py | .py | 65aa948c63f4ad7e | 7.24 | 2 |
"""Delete UBFAI_CROPS entries whose parent image was never human-reviewed.
`prepare_USGS.py` previously fed Tallgrass/Normandeau machine predictions into
`split_raster`, leaving ~6,689 per-image crop CSVs (and their tile PNGs) in
UBFAI_CROPS whose only annotation source was a model. The training reader
globs every CSV... | weecology/BOEM | scripts/cleanup_machine_only_crops.py | .py | d9cd99c96b652a23 | 7.24 | 2 |
#!/usr/bin/env python3
"""
Collect images that have at least one detection above min_score from all
.prediction_cache runs, and report (dry run) or copy them to a screened_images dir.
Usage:
uv run python collect_screened_images.py [ROOT_DIR]
ROOT_DIR: root to search for .prediction_cache dirs (default: BOEM image... | weecology/BOEM | scripts/collect_screened_images.py | .py | f998b874efe7e945 | 7.24 | 2 |
"""Count Tursiops truncatus at each pipeline stage (annotations → detection crops → UBFAI → classification train/val).
Run from repo root: uv run python count_tursiops_by_stage.py
"""
import glob
import os
import numpy as np
import pandas as pd
ANNOTATIONS_BASE = "/blue/ewhite/b.weinstein/BOEM/annotations"
DETECTIO... | weecology/BOEM | scripts/count_tursiops_by_stage.py | .py | b7359ee81b07d464 | 7.24 | 2 |
#!/usr/bin/env python3
"""
Export all Label Studio annotations (train / validation / review) to a single CSV.
For each image_path, only the annotation from the most recent CSV file is kept.
The output CSV adds a 'split' column indicating which project the annotation came from.
Usage:
python scripts/export_annotat... | weecology/BOEM | scripts/export_annotations.py | .py | e56c3ea4c15484c7 | 7.24 | 2 |
#!/usr/bin/env python3
"""Find classification crops with highest loss and upload to Label Studio for review.
Uses DeepForest CropModel on training crop data: per-crop cross-entropy loss.
Uploads the parent image (patch) for each high-loss crop to Label Studio with
detections overlaid (same UI as pipeline: RectangleLab... | weecology/BOEM | scripts/find_high_loss_crops.py | .py | af95ab1a2ebca803 | 7.24 | 2 |
"""Download land/water annotations and fit the logistic regression land filter.
uv run python scripts/fit_land_filter.py
The repo's `download_completed_tasks` parses bounding boxes, so it cannot read this
project's whole-frame Choices annotations; this pulls them directly instead. Labels
are joined back to the mi... | weecology/BOEM | scripts/fit_land_filter.py | .py | 01605a279f585749 | 7.24 | 2 |
#!/usr/bin/env python3
"""Trace classification crop paths back to parent images and patch geometry.
Classification crops (USGS_classification / write_crops) are named
{patch_basename}_{row_index}.png
e.g. 950561-0926191842531-CAM9_24_7288.png -> parent patch 950561-0926191842531-CAM9_24.png,
row_index 7288 = 7289-th... | weecology/BOEM | scripts/investigate_duplicate_crops.py | .py | 5ff679d407785b1d | 7.24 | 2 |
#!/usr/bin/env python3
"""
List the largest N flights (by directory size) that have a prediction cache
but no Tursiops truncatus predictions. Use to identify candidate flights to
move/archive to free space without affecting Label Studio (no dolphin predictions).
"""
from pathlib import Path
import subprocess
import sys... | weecology/BOEM | scripts/list_flights_without_tursiops.py | .py | 8f2fee0f812100e4 | 7.24 | 2 |
"""Hard-mine land/water frames for annotation, to fit a learned land filter.
`src/land_filter.py` currently uses four hand-tuned thresholds fitted to 88 frames
labelled by eye. That is thin, and the Dec-2024 whitecaps showed the thresholds do not
transfer across sea states. This script selects the frames worth paying ... | weecology/BOEM | scripts/mine_land_examples.py | .py | 1ce39e4c3dadbef4 | 7.24 | 2 |
"""Probe whether the trained SpatialTemporalEncoder actually contributes signal.
verify_metadata_fallback.py found that real metadata and zeroed metadata give
byte-identical predictions (mean AND max prob delta 0.0000), which would mean the
metadata branch is dead weight rather than a small contributor. The encoder is... | weecology/BOEM | scripts/probe_metadata_encoder.py | .py | 72cdc0689e8331bb | 7.24 | 2 |
import cProfile
import pstats
import sys
import time
from pathlib import Path
# Add project root so we can import src
PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
from src.detection import predict
import hydra
from deepforest import... | weecology/BOEM | scripts/profile_predict.py | .py | 12e7aa9c35d30bcf | 7.24 | 2 |
"""Score a random sample of frames from flights the land filter has never seen.
uv run python scripts/score_flights.py --n 5000 --out /path/scores.csv
Land is rare and clustered -- a flight line clips the coast for a few hundred frames
and is open water for the rest -- so a flight's land content is not something ... | weecology/BOEM | scripts/score_flights.py | .py | 2caeeb9e0a76b4c3 | 7.24 | 2 |
from datetime import datetime
import os
import re
import shutil
from typing import Any
from django.conf import settings
from django.core.files.storage import FileSystemStorage, Storage
from storages.backends.gcloud import GoogleCloudStorage # type: ignore
from django.core.files.base import ContentFile
def add_filena... | bcgov/cas-registration | bc_obps/bc_obps/storage_backends.py | .py | c44f641b005bb6eb | 7.15 | 1 |
from typing import Any, Callable, Iterable, List, Optional, Tuple
def _field_filter(
obj: List[Tuple[str, Any]], include: Optional[set] = None, exclude_none: bool = False
) -> Iterable[Tuple[str, Any]]:
"""
Helper function to include only specified fields from a dataclass in the output dict.
The field... | bcgov/cas-registration | bc_obps/common/lib/dataclasses/dict_factory.py | .py | 434dcf94f7c03afd | 7.15 | 1 |
import django.apps
import django.db.backends.postgresql.schema as postgresql_schema
from django.conf import settings
from django.core.management.commands import makemigrations, migrate
from django.db.migrations import state
from django.db.models import options
from django.db.models.signals import post_migrate
from djan... | bcgov/cas-registration | bc_obps/common/lib/pgtrigger/apps.py | .py | c44f24ab51128af7 | 7.15 | 1 |
"""Additional goodies"""
import functools
import itertools
import operator
from typing import Any, List, Tuple, Union
from . import core, utils
# A sentinel value to determine if a kwarg is unset
_unset = object()
class Protect(core.Trigger):
"""A trigger that raises an exception."""
when: core.When = cor... | bcgov/cas-registration | bc_obps/common/lib/pgtrigger/contrib.py | .py | 8d2857f2d60b836e | 7.15 | 1 |
import contextlib
import re
from django import __version__ as DJANGO_VERSION
from django.apps import apps
from django.db import transaction
from django.db.migrations.operations.fields import AddField
from django.db.migrations.operations.models import CreateModel, IndexOperation
from . import compiler, utils
if DJANG... | bcgov/cas-registration | bc_obps/common/lib/pgtrigger/migrations.py | .py | f97eb50d3fae1200 | 7.15 | 1 |
import collections
from typing import TYPE_CHECKING, Callable, List, Tuple
from . import features
_unset = object()
if TYPE_CHECKING:
from django.db.models import Model
from .core import Trigger
# All registered triggers for each model
class _Registry(collections.UserDict):
@property
def pg_funct... | bcgov/cas-registration | bc_obps/common/lib/pgtrigger/registry.py | .py | a6581328f7e7dd40 | 7.15 | 1 |
"""
Functions for runtime-configuration of triggers, such as ignoring
them or dynamically setting the search path.
"""
from __future__ import annotations
import contextlib
import threading
from collections.abc import Generator
from typing import TYPE_CHECKING, List, Union
from django.db import connections
from pgtr... | bcgov/cas-registration | bc_obps/common/lib/pgtrigger/runtime.py | .py | 7f145ae2fc741116 | 7.15 | 1 |
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db import DEFAULT_DB_ALIAS, connections
from django.utils.version import get_version_tuple
def _psycopg_version():
try:
import psycopg as Database
except ImportError:
import psycopg2 as Databas... | bcgov/cas-registration | bc_obps/common/lib/pgtrigger/utils.py | .py | 85195116697267f3 | 7.15 | 1 |
import os
import subprocess
from typing import Optional
import logging
import random
from django.core.management.base import BaseCommand
from django.db import connections
from registration.models import User
# Constants
PROD_DB_NAME = 'obps'
PROD_DB_USER = 'registration'
SCHEMA_NAMES = ['public', 'erc', 'erc_history',... | bcgov/cas-registration | bc_obps/common/management/commands/check_migrations_with_prod_data.py | .py | e20601f093262289 | 7.15 | 1 |
import logging
import traceback
from django.conf import settings
from django.core.management.base import BaseCommand
from django.core.management import call_command
from rls.utils.manager import RlsManager
from registration.models import Operation
from django.db.migrations.loader import MigrationLoader
from django.db ... | bcgov/cas-registration | bc_obps/common/management/commands/custom_migrate.py | .py | 33f9125ca4ec55a3 | 7.15 | 1 |
import logging
from typing import Callable
from django.http import HttpResponse, HttpResponseServerError, HttpRequest
logger = logging.getLogger("liveness")
class KubernetesHealthCheckMiddleware(object):
def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]):
self.get_response = get_resp... | bcgov/cas-registration | bc_obps/common/middleware/kubernetes_health_check.py | .py | 502414853dca4265 | 7.15 | 1 |
"""Bot client setup and initialization."""
import asyncio
import discord
from discord.ext import commands
import logging
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
from database import DatabaseManager
from bot.locale import load_locales
logger = logging.getLogger(__name... | Garry-Marshall/LastSeen | bot/client.py | .py | 763dc92fbc41e71e | 7 | 0 |
"""Configuration loader for LastSeen bot."""
import os
import logging
from logging.handlers import TimedRotatingFileHandler
from pathlib import Path
from typing import Optional
from dotenv import load_dotenv
logger = logging.getLogger(__name__)
class Config:
"""Bot configuration loaded from .env file."""
d... | Garry-Marshall/LastSeen | bot/config.py | .py | 11d45398f4a99448 | 7 | 0 |
"""Locale loading and translation for LastSeen bot.
Runtime user-facing strings live in ``locales/<lang>.json`` as flat
``key -> template`` maps. English (``en``) is the canonical catalog and the
fallback for any key missing from another language. Templates use named
placeholders filled via :meth:`str.format`, e.g. ``... | Garry-Marshall/LastSeen | bot/locale.py | .py | eed1cd4bd1341049 | 7 | 0 |
"""Utility functions for LastSeen bot."""
import discord
import pytz
import logging
from datetime import datetime, timezone
from typing import Optional
from bot.locale import t
logger = logging.getLogger(__name__)
def format_timestamp(timestamp: Optional[int], style: str = 'F', guild_id: Optional[int] = None, db =... | Garry-Marshall/LastSeen | bot/utils.py | .py | a4e20b22378be1f8 | 7 | 0 |
"""Admin commands cog for bot configuration."""
import asyncio
import discord
from discord import app_commands
from discord.ext import commands
import logging
from datetime import datetime, timezone
from typing import Optional
import psutil
import sys
import os
from database import DatabaseManager
from bot.utils impo... | Garry-Marshall/LastSeen | cogs/admin/admin_cog.py | .py | 0f92cb7117c68602 | 7 | 0 |
"""Channel-based command restriction modal."""
import asyncio
import discord
import logging
from database import DatabaseManager
from bot.utils import create_error_embed, create_success_embed
from bot.locale import t, guild_language
logger = logging.getLogger(__name__)
class AllowedChannelsModal(discord.ui.Modal):... | Garry-Marshall/LastSeen | cogs/admin/channel_filter.py | .py | 5445419e484f11cb | 7 | 0 |
"""Member database synchronization functionality."""
import asyncio
import discord
import logging
from datetime import datetime, timezone
from database import DatabaseManager
from bot.utils import get_member_roles, create_success_embed, create_error_embed
from bot.locale import t, guild_language
logger = logging.get... | Garry-Marshall/LastSeen | cogs/admin/member_mgmt.py | .py | 1cd7670bb961171a | 7 | 0 |
"""Shared permission checking utilities for admin commands."""
import asyncio
import discord
import logging
from typing import Optional
from database import DatabaseManager
from bot.utils import has_bot_admin_role, create_error_embed
from bot.locale import t, guild_language
logger = logging.getLogger(__name__)
asy... | Garry-Marshall/LastSeen | cogs/admin/permissions.py | .py | 989a50479f52e1a0 | 7 | 0 |
"""Quick Setup wizard for first-time configuration."""
import discord
import logging
from typing import Optional
from database import DatabaseManager
from bot.utils import create_embed, create_success_embed
from bot.locale import t, guild_language
from .channel_config import ChannelModal, InactiveDaysModal, TimezoneM... | Garry-Marshall/LastSeen | cogs/admin/quick_setup.py | .py | a173a0b92298b008 | 7 | 0 |
"""
LastSeen Discord Bot - Main Entry Point
A Discord bot for monitoring and tracking user activity across guilds.
Tracks user joins, leaves, nickname changes, and presence updates.
"""
import asyncio
import logging
import sys
import traceback
from datetime import datetime, timezone
from pathlib import Path
from bot... | Garry-Marshall/LastSeen | main.py | .py | 5b2d7324b12351ca | 7 | 0 |
#!/usr/bin/env python3
"""Locale consistency checker for LastSeen.
Run from the project root: python tools/check_locales.py
Validates three things and exits non-zero if any fail:
1. Every t("key") referenced in the code exists in the canonical English
catalog (locales/en.json). A missing key means a runtime ... | Garry-Marshall/LastSeen | tools/check_locales.py | .py | 34ac73ba0f316d64 | 7 | 0 |
"""
Example module for network graph sample data generation and plotting.
This module provides functions to generate and plot sample network data for testing.
"""
import sys
from pathlib import Path
from matplotlib.figure import Figure
import pandas as pd
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / ... | fatmambot33/MatplotLibAPI | examples/bubble.py | .py | ed69208f0fe4548c | 7.15 | 1 |
"""
Example module for network graph sample data generation and plotting.
This module provides functions to generate and plot sample network data for testing.
"""
import sys
from pathlib import Path
from matplotlib.figure import Figure
import pandas as pd
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / ... | fatmambot33/MatplotLibAPI | examples/network.py | .py | 1322acfe81c8ad84 | 7.15 | 1 |
"""Area chart helpers for Matplotlib-based area visualizations."""
from typing import Any, Optional, Tuple
import pandas as pd
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from .base_plot import BasePlot
from .style_template import (
AREA_STYLE_TEMPLATE,
StyleTemplate,
string_fo... | fatmambot33/MatplotLibAPI | src/MatplotLibAPI/area.py | .py | 9e1f4bbabd6af05a | 7.15 | 1 |
"""Bar and stacked bar chart helpers."""
from typing import Any, Optional, Tuple
import pandas as pd
import seaborn as sns
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from .base_plot import BasePlot
from .style_template import (
DISTRIBUTION_STYLE_TEMPLATE,
StyleTemplate,
strin... | fatmambot33/MatplotLibAPI | src/MatplotLibAPI/bar.py | .py | 6de0d34366cca81d | 7.15 | 1 |
"""Abstract base class for all plot types."""
from abc import ABC, abstractmethod
from typing import Any, Optional, Tuple, cast, Dict
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from .style_template import StyleTemplate, FIG_SIZE
class B... | fatmambot33/MatplotLibAPI | src/MatplotLibAPI/base_plot.py | .py | 3895e58d04472451 | 7.15 | 1 |
"""Box and violin plot helpers."""
from typing import Any, Optional, Tuple
import pandas as pd
import seaborn as sns
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from .base_plot import BasePlot
from .style_template import (
DISTRIBUTION_STYLE_TEMPLATE,
StyleTemplate,
string_form... | fatmambot33/MatplotLibAPI | src/MatplotLibAPI/box_violin.py | .py | 8afc026163a17b5f | 7.15 | 1 |
"""Plugin scaffolding and deterministic conformance validation."""
from __future__ import annotations
from dataclasses import dataclass
import re
from pathlib import Path
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
from .plugins import PLUGIN_API_VERSION, Plugin, PluginRegistry
@dataclas... | fatmambot33/MatplotLibAPI | src/MatplotLibAPI/conformance.py | .py | 78c4b6cdf17035ff | 7.15 | 1 |
"""Heatmap and correlation matrix helpers."""
from typing import Any, Optional, Sequence, Tuple, cast
import pandas as pd
import seaborn as sns
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from .base_plot import BasePlot
from .types import CorrelationMethod
from .style_template import (
... | fatmambot33/MatplotLibAPI | src/MatplotLibAPI/heatmap.py | .py | 8c5d57c86061203c | 7.15 | 1 |
"""Histogram and KDE plotting helpers."""
from typing import Any, Optional, Tuple
import pandas as pd
import seaborn as sns
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from .base_plot import BasePlot
from .style_template import (
DISTRIBUTION_STYLE_TEMPLATE,
NETWORK_STYLE_TEMPLATE... | fatmambot33/MatplotLibAPI | src/MatplotLibAPI/histogram.py | .py | 0d8f4e558574a1b9 | 7.15 | 1 |
"""Explicit compatibility diagnostics and preparation for MatplotLibAPI 5.0."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Any, Dict, Mapping, Optional, Tuple
from .specs import PlotSpec
V5_REMOVAL_NOT_BEFORE = date(2027, 2, 6)
V5_CANONICAL_CHAR... | fatmambot33/MatplotLibAPI | src/MatplotLibAPI/migration.py | .py | 69b9c8dc4a6acbd1 | 7.15 | 1 |
"""Weight scaling helpers for network plots."""
from __future__ import annotations
from typing import Iterable, List, Optional
import numpy as np
from .constants import _WEIGHT_PERCENTILES
def _softmax(x: Iterable[float]) -> np.ndarray:
"""Compute softmax values for array-like input."""
x_arr = np.array(x... | fatmambot33/MatplotLibAPI | src/MatplotLibAPI/network/scaling.py | .py | 81d6eeb161cdfb22 | 7.15 | 1 |
"""Pie and donut chart helpers."""
from typing import Any, Dict, Optional, Tuple
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from .base_plot import BasePlot
from .style_template import PIE_STYLE_TEMPLATE, StyleTempla... | fatmambot33/MatplotLibAPI | src/MatplotLibAPI/pie.py | .py | 0739d28f65691dbe | 7.15 | 1 |
"""Typed plugin discovery and schema-rich plot registration."""
from __future__ import annotations
from dataclasses import dataclass, field
from importlib import metadata
import inspect
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Mapping,
Optional,
Protocol,
Sequence,... | fatmambot33/MatplotLibAPI | src/MatplotLibAPI/plugins.py | .py | 35906cb855aedea3 | 7.15 | 1 |
"""Sankey plotting helpers."""
from dataclasses import dataclass
from typing import Dict, List, Optional, cast
import pandas as pd
import plotly.graph_objects as go
from .style_template import SANKEY_STYLE_TEMPLATE, StyleTemplate, validate_dataframe
__all__ = ["SANKEY_STYLE_TEMPLATE", "fplot_sankey"]
@dataclass
c... | fatmambot33/MatplotLibAPI | src/MatplotLibAPI/sankey.py | .py | 3ad416cf340ff623 | 7.15 | 1 |
"""Common style utilities and formatters for plotting."""
import math
from dataclasses import dataclass
from typing import Callable, Dict, List, Optional, Union, cast
import numpy as np
import pandas as pd
from matplotlib.dates import num2date
from matplotlib.ticker import FuncFormatter
# Type alias for formatter fu... | fatmambot33/MatplotLibAPI | src/MatplotLibAPI/style_template.py | .py | 0058a17bab70a4c2 | 7.15 | 1 |
"""Sunburst chart plotting utilities."""
from __future__ import annotations
from typing import Optional
import pandas as pd
import plotly.graph_objects as go
from .style_template import (
TREEMAP_STYLE_TEMPLATE,
StyleTemplate,
validate_dataframe,
)
__all__ = ["TREEMAP_STYLE_TEMPLATE", "fplot_sunburst"]... | fatmambot33/MatplotLibAPI | src/MatplotLibAPI/sunburst.py | .py | f543f3a2fd47f615 | 7.15 | 1 |
"""Timeserie plotting helpers."""
from typing import Any, Dict, Optional, Tuple, cast
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from .base_plot import BasePlot
from .style_template import (
TIMESERIE_STYLE_TEMP... | fatmambot33/MatplotLibAPI | src/MatplotLibAPI/timeserie.py | .py | 2d5c1772b2514e2f | 7.15 | 1 |
"""Waffle chart helpers."""
from typing import Any, Optional, Tuple, cast
import pandas as pd
import seaborn as sns
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from matplotlib.patches import Rectangle
from .base_plot import BasePlot
from .style_template import PIE_STYLE_TEMPLATE, StyleTemp... | fatmambot33/MatplotLibAPI | src/MatplotLibAPI/waffle.py | .py | 8c7fdbd5646ed9ae | 7.15 | 1 |
"""Word cloud plotting utilities."""
from __future__ import annotations
from typing import Any, Dict, Iterable, Optional, Sequence, Tuple, Union
from matplotlib.transforms import BboxBase
import numpy as np
import pandas as pd
from matplotlib import colormaps
from matplotlib.axes import Axes
from matplotlib.backend_... | fatmambot33/MatplotLibAPI | src/MatplotLibAPI/word_cloud.py | .py | b224540c8c90b87d | 7.15 | 1 |
"""Shared fixtures for visualization tests."""
import os
from pathlib import Path
import sys
from typing import Any, Callable, Generator
import pandas as pd
import pytest
# Ensure the src directory is on the Python path for src layout
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from example... | fatmambot33/MatplotLibAPI | tests/conftest.py | .py | d2d4aac131ba49db | 7.65 | 1 |
"""Regression tests for the stable package-root plotting contract."""
from inspect import Parameter, Signature, signature
from typing import get_type_hints
from matplotlib.figure import Figure as MatplotlibFigure
from plotly.graph_objects import Figure as PlotlyFigure
import MatplotLibAPI
PLOT_HELPERS = {
name... | fatmambot33/MatplotLibAPI | tests/test_api_contract.py | .py | abcc9ceb3c8473bb | 7.65 | 1 |
"""Tests for bar and stacked bar visualizations."""
from matplotlib.figure import Figure
from MatplotLibAPI.bar import aplot_bar, fplot_bar
def test_fplot_bar(load_sample_df):
"""Render a bar chart from sample data."""
df = load_sample_df("bar.csv")
fig = fplot_bar(
pd_df=df, category="product... | fatmambot33/MatplotLibAPI | tests/test_bar.py | .py | 56f7c04eac23084b | 7.65 | 1 |
import os
from typing import Callable
import pandas as pd
from ..customs.ga_stage.analysis import load_ga_stage_attributes
from .run_analysis import RunData
from .utils import get_statistics_overview
class MultiRunData:
"""Collects and structures the data produced by multiple runs.
The provided directory i... | OHANAN1/fucrimodo | src/fucrimodo/analysis/multi_run_analysis.py | .py | 5d4002da671132f1 | 7.24 | 2 |
import os
import warnings
from datetime import datetime
from typing import Any, Callable
import ase
import numpy as np
import pandas as pd
from ..core import Individual
from ..customs.ga_stage.analysis import load_ga_stage_attributes
from ..utils import ase_tools
from .stage_analysis import StageData
from .utils impo... | OHANAN1/fucrimodo | src/fucrimodo/analysis/run_analysis.py | .py | ab277c5ec4631bf1 | 7.24 | 2 |
import json
import os
from datetime import datetime
import pandas as pd
def load_dict_from_file(dir: str | os.PathLike, file_name: str) -> dict:
"""Load a dictionary from a json file with name :data:`file_name` from
the directory ``dir``.
:param file_name: Name of the file that should be loaded.
:r... | OHANAN1/fucrimodo | src/fucrimodo/analysis/utils.py | .py | 9c8647ce2a41437c | 7.24 | 2 |
import os
import click
from ..utils.import_helper import ConfigScript
class Runner:
"""Analyse data collected during a run or stage.
:param analysis_object: Type of object to analyse. One of:
``run``, ``stage``, ``multi_run``.
:param dir_path: Directory where the run or stage results are saved.... | OHANAN1/fucrimodo | src/fucrimodo/cli/analyse.py | .py | ddcc17b62138a4af | 7.24 | 2 |
import importlib
import click
from fucrimodo import __version__
@click.group(
no_args_is_help=True,
invoke_without_command=False,
epilog=(
"Run 'fucrimodo COMMAND --help' for more information on a specific command.\n\n"
"\b\n"
"Example:\n"
" fucrimodo init --save_dir ./m... | OHANAN1/fucrimodo | src/fucrimodo/cli/main.py | .py | 3ebc16382a202573 | 7.24 | 2 |
import os
from pathlib import Path
import click
from ..utils.import_helper import ConfigScript
class Runner:
"""Perform an inversion run on a target file.
:param input_file_path: Path to the input/target file to process.
:param verbose: Whether to enable verbose logging/output.
:param save_dir: Dir... | OHANAN1/fucrimodo | src/fucrimodo/cli/run.py | .py | 991891f51fdc33fb | 7.24 | 2 |
import os
import click
from ..utils.import_helper import ConfigScript
class Runner:
"""Execute a configured utility with parsed parameters.
:param config_path: Path to the configuration script used to build
the runner's configuration.
:param verbose: Whether to enable verbose output.
:param... | OHANAN1/fucrimodo | src/fucrimodo/cli/utils.py | .py | 4d76d40615b426cf | 7.24 | 2 |
from abc import ABC, abstractmethod
from ..population import Population
class BreakCondition(ABC):
"""Checks if algorithm should stop based on the state of the population.
Children of this class should implement the :meth:`check` method, to test if
the algorithm should be stopped based on the state of t... | OHANAN1/fucrimodo | src/fucrimodo/core/abstracts/break_condition.py | .py | 049db215e271758c | 7.24 | 2 |
from abc import ABC, abstractmethod
from ..individual import Individual
from ..population import Population
class FitnessFunction(ABC):
"""Evaluates how well individuals fullfill an objective.
Fitness functions are used for example in the genetic algorithm to
calculate the fitness value of an individual... | OHANAN1/fucrimodo | src/fucrimodo/core/abstracts/fitness_function.py | .py | 6527a9f14b9316f5 | 7.24 | 2 |
from abc import ABC, abstractmethod
from ..individual import Individual
from ..population import Population
class PopulationGenerator(ABC):
"""Generates a new population.
The population generator should create the individuals of a population with
the :meth:`generate_individuals` method.
"""
def... | OHANAN1/fucrimodo | src/fucrimodo/core/abstracts/population_generator.py | .py | 82747934d66bd9ba | 7.24 | 2 |
from abc import ABC, abstractmethod
from ..individual import Individual
class PopulationSelection(ABC):
"""Select a subset of individuals based on their properties.
Population selection is used to select individuals from the population based
on a selection strategy. E.g. in the genetic algorithms this i... | OHANAN1/fucrimodo | src/fucrimodo/core/abstracts/population_selection.py | .py | 2341f42e4c2a9b94 | 7.24 | 2 |
import logging
import os
from abc import ABC, abstractmethod
from datetime import datetime
from typing import Callable
from ase.db.core import Database
from deap import tools
from ..individual import Individual
from ..population import Population
class Stage(ABC):
"""Abstract base class for stages in the optimi... | OHANAN1/fucrimodo | src/fucrimodo/core/abstracts/stage.py | .py | 04ea017a7cd85dbc | 7.24 | 2 |
import datetime
import sys
from operator import mul, truediv
from typing import Self
import ase
import numpy as np
class FitnessStorage(object):
"""Storage of fitness and their weight values.
Implementation is inspired by the `DEAP library <https://github.com/deap/deap>`__.
FitnessStorages can be compar... | OHANAN1/fucrimodo | src/fucrimodo/core/individual.py | .py | dc3b247bf7aa7c77 | 7.24 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.