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 |
|---|---|---|---|---|---|---|
'''
Leetcode 1268. Search Suggestions System
Output at most 3 sorted word suggestions when typing each letter of searchWord
Use binary search to find the start-stop positions of current input in sorted words array
'''
from typing import List
from bisect import bisect_left, bisect_right
class Solution:
def sugges... | YL159/blog_app | problems/1268_Search_Suggestions.py | .py | bc37332710592362 | 7 | 0 |
'''
Leetcode 1269. Number of Ways to Stay in the Same Place After Some Steps
Given an array of fixed length arrLen, a pointer starting at index 0
For each step, the pointer can move to left 1 slot, stay or right 1 slot.
pointer can't move out of the array at any time
Find the number of ways to stay at index 0 after ex... | YL159/blog_app | problems/1269_Ways_to_Stay_After_Steps.py | .py | 7aa45f5b8dcbb67b | 7 | 0 |
'''
Leetcode 1283. Find the Smallest Divisor Given a Threshold
Given an array of numbers, find the smallest divisor, so that the sum(ceil(number/divisor)) <= threshold.
Use double binary search.
Outer loop binary search the divisor in [1, max(nums)] range.
Result of a divisor can be obtained by counting the numbers wi... | YL159/blog_app | problems/1283_Smallest_Divisor_with_Threshold.py | .py | 019eee7f205b3782 | 7 | 0 |
'''
Leetcode 1314. Matrix Block Sum
Use prefix sum matrix to reduce complexity from O(mnk^2) to O(mn)
Prefix sum of rows of matrix only reduce to O(mnk)
'''
from typing import List
class Solution:
def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]:
n, m = len(mat), len(mat[0])
... | YL159/blog_app | problems/1314_Matrix_Block_Sum.py | .py | 2ef9d1c07ed930a1 | 7 | 0 |
'''
Leetcode 1319. Number of Operations to Make Network Connected
Find min operations to make computer graph connected, use existing cables(edges)
# of edges should be at least n-1, then computer group - 1 is the minimum operation needed to connect them all
'''
from typing import List
class Solution:
def makeCon... | YL159/blog_app | problems/1319_Num_Op_Network_Connected.py | .py | f8edfe3708fbe91c | 7 | 0 |
'''
Leetcode 1335. Minimum Difficulty of a Job Schedule
Partition a job list into exactly d non-empty parts/days.
Difficulty of each day is max(difficulty(jobs of a day)).
Find min total difficulty of all d days.
Similar to #813 largest sum of avg, find min difficulty of:
1st job allocated into 1 day -> all job alloc... | YL159/blog_app | problems/1335_Min_Difficulty_Job_Schedule.py | .py | 213c74d1c6a519a8 | 7 | 0 |
'''
Leetcode 1353. Maximum Number of Events That Can Be Attended
Given a list of events with [start, end] day number
Each day can only attend 1 event that has end >= current day
Find max number of events to attend
For each day, we should attend 1 event if there is any available
If multiple events ends at current day, ... | YL159/blog_app | problems/1353_Max_Number_of_Events_Attended.py | .py | 0f4b5432d4c70df8 | 7 | 0 |
'''
Leetcode 1354. Construct Target Array With Multiple Sums
Start from a list arr of 1, for each operation:
replace arr[i] with sum(arr), i is free to choose
Find if possible to construct arr to target array with any # of operations.
Observation:
target number (not 1) showing twice is impossible
arr sum is always in... | YL159/blog_app | problems/1354_Construct_Target_Arr_With_Multiple_Sums.py | .py | b5163962e38f38dd | 7 | 0 |
'''
leetcode 1358. Number of Substrings Containing All Three Characters
Find the number of substrings containing a, b, c
Method 1, left index incremental
Use matrix and index reference to keep track of current triplet of tight abc substring
And count its right options. Left option is always 1 because s contains only a... | YL159/blog_app | problems/1358_Number_of_abc_Subs.py | .py | b364c0297ea7cfa3 | 7 | 0 |
'''
Leetcode 1361. Validate Binary Tree Nodes
Given n nodes and their left/right child array, check if they form 1 valid tree.
Form an adjacency map of all nodes.
If parent nodes not exactly 1 more than parent.intersect(children), invalid.
When BFS on the root, if a child is already visited or appear again in the same... | YL159/blog_app | problems/1361_Validate_BT_Nodes.py | .py | 9cc30e7d24b2d28c | 7 | 0 |
'''
Leetcode 1371. Find the Longest Substring Containing Vowels in Even Counts
As title describes. Vowels are 'aeiou'
Standard solution uses bit mask prefix XOR to note each vowel's count parity.
And bit mask is translated(hash) to idx of last appearance array.
Here is the same general idea with different approach
Us... | YL159/blog_app | problems/1371_Longest_Substr_Even_Vowels.py | .py | f354a1ff07dc2631 | 7 | 0 |
import json
from compression import zstd
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import click
from click.core import Context
from jinja2 import Template
from loguru import logger
from app.core.config import Configuration
from app.core.notify import send_feishu_updates, send_mail
from a... | designinlife/version-checker | src/app/commands/combine.py | .py | 12982398d1a4bee2 | 7 | 0 |
import base64
import hashlib
import hmac
import os
import smtplib
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr
from typing import List, Optional
import requests
from loguru import logger
FEISHU_WEBHOOK_URL = "https://open.feishu.cn/... | designinlife/version-checker | src/app/core/notify.py | .py | 19ff594a61c2214a | 7 | 0 |
def strtobool(val):
"""Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = val.lower()
if val in ("y", "yes... | designinlife/version-checker | src/app/core/utils.py | .py | 058e20082792d23f | 7 | 0 |
import re
from typing import Any, List, Mapping, Optional, Tuple
from pydantic import BaseModel
class Version(BaseModel):
"""正则命名组解析后的版本对象,保留原始字符串和解析器附带的原始数据。"""
major: int
minor: Optional[int] = None
patch: Optional[int] = None
build: Optional[int] = None
letter: Optional[str] = None
ve... | designinlife/version-checker | src/app/core/version.py | .py | 57389f9a4889c80d | 7 | 0 |
import importlib
import json
import operator
import os
from abc import ABCMeta, abstractmethod
from asyncio import Semaphore
from typing import Dict, List, Mapping, Optional, Tuple
import aiofiles
import arrow
from loguru import logger
from app.core.config import AppSettingSoftItem, Configuration, OutputResult
from a... | designinlife/version-checker | src/app/parser/__init__.py | .py | bc055b0e937279e0 | 7 | 0 |
import asyncio
import re
from asyncio import Semaphore
from loguru import logger
from app.core.config import GitLsRemoteSoftware
from app.core.version import VersionHelper
from . import Base
class Parser(Base):
async def handle(self, sem: Semaphore, soft: GitLsRemoteSoftware):
"""执行 `git ls-remote --ta... | designinlife/version-checker | src/app/parser/git_ls_remote.py | .py | deb12db0b8e28343 | 7 | 0 |
import importlib
from typing import Iterable, Type
from app.core.config import AppSettingSoftItem
from app.parser import Base
def parser_to_module_name(parser_name: str) -> str:
"""把配置中的 parser 名称转换为对应的 Python 模块名。"""
return parser_name.replace("-", "_")
def load_parser_class(parser_name: str) -> Type[Base... | designinlife/version-checker | src/app/parser/registry.py | .py | b7e2b211913e2c2d | 7 | 0 |
#!/usr/bin/env python
#
# @license Apache-2.0
#
# Copyright (c) 2023 The Stdlib Authors.
#
# 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
#
# ... | stdlib-js/math-base-special-factorial2 | benchmark/python/scipy/benchmark.py | .py | 52da036159fcedd4 | 7.15 | 1 |
"""Trivial example of a hub-based analysis operation for interpretune framework testing."""
import torch
from interpretune.protocol import BaseAnalysisBatchProtocol, DefaultAnalysisBatchProtocol
class SomeDifferentBatchDef(BaseAnalysisBatchProtocol):
"""Example of batch definition for a trivial demo op."""
... | speediedan/interpretune | docs/notebook_artifacts/example_op_collections/hub_op_collection/hub_op_definitions.py | .py | 423bf5982fae43be | 7.24 | 2 |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | speediedan/interpretune | requirements/utils/collect_env_details.py | .py | bfc6c05166e26e09 | 7.24 | 2 |
#!/usr/bin/env python3
"""Prune packages that are ONLY dependencies of torch from a lockfile.
This reduces the dependency confusion attack surface when using unsafe-best-match
by removing any packages that could potentially be resolved from the nightly index only.
How it works:
1. Parse the lockfile to find all packa... | speediedan/interpretune | requirements/utils/prune_torch_deps.py | .py | 714ac622174fde96 | 7.24 | 2 |
#!/usr/bin/env python3
"""CLI wrapper for publishing a columnar dashboard run to a Hugging Face bucket or dataset repo.
All logic lives in :mod:`interpretune.utils.neuronpedia_dashboard_hub`; this file is argument
parsing and reporting only. See that module's docstring for what is excluded and why the page-index
check... | speediedan/interpretune | scripts/publish_dashboards_to_hub.py | .py | 2737406ef5e8da6c | 7.24 | 2 |
#!/usr/bin/env python3
"""Notebook Publisher Script.
Copies notebooks from dev/ to publish/ directory, strips "remove-cell" tags,
and adds Colab badges and installation cells for published versions.
Usage:
python scripts/publish_notebooks.py [--dry-run] [--check-only] [--force]
Options:
--dry-run: Show what ... | speediedan/interpretune | scripts/publish_notebooks.py | .py | e875d0e37f26cdb3 | 7.24 | 2 |
#!/usr/bin/env python3
"""Compute a short top-5 package-change summary from a git diff patch.
Usage: python scripts/regen_summary.py <patch_path> <out_path>
Writes an empty file if no package-like changes are found.
"""
from pathlib import Path
import re
import sys
def parse_req(line: str):
# strip leading +/- ... | speediedan/interpretune | scripts/regen_summary.py | .py | 2d3933b8ad30499a | 7.24 | 2 |
import argparse
import json
from collections import defaultdict
from pathlib import Path
try:
from tabulate import tabulate # type: ignore
except Exception:
# lightweight fallback if tabulate isn't installed
def tabulate(rows, headers, **_kwargs): # type: ignore
header_line = " | ".join(headers)
... | speediedan/interpretune | scripts/speedscope_top_packages.py | .py | 8e1cefc8a8a53711 | 7.24 | 2 |
"""
Interpretune
=====================
The interpretune package provides analysis tools for exploring model interpretability.
"""
import os
import sys
from importlib.abc import MetaPathFinder
from importlib.machinery import ModuleSpec
from importlib.metadata import version, PackageNotFoundError
# we ignore these for... | speediedan/interpretune | src/interpretune/__init__.py | .py | d07344b9fe30e24c | 7.24 | 2 |
"""Adapter registry with lazy initialization.
We intentionally defer the light-weight adapter registration pass until the registry is first accessed. This mirrors the
lazy-loading pattern used by the example module registry and avoids importing optional heavy dependencies at package
import time while still ensuring th... | speediedan/interpretune | src/interpretune/adapter_registry.py | .py | 79c89f61e6d096d4 | 7.24 | 2 |
"""Adapters package lazy exports.
This module exposes adapter classes/registries lazily to avoid importing heavy third-party dependencies (e.g.,
transformer_lens, sae_lens, nnsight) at package import time.
"""
_LAZY_ADAPTER_ATTRS = {
"ADAPTER_REGISTRY": "interpretune.adapter_registry.ADAPTER_REGISTRY",
"Compo... | speediedan/interpretune | src/interpretune/adapters/__init__.py | .py | 97ef9ae21a5ba8a6 | 7.24 | 2 |
"""Lightweight adapter registration utilities.
This module performs the minimal imports necessary to populate the
`ADAPTER_REGISTRY` by calling `register_adapter_ctx` on adapter classes.
It intentionally avoids importing heavy runtime dependencies to enable
adapter implementation modules to be written (optionally) to ... | speediedan/interpretune | src/interpretune/adapters/_light_register.py | .py | dc86757112feb540 | 7.24 | 2 |
from __future__ import annotations
from typing import TYPE_CHECKING
from transformers.tokenization_utils_base import BatchEncoding
from interpretune.base import CoreHelperAttributes, BaseITModule, ITDataModule
from interpretune.utils import to_device
from interpretune.protocol import Adapter
if TYPE_CHECKING:
fr... | speediedan/interpretune | src/interpretune/adapters/core.py | .py | 1e2c31cae77fd17f | 7.24 | 2 |
from interpretune.base import ITDataModule, BaseITModule
from interpretune.utils import _LIGHTNING_AVAILABLE
from interpretune.protocol import Adapter
from interpretune.adapters import CompositionRegistry
if _LIGHTNING_AVAILABLE:
from lightning.fabric.utilities.device_dtype_mixin import _DeviceDtypeModuleMixin
... | speediedan/interpretune | src/interpretune/adapters/lightning.py | .py | 658c88f0bbd31ffd | 7.24 | 2 |
from __future__ import annotations
from typing import Any, Tuple, Callable, Type, Protocol, Set, runtime_checkable, Sequence, cast
from inspect import getmembers, isclass
from typing_extensions import override
from types import ModuleType
from pprint import pformat
from interpretune.utils import rank_zero_warn
from in... | speediedan/interpretune | src/interpretune/adapters/registration.py | .py | a4974f3775415784 | 7.24 | 2 |
"""Backend capability enums, module capability aggregation, and the named-backend registry.
Part of the sanctioned :mod:`interpretune.analysis.backends` seam that op implementations (bundled,
local, or hub) may import. Ops should ask for capabilities rather than branching on backend or
adapter class names.
"""
from _... | speediedan/interpretune | src/interpretune/analysis/backends/capabilities.py | .py | 7542e03ded79eafb | 7.24 | 2 |
"""Feature-selection specs and filters shared by feature-attribution ops.
Part of the sanctioned :mod:`interpretune.analysis.backends` seam that op implementations (bundled,
local, or hub) may import.
"""
from __future__ import annotations
from dataclasses import dataclass, field
import torch
@dataclass
class Fea... | speediedan/interpretune | src/interpretune/analysis/backends/feature_selection.py | .py | d000740c304089de | 7.24 | 2 |
"""TransformerLens model backend implementation."""
from __future__ import annotations
from collections.abc import Mapping, Sequence
from typing import Any, Callable
import torch
from interpretune.analysis.backends import (
BackendCapability,
InterventionDict,
InterventionValue,
apply_intervention_t... | speediedan/interpretune | src/interpretune/analysis/backends/impls/transformer_lens.py | .py | fc17b6b90ba7f2da | 7.24 | 2 |
from logging.config import fileConfig
import os
from alembic import context
from app.db.database import create_sync_engine
from app.db.models import Base
# Import all model modules here so autogenerate can detect them.
import app.db.models # noqa: F401
# this is the Alembic Config object, which provides
# access t... | fedecarboni7/armar-equipos | alembic/env.py | .py | d35040b92a449167 | 7.15 | 1 |
"""add google_id to users
Revision ID: 3748d7264451
Revises: b03d8482acff
Create Date: 2026-05-18 20:31:50.816663
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "3748d7264451"
down_revision: Union[str, Sequence[str], N... | fedecarboni7/armar-equipos | alembic/versions/3748d7264451_add_google_id_to_users.py | .py | 001834f87b99e232 | 7.15 | 1 |
"""change matches played_at to date
Revision ID: 4c2f6d9e1b7a
Revises: 8b1e2f3a9f7b
Create Date: 2026-05-21
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "4c2f6d9e1b7a"
down_revision = "8b1e2f3a9f7b"
branch_labels = None
depends_on = None
def upgrade() -> N... | fedecarboni7/armar-equipos | alembic/versions/4c2f6d9e1b7a_change_matches_played_at_to_date.py | .py | ec4f8bb6888d9704 | 7.15 | 1 |
"""add match notes, goals, assists
Revision ID: 8b1e2f3a9f7b
Revises: c6a9f1b0c2d3
Create Date: 2026-05-20 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "8b1e2f3a9f7b"
down_revision = "c6a9f1b0c2d3"
branch_labels = None
depends_on = None
def... | fedecarboni7/armar-equipos | alembic/versions/8b1e2f3a9f7b_add_match_notes_goals_assists.py | .py | 43798bd1d2039e15 | 7.15 | 1 |
"""remove photo_data from players
Revision ID: 9f5f1df834e3
Revises: b7e5f2c3d4a6
Create Date: 2026-05-22 15:53:36.563043
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "9f5f1df834e3"
down_revision: Union[str, Sequence... | fedecarboni7/armar-equipos | alembic/versions/9f5f1df834e3_remove_photo_data_from_players.py | .py | 8e17ebbde9a2e2b3 | 7.15 | 1 |
"""add matches tables
Revision ID: c6a9f1b0c2d3
Revises: 3748d7264451
Create Date: 2026-05-19 00:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "c6a9f1b0c2d3"
down_revision: Union[str, Sequence[str], None]... | fedecarboni7/armar-equipos | alembic/versions/c6a9f1b0c2d3_add_matches_tables.py | .py | b4341a9f6b9bee9d | 7.15 | 1 |
"""add photo_url to players
Revision ID: c980ceef5766
Revises: d94d249f85cc
Create Date: 2026-07-22 17:25:25.642359
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "c980ceef5766"
down_revision: Union[str, Sequence[str],... | fedecarboni7/armar-equipos | alembic/versions/c980ceef5766_add_photo_url_to_players.py | .py | a2efe24c2590e608 | 7.15 | 1 |
"""rename player indexes to match model
Revision ID: d94d249f85cc
Revises: 9f5f1df834e3
Create Date: 2026-05-22 16:02:03.962660
"""
from typing import Sequence, Union
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "d94d249f85cc"
down_revision: Union[str, Sequence[str], None] = "9f... | fedecarboni7/armar-equipos | alembic/versions/d94d249f85cc_rename_player_indexes_to_match_model.py | .py | 48c44bdaf08deb9f | 7.15 | 1 |
"""add last_seen_at to users
Revision ID: f1a2b3c4d5e6
Revises: c980ceef5766
Create Date: 2026-07-23 00:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "f1a2b3c4d5e6"
down_revision: Union[str, Sequence[str]... | fedecarboni7/armar-equipos | alembic/versions/f1a2b3c4d5e6_add_last_seen_at_to_users.py | .py | aa605f932061dfc3 | 7.15 | 1 |
import asyncio
from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import JsonOutputParser
from app.config.llm import get_llm
# Define el template del prompt
formation_prompt = PromptTemplate(
input_variables=["num_players", "team_data", "allowed_formations"],
template="""
... | fedecarboni7/armar-equipos | app/utils/ai_formations.py | .py | c9192d3250f72ac3 | 7.15 | 1 |
import re
from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import JsonOutputParser
from app.config.llm import get_llm
# Limits for input validation
MAX_NAMES = 22 # Maximum player names to match (typical futbol 5/7/11 teams)
MAX_LINES = 30 # Allow extra lines for metadata like ma... | fedecarboni7/armar-equipos | app/utils/ai_player_matcher.py | .py | 6da3a3843558549e | 7.15 | 1 |
from datetime import datetime, timedelta, timezone
import secrets
from typing import Optional
from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
import jwt
from sqlalchemy.orm import Session
from app.db.models import User
from app.config.settings import Settings
SECRET_KEY =... | fedecarboni7/armar-equipos | app/utils/security.py | .py | a72b061cc94a4124 | 7.15 | 1 |
#!/usr/bin/env python3
"""Single source of truth for the CPython ABIs this project builds for.
Consumed two ways:
* Python (docker-build.py): ``import python_abis`` and read the values directly.
* Shell (build-twostage.sh, package-twostage.sh): ``eval "$(python python_abis.py)"``
which defines PYTHON_ABI_MINOR... | karellen/karellen-llvm | python_abis.py | .py | bec595e17dba4694 | 7.35 | 4 |
"""Authenticating a request with an API key.
Registered in DEFAULT_AUTHENTICATION_CLASSES only when API_KEYS_ENABLED is on,
alongside SessionAuthentication rather than instead of it -- the browser keeps
using cookies.
"""
import hmac
from django.utils import timezone
from rest_framework import exceptions
from rest_f... | DeltaV93/drf-starter | apps/api_keys/authentication.py | .py | 07eac5032ed1dc59 | 7.15 | 1 |
"""Long-lived credentials for programmatic access.
Session cookies work for a browser and for nothing else: no CLI, no CI job, no
server-to-server integration. This is the other credential.
The key is shown once, at creation, and never again. Only a digest is stored,
so a database dump, a backup or a stray log line y... | DeltaV93/drf-starter | apps/api_keys/models.py | .py | 296276385f4a93a8 | 7.15 | 1 |
"""Scope enforcement for key-authenticated requests."""
from rest_framework.permissions import SAFE_METHODS, BasePermission
from .models import APIKey
class HasWriteScope(BasePermission):
"""Refuse unsafe methods to a read-only key.
Requests that did not come from a key are unaffected: a browser session
... | DeltaV93/drf-starter | apps/api_keys/permissions.py | .py | aeb5575aa55e8df6 | 7.15 | 1 |
"""Teaching drf-spectacular about the API-key credential.
Without this the generator cannot resolve `APIKeyAuthentication` and drops it
with a warning, so the published schema documents session cookies as the only
way in -- while the README hands out a curl command that uses a key. The
extension is imported from `apps... | DeltaV93/drf-starter | apps/api_keys/schema.py | .py | f5cd3e80fe4760b6 | 7.15 | 1 |
from django.utils import timezone
from rest_framework import serializers
from .models import APIKey
class APIKeySerializer(serializers.ModelSerializer):
"""A key as it appears in a listing.
There is no field for the secret, and there cannot be one: only a digest
is stored. The prefix identifies the key ... | DeltaV93/drf-starter | apps/api_keys/serializers.py | .py | 5838682dc35bb6ba | 7.15 | 1 |
"""API keys are opt-in; the app is not installed when the flag is off."""
import pytest
from django.conf import settings
collect_ignore_glob = [] if settings.API_KEYS_ENABLED else ['test_*.py']
@pytest.fixture
def make_key(db):
"""Create a key and hand back (APIKey, raw_key)."""
from apps.api_keys.models im... | DeltaV93/drf-starter | apps/api_keys/tests/conftest.py | .py | 0a85ff144351dc96 | 7.65 | 1 |
"""The secret exists once, in the response that created it.
If any of these fail, a key can be recovered by someone who should not have
it -- a staff member reading the admin, anyone with database access, or anyone
who can replay a listing response.
"""
import pytest
from django.urls import reverse
from apps.api_key... | DeltaV93/drf-starter | apps/api_keys/tests/test_key_secrecy.py | .py | 60c88a8a6bc26520 | 7.65 | 1 |
from rest_framework.throttling import UserRateThrottle
class APIKeyRateThrottle(UserRateThrottle):
"""A separate budget for machine traffic.
Integrations are legitimately noisier than a person clicking around, and
they should not spend the interactive user's allowance -- nor should a
runaway script e... | DeltaV93/drf-starter | apps/api_keys/throttles.py | .py | 49fa09e8b0419760 | 7.15 | 1 |
"""Managing your own API keys.
Session-only on purpose: minting a credential with a credential means a leaked
read key can be traded for a write key, and a stolen key can mint replacements
that survive revoking the original.
"""
from django.shortcuts import get_object_or_404
from drf_spectacular.utils import extend_s... | DeltaV93/drf-starter | apps/api_keys/views.py | .py | 77cf69418aece64a | 7.15 | 1 |
"""Recording an event.
`record()` is the only way in, and it allow-lists metadata per action. That is
the point: a caller passing a whole request body, a serializer's validated_data
or a model's __dict__ would put passwords, tokens and card numbers into a table
that is deliberately hard to edit and deliberately kept f... | DeltaV93/drf-starter | apps/audit/events.py | .py | 2730c6e05563dd2b | 7.15 | 1 |
"""Drop audit entries past the retention window.
The only sanctioned way rows leave the table. It deletes whole rows by age --
it cannot alter one -- and it uses a queryset delete so the model's own delete
guard does not have to be weakened.
"""
from datetime import timedelta
from django.conf import settings
from dj... | DeltaV93/drf-starter | apps/audit/management/commands/prune_audit_log.py | .py | fa7ab99760152cab | 7.15 | 1 |
"""An append-only record of the things worth being able to answer for.
Written from explicit call sites, not from a blanket signal. A signal on every
save records mostly noise and, worse, records whatever happens to be on the
model -- which is how a password hash or a card number ends up in an audit
table nobody thoug... | DeltaV93/drf-starter | apps/audit/models.py | .py | fa296ba77b29cfeb | 7.15 | 1 |
"""The audit app is opt-in; not installed when the flag is off."""
import pytest
from django.conf import settings
collect_ignore_glob = [] if settings.AUDIT_LOG_ENABLED else ['test_*.py']
@pytest.fixture
def signed_in(client):
from apps.users.factories import UserFactory
def _sign_in(user=None):
us... | DeltaV93/drf-starter | apps/audit/tests/conftest.py | .py | 2930ca47c11e4aa2 | 7.15 | 1 |
"""What may be stored, and what must never be.
The audit table is deliberately hard to edit and deliberately kept for a long
time, which makes it the worst possible place for a secret to land. Metadata is
allow-listed per action so a careless call site cannot widen it.
"""
import pytest
from apps.core.audit import A... | DeltaV93/drf-starter | apps/audit/tests/test_metadata_is_allowlisted.py | .py | 36cc1c87e8e63a9f | 7.65 | 1 |
"""Reading the audit log.
Scoped to the caller's own events. There is no endpoint that returns everybody's
-- staff read the admin, which is authenticated and access-controlled
separately, rather than through an API surface a stolen session could reach.
"""
from drf_spectacular.utils import extend_schema
from rest_fr... | DeltaV93/drf-starter | apps/audit/views.py | .py | f90b55af95f80034 | 7.15 | 1 |
"""Two-factor enrolment.
The rest of this app is views, serializers and permissions; the user model
lives in apps.users. These two tables exist because TWO_FACTOR_ENABLED gates
behaviour rather than INSTALLED_APPS -- see apps/authentication/two_factor.py.
"""
from django.conf import settings
from django.db import mod... | DeltaV93/drf-starter | apps/authentication/models.py | .py | 303fdf874f870fbe | 7.15 | 1 |
from rest_framework.permissions import BasePermission
class IsEmailVerified(BasePermission):
"""Require a confirmed email address.
Not applied globally: signup leaves the user logged in but unverified so
they can look around. Add this to the views that must not be reachable
until the address is confi... | DeltaV93/drf-starter | apps/authentication/permissions.py | .py | 41947ce9c007a5be | 7.15 | 1 |
from django.contrib.auth import authenticate, get_user_model
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError as DjangoValidationError
from rest_framework import serializers
from apps.users.serializers import UserSerializer
User = get_user_model(... | DeltaV93/drf-starter | apps/authentication/serializers.py | .py | 300946b4588c3413 | 7.15 | 1 |
from rest_framework import serializers
class TwoFactorStatusSerializer(serializers.Serializer):
enabled = serializers.BooleanField()
pending = serializers.BooleanField()
recovery_codes_remaining = serializers.IntegerField()
class TwoFactorPasswordSerializer(serializers.Serializer):
"""Re-authenticat... | DeltaV93/drf-starter | apps/authentication/serializers_two_factor.py | .py | c558fa9f824bbf3f | 7.15 | 1 |
"""The social-auth pipeline, and the one decision in it that matters.
python-social-auth's default pipeline includes `associate_by_email`, which
hands a social identity the existing account with the same address. That is an
account-takeover path: anyone who can make a provider assert an address --
through a provider t... | DeltaV93/drf-starter | apps/authentication/social_pipeline.py | .py | 523056ef5d904814 | 7.15 | 1 |
"""
Serviço de Scraping — adapta o pipeline de coleta (core.scraping) ao WebSocket,
sem depender de input()/print() do console.
Toda a lógica de coleta (Selenium, HTTP API v2, paginação, dedupe) vive em
core/scraping/. Aqui só fazemos a ponte: normalizar a URL/opção e traduzir os
logs/contadores do pipeline para os ev... | Felipe-Alcantara/SoundScraper-soundcloud_track_scraper_downloader | backend/services/scraper_service.py | .py | 3b69105dd4b125e3 | 7.3 | 3 |
"""
platform_utils.py — Helpers cross-platform compartilhados pelo CLI e pelo backend.
Centraliza tudo que depende do sistema operacional (nome do binário do FFmpeg,
localização do FFmpeg, abertura da pasta de destino) para que SoundScraper funcione
de forma idêntica em Windows, Linux e macOS — sem código preso a um S... | Felipe-Alcantara/SoundScraper-soundcloud_track_scraper_downloader | core/platform_utils.py | .py | b3dbab5b88f52120 | 7.3 | 3 |
"""
http_api.py — Adapter de coleta via API v2 do SoundCloud (sem navegador).
É o método PREFERIDO: não depende de Chrome/Selenium, é estável e funciona em
qualquer SO. Faz apenas o I/O HTTP (urllib, sem dependências extras) e delega
todo o parsing para core/scraping/parsers.py (testável offline).
"""
import time
fro... | Felipe-Alcantara/SoundScraper-soundcloud_track_scraper_downloader | core/scraping/adapters/http_api.py | .py | 603250ebf77cb72a | 7.3 | 3 |
"""
base.py — Interface Strategy comum a todos os métodos de coleta.
Cada método (HTTP API, Selenium, ...) implementa um SourceAdapter. O pipeline
não precisa conhecer detalhes de cada um — só a interface. Adicionar um método
novo é criar um adapter e registrá-lo na ordem do pipeline.
"""
from abc import ABC, abstrac... | Felipe-Alcantara/SoundScraper-soundcloud_track_scraper_downloader | core/scraping/base.py | .py | dd90be6592e33b14 | 7.3 | 3 |
"""
config.py — Limites operacionais do pipeline de coleta.
Centraliza os números mágicos (antes espalhados pelo código) num único ponto,
configurável por variável de ambiente. Tudo tem padrão seguro.
"""
import os
from dataclasses import dataclass
def _env_int(name: str, default: int) -> int:
try:
retu... | Felipe-Alcantara/SoundScraper-soundcloud_track_scraper_downloader | core/scraping/config.py | .py | e3e93cf79260429c | 7.3 | 3 |
"""
models.py — DTOs puros do pipeline de coleta.
Contrato entre coleta (adapters), orquestração (pipeline) e consumidores (CLI / backend).
Mantém-se PURO: não importa Selenium, urllib, FastAPI nem nenhuma camada de I/O ou framework.
"""
from dataclasses import dataclass, field
# Identificadores estáveis dos método... | Felipe-Alcantara/SoundScraper-soundcloud_track_scraper_downloader | core/scraping/models.py | .py | 9c73d427de200147 | 7.3 | 3 |
"""
parsers.py — Parsers PUROS da API v2 do SoundCloud.
Recebem texto/JSON já baixado e devolvem dados estruturados. Não tocam a rede,
o que os torna totalmente testáveis offline com fixtures sanitizadas (ver tests/).
Esta é a única fonte de verdade do parsing; browser_handler.py delega para cá.
"""
import json
impor... | Felipe-Alcantara/SoundScraper-soundcloud_track_scraper_downloader | core/scraping/parsers.py | .py | 96655b2c42e91f08 | 7.3 | 3 |
"""
pipeline.py — Orquestração da coleta com fallback entre métodos.
Estratégia (decisão do projeto): tentar o método MAIS FÁCIL e robusto primeiro
(API v2 HTTP, sem navegador) e só cair para o navegador (Selenium) se necessário.
A ordem fica em get_pipeline(), então somar um método novo é só registrar o adapter.
Fal... | Felipe-Alcantara/SoundScraper-soundcloud_track_scraper_downloader | core/scraping/pipeline.py | .py | 0a0968f4b027d25e | 7.3 | 3 |
"""
registry.py — Mapeamento único das 7 opções de coleta do SoundScraper.
Concentra num só lugar o que antes estava espalhado entre scraper_service.py e
browser_handler.py (collection_map, choice_names, sufixos de URL, seletores CSS).
Adicionar/alterar uma opção passa a ser uma mudança local e auditável.
"""
from da... | Felipe-Alcantara/SoundScraper-soundcloud_track_scraper_downloader | core/scraping/registry.py | .py | 69f61de4d504b9e3 | 7.3 | 3 |
"""
SoundScraper — Launcher
Inicia o servidor FastAPI e abre o navegador na interface.
Pode ser usado tanto em dev quanto empacotado via PyInstaller.
"""
import os
import sys
import time
import webbrowser
import threading
def main():
# Adiciona o diretório raiz ao path para imports funcionarem
root = os.path.... | Felipe-Alcantara/SoundScraper-soundcloud_track_scraper_downloader | run_web.py | .py | 484c7b992d58ceb4 | 7.3 | 3 |
"""
conftest.py — Fixtures e configurações compartilhadas para os testes do SoundScraper.
"""
import sys
import os
import pytest
import tempfile
import shutil
# Adiciona a pasta core ao sys.path para importar os módulos
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CORE_DIR = os.path.join... | Felipe-Alcantara/SoundScraper-soundcloud_track_scraper_downloader | tests/conftest.py | .py | 5b4608feaa176ae7 | 7.8 | 3 |
"""The Python leg of the differential harness. See README.md.
Prints one `label|result` line per case. Every port prints the same labels in
the same order; conformance/compare.py runs all four and diffs.
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "python" ... | octopranav/Grid-Point-Code | conformance/driver.py | .py | 6f4111c54d3af010 | 7.15 | 1 |
# Copyright 2017 Pranavkumar Patel
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | octopranav/Grid-Point-Code | python/src/gridpointcode_algo_pranavpatel_ca/errors.py | .py | e24e70bf614fc44b | 7.15 | 1 |
# Copyright 2020 Pranavkumar Patel
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | octopranav/Grid-Point-Code | python/src/gridpointcode_algo_pranavpatel_ca/table.py | .py | def1bee62bd61cff | 7.15 | 1 |
# Copyright 2017 Pranavkumar Patel
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | octopranav/Grid-Point-Code | python/src/gridpointcode_algo_pranavpatel_ca/v1.py | .py | dd0ebbeb3bb9ddb2 | 7.15 | 1 |
# Copyright 2026 Pranavkumar Patel
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | octopranav/Grid-Point-Code | reference/from_spec.py | .py | ac7805b7df48e5bf | 7.65 | 1 |
# Copyright 2026 Pranavkumar Patel
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | octopranav/Grid-Point-Code | reference/geodesy.py | .py | 8531fa01535b1d3d | 7.15 | 1 |
# Copyright 2026 Pranavkumar Patel
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | octopranav/Grid-Point-Code | screening/expand.py | .py | 87cb1ead5945d969 | 7.15 | 1 |
# Copyright 2017 Pranavkumar Patel
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | octopranav/Grid-Point-Code | test_data/v1_encoder.py | .py | 1feb0e4b0c71ee67 | 7.65 | 1 |
#!/usr/bin/env python3
"""
This script fetches the download count of an Ansible role from Ansible Galaxy,
writes the count to a JSON file, and generates a bar chart of the download counts
for the last 30 days.
"""
import os.path
import subprocess
import re
import json
import pandas as pd
import matplotlib.pyplot as plt... | marcinpraczko/ansible-goss-install-stats | get-download-counts-from-galaxy.py | .py | ec32e8e7ae0ff5de | 7 | 0 |
# path: f2/apps/douyin/algorithm/webcast_signature.py
import execjs
import hashlib
from pathlib import Path
from funmedia.utils.utils import get_resource_path
class DouyinWebcastSignature:
def __init__(self, user_agent: str = None):
self.user_agent = (
user_agent
if user_agent is ... | farfarfun/funmedia | funmedia/apps/douyin/algorithm/webcast_signature.py | .py | 5f8af5b93bde84cd | 7 | 0 |
import typing
from pathlib import Path
import click
import funmedia
from funmedia import helps
from funmedia.cli.cli_commands import set_cli_config
from funmedia.i18n.translator import TranslationManager, _
from funmedia.log.logger import logger
from funmedia.utils.conf_manager import ConfigManager
from funmedia.utils... | farfarfun/funmedia | funmedia/apps/douyin/cli.py | .py | 4e5dc157178916cb | 7 | 0 |
# path: f2/apps/tiktok/cli.py
import funmedia
import click
import typing
from pathlib import Path
from funmedia import helps
from funmedia.cli.cli_commands import set_cli_config
from funmedia.log.logger import logger
from funmedia.utils.utils import (
split_dict_cookie,
get_resource_path,
get_cookie_from... | farfarfun/funmedia | funmedia/apps/tiktok/cli.py | .py | 783be6a2df0b1820 | 7 | 0 |
# path: f2/apps/twitter/cli.py
import funmedia
import click
import typing
from pathlib import Path
from funmedia import helps
from funmedia.cli.cli_commands import set_cli_config
from funmedia.log.logger import logger
from funmedia.utils.utils import (
split_dict_cookie,
get_resource_path,
get_cookie_fro... | farfarfun/funmedia | funmedia/apps/twitter/cli.py | .py | 70b89a9b74e305fb | 7 | 0 |
"""Publish a random batch of generated demo entries."""
from __future__ import annotations
import asyncio
import random
from collections.abc import Sequence
from django.core.management.base import BaseCommand, CommandError
from dashboard.demo_worker import build_demo_payload, generate_demo_message
from django_queue... | deeprave/django-queues | demo_aq/dashboard/management/commands/demo.py | .py | 0f30b004ec20b063 | 7 | 0 |
"""Observer-backed, process-local rows for the async queue dashboard."""
from __future__ import annotations
import json
import threading
from collections.abc import Iterator, Mapping
from typing import Any
from django_queue import QueueSubscription, queue_observer
from django_queue.entries import QueueEntry, QueueEn... | deeprave/django-queues | demo_aq/dashboard/projection.py | .py | 92275b97bb956c4d | 7 | 0 |
from django.http import StreamingHttpResponse
from django.shortcuts import redirect, render
from django.views.decorators.http import require_GET, require_POST
from .projection import projection
def index(request):
"""Render the observer-backed dashboard table shell."""
projection.start()
return render(re... | deeprave/django-queues | demo_aq/dashboard/views.py | .py | ea95695b6f1ba5f8 | 7 | 0 |
"""Publish a continuous movement stream to the event queue demo."""
from __future__ import annotations
import asyncio
from django.core.management.base import BaseCommand, CommandError
from django_queue import queues
from django_queue.backends.base import EventQueue
from ...movement import MovementGenerator
class... | deeprave/django-queues | demo_eq/dashboard/management/commands/demo.py | .py | 9fc7fd6e9e38fb86 | 7 | 0 |
"""Dashboard and SSE views for the event queue demo."""
from django.http import StreamingHttpResponse
from django.shortcuts import render
from django.views.decorators.http import require_GET
from .projection import projection
@require_GET
def index(request):
"""Render the listener-driven dashboard shell."""
... | deeprave/django-queues | demo_eq/dashboard/views.py | .py | 971e44ec7d856506 | 7 | 0 |
"""Configured worker and handler for the priority queue dashboard demo."""
from __future__ import annotations
import asyncio
import contextlib
import logging
import random
import time
from collections.abc import Mapping
from faker import Faker
from django_queue.backends.base import BaseQueue
from django_queue.backe... | deeprave/django-queues | demo_pq/dashboard/demo_worker.py | .py | 0e754c5d058477fb | 7 | 0 |
"""Publish a random batch of generated demo entries across priority tiers."""
from __future__ import annotations
import asyncio
import random
from collections.abc import Sequence
from django.core.management.base import BaseCommand, CommandError
from dashboard.demo_worker import (
PRIORITY_TIERS,
build_demo_... | deeprave/django-queues | demo_pq/dashboard/management/commands/demo.py | .py | c9e8fbfa1c0b5a9e | 7 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.