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 |
|---|---|---|---|---|---|---|
"""
Terminal Colors and Formatting Utilities
Provides consistent color schemes and formatting for CLI output.
Supports both ANSI colors and fallback for systems without color support.
"""
import os
import sys
from typing import Optional
class Colors:
"""ANSI color codes and formatting constants."""
# B... | Dhayalsanthosh/Python-Mastery-Hub | src/python_mastery_hub/cli/utils/colors.py | .py | 9d858882725ff36b | 7 | 0 |
"""
Input Validation Utilities
Provides comprehensive input validation and sanitization functions
for CLI applications with user-friendly error messages and suggestions.
"""
import re
import ast
from typing import Any, List, Optional, Union, Callable, Dict, Tuple
from pathlib import Path
import email_validator
from ... | Dhayalsanthosh/Python-Mastery-Hub | src/python_mastery_hub/cli/utils/input_validation.py | .py | d11c3f479efc94c3 | 7 | 0 |
"""
Progress Bar Utilities for CLI
Provides various progress visualization components for terminal output.
Supports different styles and animations for progress tracking.
"""
import time
import sys
from typing import Optional, List, Dict, Any
from math import ceil
from .colors import Colors, supports_color, get_prog... | Dhayalsanthosh/Python-Mastery-Hub | src/python_mastery_hub/cli/utils/progress_bar.py | .py | bf1a075899d15226 | 7 | 0 |
"""
Core learning modules for Python Mastery Hub.
This package contains all the interactive learning modules covering different
aspects of Python programming from basics to advanced topics.
"""
from typing import Dict, List, Type, Any
from abc import ABC, abstractmethod
import logging
logger = logging.getLogger(__na... | Dhayalsanthosh/Python-Mastery-Hub | src/python_mastery_hub/core/__init__.py | .py | ac3eb0cb235084bc | 7 | 0 |
"""
Base classes and utilities for the Advanced Python module.
"""
from typing import Dict, List, Any
from python_mastery_hub.core import LearningModule
class AdvancedConcepts(LearningModule):
"""Interactive learning module for Advanced Python concepts."""
def __init__(self):
super().__init__(
... | Dhayalsanthosh/Python-Mastery-Hub | src/python_mastery_hub/core/advanced/base.py | .py | faf275842455d3bd | 7 | 0 |
"""
Caching Decorator Exercise Implementation.
This module provides a sophisticated caching decorator exercise that demonstrates
advanced decorator patterns with TTL, size limits, and thread safety.
"""
import time
import functools
import threading
from collections import OrderedDict
from typing import Any, Callable,... | Dhayalsanthosh/Python-Mastery-Hub | src/python_mastery_hub/core/advanced/classes/utilities/exercises/caching_director.py | .py | 1861392be0a49deb | 7 | 0 |
"""
File Processing Pipeline Exercise Implementation.
This module provides a generator-based file processing pipeline exercise
that demonstrates memory-efficient data processing patterns.
"""
import re
from typing import Iterator, Callable, Any, Dict, List
class FilePipelineExercise:
"""Exercise for building a ... | Dhayalsanthosh/Python-Mastery-Hub | src/python_mastery_hub/core/advanced/classes/utilities/exercises/file_pipeline.py | .py | d38f87afe73d0cea | 7 | 0 |
"""
Transaction Manager Exercise Implementation.
This module provides a context manager exercise for database transaction
management with rollback, commit, and nested transaction support.
"""
import threading
import time
from contextlib import contextmanager
from typing import Optional, Any, Dict, List
class Transa... | Dhayalsanthosh/Python-Mastery-Hub | src/python_mastery_hub/core/advanced/classes/utilities/exercises/transaction_manager.py | .py | 2b39ff75d1adf3dc | 7 | 0 |
"""
Context manager examples and demonstrations for the Advanced Python module.
"""
import contextlib
import tempfile
import sys
import io
import time
from typing import Dict, List, Any, Iterator, Generator
from .base import TopicDemo
class ContextManagersDemo(TopicDemo):
"""Demonstration class for Python contex... | Dhayalsanthosh/Python-Mastery-Hub | src/python_mastery_hub/core/advanced/context_managers.py | .py | 7529ce94f9ffd644 | 7 | 0 |
"""
Decorator examples and demonstrations for the Advanced Python module.
"""
import functools
import time
import inspect
import threading
from typing import Dict, List, Any, Callable, Optional
from .base import TopicDemo
class DecoratorsDemo(TopicDemo):
"""Demonstration class for Python decorators."""
... | Dhayalsanthosh/Python-Mastery-Hub | src/python_mastery_hub/core/advanced/decorators.py | .py | 4eaf5b9456457cb3 | 7 | 0 |
"""
Generator examples and demonstrations for the Advanced Python module.
"""
import itertools
from typing import Dict, List, Any, Iterator, Callable
from .base import TopicDemo
class GeneratorsDemo(TopicDemo):
"""Demonstration class for Python generators."""
def __init__(self):
super().__init__... | Dhayalsanthosh/Python-Mastery-Hub | src/python_mastery_hub/core/advanced/generators.py | .py | 24544cd88a4960f7 | 7 | 0 |
"""
Metaclass examples and demonstrations for the Advanced Python module.
"""
from typing import Dict, List, Any, Type
from .base import TopicDemo
class MetaclassesDemo(TopicDemo):
"""Demonstration class for Python metaclasses."""
def __init__(self):
super().__init__("metaclasses")
def ... | Dhayalsanthosh/Python-Mastery-Hub | src/python_mastery_hub/core/advanced/metaclasses.py | .py | 236317a4e9226c5d | 7 | 0 |
"""
Base classes and utilities for the Algorithms module.
"""
from typing import Dict, List, Any
from python_mastery_hub.core import LearningModule
class Algorithms(LearningModule):
"""Interactive learning module for Algorithms."""
def __init__(self):
super().__init__(
name="Algorith... | Dhayalsanthosh/Python-Mastery-Hub | src/python_mastery_hub/core/algorithms/base.py | .py | d0102f18487e9ec4 | 7 | 0 |
"""Shared typing helpers for the AWS Lambda entry points."""
from __future__ import annotations
from typing import Protocol, TypedDict
class LambdaContext(Protocol):
"""The subset of the Lambda context object this package uses."""
invoked_function_arn: str
def get_remaining_time_in_millis(self) -> int... | bsoyka/wikipedia-bot | src/bsoykabot/aws/_typing.py | .py | da4e3fd168c7e5ab | 7 | 0 |
"""AWS Lambda entry points.
Two discovery functions and one worker function all live in this module
and share the same deployed code; Lambda is configured to call a different
top-level function in each case. The two discovery functions differ only
in which task they run -- see ``infra/lambda.tf``.
"""
from __future__... | bsoyka/wikipedia-bot | src/bsoykabot/aws/handlers.py | .py | d3f416765833d0f5 | 7 | 0 |
"""Custom CloudWatch metrics for bot activity, via the Embedded Metric Format.
EMF metrics are extracted from ordinary CloudWatch Logs lines: CloudWatch
scans each log event for a specially-shaped JSON document and turns it into
real metric data points, with no ``cloudwatch:PutMetricData`` call, no
extra IAM permissio... | bsoyka/wikipedia-bot | src/bsoykabot/aws/metrics.py | .py | 55a46bc878a233da | 7 | 0 |
"""Tasks for BsoykaBot."""
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import TYPE_CHECKING
from bsoykabot import __version__
if TYPE_CHECKING:
from collections.abc import Iterator
import pywikibot
@dataclass(frozen=True, slots=True... | bsoyka/wikipedia-bot | src/bsoykabot/tasks/__init__.py | .py | a94050ddc6d9f677 | 7 | 0 |
"""Fixes linked miscapitalization of "NFL draft" in articles.
See https://en.wikipedia.org/wiki/User:BsoykaBot/Task_3 for more info.
"""
from __future__ import annotations
import json
import re
from datetime import UTC, datetime
from functools import lru_cache
from typing import TYPE_CHECKING
import mwparserfromhel... | bsoyka/wikipedia-bot | src/bsoykabot/tasks/draft_case.py | .py | aa39d1a267a37e28 | 7 | 0 |
"""Replaces proxy domains from Wikipedia Library.
See https://en.wikipedia.org/wiki/User:BsoykaBot/Task_2 for more info.
"""
from __future__ import annotations
from functools import cache
from pathlib import Path
from typing import TYPE_CHECKING
from urllib.parse import urlparse
from pywikibot import pagegenerators... | bsoyka/wikipedia-bot | src/bsoykabot/tasks/proxy_urls.py | .py | 465428e00de1fe83 | 7 | 0 |
"""Materialize Pywikibot's credential files before Pywikibot is imported.
Pywikibot resolves its configuration directory -- and therefore whether it
can find any credentials at all -- at import time; see
:mod:`bsoykabot.wiki` for the ordering guarantee this module relies on. On
AWS Lambda, nothing is on disk between c... | bsoyka/wikipedia-bot | src/bsoykabot/wiki/_bootstrap.py | .py | 903537ea48f5a15e | 7 | 0 |
"""Test cases for the fix_nfl_draft_case task."""
from datetime import UTC, datetime
from unittest.mock import Mock
import pytest
from bsoykabot.tasks import draft_case
from bsoykabot.tasks.draft_case import DraftCaseTask, _redirect_titles
def test_redirect_titles() -> None:
"""Test that _redirect_titles cover... | bsoyka/wikipedia-bot | tests/draft_case_test.py | .py | db08f3913516794f | 7.5 | 0 |
"""Test cases for the EMF metrics helpers."""
import json
import pytest
from bsoykabot.aws.metrics import emit_page_outcome, emit_pages_discovered
def _last_emf_document(capsys: pytest.CaptureFixture[str]) -> dict[str, object]:
"""Parse the most recently printed line as an EMF document.
Args:
caps... | bsoyka/wikipedia-bot | tests/metrics_test.py | .py | e4f1c8b48e6e2e90 | 7.5 | 0 |
"""Test cases for the fix_proxy_urls task."""
from unittest.mock import Mock
from bsoykabot.tasks.proxy_urls import ProxyUrlsTask, _parse_domains, _replacements
def test_parse_domains() -> None:
"""Test that _parse_domains correctly extracts domains from the config."""
# Create a mock proxy config
mock_... | bsoyka/wikipedia-bot | tests/proxy_urls_test.py | .py | a2e55a9bb2913b1a | 7.5 | 0 |
"""Test cases for shared task utilities."""
from collections.abc import Iterator
import pytest
import pywikibot
from bsoykabot import __version__
from bsoykabot.tasks import Discovered, Task
class _StubTask(Task):
"""A minimal concrete Task, for exercising shared base-class behavior."""
name = 'stub'
... | bsoyka/wikipedia-bot | tests/task_test.py | .py | 8722ca06646226bf | 7.5 | 0 |
"""Compare the MCP ``search_terms`` search with the website's main search.
Both hit the same Solr ``ontology`` core with edismax. They differ in ``q``
construction (one phrase+wildcards vs a per-token AND of wildcard groups), in
``fq`` (hard-exclude Deprecated or only demote it), in ``bq`` boosts (the website
floats C... | VirtualFlyBrain/VFBquery | docs/compare_search_configs.py | .py | 1358b7ac6cf87b26 | 7.15 | 1 |
#!/usr/bin/env python3
"""Lint test files for the silently-passing anti-patterns documented in TESTING.md.
Operates on the lines a change ADDS (diffs ``<base>...HEAD``), so it flags what a
PR introduces rather than pre-existing code. For a genuine exception (a
deliberate empty-result test, a graceful-handling test), p... | VirtualFlyBrain/VFBquery | scripts/lint_tests.py | .py | 462bc91731479396 | 7.65 | 1 |
import re
import json
import ast
import os.path
def extract_code_blocks(readme_path):
"""
Extracts Python code blocks and JSON blocks from a README.md file
and returns them as separate lists.
"""
if not os.path.isfile(readme_path):
raise FileNotFoundError(f"README file not found at {readme_... | VirtualFlyBrain/VFBquery | src/test/readme_parser.py | .py | 63970661a15a4c17 | 7.65 | 1 |
"""
Test suite for AnatomyExpressedIn query (get_expression_overlaps_here).
INVERSE-direction query — given an expression pattern, return the anatomy
classes whose Individuals overlap with the pattern's Individuals. The
forward direction (anatomy -> expression patterns) is solely owned by
TransgeneExpressionHere.
XMI... | VirtualFlyBrain/VFBquery | src/test/test_anatomy_expressed_in.py | .py | ef3544b19fed350d | 7.65 | 1 |
"""
Unit tests for dataset and template queries.
This tests all 5 dataset/template-related queries:
1. get_painted_domains - Template painted anatomy domains
2. get_dataset_images - Images in a dataset
3. get_all_aligned_images - All images aligned to template
4. get_aligned_datasets - All datasets aligned to template... | VirtualFlyBrain/VFBquery | src/test/test_dataset_template_queries.py | .py | 3eced60e6743f5f2 | 7.65 | 1 |
"""Tests for DownstreamClassConnectivity query.
Tests the query that finds downstream partner neuron classes for a given
neuron class, using the pre-indexed downstream_connectivity_query Solr field.
"""
import pytest
import pandas as pd
from vfbquery.vfb_queries import (
get_downstream_class_connectivity,
Do... | VirtualFlyBrain/VFBquery | src/test/test_downstream_class_connectivity.py | .py | 14e9bbad18cc6225 | 7.65 | 1 |
import sys
import json
import vfbquery as vfb
from deepdiff import DeepDiff
from io import StringIO
from colorama import Fore, Back, Style, init
import numpy as np
# Custom JSON encoder to handle NumPy types
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
... | VirtualFlyBrain/VFBquery | src/test/test_examples_diff.py | .py | 0c7754a714b86182 | 7.65 | 1 |
"""
Test suite for epFrag (Expression Pattern Fragments) query.
This query uses Owlery instances endpoint to find individual expression pattern
fragment images that are part of a specified expression pattern.
FIXED: Query now works correctly with proper IRI resolution for VFBexp_* IDs.
The three execution tests belo... | VirtualFlyBrain/VFBquery | src/test/test_expression_pattern_fragments.py | .py | 6d3f84fcc26eaa93 | 7.65 | 1 |
"""
Unit tests for the ImagesNeurons query.
This tests the ImagesNeurons query which retrieves individual neuron images
(instances) with parts in a synaptic neuropil or domain.
Test term: FBbt_00007401 (antennal lobe) - a synaptic neuropil
"""
import unittest
import sys
import os
# Add src directory to path
sys.pa... | VirtualFlyBrain/VFBquery | src/test/test_images_neurons.py | .py | 1ea1e347ffc4c22f | 7.65 | 1 |
"""
Test suite for ImagesThatDevelopFrom query.
This query uses Owlery instances endpoint to find individual neuron images
that develop from a specified neuroblast.
"""
import unittest
import sys
import os
# Add src to path for imports
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from vfbquery.... | VirtualFlyBrain/VFBquery | src/test/test_images_that_develop_from.py | .py | 1eedc0a1eef15a09 | 7.65 | 1 |
#!/usr/bin/env python3
"""
Test suite for LineageClonesIn query.
Tests the query that finds lineage clones that overlap with a synaptic neuropil.
This implements the LineageClonesIn query from the VFB XMI specification.
Test cases:
1. Query execution with known neuropil
2. Schema generation and validation
3. Term inf... | VirtualFlyBrain/VFBquery | src/test/test_lineage_clones_in.py | .py | dd14bc3714a273ee | 7.65 | 1 |
"""Unit tests for _linkify_citations (definition/description citation linking).
Regression guard for the dropped-`)` bug: the linkifier's `\\)?` used to consume
the closing paren of a `(Author, 2020)` citation without putting it back, so
definitions rendered as `(Author, 2020.` — see the LPT-neuron description. Pure,
... | VirtualFlyBrain/VFBquery | src/test/test_linkify_citations.py | .py | 2e376488d2e9772b | 7.65 | 1 |
import unittest
from vfbquery.term_info_queries import deserialize_term_info, synonym_type_label
# Trimmed real medulla (FBbt_00003748) term_info: the synonym block only, plus
# one synthetic row — an untyped "ME" (Doe et al., 2019) alongside the real typed
# "ME" (BRAIN_NAME_ABV) — so the untyped-distinct-from-typed... | VirtualFlyBrain/VFBquery | src/test/test_merge_synonyms.py | .py | efc7b51c562c5ac7 | 7.65 | 1 |
"""
Unit tests for NBLAST similarity queries.
This tests all 6 NBLAST-related queries:
1. get_similar_morphology - NBLAST matches
2. get_similar_morphology_part_of - NBLASTexp to expression patterns
3. get_similar_morphology_part_of_exp - Reverse NBLASTexp
4. get_similar_morphology_nb - NeuronBridge matches
5. get_sim... | VirtualFlyBrain/VFBquery | src/test/test_nblast_queries.py | .py | 64b0f7aa769b5d4a | 7.65 | 1 |
#!/usr/bin/env python3
"""
Test suite for NeuronClassesFasciculatingHere query.
Tests the query that finds neuron classes that fasciculate with (run along) tracts or nerves.
This implements the NeuronClassesFasciculatingHere query from the VFB XMI specification.
Test cases:
1. Query execution with known tract
2. Sche... | VirtualFlyBrain/VFBquery | src/test/test_neuron_classes_fasciculating.py | .py | 9fa8740827a87213 | 7.65 | 1 |
#!/usr/bin/env python3
"""
Test suite for NeuronInputsTo query.
Tests the query that finds neurons with synapses into a specified neuron.
This implements the NeuronInputsTo query from the VFB XMI specification.
Test cases:
1. Query execution with known neuron
2. Schema generation and validation
3. Term info integrati... | VirtualFlyBrain/VFBquery | src/test/test_neuron_inputs.py | .py | ac451b44520f7dbc | 7.65 | 1 |
"""Tests for NeuronRegionConnectivityQuery.
Tests the query that finds brain regions where a given neuron has synaptic terminals.
This implements the neuron_region_connectivity_query from the VFB XMI specification.
"""
import pytest
import pandas as pd
from vfbquery.vfb_queries import (
get_neuron_region_connect... | VirtualFlyBrain/VFBquery | src/test/test_neuron_region_connectivity.py | .py | cd7c8251d06afb71 | 7.65 | 1 |
import unittest
import pandas as pd
from vfbquery.vfb_queries import encode_markdown_links
class PreviewStrayBackslashTest(unittest.TestCase):
"""Query preview rows are assembled in vfb_queries.py from raw Neo4j labels
(via apoc.text.format), NOT through term_info_queries.clean_label. So the
stray backs... | VirtualFlyBrain/VFBquery | src/test/test_preview_stray_backslash.py | .py | f6de50a60c87ea5d | 7.65 | 1 |
"""
Unit tests for publication and transgene queries.
This tests:
1. get_terms_for_pub - Terms referencing a publication
2. get_transgene_expression_here - Complex transgene expression query
Test terms:
- DOI_10_7554_eLife_04577 - Example publication
- FBbt_00003748 - mushroom body (for transgene expression)
"""
imp... | VirtualFlyBrain/VFBquery | src/test/test_publication_transgene_queries.py | .py | eeaf62d1876919d5 | 7.65 | 1 |
"""Regression tests: query `count` must match the rows returned at limit=-1.
These guard against the enrichment-CALL row-drop bug fixed alongside the
expression-pattern stock work: a thumbnail/image `CALL {}` subquery that ended
in `WHERE i IS NOT NULL` silently eliminated every result row with no aligned
image, so th... | VirtualFlyBrain/VFBquery | src/test/test_query_count_rows_consistency.py | .py | 6200ffe74fd97a89 | 7.65 | 1 |
#!/usr/bin/env python
#
# @license Apache-2.0
#
# Copyright (c) 2018 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-minabs | benchmark/python/benchmark.py | .py | 94c8127626634974 | 7.15 | 1 |
#!/usr/bin/env python
#
# @license Apache-2.0
#
# Copyright (c) 2018 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-min | benchmark/python/benchmark.py | .py | f43a4656c8d167af | 7.15 | 1 |
#!/usr/bin/env python
#
# @license Apache-2.0
#
# Copyright (c) 2018 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/stats-base-dists-arcsine-pdf | benchmark/python/benchmark.scipy.py | .py | 04c31ad02927db89 | 7.15 | 1 |
#!/usr/bin/env python
#
# @license Apache-2.0
#
# Copyright (c) 2018 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-maxabs | benchmark/python/benchmark.py | .py | ed65e8bb2f414851 | 7.15 | 1 |
#!/usr/bin/env python
#
# @license Apache-2.0
#
# Copyright (c) 2018 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-max | benchmark/python/benchmark.py | .py | ed4f3e2de9771b18 | 7.15 | 1 |
#!/usr/bin/env python
#
# @license Apache-2.0
#
# Copyright (c) 2018 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/stats-base-dists-binomial-stdev | test/fixtures/python/runner.py | .py | 9a944c88e3e9ff8e | 7.65 | 1 |
#!/usr/bin/env python
#
# @license Apache-2.0
#
# Copyright (c) 2018 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/stats-base-dists-laplace-stdev | test/fixtures/python/runner.py | .py | 7524a67e50ffe0ac | 7.74 | 2 |
#!/usr/bin/env python3
"""
Daily telemetry snapshot for portfolio repos.
Fetches views, clones, referrers, and paths from the GitHub Traffic API.
Normalizes clone counts by subtracting Actions runs (CI clones inflate the signal).
Usage:
GH_TOKEN=<token> python snapshot.py [--date YYYY-MM-DD] [--dry-run]
"""
impor... | CSalcedoDataBI/CSalcedoDataBI | telemetry/scripts/snapshot.py | .py | 9218b619444d96e7 | 7.15 | 1 |
#!/usr/bin/env python3
#
# Copyright (c) 2022 Cisco and/or its affiliates.
# 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 require... | vpp-dev/vpp-gerrit-report | scripts/get_changes.py | .py | d1b3a4961ad1645c | 7 | 0 |
#!/usr/bin/env python3
#
# Copyright (c) 2025 Cisco and/or its affiliates.
# 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 require... | vpp-dev/vpp-gerrit-report | scripts/venv_builder.py | .py | 056036a6d9229e16 | 7 | 0 |
#!/usr/bin/env python3
# Description: Common helper functions
import re
import subprocess
import sys
import time
def create_gitignore(folder):
"""
Create a gitignore that ignores all files in a folder. Some folders are not
known until the script is run so they can't be added to the root .gitignore
:p... | Clurfe/clang-builder | utils.py | .py | dc56785060f25fb3 | 7 | 0 |
from typing import Callable
from analyser.cloudplatforms import cp_check
from analyser.database import db_check
from analyser.language import language_check
from analyser.libraries import libraries_check
from analyser.location import location_count
from analyser.os import os_check
from analyser.tools import tools_check... | creme332/myjobviz | backend/src/analyser/runner.py | .py | d74ef6bb33b67520 | 7.3 | 3 |
import logging
import logging.handlers
import os
import json
from datetime import datetime
from dotenv import load_dotenv, find_dotenv
from huggingface_hub import HfApi, create_repo, login
from classes.database import Database
from utils.service_key import get_service_account_key
log = logging.getLogger(__name__)
d... | creme332/myjobviz | backend/src/backup.py | .py | e6e6fbbc1aa67a52 | 7.3 | 3 |
import logging
import logging.handlers
import os
from classes.database import Database
from miner import JobScraper
from analyser.runner import update_analytics
from utils.service_key import get_service_account_key
from badge_generator import update_job_count_badge
log = logging.getLogger(__name__)
def _setup_loggi... | creme332/myjobviz | backend/src/main.py | .py | d47f019d1ee77e21 | 7.3 | 3 |
from __future__ import annotations
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdri... | creme332/myjobviz | backend/src/miner.py | .py | d094da5b2db0cd99 | 7.3 | 3 |
import os
from dotenv import load_dotenv, find_dotenv
import json
import base64
def get_service_account_key(forMainDB: bool = False) -> dict:
"""
Returns service account key for firestore
Args:
forMainDB (bool, optional): If false, service account key for database
containing only statisti... | creme332/myjobviz | backend/src/utils/service_key.py | .py | eb995eda3a6ce620 | 7.3 | 3 |
from django.views import View
class BasketMixin(View):
"""
Generic mixin is for a user's basket
"""
def __init__(self):
"""
Receives data from the post method:
:self.current: A string representing the full path to the requested page.
:self.nmb: The number of products.
... | Rocky-04/Multishop_Django_Web_Store | src/basket/ultis.py | .py | 0d7ea07122aaf07b | 7.3 | 3 |
import logging
from typing import Dict
from typing import Tuple
from django.db.models import Count
from django.db.models import F
from django.db.models import QuerySet
from news.models import Category
from news.models import News
logger = logging.getLogger(__name__)
def count_news_from_categories() -> Tuple[QueryS... | Rocky-04/Multishop_Django_Web_Store | src/news/services.py | .py | 13ca59e06a33983f | 7.3 | 3 |
import logging
from typing import Dict
from typing import Union
from django import template
from django.db.models import QuerySet
from news.services import count_news_from_categories
from news.services import get_all_categories
register = template.Library()
logger = logging.getLogger(__name__)
@register.simple_tag... | Rocky-04/Multishop_Django_Web_Store | src/news/templatetags/news_tags.py | .py | 1c015d8fa02f1392 | 7.3 | 3 |
r"""*Module to generate CPython release RSS feed.*
**Author**
Brian Skinn (brian.skinn@gmail.com)
**File Created**
25 Feb 2021
**Copyright**
\(c) Brian Skinn 2021-2024
**Source Repository**
http://www.github.com/bskinn/cpython-release-feed
**Documentation**
N/A
**License**
The MIT License;... | bskinn/cpython-release-feed | make_feed.py | .py | f2691c16fe33be15 | 7.24 | 2 |
from music.artist import Artist
import logging
import psycopg2
import psycopg2.extras
from utilities.gen import clean_str
from utilities.navidrome import Navidrome
from utilities.exceptions import FatalError, AlbumNotFound
logger = logging.getLogger(__name__)
class Album:
"Music Album class"
def __init__(sel... | 1i-medialib/media-lib-tools | music/album.py | .py | 0cbb0df222707b59 | 7 | 0 |
import logging
import psycopg2
import psycopg2.extras
from utilities.gen import clean_str
from utilities.navidrome import Navidrome
from utilities.exceptions import FatalError, ArtistNotFound
logger = logging.getLogger(__name__)
class Artist:
"Music Artist class"
def __init__(self, ytmusic, dbh, name=None, r... | 1i-medialib/media-lib-tools | music/artist.py | .py | b2a6b9c04290f904 | 7 | 0 |
from music.song import Song
import logging
logger = logging.getLogger(__name__)
class Playlist:
"Music Playlist class"
def __init__(self, utilities, ytmusic, dbh, info=None):
logger = utilities # Utilities Object
self.ytm = ytmusic # youtube Music API object
self.dbh = dbh # dat... | 1i-medialib/media-lib-tools | music/playlist.py | .py | 73f5c593fe49e4bd | 7 | 0 |
import sqlite3
import logging
from utilities.exceptions import InvalidFileExtension, FatalError
logger = logging.getLogger(__name__)
#local_music_path = r"E:\media\music"
local_music_path = r"E:\media\music"
#dbFileName=r"Z:\appdata\plexmediaserver\app\Library\Application Support\Plex Media Server\Plug-in Support\Data... | 1i-medialib/media-lib-tools | set-plex-rating.py | .py | 2d4f943fc49fd148 | 7 | 0 |
# Copyright 2021 Niklas van Schrick
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribu... | Taucher2003/date-difference-action | main.py | .py | 5fbadd1167292242 | 7 | 0 |
#!/usr/bin/env python3
"""
Ansible Collection Mermaid Diagram Generator Pre-commit Hook
Generates a Mermaid diagram from an Ansible collection structure
and updates repo README.
"""
from pathlib import Path
import sys
import re
class AnsibleCollectionAnalyzer:
def __init__(self, collection_path: str):
se... | CowDogMoo/ansible-collection-workstation | .hooks/gen-arch-diagram.py | .py | 8843202155ffddc1 | 7.24 | 2 |
"""End-to-end tests for ovos-skill-news."""
from unittest import TestCase
from ovoscope import get_minicroft
class TestNewsSkillLoads(TestCase):
"""Verify the skill plugin loads and reaches READY state."""
@classmethod
def setUpClass(cls):
cls.skill_id = "ovos-skill-news.openvoiceos"
cls... | OpenVoiceOS/ovos-skill-news | test/end2end/test_news_intents.py | .py | a88384084186392e | 7.8 | 3 |
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "rich",
# ]
# ///
import json
import subprocess
import re
import sys
import urllib.request
import os
import random
from datetime import datetime, timezone
from rich.console import Console
from rich.panel import Panel
from rich.th... | gbvk312/gbvk312 | scripts/update_profile.py | .py | f67ad3fdcfef2567 | 7 | 0 |
import requests
import csv
from datetime import datetime
import os
import time
IMAGES = ['kwdb/kwdb', 'kwdb/kwdb_comp_env']
DATA_PATH = 'data/stats.csv'
def get_docker_stats(image, max_retries=3, base_delay=1):
url = f'https://hub.docker.com/v2/repositories/{image}/'
for attempt in range(max_retries):
... | sunny0826/docker-pulls-statistics | scripts/fetch_stats.py | .py | 7a3fd8fa7623e165 | 7 | 0 |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from fake_useragent import UserAgent
import random
import logging
impo... | ledhcg/ledhcg | readme-update.py | .py | a21a223fed33c605 | 7 | 0 |
"""Filtering applied to raw traces before they are looked at.
Neuropixels 2.0 saves wideband: the AP file carries the LFP and the per-channel
DC offset as well as the spikes. On our data the unfiltered median absolute
voltage is around 1100 uV, so any figure that draws raw traces without a
high-pass is drawing offsets... | SteinmetzLab/qualityMetrics | src/qualitymetrics/preproc.py | .py | e50ac60d50e7c90e | 7.35 | 4 |
"""Lab plotting conventions, applied once so every figure obeys them.
Arial, no top/right spines, editable text in vector output, sentence-case
labels with units. Importing :func:`use_lab_style` and calling it is the only
thing a plotting module has to do; nothing here reaches into a figure after the
fact, so a caller... | SteinmetzLab/qualityMetrics | src/qualitymetrics/style.py | .py | 6e8a808002b254fe | 7.35 | 4 |
"""A synthetic sorter output and recording, so the suite needs no server.
Small enough to build in a fraction of a second, real enough that the loaders,
the unit conversions and the figure code all run against it.
"""
from __future__ import annotations
import numpy as np
import pytest
FS = 30000.0
N_CHANNELS = 16
N_... | SteinmetzLab/qualityMetrics | tests/conftest.py | .py | c570d3398160f38f | 7.85 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import subprocess
from maxiconda import supported_subdirs
def release():
"""
This function uploads the packages in `./build` to anaconda.org/Semi-ATE.
It uses the `CONDA_UPLOAD_TOKEN` and `MAXICONDA_ENV_RELEASE` environment
variables to do so.
... | Semi-ATE/maxiconda-envs | scripts/release.py | .py | a671466064963d39 | 7.24 | 2 |
"""Crawler for ETNews AI/SW section articles.
Discovers article IDs by paginating through the section's AJAX listing
endpoint (the same one the site's own "더보기"/load-more button uses), then
retrieves full article content (title, published date, body text) for each.
Paginating rather than reading only the single visibl... | ColdNine/coldnine.github.io | scripts/crawl.py | .py | b4d7f6b559c664c3 | 7 | 0 |
"""Korean keyword extraction and summarization.
Keyword extraction: Okt noun tokenization + TF-IDF scoring.
Summarization: TextRank over Korean sentences.
"""
import logging
import re
from collections import Counter
from typing import Dict, List, Optional
from sklearn.feature_extraction.text import TfidfVectorizer
f... | ColdNine/coldnine.github.io | scripts/extract.py | .py | ff4ba95e4979a7f6 | 7 | 0 |
"""Generate Jekyll-compatible Markdown posts from crawled articles."""
import logging
import os
from datetime import datetime
from typing import List
import yaml
from slugify import slugify
from crawl import Article
logger = logging.getLogger(__name__)
MAX_SLUG_LENGTH = 50
TIMEZONE_OFFSET = "+0900" # matches _con... | ColdNine/coldnine.github.io | scripts/generate_post.py | .py | 165e442cdb999424 | 7 | 0 |
"""Tracks processed article IDs to prevent duplicate post generation across runs."""
import json
import logging
import os
import shutil
from datetime import datetime, timezone, timedelta
from typing import List
logger = logging.getLogger(__name__)
DEFAULT_STATE_FILE = "data/processed_articles.json"
KST = timezone(ti... | ColdNine/coldnine.github.io | scripts/state.py | .py | e3b4772962e02c2a | 7 | 0 |
import re
import os
import sys
import ast
from enum import Enum
from datetime import datetime
import chess
import chess.pgn
import yaml
from github import Github
import src.markdown as markdown
import src.selftest as selftest
# TODO: Use an image instead of a raw link to start new games
class Action(Enum):
UNKN... | hoprik/hoprik | main.py | .py | cb39f8393a009483 | 7 | 0 |
#!/usr/bin/env python3
"""
Generate a calendar heatmap from WakaTime daily totals.
Requires WAKATIME_API_KEY environment variable.
"""
import os
import sys
from datetime import datetime, timedelta
from collections import defaultdict
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatc... | hoprik/hoprik | src/wakatime.py | .py | a88d7dc380f623b3 | 7 | 0 |
"""Instagram Graph API profile fetching and token refresh functions."""
import requests
from pathlib import Path
from . import config
from .config import SAVE_PROFILE_IMAGES
from .utils import download_image
def refresh_token():
"""Refresh the Instagram long-lived access token.
Long-lived tokens expire aft... | Jerit3787/personal | social_fetcher/instagram.py | .py | 0d0242821aa714d6 | 7 | 0 |
"""Twitter/X API profile fetching functions.
NOTE: As of 2024+, the X free API tier no longer supports reading user data.
These functions are retained for future use if the API tier is upgraded.
"""
import requests
from .config import TWITTER_BEARER_TOKEN, TWITTER_USER_ID, TWITTER_USERNAME, SAVE_PROFILE_IMAGES
from ... | Jerit3787/personal | social_fetcher/twitter.py | .py | 7b785ff8188a60e1 | 7 | 0 |
"""Utility functions for image handling and data persistence."""
import os
import json
import requests
from .config import OUTPUT_PATH
def download_image(image_url, filename):
"""Download an image from the given URL and save it to the src/img directory."""
if not image_url:
return None
try:
... | Jerit3787/personal | social_fetcher/utils.py | .py | e9257ab8d77d1a2c | 7 | 0 |
"""Public exception hierarchy for kfbatch."""
class KFBatchError(Exception):
"""Base class for expected command-line failures."""
class KFBatchUsageError(KFBatchError):
"""Raised for invalid or unsupported command-line combinations."""
class KFBatchCommandError(KFBatchError):
"""Raised when a schedule... | kfuku52/kfbatch | kfbatch/errors.py | .py | 79358705698a9d9f | 7 | 0 |
"""Scheduler memory parsing and safe display helpers."""
from __future__ import annotations
import math
import re
import pandas
_MIB_PER_UNIT = {
"K": 1.0 / 1024.0,
"M": 1.0,
"G": 1024.0,
"T": 1024.0 * 1024.0,
"P": 1024.0 * 1024.0 * 1024.0,
}
_DECIMAL_BYTES_PER_UNIT = {
"k": 1000.0,
"m":... | kfuku52/kfbatch | kfbatch/memory.py | .py | 030fa9acd6575c64 | 7 | 0 |
import functools
from collections.abc import Callable
from typing import Any
from django.conf import settings
from fastapi import APIRouter as FastAPIRouter
from fastapi import FastAPI, Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.resp... | xshapira/fastapi-django-template | api/main.py | .py | 9472facd56b1578a | 7 | 0 |
import functools
import importlib
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") # noqa
import anyio
from asgiref.sync import sync_to_async
from django.conf import settings
from django.core.wsgi import get_wsgi_application
from django.db import (
InterfaceError,
OperationalErro... | xshapira/fastapi-django-template | config/asgi.py | .py | 40e0a092ab5c2180 | 7 | 0 |
import os
from datetime import datetime
import pandas as pd
import requests
# If output folder does not exist, create it
if not os.path.exists('output'):
os.makedirs('output')
def get_data(url):
'''
This function reaches out to SAPD's arcgis server and returns the data.
'''
r = requests.get(url)
... | ryan-serpico/sa-sapd-calls-mirror | app.py | .py | ee54494df8925288 | 7.24 | 2 |
"""
This code uses a job_list.py to clip history files to box locations
in the LO domain
From that temp file 'box_###.nc' we calculate freshwater content
in get_one_Fwc.py.
running testing code with two history files on kh personal mac, looks like:
run extract_Fwc -gtx cas7_t0_x4b -ro 1 -0 2017.12.12 -1 2017.12.13 ... | katehewett/LO_user | extract/Fwc/extract_Fwc.py | .py | 8c09e77c5685e687 | 7 | 0 |
"""
Code to extract a box-like region, typically for another modeler to use
as a boundary contition. In cases where it gets velocity in addition to
the rho-grid variables the grid limits mimic the standard ROMS organization,
with the outermost corners being on the rho-grid.
Job definitions are in LO_user/extract/box/... | katehewett/LO_user | extract/box_ubc/extract_box_lowpass_nocat.py | .py | 65889cf6d1fe61a6 | 7 | 0 |
"""
This code uses a job_list.py to clip history files to box locations
in the LO domain
From that temp file 'box_###.nc' we calculate a pycnocline and thermocline
in get_one_cline.py. That script will find the depth of dp/dz dT/dz max
flag the depth, value, and extract the S and T at that depth
This code was create... | katehewett/LO_user | extract/clines/extract_clines.py | .py | 6b9f5dc0bc7b3f72 | 7 | 0 |
"""
This code uses a job_list.py to clip history files to box locations
in the LO domain
From that temp file 'box_###.nc' we calculate a pycnocline and thermocline
in get_one_cline.py. That script will find the depth of dp/dz dT/dz max
flag the depth, value, and extract the S and T at that depth
This code was create... | katehewett/LO_user | extract/clines/old_ELG/test_extract_clines.py | .py | ed1d3d33931d9826 | 7.5 | 0 |
"""
This code uses a job_list.py to clip history files to box locations
in the LO domain
From that temp file 'box_###.nc' we calculate a corrosive volume
in get_one_corrosive_volume_rev1.py.
This code was created because extract_corrosive_volume was taking a
very long time to run on apogee (and would stop on day 100... | katehewett/LO_user | extract/corrosive_volume/extract_corrosive_box.py | .py | cc341e87276da0e8 | 7 | 0 |
from gyomu_schema.config.config_loader_option import EnvironmentLoaderOption
from gyomu_schema.db.config import DbConfig
from gyomu_schema.error import ConfigError
from returns.result import Failure
from sqlalchemy import Engine, create_engine
from sqlalchemy.exc import SQLAlchemyError
from gyomu_infra.config.loader i... | Yoshihisa-Matsumoto/Gyomu_Python | packages/infra/src/gyomu_infra/db/connection/factory.py | .py | bd626b68fdc25cec | 7 | 0 |
"""Provide a client for the Open Exchange Rates API."""
from __future__ import annotations
from http import HTTPStatus
from types import TracebackType
from typing import Any, Self, cast
from aiohttp import ClientError, ClientResponse, ClientResponseError, ClientSession
from .exceptions import (
OpenExchangeRate... | MartinHjelmare/aioopenexchangerates | src/aioopenexchangerates/client.py | .py | cd26ac09fa0481f2 | 7 | 0 |
"""Provide common fixtures."""
from collections.abc import AsyncGenerator, Callable
from typing import Any
from aiohttp import ClientSession
from aiointercept import aiointercept
import pytest
from yarl import URL
from aioopenexchangerates.client import BASE_API_ENDPOINT, Client
@pytest.fixture(name="session")
asy... | MartinHjelmare/aioopenexchangerates | tests/conftest.py | .py | f62329d18c89e44d | 7.5 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.