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 pandas as pd
from io import StringIO
from typing import Dict, Tuple, List
PI_TITLE = "__calculated__ reward PI by bucket"
MEDDIST_TITLE = "median distance to reward circle center, by sync bucket (exp and yoked control), by training"
RPD_TITLE = "rewards per distance traveled [m⁻¹]"
NUM_RWD_TITLE = "number __cal... | rcalfredson/nvsl-analysis | scripts/find_csv_inconsistencies.py | .py | a2b3f97df2423871 | 7.15 | 1 |
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import os
import numpy as np
# ----------------------------
# Helpers
# ----------------------------
def _load_npz(path: str) -> dict:
d = np.load(path, allow_pickle=True)
return {k: d[k] for k in d.files}
def _as_scalar(x):
# ... | rcalfredson/nvsl-analysis | scripts/make_turnback_contrast_bundle.py | .py | ccc7a08e2210c943 | 7.15 | 1 |
#!/usr/bin/env python3
"""
Compute mean and 95% CI for per-row sums of specific columns in a CSV section.
This script looks for a marker row whose first column contains:
"number __calculated__ rewards by sync bucket:"
Immediately after that marker, it expects a CSV "table" that continues until the
next empty line... | rcalfredson/nvsl-analysis | scripts/stats_from_csv.py | .py | d70630585a07fbf5 | 7.15 | 1 |
from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin
from core.models import Notification
from django.db.models.signals import post_save, m2m_changed
from django.dispatch import receiver
class CustomUserManager(BaseUserManager):
def create_us... | Apfirebolt/quora_clone_vue_and_django | accounts/models.py | .py | 33ca63b46583aba5 | 7.15 | 1 |
from collections import OrderedDict
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
class PageNumberPaginationNoCount(PageNumberPagination):
"""Override get_paginated_response to remove 'count' from Response"""
def get_paginated_response(self, data):
... | Apfirebolt/quora_clone_vue_and_django | api/pagination.py | .py | 23696302c7acc038 | 7.15 | 1 |
"""
Integration tests and edge cases for the API.
"""
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
from core.models import Question, Answer, Comment, Tag, Notification
from api.... | Apfirebolt/quora_clone_vue_and_django | api/tests/test_integration.py | .py | 313280696699c014 | 7.65 | 1 |
OPERATORS: list[str] = [
SET := '=',
APP := '+',
PRE := '-',
SWP := '#',
]
COMMANDS: list[str] = [
INFO_FULL := '--info',
INFO_INIT := '-i',
HELP_FULL := '--help',
HELP_INIT := '-h',
VERSION_FULL := '--version',
VERSION_INIT := '-v',
RESTART_FULL := '--restart',
... | POLA-LCS/CPS-v2 | _scripts/tokens.py | .py | 3445ddc4e15f96aa | 7.15 | 1 |
class Solution(object):
def smallestSubsequence(self, s):
"""
:type s: str
:rtype: str
"""
last = {}
for i, ch in enumerate(s):
last[ch] = i
stack = []
seen = set()
for i, ch in enumerate(s):
if ch in seen:
... | tamim-ar/leetcode | solutions/1081. Smallest Subsequence of Distinct Characters/1081.py | .py | e1f455abbd8a8567 | 7.35 | 4 |
from playwright.async_api import async_playwright
import gui
class PlaywrightMixin:
"""This mixin is for initalizing a playwright context."""
playapi = None
browser = None
browser_on = False
async def start_player(self):
"""Initalize an instance of Playwright"""
gui.print("Playwr... | CrosswaveOmega/NikkiBot | bot/PlaywrightAPI.py | .py | 21a9fe53c60df1a2 | 7.3 | 3 |
import gui
import inspect
import discord
from discord.app_commands import ContextMenu, locale_str
import random
from discord.ext import commands
from typing import (
Any,
Dict,
List,
Union,
)
MISSING: Any = discord.utils.MISSING
ctx_comms = {}
class NonContextMenu:
"""
A simple class that ... | CrosswaveOmega/NikkiBot | bot/TCMixins.py | .py | ca00bc3c051d4df6 | 7.3 | 3 |
import asyncio
from datetime import datetime as dt
from typing import Any, Callable, Coroutine, Dict, Optional, Type, Literal, TypeVar
import gui
from dateutil.rrule import rrule
import heapq
from queue import PriorityQueue
import logging
_coro = Callable[..., Coroutine[Any, Any, Any]]
CoroutineWrap = TypeVar("Corout... | CrosswaveOmega/NikkiBot | bot/Tasks/TCTasks.py | .py | 0ef6ef989eacd537 | 7.3 | 3 |
from utility import urltomessage
from .Tasks.TCTasks import TCTask, TCTaskManager
from database import DatabaseSingleton
import sqlalchemy
import gui
from sqlalchemy import (
Boolean,
Column,
Integer,
String,
DateTime,
delete,
select,
)
from sqlalchemy import PrimaryKeyConstraint
from sqlalc... | CrosswaveOmega/NikkiBot | bot/TcGuildTaskDB.py | .py | 1ab041e7294f0d17 | 7.3 | 3 |
import asyncio
import datetime
import logging
import logging.handlers
import traceback
from collections import defaultdict
from typing import Any
import discord
from dateutil.rrule import SECONDLY, rrule
from discord.ext import commands
import gui
from utility import MessageTemplates
from .config_gen import config_u... | CrosswaveOmega/NikkiBot | bot/bot_setup.py | .py | 7b642c99157587f6 | 7.3 | 3 |
"""
Experimental secure key storage.
"""
import os
import gui
from .TauCetiBot import ConfigParserSub
import keyring
import sys
import nacl.secret
import nacl.utils
import nacl.exceptions
import base64
from typing import List
def print_package():
print(f"__package__ is {__package__}")
#
def get_or_generate_ke... | CrosswaveOmega/NikkiBot | bot/key_vault.py | .py | e3e44f31cfc8190a | 7.3 | 3 |
import gui
import asyncio
from datetime import datetime, timezone
from typing import List, Tuple
from .archive_database import HistoryMakers, ChannelArchiveStatus
from database import ServerArchiveProfile
import discord
from bot import StatusEditMessage
import utility.formatutil as futil
from discord import ChannelTyp... | CrosswaveOmega/NikkiBot | cogs/ArchiveSub/historycollect.py | .py | a3278b18c62cd87a | 7.3 | 3 |
import gui
import datetime
import os
import random
from typing import Any, Callable, Dict, List
import urllib
import discord
import subprocess
import re
import logging
import yt_dlp # type: ignore
import itertools
import json
from .MusicUtils import is_url
from .MusicDatabase import MusicJSONMemoryDB
from utility imp... | CrosswaveOmega/NikkiBot | cogs/AudioPlaybackSub/AudioContainer.py | .py | 52aea9898e7a5d50 | 7.3 | 3 |
import json
from typing import List, Tuple
from sqlalchemy import (
Column,
ForeignKey,
Integer,
String,
Double,
JSON,
and_,
or_,
)
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import relationship, Session
from database import DatabaseSingleton
from sqlalchemy import c... | CrosswaveOmega/NikkiBot | cogs/AudioPlaybackSub/MusicDatabase.py | .py | ea97bfb91ecb0a84 | 7.3 | 3 |
from typing import Union
import discord
from .MusicPlayer import MusicPlayer
class MusicPlayers:
"""class that stores a dictionary of all active music player, managed per guild."""
def __init__(self):
self.players = {}
def add_player(self, bot, guild: discord.Guild):
key = str(guild.id)
... | CrosswaveOmega/NikkiBot | cogs/AudioPlaybackSub/MusicPlayerManager.py | .py | 8504d504b046e90f | 7.3 | 3 |
from typing import (
Literal,
Tuple,
Union,
)
from .AudioContainer import AudioContainer
import random
import discord
from discord.ext import commands
"""
I'm putting the playback/playlist management functions in these two mixins because MusicPlayer was getting crowded.
"""
class PlayerMixin:
def se... | CrosswaveOmega/NikkiBot | cogs/AudioPlaybackSub/MusicPlayer_Mixins.py | .py | 55a30d8f3e2cb795 | 7.3 | 3 |
import gui
import discord
# import datetime
from datetime import timedelta
from discord.ext import commands
from discord import app_commands
from bot import TC_Cog_Mixin
from discord import (
AutoModRule,
AutoModAction,
AutoModTrigger,
AutoModRuleTriggerType,
AutoModRuleAction,
)
class Autom... | CrosswaveOmega/NikkiBot | cogs/AutomodCog.py | .py | c5bf89eb2a088788 | 7.3 | 3 |
import gui
import discord
# import datetime
import io
from discord.ext import commands
import random
from random import seed
import traceback
from bot import TC_Cog_Mixin
from discord import app_commands
from utility.globalfunctions import prioritized_string_split
from .StepCalculator import evaluate_expression, ... | CrosswaveOmega/NikkiBot | cogs/CalculatorCog.py | .py | b2ed6398d156616a | 7.3 | 3 |
from sqlalchemy import (
Column,
Integer,
String,
)
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import Session
from database import DatabaseSingleton
SuperEarthBase = declarative_base(name="HD API Base")
# Also for testing DatabaseSingleton's asyncronous mode.
class ServerHDProfile(S... | CrosswaveOmega/NikkiBot | cogs/HD2/db.py | .py | ba36cfe693a9881e | 7.3 | 3 |
"""
Pytest configuration and global fixtures for unidas.
"""
import importlib.util
import platform
import dascore as dc
import daspy
import pooch
import pytest
from xdas.synthetics import wavelet_wavefronts
@pytest.fixture(scope="session")
def dascore_patch():
"""Get a dascore patch for testing."""
return d... | DASDAE/unidas | test/conftest.py | .py | b0a4c0a639d7a169 | 7.8 | 3 |
#!/usr/bin/env python3.11
# -*- coding: utf-8 -*-
"""
QubitCreator Script
This script creates and manages qubits in "neuron" groupings, where each
neuron has 50 qubits. It uses a 3-layer quantum scheme (middle layer is in
superposition) and leverages Grover's algorithm for search across neurons.
The structure can kee... | R-D-BioTech-Alaska/Brain | Qcer.py | .py | 24cc015a72cd4a4e | 7.3 | 3 |
#!/usr/bin/env python3
# Copyright 2024 Philipp Stephani
#
# 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 ... | phst/merge-bazel-lockfiles | test.py | .py | 90fc5a90444e1c4b | 7.5 | 0 |
#!/usr/bin/env python3
"""Write or verify the checksummed homelab release manifest before committing."""
from __future__ import annotations
import argparse
import hashlib
import json
import sys
from pathlib import Path
from typing import List, Optional
ROOT = Path(__file__).resolve().parents[2]
MANIFEST = ROOT / "d... | yassinsolim/soundalike | deploy/homelab/write_manifest.py | .py | 3ebe070a3c05dfcd | 7.15 | 1 |
"""Acoustic feature extraction from raw audio (digital signal processing).
This is the "science" core: instead of trusting anyone's precomputed numbers
(Spotify, a dataset, a website), we compute features directly from the audio
waveform of a track using librosa. Two songs are "similar" when these measured
acoustic ve... | yassinsolim/soundalike | src/soundalike/audio/features.py | .py | cc4d32dde21cfcf5 | 7.15 | 1 |
"""Rich "vibe" features that capture how a song actually sounds and feels.
The original acoustic engine averaged every feature over the whole clip, which
washes out exactly what makes a track's vibe: its bass profile and its dynamics.
A song with quiet verses and a heavy drop ends up looking "medium" everywhere.
This... | yassinsolim/soundalike | src/soundalike/audio/vibe.py | .py | 1d95986f2cbeb867 | 7.15 | 1 |
"""Runtime configuration loaded from environment / a local .env file.
Secrets never live in the repo: copy .env.example to .env (git-ignored) and fill
in your own values. See SETUP.md.
"""
from __future__ import annotations
import os
from dataclasses import dataclass
from pathlib import Path
from typing import Optio... | yassinsolim/soundalike | src/soundalike/config.py | .py | 5a87feb94003686d | 7.15 | 1 |
"""Audio-feature definitions and configuration for the recommender."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Dict, List
# Sonic features used for similarity. `bpm` lives on a very different scale
# (~40-220) than the 0-100 percentage features, so normalization... | yassinsolim/soundalike | src/soundalike/features.py | .py | 6cfe59ff6084f82e | 7.15 | 1 |
"""Aggregate Last.fm similar-tracks across a set of seed songs into a ranking.
A song similar to *several* of your seeds should rank above one similar to just
a single seed, so scores are summed across seeds. This turns per-track
similarity into a taste-profile recommendation that works for any catalog.
"""
from __fu... | yassinsolim/soundalike | src/soundalike/lastfm/recommender.py | .py | 6f0b4d0203b8e637 | 7.15 | 1 |
"""Measure recommendation quality — and the library-size vs accuracy trade-off.
Everything so far has been eyeballed ("these look right"). This module puts
numbers on it, using two label-free metrics computed straight from the bundled
deep-vibe index (no downloads, no human labels):
* **same-artist recall@K** (a *pre... | yassinsolim/soundalike | src/soundalike/ml/benchmark.py | .py | d7c04890849a25ef | 7.15 | 1 |
"""Dataset preparation and a torch Dataset for contrastive training.
Downloading a preview and computing its mel-spectrogram is slow, so we do it
once and cache each spectrogram as a .npy file keyed by track id. Training then
reads those cached arrays quickly and applies random augmentations on the fly.
"""
from __fu... | yassinsolim/soundalike | src/soundalike/ml/data.py | .py | dae46bfc2dff2512 | 7.15 | 1 |
"""Load a trained encoder as a feature extractor for arbitrary audio.
The FMA-trained encoder learned a rich *timbre/texture* representation. Here we
reuse it purely as a feature extractor: given any preview file, produce its
neural embedding. This is what lets the deep-vibe engine apply the learned model
to real, pop... | yassinsolim/soundalike | src/soundalike/ml/encoder_infer.py | .py | 3d311df0f9871458 | 7.15 | 1 |
"""Evaluate learned embeddings: kNN genre probe, silhouette, retrieval.
For self-supervised models the standard quality measure is a *probe*: freeze the
embeddings and see how well a simple classifier (here kNN) recovers genre from
them. If similar-sounding songs really are neighbors, kNN accuracy climbs well
above ch... | yassinsolim/soundalike | src/soundalike/ml/evaluate.py | .py | fab0af755b24b003 | 7.15 | 1 |
"""Approach 2 — Artist-centroid genre-coherence reranker.
Problem: the neural embedding's whitened cosine similarity captures timbre
and texture well, but at 272k songs the top-50 candidates for a given seed
can span multiple unrelated genres. A song by "The Weeknd" ends up near
rock ballads and reggae songs because ... | yassinsolim/soundalike | src/soundalike/ml/genre_rerank.py | .py | 8727ea4f08cee2ec | 7.15 | 1 |
"""GPU + cuDNN inspection utilities.
This module is a learning tool as much as a practical one. It lets you *see*
how NVIDIA's libraries choose the low-level algorithm ("solver") for an
operation at runtime:
* cuDNN keeps several algorithms for a convolution (implicit GEMM, Winograd,
FFT, ...). With the autotuner e... | yassinsolim/soundalike | src/soundalike/ml/gpu.py | .py | d6057b793f888690 | 7.15 | 1 |
"""Fetch the deep-vibe pack (encoder + song index) from a GitHub Release.
The bundled index is capped by GitHub's 100 MB per-file limit, so a large
library (hundreds of thousands of songs, or a higher-dimensional embedding)
can't live in the repo. This module lets the pack live on a **GitHub Release**
instead — releas... | yassinsolim/soundalike | src/soundalike/ml/index_store.py | .py | 8a76f14029fe3a34 | 7.15 | 1 |
"""Project learned embeddings to 2D and plot them, colored by genre.
This is the visual sanity check: if the self-supervised model learned anything
musically meaningful, songs of the same genre should form clusters even though
the model never saw genre labels during training. Genres are used only to color
the points.
... | yassinsolim/soundalike | src/soundalike/ml/map.py | .py | 3dc93ecbd7f6a6e4 | 7.15 | 1 |
"""Audio embedding model and self-supervised contrastive loss.
The encoder is a small convolutional network that maps a mel-spectrogram to a
fixed-length embedding vector. Songs that *sound* alike should land close
together in this space.
We train it self-supervised with NT-Xent (the SimCLR loss): two augmented views... | yassinsolim/soundalike | src/soundalike/ml/model.py | .py | 3c76fdbd12004c7e | 7.15 | 1 |
from __future__ import annotations
from collections import defaultdict
from typing import TYPE_CHECKING, TypeVar, cast
from mersal.exceptions import MersalExceptionError
from mersal.pipeline import MessageContext
if TYPE_CHECKING:
from collections.abc import Sequence
from mersal._activation.handler_activato... | mersal-org/mersal | src/mersal/_activation/builtin_handler_activator.py | .py | 14a102ce8dadd3a5 | 7.35 | 4 |
from __future__ import annotations
from collections.abc import Callable, Sequence
from typing import TYPE_CHECKING, Protocol, TypeAlias, TypeVar
from mersal.handlers import MessageHandler
from mersal.pipeline import MessageContext
# Define a type variable for messages
MessageT = TypeVar("MessageT")
#: A factory fun... | mersal-org/mersal | src/mersal/_activation/handler_activator.py | .py | 5bef68112e18bd22 | 7.35 | 4 |
from typing import Any
__all__ = (
"ConcurrencyExceptionError",
"MersalExceptionError",
"MissingDependencyExceptionError",
)
class MersalExceptionError(Exception):
"""Base exception class from which all Mersal exceptions inherit."""
detail: str
def __init__(self, *args: Any, detail: str = "... | mersal-org/mersal | src/mersal/exceptions/base_exceptions.py | .py | 172c593f5f7dde0e | 7.35 | 4 |
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
from mersal.idempotency.plugin import IdempotencyPlugin
if TYPE_CHECKING:
from mersal.idempotency.message_tracker import MessageTracker
__all__ = ("IdempotencyConfig",)
@dataclass
class IdempotencyConfig:
... | mersal-org/mersal | src/mersal/idempotency/config.py | .py | 2997974dbf6d4b2c | 7.35 | 4 |
from typing import Any, Protocol
from mersal.transport import TransactionContext
__all__ = ("MessageTracker",)
class MessageTracker(Protocol):
"""Idempotency tracker."""
async def track_message(self, message_id: Any, transaction_context: TransactionContext) -> None:
"""Set message identified by `me... | mersal-org/mersal | src/mersal/idempotency/message_tracker.py | .py | a15b1373abe772f7 | 7.35 | 4 |
import atexit
from logging import Handler, LogRecord, StreamHandler
from logging.handlers import QueueHandler, QueueListener
from queue import Queue
from typing import Any
__all__ = (
"LoggingQueueListener",
"QueueListenerHandler",
)
class LoggingQueueListener(QueueListener):
def __init__(self, queue: Qu... | mersal-org/mersal | src/mersal/logging/stdlib/queue.py | .py | 57b0ff02f6d0e3f6 | 7.35 | 4 |
"""
Module used for defining the certificate class and it's functionality.
"""
import random
import string
from copy import deepcopy
from datetime import datetime, timedelta
from typing import Union
from cryptography.hazmat.primitives.asymmetric import rsa, ec
from cryptography.hazmat.primitives.asymmetric.padding imp... | laoluadewoye/PKI_Practice_Python | PKIPractice/Simulation/Certificate.py | .py | 39b79f69840fba49 | 7 | 0 |
"""
Module used for defining the network class and it's functionality.
"""
import time
import datetime
from threading import Thread, Event
from queue import Queue
from os import makedirs
from os.path import dirname, exists
from typing import Union, List, Dict
from .Holder import PKIHolder
from .SocketUtils import star... | laoluadewoye/PKI_Practice_Python | PKIPractice/Simulation/Network.py | .py | ee77c112eac76936 | 7 | 0 |
"""
Simulation specific utilities that make more sense to keep outside classes.
"""
import random
from typing import Union
from cryptography.hazmat.primitives.hashes import *
from cryptography.hazmat.primitives.asymmetric import rsa, ec
def hash_info(information: str, hash_func_string: str) -> str:
"""
Uses ... | laoluadewoye/PKI_Practice_Python | PKIPractice/Simulation/SimUtils.py | .py | 3a6f70323c9d215a | 7 | 0 |
"""
Module used for defining the REST API for the Flask web app.
Global Attributes:
APP: The flask application to serve.
APP_DATABASE: The PKIDatabase object that will be creating and passed in.
"""
from waitress import serve
from flask import Flask, send_from_directory # TODO: Use this send_from_directory a... | laoluadewoye/PKI_Practice_Python | PKIPractice/Simulation/SocketUtils.py | .py | e4644dd5a72a88f8 | 7 | 0 |
"""
Testing module for command line interface.
"""
import unittest
import subprocess
import random
import string
from typing import List
import sys
from os.path import abspath, dirname, join, basename, curdir
script_dir = dirname(abspath(__file__))
if script_dir in ['PKI_Practice', 'PKI Practice', 'app']:
sys.pat... | laoluadewoye/PKI_Practice_Python | PKIPractice/tests/test_cli.py | .py | 82723df1ca1b9a04 | 7.5 | 0 |
"""
Module to test enumeration functionality.
"""
import unittest
import inspect
import random
import string
import sys
from os.path import abspath, dirname, join
script_dir = dirname(abspath(__file__))
if script_dir in ['PKI_Practice', 'PKI Practice', 'app']:
sys.path.append(abspath(script_dir))
elif script_dir ... | laoluadewoye/PKI_Practice_Python | PKIPractice/tests/test_enums.py | .py | 0e3559c9b257e217 | 7.5 | 0 |
"""
Module for testing the holder class.
"""
import unittest
from time import sleep
from random import choice, randint
import threading
from argparse import ArgumentParser
import sys
from os.path import abspath, dirname, join
script_dir = dirname(abspath(__file__))
if script_dir in ['PKI_Practice', 'PKI Practice', 'a... | laoluadewoye/PKI_Practice_Python | PKIPractice/tests/test_holder.py | .py | a4409d3ed3742e86 | 7.5 | 0 |
"""
Module for testing the network class.
"""
import unittest
import time
import tempfile
from threading import enumerate
from datetime import datetime
from typing import List
from argparse import ArgumentParser
import sys
from os.path import abspath, dirname, join, exists
script_dir = dirname(abspath(__file__))
if s... | laoluadewoye/PKI_Practice_Python | PKIPractice/tests/test_network.py | .py | 40f4575eb9015d50 | 7.5 | 0 |
import inspect
from dataclasses import dataclass, replace
from typing import Any, Protocol
import numpy as np
from slurmise.job_data import JobData
class ResourceFunction(Protocol):
def __call__(self, rule: Any, wildcards: Any, input: Any) -> Any: ...
def input(index: str | int | None = None) -> ResourceFunct... | PrincetonUniversity/slurmise | src/slurmise/extras/snake_parsers.py | .py | e25cf157324f83f6 | 7.3 | 3 |
from __future__ import annotations
import datetime
import hashlib
import json
import pathlib
from dataclasses import asdict, dataclass, field
import joblib
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.metrics import mean_squared_error
from skle... | PrincetonUniversity/slurmise | src/slurmise/fit/resource_fit.py | .py | 10c376336dfd9ad7 | 7.3 | 3 |
from __future__ import annotations
from dataclasses import astuple, dataclass, field
import h5py
import numpy as np
def array_safe_eq(a, b) -> bool:
"""
Check if a and b are equal, even if they are numpy arrays.
When a and be are dictionaries call recursively for all key, value pairs.
"""
if a ... | PrincetonUniversity/slurmise | src/slurmise/job_data.py | .py | 04da97c52106dc60 | 7.3 | 3 |
from __future__ import annotations
import contextlib
import dataclasses
import os
import time
from collections.abc import Generator
from typing import Any
import h5py
import numpy as np
from slurmise import slurm
from slurmise.job_data import JobData
class JobDatabase:
"""
This class creates the database t... | PrincetonUniversity/slurmise | src/slurmise/job_database.py | .py | c8163675e62a95d2 | 7.3 | 3 |
from __future__ import annotations
import json
import os
import subprocess
from math import ceil
JOB_ID_ENV_VARS = ("SLURM_JOB_ID", "SLURM_JOBID") # modern name first; SLURM sets both
def get_current_job_id() -> str | None:
"""Return the job ID of the current SLURM job, or None when not inside a SLURM job."""
... | PrincetonUniversity/slurmise | src/slurmise/slurm.py | .py | a4405be998cfa0a6 | 7.3 | 3 |
import multiprocessing
import time
from unittest import mock
import pytest
from slurmise import job_database
from slurmise.api import Slurmise
from slurmise.job_data import JobData
def slurmise_record(toml, process_id, error_queue):
def mock_metadata(kwargs):
return {
"slurm_id": kwargs["slu... | PrincetonUniversity/slurmise | tests/test_api.py | .py | 294541e764e47b2a | 7.8 | 3 |
import pandas as pd
import logging
import wget
import os
class MeasurementReader():
def __init__(self, measurement='dew_point'):
self.measurement = measurement
self.dl_path = f'dl_{measurement}.csv'
self.col_name = {
'pressure_qnh': 'Pressure hPa',
'pressure_qfe': '... | marc-moreaux/silvaplana_winds | src/merge_measurements.py | .py | 8c05bbf2c9633d41 | 7 | 0 |
# app_paths.py
"""Decides where the player keeps the files it writes.
The player writes four things: `music.ini`, `play_history.json`,
`song_metadata_cache.json`, and `custom_practice_types.json` from the practice
type editor. They have always lived beside `music_player.py`, which is right for
a git checkout and for a... | rrusk/DancePracticeMusicPlayer | app_paths.py | .py | d240a8d76655fa45 | 7 | 0 |
# song_cache.py
"""A small on-disk cache of song metadata for the Dance Practice Music Player.
Reading tags with TinyTag is cheap on a fast machine and not cheap at all on the
older laptops used at practices, where every "New Playlist" re-reads the header of
every song it considers. This caches what `TinyTag.get` retu... | rrusk/DancePracticeMusicPlayer | song_cache.py | .py | f25d92b74f3afe86 | 7 | 0 |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
Scans a directory for audio files to find duplicates.
This script identifies duplicates by "normalizing" titles to find
files that are exact matches or semantically similar.
For example, it can match "A Wink and a Smile" with
"1-04 F - 29_2_41 M - A Wink & A Smile"... | rrusk/DancePracticeMusicPlayer | utils/detect_duplicates.py | .py | b37fb9c0cff60c03 | 7 | 0 |
#!/usr/bin/env python3
"""
Collision Detector
Scans the source library and checks if multiple input files
map to the exact same output filename.
"""
import os
import sys
import re
import mutagen
# --- COPYING EXACT LOGIC FROM YOUR MAIN SCRIPT ---
def smart_title(s):
if not s: return ""
s = str(s).title()
... | rrusk/DancePracticeMusicPlayer | utils/find_name_collisions.py | .py | 6117c71b6b7cf003 | 7 | 0 |
import ply.lex as lex
import sys
reserved = {
'if': 'IF',
'then': 'THEN',
'else': 'ELSE',
'fdef': 'FDEF',
'let': 'LET',
'int':'INT',
'float':'FLOAT',
'char':'CHAR',
'bool':'BOOL',
'alias':'ALIAS',
'undefined':'UNDEFINED',
# misc
'//': 'DIV',
'->':'RARROW',
'.... | acmota2/fpy | src/lexer.py | .py | c32afbf8cfc30ce3 | 7 | 0 |
import ply.lex as lex
import sys
reserved = {
'if': 'IF',
'then': 'THEN',
'else': 'ELSE',
'fdef': 'FDEF',
'let': 'LET',
'int':'INT',
'float':'FLOAT',
'char':'CHAR',
'bool':'BOOL',
'alias':'ALIAS',
'undefined':'UNDEFINED',
# misc
'//': 'DIV',
'->':'RARROW',
# ... | acmota2/fpy | src/testing/python_files/lexer_tester.py | .py | 62843c07692c9e34 | 7.5 | 0 |
"""Application services for interacting with DomainBib objects during processing."""
from __future__ import annotations
import io
import logging
from collections import Counter
from typing import Any
from overload_web.application import ports
from overload_web.domain.pvf import bibs, cataloging_rules
logger = loggi... | BookOps-CAT/overload-web | overload_web/application/pvf/marc.py | .py | c190e6a70ee90ef0 | 7 | 0 |
"""Application service for matching incoming records against ports.
This module defines the `BibMatcher`, an application service responsible for
finding duplicate records in Sierra for a `DomainBib`. Matching is based on
specific identifiers such as OCLC number, ISBN, or Sierra Bib ID.
"""
from __future__ import anno... | BookOps-CAT/overload-web | overload_web/application/pvf/match_service.py | .py | 9859d28f2ef6ce25 | 7 | 0 |
"""Application services to use when reporting on process vendor file services."""
import logging
from typing import Any
from overload_web.application import ports
from overload_web.domain.pvf import reporting
logger = logging.getLogger(__name__)
class PVFReporter:
@staticmethod
def create_output_report(dat... | BookOps-CAT/overload-web | overload_web/application/pvf/report_services.py | .py | e36e9c02f8141c8b | 7 | 0 |
"""Domain models that define order templates.
Classes:
`OrderTemplateBase`
Defines a base entity for an order template. This includes all fields required for
creating or updating an order template.
`OrderTemplate`
Defines an order template domain entity. This includes all fields required for
persistin... | BookOps-CAT/overload-web | overload_web/domain/pvf/order_templates.py | .py | 0b7b211befda8c27 | 7 | 0 |
"""Domain models that define of vendor-supplied MARC files.
Classes:
`VendorFile`
Represents a vendor file.
"""
from __future__ import annotations
from dataclasses import dataclass
@dataclass(kw_only=True)
class VendorFile:
"""
Represents a vendor file.
Attributes:
content: binary content... | BookOps-CAT/overload-web | overload_web/domain/shared/files.py | .py | ed5e3a8a2a1d172b | 7 | 0 |
"""Adapter module that defines classes and models related to batches of processed files.
Classes:
`PVFBatchRepository`
`SQLModel` implementation of `SqlRepositoryProtocol` for managing
`PVFBatch` objects in a SQL database.
Models:
`PVFBatch`
A pydantic/sqlmodel model that defines a batch containing one ... | BookOps-CAT/overload-web | overload_web/infrastructure/batch_db.py | .py | 1536bf9adc3c8b3c | 7 | 0 |
"""
Local and FTP/SFTP file I/O implementations for Overload.
This module contains classes to load files from and write files to local
directories and remote FTP/SFTP servers. The classes that interact with remote
directories within this module use the BookOps/file-retriever library.
The classes within this module are... | BookOps-CAT/overload-web | overload_web/infrastructure/file_io.py | .py | 70f59b754c6eb2af | 7 | 0 |
"""Adapter module defining classes used to parse and update MARC records.
Includes wrapper that allows for MARC records to be translated from pymarc/bookops_marc
objects to domain objects. The `MarcEngine` service also updates and extracts values
from fields.
Protocols:
`DomainBibProtocol`
A protocol that define... | BookOps-CAT/overload-web | overload_web/infrastructure/marc_engine.py | .py | 41f30c98e37a59e7 | 7 | 0 |
"""Adapter module that defines a handlers used to create and write processing reports.
Classes:
`ReportHandler`
Concrete implementation of `ReportHandler` protocol which generates reports from
processing statistics.
`GoogleSheetsReporter`
Concrete implementation of `ReportWriter` protocol which uses goog... | BookOps-CAT/overload-web | overload_web/infrastructure/reporter.py | .py | 60ba921b4e64e8dd | 7 | 0 |
"""Adapter module defining classes used to fetch bib records from Sierra.
Includes wrappers for session object in `bookops_bpl_solr` and `bookops_nypl_platform`
libraries and a class that uses these sessions to fetch bib records from Sierra.
Protocols:
`SierraSessionProtocol`
Abstracts methods required for a Sie... | BookOps-CAT/overload-web | overload_web/infrastructure/sierra_clients.py | .py | 8b3cb9b05a1750e9 | 7 | 0 |
"""Adapter module that defines a relational database and associated tables for
order template (`TemplateModel`) objects.
Classes:
`OrderTemplateRepository`
`SQLModel` implementation of `SqlRepositoryProtocol` for managing
`TemplateModel` objects in a SQL database.
Models:
`_TemplateModelBase`
The base d... | BookOps-CAT/overload-web | overload_web/infrastructure/template_db.py | .py | 5596be8115667af5 | 7 | 0 |
"""Dependency injection functions."""
from __future__ import annotations
import json
import logging
import os
from typing import Annotated, Any, Generator, Literal
from fastapi import Depends, Form
from pydantic import BaseModel, field_validator, model_validator
from sqlmodel import Session, SQLModel, create_engine
... | BookOps-CAT/overload-web | overload_web/presentation/deps.py | .py | bcd318461cc3f516 | 7 | 0 |
"""Frontend router used to generate pages using `Jinja2` templates.
Serves HTML pages for Overload Web's user interface.
"""
from __future__ import annotations
import logging
import uuid
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
logger = logging.getLogger(__name__)
fronten... | BookOps-CAT/overload-web | overload_web/presentation/routers/frontend.py | .py | a4c39b01c0ef8312 | 7 | 0 |
from psi.application import configure_logging
#configure_logging('DEBUG')
import importlib
# NOTE: do NOT set pg.setConfigOptions(useOpenGL=True) here. It was
# previously enabled to make cftscal's result plots smoother, on the
# assumption that it stayed isolated to cftscal's own process and never
# reached psiexper... | psiexperiment/cftscal | cftscal/main.py | .py | 610391da91ad7ded | 7 | 0 |
'''
One-off cleanup script, specific to labs that run Thevenin-equivalent
calibrations for their starships.
A Thevenin-equivalent calibration uses a special-case coupler (named with a
``TH-`` prefix, e.g. ``TH-32``) that isn't a normal in-ear coupler -- it's
only used to compute the starship's Thevenin equivalent circ... | psiexperiment/cftscal | cftscal/migrate_thevenin.py | .py | 0c5230055548b4fb | 7 | 0 |
'''
Seeds psiexperiment's per-paradigm default layout/preferences files from
cftscal's own packaged copies, so a fresh cftscal install starts from a
curated dock-panel arrangement instead of Enaml's unopinionated default.
psi itself already has this concept -- ``psi.get_default_layout``/
``psi.get_default_preferences`... | psiexperiment/cftscal | cftscal/paradigms/default_state.py | .py | 2aa397b5cdca5720 | 7 | 0 |
'''
Exports a recording to a calibrated WAV file.
A value of 1.0 in the exported WAV file represents 1 Pascal. Arbitrary
JSON-serializable metadata (e.g. sensitivity, microphone identity,
calibration date) is embedded in a custom RIFF chunk tagged ``CFTS``,
appended after the standard ``data`` chunk. Programs that don... | psiexperiment/cftscal | cftscal/plugins/export.py | .py | 26c35c50c9d27230 | 7 | 0 |
from atom.api import Dict, Int, set_default, List, Str, Typed
from ..settings import (
CalibrationSettings, GeneratorSettings, InputSettings,
MultiTypeSensorReference,
)
class InputRecordingSettings(CalibrationSettings):
available_inputs = List(Typed(InputSettings, ())).tag(persist=True)
generator =... | psiexperiment/cftscal | cftscal/plugins/input_recording/settings.py | .py | 973cfcd7ccd46993 | 7 | 0 |
from atom.api import Atom, Bool, Event, Value, List, observe
class ObjectNode(Atom):
'''
Represents a single recording or calibration in the tree hierarchy
'''
selected = Bool(False)
item = Value()
parent = Value()
color = Value(None)
def _observe_selected(self, event):
if self... | psiexperiment/cftscal | cftscal/plugins/object_collection.py | .py | 348602475d9dc9d5 | 7 | 0 |
'''
Tests for the plugin-loading logic in :mod:`cftscal.plugins.manifest`.
Focus on ``_CalibrationPluginManifest._get_available``'s two ways a
plugin can be considered available: hardware detection via
``settings_config`` probes (the original behavior), and a plugin's id
being force-enabled via ``WorkspaceSettings.ena... | psiexperiment/cftscal | tests/test_manifest.py | .py | ab73da1866924635 | 7.5 | 0 |
'''
Tests for :mod:`cftscal.plugins.widgets`.
'''
import enaml
import pytest
with enaml.imports():
from cftscal.plugins.widgets import BasePlotManager, SensorView, _remove_selected
import pyqtgraph as pg
class TestCreatePlot:
'''
create_plot() must build a ``pg.PlotDataItem``, not a bare
``pg.PlotCu... | psiexperiment/cftscal | tests/test_widgets.py | .py | fae786066ca4e6b9 | 7.5 | 0 |
import yaml
from easydict import EasyDict
from django.utils.functional import classproperty
from schema import Schema, SchemaError
from helpers.logger import logger
class Config:
"""
The configuration of LDM.
USAGE:
from core.config import Config
Config.current. ...
"""
config_schema =... | ETH-NEXUS/lab_data_management | api/app/core/config.py | .py | 33fe4d9a2c774928 | 7.35 | 4 |
from string import ascii_uppercase
import re
def charToAlphaPos(letters: str):
"""
Maps a character sequence to a number
A,a -> 1
B,b -> 2
...
Z,z -> 26
AA,aa -> 27
AB,ab -> 28
...
AZ,az -> 52
"""
if not re.match(r"[A-z]+", letters):
raise ValueError("Only lette... | ETH-NEXUS/lab_data_management | api/app/core/helper.py | .py | 9df358919db75c98 | 7.35 | 4 |
from django.core.management.base import BaseCommand
from django.core.management import call_command
import traceback
from django.conf import settings
from django.db import connection, connections
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("action", type=str, help="Th... | ETH-NEXUS/lab_data_management | api/app/core/management/commands/db.py | .py | 7b142813e0fa3535 | 7.35 | 4 |
import time
from django.core.management.base import BaseCommand
from django.db import connections
from django.db.utils import OperationalError
class Command(BaseCommand):
"""Django command to pause execution until database is available"""
def handle(self, *args, **options):
self.stdout.write("Waiting... | ETH-NEXUS/lab_data_management | api/app/core/management/commands/wait_for_db.py | .py | 8bfd9d5d1bd86688 | 7.35 | 4 |
import yfinance as yf
import sys
from dataclasses import dataclass
import numpy as np
from datetime import datetime, timedelta
from sklearn.preprocessing import StandardScaler
@dataclass
class ProcessTickerData:
ticker : str
def _generate(self):
"""
Generate historical data and derive... | MunjPatel/LSTM-FinTrends | preprocessing.py | .py | da12b47d6aec5334 | 7.3 | 3 |
import random
from datetime import UTC, datetime
from enum import Enum
from unittest.mock import MagicMock, patch
import django
import pytest
from datedelta import datedelta
from django.conf import settings
from django.contrib.auth.models import Group
from django.core.exceptions import ValidationError
from django.core... | ThePalaceProject/virtual-library-card | tests/test_models.py | .py | 2936e5f537a89d90 | 7.74 | 2 |
"""AniList feed rendering: one activity as a card, a busy tick's remainder as a digest.
The spoiler-safe, security-grade post/embed construction. :class:`ActivityCard`
turns one normalised activity into a Components V2 card and :class:`ActivityDigest`
coalesces a busy tick's remainder into one compact card; both lean ... | yaniswav/Yasuho | cogs/anilist/feed_render.py | .py | d02fc4a932d527ca | 7.24 | 2 |
"""The /anilist discoverability hub: one author-restricted Components V2 panel.
The bare ``anilist`` group used to print help; it now opens this hub, a single
LayoutView that routes into the EXISTING lookup / browse / account flows. Nothing
here re-implements those flows: each button re-enters a shared seam on the cog... | yaniswav/Yasuho | cogs/anilist/hub.py | .py | 0b5a55e76323b451 | 7.24 | 2 |
"""One rule for every reply this package sends: it can never ping.
THE HAZARD. Almost everything the AniList cogs say back carries text somebody
else wrote - a media title fetched from AniList, the search term the member
typed, an AniList username - quoted into the message CONTENT ("Found {count}
results for **{search... | yaniswav/Yasuho | cogs/anilist/replies.py | .py | 72ce5ef207367ad3 | 7.24 | 2 |
"""Interactive AniList API-abuse throttle (audit P-2).
The background pollers (airing / feed / chapters) share AniList's per-IP 429
budget with every user-driven lookup and interactive button click. A promo spike
of clicks or ``/search`` could burn that shared budget and silently degrade the
alert pollers for ALL guil... | yaniswav/Yasuho | cogs/anilist/throttle.py | .py | 024500c45bdbf7b7 | 7.24 | 2 |
"""AFK statuses: a member says they are away, and anyone pinging them is told.
TWO PROPERTIES THE FIRST VERSION DID NOT HAVE, both of them about the fact that
the status is FREE TEXT its author typed once and the bot then re-broadcasts on
a trigger anybody else can pull:
* IT IS PER GUILD. The status is stored agains... | yaniswav/Yasuho | cogs/community/afk.py | .py | e84754a2efb0949b | 7.24 | 2 |
"""Per-user and per-guild language selection for Yasuho's replies.
This is the user-facing half of the i18n system (see tools/i18n.py). The locale
is stored as a "locale" key in the JSONB user/guild settings and read back by
i18n.resolve_locale on every command.
"""
import logging
import discord
from discord.ext imp... | yaniswav/Yasuho | cogs/community/language.py | .py | a0fc8bccd0824499 | 7.24 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.