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 |
|---|---|---|---|---|---|---|
#!/usr/bin/env python3
"""Global utility methods and classes."""
from typing import Any
def strtobool(value: str) -> bool:
"""Convert a string representation of truth to true or false."""
_map = {
"y": True,
"yes": True,
"t": True,
"true": True,
"on": True,
"1... | thegeeklab/docker-tidy | dockertidy/utils.py | .py | 754dc2b0ccfb3293 | 7.39 | 5 |
# SPDX-FileCopyrightText: 2016-2018 CERN.
# SPDX-License-Identifier: MIT
"""Add index on deposit id."""
from alembic import op
# revision identifiers, used by Alembic.
revision = "3ca42db77c30"
down_revision = "f3542dda222d"
branch_labels = ()
depends_on = None
def upgrade():
"""Upgrade database."""
op.cre... | inveniosoftware/invenio-swh | invenio_swh/alembic/3ca42db77c30_add_index_on_deposit_id.py | .py | fefa8feaabf9baac | 7 | 0 |
# SPDX-FileCopyrightText: 2016-2018 CERN.
# SPDX-License-Identifier: MIT
"""Create swh table."""
import sqlalchemy as sa
import sqlalchemy_utils
from alembic import op
# revision identifiers, used by Alembic.
revision = "ed8813bfcb2b"
down_revision = "6cfb865654d2"
branch_labels = ()
depends_on = None
def upgrade(... | inveniosoftware/invenio-swh | invenio_swh/alembic/ed8813bfcb2b_create_swh_table.py | .py | 6d4344cdd25a34c0 | 7 | 0 |
# SPDX-FileCopyrightText: 2024 CERN.
# SPDX-License-Identifier: MIT
"""Increase identifier string length."""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "f3542dda222d"
down_revision = "ed8813bfcb2b"
branch_labels = ()
depends_on = None
def upgrade():
"""Up... | inveniosoftware/invenio-swh | invenio_swh/alembic/f3542dda222d_increase_identifier_string_length.py | .py | c5e23cca1467eec2 | 7 | 0 |
# SPDX-FileCopyrightText: 2023-2025 CERN.
# SPDX-License-Identifier: MIT
"""API representation of a Software Heritage deposit."""
from invenio_db import db
from invenio_rdm_records.proxies import current_rdm_records_service as record_service
from werkzeug.utils import cached_property
from invenio_swh.models import SW... | inveniosoftware/invenio-swh | invenio_swh/api.py | .py | 6aa0f3ceb34590d6 | 7 | 0 |
# SPDX-FileCopyrightText: 2023 CERN.
# SPDX-License-Identifier: MIT
"""Client integration with SWH."""
import json
import urllib
import xmltodict
from lxml import etree
from invenio_swh.errors import ClientException
from invenio_swh.serializer import SoftwareHeritageXMLSerializer
class SWHCLient(object):
"""Ab... | inveniosoftware/invenio-swh | invenio_swh/client.py | .py | 90bb1ee7d9d4c7a8 | 7 | 0 |
# SPDX-FileCopyrightText: 2023 CERN.
# SPDX-License-Identifier: MIT
"""Controller for Software Heritage integration."""
from invenio_swh.client import SWHCLient
from invenio_swh.errors import DeserializeException
class SWHController:
"""Software Heritage controller."""
def __init__(self, client: SWHCLient) ... | inveniosoftware/invenio-swh | invenio_swh/controller/controller.py | .py | 04258ce1318824a8 | 7 | 0 |
# SPDX-FileCopyrightText: 2020 CERN
# SPDX-FileCopyrightText: 2020 Cottage Labs LLP.
# SPDX-License-Identifier: MIT
"""Support for onward deposit of software artifacts to Software Heritage."""
import sword2
from flask.blueprints import Blueprint
from invenio_rdm_records.services.signals import post_publish_signal
fr... | inveniosoftware/invenio-swh | invenio_swh/ext.py | .py | 7d13e85adb196b45 | 7 | 0 |
# SPDX-FileCopyrightText: 2023 CERN.
# SPDX-License-Identifier: MIT
"""Databatase models for software heritage integration."""
from enum import Enum
from invenio_db import db
from sqlalchemy_utils import Timestamp
from sqlalchemy_utils.types import ChoiceType, UUIDType
class SWHDepositStatus(Enum):
"""Constants... | inveniosoftware/invenio-swh | invenio_swh/models.py | .py | 1ac2bf03b7dc8d38 | 7 | 0 |
# SPDX-FileCopyrightText: 2024-2025 CERN.
# SPDX-License-Identifier: MIT
"""Software Heritage system fields."""
from invenio_records.systemfields import SystemField
from invenio_swh.api import SWHDeposit
class SWHObj:
"""Software Heritage object.
Implements logic around accessing the SWH object and dumping... | inveniosoftware/invenio-swh | invenio_swh/records/systemfields.py | .py | 65d90ad9587f919f | 7 | 0 |
# SPDX-FileCopyrightText: 2023-2024 CERN.
# SPDX-License-Identifier: MIT
"""Invenio-SWH service schema."""
from flask import current_app
from invenio_rdm_records.contrib.codemeta.processors import CodemetaDumper
from invenio_rdm_records.resources.serializers.codemeta import CodemetaSchema
from marshmallow import field... | inveniosoftware/invenio-swh | invenio_swh/schema.py | .py | e38913d4502c4648 | 7 | 0 |
# SPDX-FileCopyrightText: 2023 CERN.
# SPDX-License-Identifier: MIT
"""Serializer for Invenio-SWH."""
import xmltodict
from flask_resources import MarshmallowSerializer
from lxml import etree
from invenio_swh.schema import SWHCodemetaSchema
class BaseFormatter:
"""Base formatter interface."""
def to_bytes(... | inveniosoftware/invenio-swh | invenio_swh/serializer.py | .py | bd969930b5213e3f | 7 | 0 |
# SPDX-FileCopyrightText: 2023-2024 CERN.
# SPDX-License-Identifier: MIT
"""Invenio Software Heritage service."""
from zipfile import Path, is_zipfile
from flask import current_app
from invenio_rdm_records.proxies import current_rdm_records_service as record_service
from invenio_records_resources.services.uow import ... | inveniosoftware/invenio-swh | invenio_swh/service.py | .py | 864d06605a625bbe | 7 | 0 |
# SPDX-FileCopyrightText: 2023-2024 CERN.
# SPDX-License-Identifier: MIT
"""Celery tasks for Invenio / Software Heritage integration."""
from datetime import datetime, timedelta
from celery.app import shared_task
from flask import current_app
from invenio_access.permissions import system_identity
from invenio_rdm_rec... | inveniosoftware/invenio-swh | invenio_swh/tasks.py | .py | 061632a79a1e331f | 7 | 0 |
# SPDX-FileCopyrightText: 2020-2024 CERN
# SPDX-FileCopyrightText: 2020 Cottage Labs LLP.
# SPDX-License-Identifier: MIT
"""Pytest configuration.
See https://pytest-invenio.readthedocs.io/ for documentation on which test
fixtures are available.
"""
from collections import namedtuple
from io import BytesIO
from unitt... | inveniosoftware/invenio-swh | tests/conftest.py | .py | 47d05299c15864ad | 7.5 | 0 |
# SPDX-FileCopyrightText: 2020 CERN
# SPDX-FileCopyrightText: 2020 Cottage Labs LLP.
# SPDX-License-Identifier: MIT
"""Module tests."""
from flask import Flask
from invenio_swh import InvenioSWH
def test_version():
"""Test version import."""
from invenio_swh import __version__
assert __version__
def... | inveniosoftware/invenio-swh | tests/test_invenio_swh.py | .py | 5844249acdc9441c | 7.5 | 0 |
"""Offline management of database."""
import os
import peewee as pw
import playhouse.migrate
from recapi.models import DATABASE
import config
# Overwrite with instance config
if os.path.exists(os.path.join("instance", "config.py")):
import instance.config as config
def init_db():
"""Initialise database."""... | anne17/recapi | manage_db_offline.py | .py | b5b18256e7638103 | 7.24 | 2 |
"""Instanciation of flask app."""
import logging
import os
import shutil
import sys
import time
from flask import Flask
from flask_cors import CORS
from flask_session import Session
from recapi import utils
from recapi.models import recipemodel, storedmodel, tagmodel, usermodel
def create_app():
"""Instanciate... | anne17/recapi | recapi/__init__.py | .py | ce7cb6ed26404a70 | 7.24 | 2 |
"""Allt om Mat parser class."""
import re
import traceback
from flask import current_app
import html2text
from recapi.html_parsers import GeneralParser
# Set html2text options
text_maker = html2text.HTML2Text()
text_maker.emphasis_mark = "*"
text_maker.ignore_tables = True
class AlltommatParser(GeneralParser):
... | anne17/recapi | recapi/html_parsers/alltommatparser.py | .py | db62613dd8c3628d | 7.24 | 2 |
"""Arla parser class."""
import json
import re
import traceback
from flask import current_app
import html2text
from recapi.html_parsers import GeneralParser
# Set html2text options
text_maker = html2text.HTML2Text()
text_maker.emphasis_mark = "*"
text_maker.ignore_images = True
class ArlaParser(GeneralParser):
... | anne17/recapi | recapi/html_parsers/arlaparser.py | .py | da22b0470cd52c15 | 7.24 | 2 |
"""Coop parser class."""
import traceback
import html2text
from flask import current_app
from recapi.html_parsers import GeneralParser
# Set html2text options
text_maker = html2text.HTML2Text()
text_maker.emphasis_mark = "*"
text_maker.ignore_images = True
text_maker.ignore_links = True
class CoopParser(GeneralPa... | anne17/recapi | recapi/html_parsers/coopparser.py | .py | ef154534f3cffdfe | 7.24 | 2 |
"""ICA parser class."""
import re
import traceback
from flask import current_app
import html2text
from recapi.html_parsers import GeneralParser
# Set html2text options
text_maker = html2text.HTML2Text()
text_maker.emphasis_mark = "*"
class ICAParser(GeneralParser):
"""Parser for recipes at ica.se."""
dom... | anne17/recapi | recapi/html_parsers/icaparser.py | .py | b317cd1db3f39f8d | 7.24 | 2 |
"""Köket parser class."""
import re
import traceback
from flask import current_app
import html2text
from recapi.html_parsers import GeneralParser
# Set html2text options
text_maker = html2text.HTML2Text()
text_maker.emphasis_mark = "*"
class KoketParser(GeneralParser):
"""Parser for recipes at koket.se."""
... | anne17/recapi | recapi/html_parsers/koketparser.py | .py | dc8053b0d8f63cc5 | 7.24 | 2 |
"""ICA parser class."""
import re
import traceback
from flask import current_app
import html2text
from recapi.html_parsers import GeneralParser
# Set html2text options
text_maker = html2text.HTML2Text()
text_maker.emphasis_mark = "*"
class KungsornenParser(GeneralParser):
"""Parser for recipes at kungsornen.s... | anne17/recapi | recapi/html_parsers/kungsornenparser.py | .py | 03e8760890597d7b | 7.24 | 2 |
"""Mitt kök parser class."""
import re
import traceback
from flask import current_app
import html2text
from recapi.html_parsers import GeneralParser
# Set html2text options
text_maker = html2text.HTML2Text()
text_maker.emphasis_mark = "*"
class MittkokParser(GeneralParser):
"""Parser for recipes at mittkok.ex... | anne17/recapi | recapi/html_parsers/mittkokparser.py | .py | f93fa22444caa8fb | 7.24 | 2 |
"""recepten.se parser class."""
import re
import traceback
from flask import current_app
import html2text
from recapi.html_parsers import GeneralParser
# Set html2text options
text_maker = html2text.HTML2Text()
text_maker.emphasis_mark = "*"
text_maker.ignore_links = True
text_maker.ignore_images = True
class Rec... | anne17/recapi | recapi/html_parsers/receptenparser.py | .py | e66f4cb7fc01ffc4 | 7.24 | 2 |
"""Tasteline parser class."""
import re
import traceback
from flask import current_app
import html2text
from recapi.html_parsers import GeneralParser
# Set html2text options
text_maker = html2text.HTML2Text()
text_maker.emphasis_mark = "*"
text_maker.ignore_images = True
text_maker.ignore_links = True
class Taste... | anne17/recapi | recapi/html_parsers/tastelineparser.py | .py | a7f003f31300625e | 7.24 | 2 |
"""Recipe database model."""
import datetime
import re
import peewee as pw
from playhouse.shortcuts import model_to_dict
from recapi.models import BaseModel, usermodel
class Recipe(BaseModel):
"""Recipe table (peewee model)."""
title = pw.CharField(unique=True, max_length="100")
url = pw.CharField(uni... | anne17/recapi | recapi/models/recipemodel.py | .py | ad7c5c314757fa9c | 7.24 | 2 |
"""Tag table models."""
import peewee as pw
from recapi.models import BaseModel
from recapi.models.recipemodel import Recipe
class Stored(BaseModel):
"""Stored model for bookmarking recipes (peewee model)."""
recipeID = pw.ForeignKeyField(Recipe)
stored = pw.BooleanField(default=False)
def toggle_sto... | anne17/recapi | recapi/models/storedmodel.py | .py | 406abecb9fc62e28 | 7.24 | 2 |
"""Tag table models."""
import peewee as pw
from playhouse.shortcuts import model_to_dict
from recapi.models import BaseModel
from recapi.models.recipemodel import Recipe
class TagCategory(BaseModel):
"""Tag category table (peewee model)."""
categoryorder = pw.IntegerField()
categoryname = pw.CharField... | anne17/recapi | recapi/models/tagmodel.py | .py | 3af529ddf567eee7 | 7.24 | 2 |
"""Collection of different models to communicate with the data base."""
import peewee as pw
from playhouse.shortcuts import model_to_dict
from werkzeug.security import check_password_hash, generate_password_hash
from recapi.models import BaseModel
class User(BaseModel):
"""User table (peewee model)."""
dis... | anne17/recapi | recapi/models/usermodel.py | .py | 046babcd3fbd1e4b | 7.24 | 2 |
"""Command line interface for administering the user data base."""
import os
import click
from flask import Flask
from getpass import getpass
from recapi.models import DATABASE, usermodel
app = Flask(__name__)
# Set default config
app.config.from_object("config")
# Overwrite with instance config
if os.path.exists... | anne17/recapi | recapi/user_cli.py | .py | f785094fae8a42c6 | 7.24 | 2 |
"""Routes related to the API documentation."""
import os
import yaml
from flask import current_app, Blueprint, jsonify, render_template, url_for, redirect
bp = Blueprint("documentation", __name__)
@bp.route("/api_spec")
def api_spec():
"""Return open API specification in json."""
spec_file = os.path.join(c... | anne17/recapi | recapi/views/documentation.py | .py | f5b3506ac687f4d3 | 7.24 | 2 |
"""
DNS Answer Object Definitions
"""
from abc import abstractmethod
from typing import Optional, Protocol, Type
from typing_extensions import Annotated, Self
from pyderive import dataclass, field
from pystructs import U16, U32, Context, Domain, Struct
from .enum import RType, RClass
from .content import ANY, CONTENT... | imgurbot12/pydns | pydns/answer.py | .py | b7092462e188ede1 | 7 | 0 |
"""
DNS Client Implementation
"""
from abc import abstractmethod
from random import randint
from typing import Protocol
from ..enum import QR, OpCode
from ..flags import Flags
from ..question import Question
from ..message import Message
#** Variables **#
__all__ = [
'new_message_id',
'build_request',
'B... | imgurbot12/pydns | pydns/client/__init__.py | .py | 24d498912b3ad690 | 7 | 0 |
"""
Web HTTPS Based DNS Client
"""
from urllib.request import Request, urlopen
from typing import Optional
from pyderive import dataclass
from . import BaseClient, Message
#** Variables **#
__all__ = ['HttpsClient']
#** Classes **#
@dataclass(slots=True)
class HttpsClient(BaseClient):
"""
Simple DNS over H... | imgurbot12/pydns | pydns/client/https.py | .py | 9a77ed8a9f6d1032 | 7 | 0 |
"""
Standard UDP/TCP Client Implementations
"""
import random
import socket
from abc import ABC, abstractmethod
from typing import List, Optional
from pypool import Pool
from pyserve import RawAddr
from pyderive import dataclass
from . import BaseClient, Message
#** Variables **#
__all__ = ['UdpClient', 'TcpClient']... | imgurbot12/pydns | pydns/client/standard.py | .py | c36c2338f0191e03 | 7 | 0 |
"""
DNS Answer RR Content Definitions
"""
from functools import lru_cache
from typing import ClassVar, Optional, Type
from typing_extensions import Annotated, Self
from pystructs import U16, U32, Context, Domain, HintedBytes, IPv4, IPv6, Struct
from . enum import RType
#** Variables **#
__all__ = [
'Content',
... | imgurbot12/pydns | pydns/content.py | .py | 41014a66a849cb1e | 7 | 0 |
"""
EDNS OPT Answer Varient Implementation
"""
from typing import Optional
from typing_extensions import Annotated, Self
from pyderive import dataclass
from pystructs import Context, Struct, Domain, U8, U16
from ..enum import RType
from ..answer import BaseAnswer
#** Variables **#
__all__ = ['ROOT', 'EdnsAnswer']
#... | imgurbot12/pydns | pydns/edns/record.py | .py | 5f5148fc84d93a1d | 7 | 0 |
"""
DNS Enumeration Definitions
"""
from enum import IntEnum
#** Variables **#
__all__ = [
'QR',
'OpCode',
'RCode',
'RType',
'RClass',
'EDNSOption',
]
#** Classes **#
class QR(IntEnum):
"""
Message Operation-Code (QUESTION/RESPONSE)
"""
Question = 0
Response = 1
class OpC... | imgurbot12/pydns | pydns/enum.py | .py | 9004d0f5f8b8fbbb | 7 | 0 |
"""
DNS RCode Exceptions
"""
from typing import Any, Optional
from .enum import RCode
#** Variables **#
__all__ = [
'DnsError',
'ServerFailure',
'NonExistantDomain',
'NotImplemented',
]
#** Functions **#
def raise_error(rcode: RCode, message: Any = None):
"""
raise best exception object to m... | imgurbot12/pydns | pydns/exceptions.py | .py | 0dc7827bade9642b | 7 | 0 |
"""
DNS Flags Implementation
"""
from enum import IntFlag
from typing_extensions import Self
from pyderive import dataclass
from .enum import QR, OpCode, RCode
#** Variables **#
__all__ = ['Flags']
#** Functions **#
def unmask(flags: int, start: int, end: int) -> int:
"""
unmask a range of bits from the gi... | imgurbot12/pydns | pydns/flags.py | .py | b6dc8ea7bce28afa | 7 | 0 |
"""
DNS Message Object Definition
"""
from typing import List, Optional
from typing_extensions import Self
from pyderive import dataclass, field
from pystructs import U16, Context, Struct
from .answer import Answer, BaseAnswer, PreRequisite, Update, peek_rtype
from .edns import EdnsAnswer
from .enum import OpCode, RC... | imgurbot12/pydns | pydns/message.py | .py | 3cb8629141621212 | 7 | 0 |
"""
DNS Server Data Backend Implementations
"""
from abc import abstractmethod
from typing import Optional, Protocol, List, ClassVar
from typing_extensions import runtime_checkable
from pyderive import dataclass
from ... import Answer, RCode, RType
#** Variables **#
__all__ = [
'Answers',
'Backend',
'Ca... | imgurbot12/pydns | pydns/server/backend/__init__.py | .py | ccc6835445238d89 | 7 | 0 |
"""
Backend Extension to support In-Memory Answer Caching
"""
import time
import math
from logging import Logger, getLogger
from threading import Lock
from typing import ClassVar, Dict, List, Optional, Set
from pyderive import InitVar, dataclass, field
from . import Answers, Backend, RType, Answer
from .memory import... | imgurbot12/pydns | pydns/server/backend/cache.py | .py | 27000ad4235f3bb5 | 7 | 0 |
"""
Backend Recursive Client-Forwarder Extension
"""
from typing import ClassVar
from pyderive import dataclass
from . import Answers, Backend
from ...client import BaseClient
from ... import RType, Answer, Question
#** Variables **#
__all__ = ['Forwarder']
#** Classes **#
@dataclass(slots=True, repr=False)
class ... | imgurbot12/pydns | pydns/server/backend/forwarder.py | .py | ecb8ecec6a810f74 | 7 | 0 |
"""
In-Memory Backend Implementation
"""
import ipaddress
from fnmatch import fnmatch
from typing import Any, ClassVar, Dict, List, Set, Union
from typing_extensions import TypedDict
from . import Backend, Answers, Answer, RType
from ...answer import get_ctype
from ...content import Content, PTR
#** Variables **#
__a... | imgurbot12/pydns | pydns/server/backend/memory.py | .py | 959715d9a75bbb71 | 7 | 0 |
"""
Recursive Manual DNS Resolver
"""
import math
import random
from abc import abstractmethod
from datetime import datetime, timedelta
from typing import (
ClassVar, Dict, Generic, List, Optional, Protocol, TypeVar, Union, cast)
from pyderive import dataclass
from .. import Answers, Backend
from .... import A, A... | imgurbot12/pydns | pydns/server/backend/resolver/__init__.py | .py | 64d47d32c5519df5 | 7 | 0 |
"""
Simple Sqlite3 Resolver Cache Implementation
"""
import os
import json
import sqlite3
from datetime import datetime
from typing import Any, List, Optional, Type, Union
from typing_extensions import Annotated, get_origin, get_args
from pyderive.extensions.serde import (
TypeEncoder, TypeDecoder, serialize, dese... | imgurbot12/pydns | pydns/server/backend/resolver/sqlite.py | .py | d3b981888d30e70b | 7 | 0 |
"""
Custom Rule Engine for Blocking Unwanted Domains
"""
from enum import Enum
from abc import abstractmethod
from ipaddress import IPv4Address, IPv6Address
from typing import ClassVar, List, Optional, Protocol, Set
from pyderive import dataclass, field
from pydns import A, AAAA, Answer, RCode
from .. import RType, A... | imgurbot12/pydns | pydns/server/backend/ruleset/__init__.py | .py | b4ab7594e705d9bd | 7 | 0 |
"""
Simple Sqlite3 Database Implementaton for Rule Engine
"""
import re
import os
import sqlite3
from io import StringIO
from datetime import datetime
from typing import List, Optional
from . import RuleEngine, RStatus
from .parser import RuleDefs, Domain, Regex, Wildcard, parse_rules
from .wildcard import WildcardMat... | imgurbot12/pydns | pydns/server/backend/ruleset/database.py | .py | a39ce1fb25c4894f | 7 | 0 |
"""
RulesList Parser AdGuard/Domain-List/uBlock/etc...
"""
import re
import ipaddress
import warnings
from typing import Iterable, NamedTuple, Optional, TextIO, Union
from . import RStatus
#** Variables **#
__all__ = [
'Domain',
'Regex',
'Wildcard',
'Rule',
'RuleDef',
'RuleDefs',
'parse_r... | imgurbot12/pydns | pydns/server/backend/ruleset/parser.py | .py | 32ba774e366341cf | 7 | 0 |
"""
WildCard Matching Implementation
"""
from typing import Optional, List
from typing_extensions import Self
from pyderive import dataclass, field
#** Variables **#
__all__ = ['WildcardMatch']
#** Classes **#
@dataclass(slots=True)
class WildcardMatch:
"""
Match a String against a Wildcarded Pattern
""... | imgurbot12/pydns | pydns/server/backend/ruleset/wildcard.py | .py | f83f457b156545e2 | 7 | 0 |
"""
Simple Sqlite3 Statistics Storage Implementation
"""
import os
import sqlite3
from datetime import datetime, timedelta
from typing import Dict, List, Optional
from . import Stats, StatStorage, date_now
from .... import RType
#** Variables **#
__all__ = ['SqliteStatStore']
#: schema file location
SCHEMA = os.path... | imgurbot12/pydns | pydns/server/backend/stats/sqlite.py | .py | 5c70913d2d336c37 | 7 | 0 |
"""
Simple and Extensible DNS Server Implementation
"""
from enum import IntEnum
from logging import Logger, getLogger
from typing import Optional
from pyserve import Address, Writer
from pyserve import Session as BaseSession
from pyderive import dataclass, field
from .backend import Backend
from ..enum import QR, Op... | imgurbot12/pydns | pydns/server/server.py | .py | 9bcb0351797960c7 | 7 | 0 |
"""
DNS Message Packing/Unpacking UnitTests
"""
from unittest import TestCase
from .. import Message, OpCode, QR, RClass, RCode, RType
from ..edns import EdnsAnswer
#** Variables **#
__all__ = ['MessageTests']
EXAMPLE_REQUEST = 'a32701200001000000000001076578616d706c6503' +\
'636f6d000001000100002904d00000000000... | imgurbot12/pydns | pydns/tests/message.py | .py | 35837ac2390938a2 | 7.5 | 0 |
"""
DNS Recursive Resolver Backend Engine UnitTests
"""
from typing import List, Optional, Type
from unittest import TestCase
from .. import A, NS, RType, Answer
from ..content import Content, Unknown
from ..server.backend.resolver import MemoryCache, Record, Resolver
#** Variables **#
__all__ = ['ResolverTests']
#*... | imgurbot12/pydns | pydns/tests/resolver.py | .py | cfb8e78008b8a18a | 7.5 | 0 |
"""
DNS Server RuleSet Backend Engine UnitTests
"""
import tempfile
from io import StringIO
from ipaddress import IPv4Address
from typing import Optional
from unittest import TestCase
from .. import RCode, RType, Answer, A
from ..server.backend import *
from ..server.backend.ruleset.parser import *
#** Variables **#
... | imgurbot12/pydns | pydns/tests/ruleset.py | .py | 73bd929bec0b1587 | 7.5 | 0 |
"""
DNS Server Stats Backend Engine UnitTests
"""
import random
from datetime import datetime, timedelta
from typing import Dict, List
from unittest import TestCase
from pydns.server.backend.stats import date_now
from .. import RType
from ..server.backend import *
from ..server.backend.stats.sqlite import round_date
... | imgurbot12/pydns | pydns/tests/stats.py | .py | 5ed0e6386f2cfcd7 | 7.5 | 0 |
"""Spell checker module with contextual correction.
Provides spell checking functionality using n-gram language models
and edit distance algorithms for word correction.
"""
import re
from functools import lru_cache
from typing import Set, List, Dict
from .trainer import Trainer
class Checker:
"""Spell checker ... | Vaporjawn/Spell-Checker | lib/checker.py | .py | 6311ed2a0e95ea16 | 7 | 0 |
"""Language model trainer for spell checker.
Trains n-gram language models from a text corpus for use
in contextual spell checking and correction.
"""
import collections
import os
import re
from typing import List, Tuple, Dict, DefaultDict
class Trainer:
"""Train n-gram language models from text corpus.
At... | Vaporjawn/Spell-Checker | lib/trainer.py | .py | 657ebf4befb40d78 | 7 | 0 |
"""Flask application for spell checking service.
This module provides both a web interface and REST API for spell checking functionality.
Includes security headers, CORS configuration, and rate limiting.
"""
from datetime import datetime, timezone
import platform
import secrets
import sys
from typing import Dict, Any... | Vaporjawn/Spell-Checker | main.py | .py | c9771a3129c6c0fe | 7 | 0 |
"""Integration tests for spell checker system.
Tests the complete spell checking workflow from input to output.
"""
import sys
import os
import pytest
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from lib.checker import Checker
from lib.trainer import Trainer
class TestIntegr... | Vaporjawn/Spell-Checker | tests/test_integration.py | .py | d070daaadd78bf5b | 7.5 | 0 |
"""Performance benchmarks for spell checker.
Measures performance characteristics of key operations.
"""
import sys
import os
import time
import pytest
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from lib.checker import Checker
class TestPerformance:
"""Performance bench... | Vaporjawn/Spell-Checker | tests/test_performance.py | .py | 73f7b4019d5a6470 | 7.5 | 0 |
# -*- coding: utf-8 -*-
"""
阶段3:嵌套 Walk-Forward 选池 (selection bias / 池子过拟合检验)
问题:原10只池(及V6池)是否"天生过拟合"——即池子是事先用代码/后视镜挖出来的?
方法:
选池窗 2019-07 ~ 2022-12:用收益/夏普从 28 只跨类全集中挑 top-N (N=10 liubuni / N=4 V6)
测试窗 2023-01 ~ 2026-07:固定该池, 跑同一把尺子(关止损R²关轮动), 看 OOS 是否还赢
对照:
- 原始池 内样本(2019-2022) vs OOS(2023-2026)
- 选池(ex-a... | hehex2000/Yijiang-Hu | analyze_liubuni_stage3_nested_wf.py | .py | 983ad08892264d63 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
补全 fina_indicator 的 Piotroski F-score 必需六列:roa / gross_margin / asset_turn / ocfps / eps / current_ratio。
背景:
计划 plan_piotroski.md 的 P0 第一优先级数据补全项。本地 fina_indicator 表已被
backfill_fina_2013_2014.py 等 ALTER 加过 ocfps/debt_to_assets/ocf_to_debt/ar_turn 等列
(value_stock_selector 在用),但 F-scor... | hehex2000/Yijiang-Hu | backfill_fina_fscore.py | .py | 10b6dd6f1d22e5f9 | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
布林带均值回归策略插件(继承 BaseStrategy)
- 信号基于前一日收盘价 + 布林带上下轨判断
- 今日开盘价成交
- 止盈止损基于前一日收盘价判断
价格触及下轨 → 买入(超卖)
价格触及上轨 → 卖出(超买)
止盈50%,止损15%
仓位管理(v2):
- use_kelly=False: 固定半仓(50%)/全仓(95%)
- use_kelly=True: 半凯利公式动态仓位(默认上限20%)
优化:使用 TA-Lib 计算布林带和 RSI(性能提升 10-100 倍)
"""
import pandas as... | hehex2000/Yijiang-Hu | backtest/_archive/bollinger_plugin.py | .py | bd3c67f02e6287f9 | 7.5 | 0 |
"""
月定投策略插件(Monthly DCA)
每月第一个交易日买入:严格投入指定金额(向下取整到100股),不够买100股就跳过
止盈 take_profit%,止损 stop_loss%
止损触发卖出50%仓位,止盈触发卖出100%仓位
继承 BaseStrategy,符合回测平台插件接口
"""
import pandas as pd
from backtest.base_strategy import BaseStrategy
from loguru import logger
class DCAStrategyPlugin(BaseStrategy):
"""月定投策略(插件版)"""
d... | hehex2000/Yijiang-Hu | backtest/_archive/dca_plugin.py | .py | a71e17c6a84652fb | 7.5 | 0 |
"""
双均线策略插件(Dual MA Cross)
MA20 上穿 MA60 金叉买入50%仓,死叉全仓卖出
止盈 take_profit%,止损 stop_loss%
继承 BaseStrategy,符合回测平台插件接口
优化:使用 TA-Lib 计算均线(性能提升 10-100 倍)
"""
import pandas as pd
import numpy as np
import talib as ta # ← 新增 TA-Lib
from backtest.base_strategy import BaseStrategy
from backtest.atr_stop_loss import ATRStopLoss
... | hehex2000/Yijiang-Hu | backtest/_archive/dual_ma_plugin.py | .py | 8e2d3b578ac307c1 | 7.5 | 0 |
"""
能量型指标计算模块 - AR/BR/CR/VR 四个指标
AR:人气指标 — 以开盘价为基准,衡量盘中多空力量对比
BR:意愿指标 — 以前日收盘价为基准,衡量隔夜情绪和买入意愿
CR:能量指标 — 以典型价格(TP)为中轴,衡量趋势动量
VR:成交量指标 — 衡量上涨日与下跌日成交量对比,判断资金流向
核心用途:
- 作为独立策略的买卖信号来源
- 作为风控模块的辅助过滤因子
"""
import pandas as pd
import numpy as np
from loguru import logger
def calculate_ar(df: pd.DataFrame, n: int = 26) -> ... | hehex2000/Yijiang-Hu | backtest/_archive/energy_indicators.py | .py | 9371b411ca5d4040 | 7.5 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MACD/RSI 组合策略插件(继承 BaseStrategy)
- 前一日MACD金叉+RSI<70 → 今日开盘买入
- 前一日MACD死叉或RSI>70 → 今日开盘卖出
- 止盈止损基于前一日收盘价判断
优化:使用 TA-Lib 计算 MACD 和 RSI(性能提升 10-100 倍)
"""
import pandas as pd
import numpy as np
import talib as ta # ← 新增 TA-Lib
from backtest.base_strategy import BaseStra... | hehex2000/Yijiang-Hu | backtest/_archive/macd_kdj_plugin.py | .py | d73fd8b2ac182e01 | 7.5 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
均值回归策略插件(继承 BaseStrategy)
基于视频《量化交易入门——均值回归策略》实现
核心逻辑:
1. 三把尺子:布林带(均值)、波动率(正常范围)、Z-Score(偏离程度)
2. 双重共振入场:价格触及下轨 AND RSI < 30(动能彻底耗尽)
3. 布林带宽度过滤:喇叭口张开(趋势启动)时禁止入场
4. 出场:Z > 2 OR RSI > 70
5. 硬止损:3%(防止均值永久下移)
信号基于前一日数据(shift(1)),避免未来函数
买入/卖出均用次日开盘价执行
"""
import pandas as... | hehex2000/Yijiang-Hu | backtest/_archive/mean_reversion_plugin.py | .py | de8fbd37e503947d | 7.5 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
RSI 超买超卖策略插件(继承 BaseStrategy)
- 前一日RSI < 超卖线 → 今日开盘买入
- 前一日RSI > 超买线 → 今日开盘卖出
- 止盈止损基于前一日收盘价判断
优化:使用 TA-Lib 计算 RSI(性能提升 10-100 倍)
"""
import pandas as pd
import numpy as np
import talib as ta # ← 新增 TA-Lib
from backtest.base_strategy import BaseStrategy
from backtest... | hehex2000/Yijiang-Hu | backtest/_archive/rsi_plugin.py | .py | 41f8e9d2efc3922d | 7.5 | 0 |
"""
海龟策略插件(Turtle Strategy)
通道上限为当前日之前n日收盘成交价最大值
通道下限为当前日之前n日收盘成交价最小值
当股价上穿上限时买入(最多加仓max_positions次),下穿下限时卖出(全仓卖出)
止盈take_profit%,止损stop_loss%
交易手续费:万分之2(买入和卖出均收取)
印花税:千分之1(仅卖出收取)
"""
import pandas as pd
from backtest.base_strategy import BaseStrategy
from loguru import logger
class TurtleStrategyPlugin(BaseStrategy)... | hehex2000/Yijiang-Hu | backtest/_archive/turtle_plugin.py | .py | 00e0c2b749cc21d1 | 7.5 | 0 |
"""
策略基类 — 所有策略必须继承此类并实现 run() 方法
"""
import pandas as pd
import sqlite3
from pathlib import Path
from backtest.kelly_sizer import KellySizer
# 数据库路径(共享)—— 统一指向平台唯一主库(2026-07-08 修正:原 data/stock_db.db 不存在)
DB_PATH = r"D:\tu-shareData\astock_daily.db"
class BaseStrategy:
"""
策略基类 — 定义标准接口
新策略只需:
1... | hehex2000/Yijiang-Hu | backtest/base_strategy.py | .py | 0fd1628f0c3c089e | 7.5 | 0 |
"""
双均线策略插件(Dual MA Cross)
MA20 上穿 MA60 金叉买入50%仓,死叉全仓卖出
止盈 take_profit%,止损 stop_loss%
继承 BaseStrategy,符合回测平台插件接口
优化:使用 TA-Lib 计算均线(性能提升 10-100 倍)
"""
import pandas as pd
import numpy as np
import talib as ta # ← 新增 TA-Lib
from backtest.base_strategy import BaseStrategy
from backtest.atr_stop_loss import ATRStopLoss
... | hehex2000/Yijiang-Hu | backtest/dual_ma_plugin.py | .py | 93f6811d915ab30b | 7.5 | 0 |
# -*- coding: utf-8 -*-
"""
ETF 折溢价率 风险过滤器
========================
来源:B站「跟着Jim学量化」《ETF溢价,就等于后面还会涨吗?》(BV1JS316dETi)
—— 经人工校验为正确知识,萃取为 ETF轮动 策略的买入前风险过滤器。
【视频核心结论(已验证正确)】
1. 折溢价率 = (市价 − 参考值) / 参考值。参考值用 IOPV(盘中估算) 或 正式净值(收盘确认),二者不可混用。
2. 溢价 ≠ 会涨;折价 ≠ 无风险套利(涉及成组份额/费用/执行条件)。
3. 跨境ETF(恒生/纳指) 因「境内交易时境外休市 + 汇率变动 ... | hehex2000/Yijiang-Hu | backtest/etf_premium_filter.py | .py | c8c17df05abb02ae | 7.5 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
均值回归策略插件(继承 BaseStrategy)
基于视频《量化交易入门——均值回归策略》实现
核心逻辑:
1. 三把尺子:布林带(均值)、波动率(正常范围)、Z-Score(偏离程度)
2. 双重共振入场:价格触及下轨 AND RSI < 30(动能彻底耗尽)
3. 布林带宽度过滤:喇叭口张开(趋势启动)时禁止入场
4. 出场:Z > 2 OR RSI > 70
5. 硬止损:3%(防止均值永久下移)
信号基于前一日数据(shift(1)),避免未来函数
买入/卖出均用次日开盘价执行
"""
import pandas as... | hehex2000/Yijiang-Hu | backtest/mean_reversion_plugin.py | .py | d2e15e6f007d2ec1 | 7.5 | 0 |
"""The time axis of a series.
Every estimator needs the same three things from a time index: numeric
positions, a representative step size, and whether the sampling is regular.
Before this module each estimator derived them itself, at fifteen call sites,
with enough drift between them that ``local_polynomial_trend`` c... | finite-sample/incline | src/incline/axis.py | .py | d0b8e05023d08a1e | 7.24 | 2 |
"""Noise models for the residual process.
A derivative estimate's sampling variance is ``diag(L Sigma L')`` where ``L`` is
the estimator's linear operator and ``Sigma`` the covariance of the noise. This
module supplies ``Sigma``.
Estimating it is the subtle part. The obvious approach -- fit the smoother, take
the res... | finite-sample/incline | src/incline/noise.py | .py | 15ed9a96987612aa | 7.24 | 2 |
"""Ranking many series by how strongly they are trending.
The point of this layer is to answer "which of these thousands of series is
moving fastest right now", and the honest version of that answer needs to know
which apparent movements are real.
Previously it could not. Each series arrived as a DataFrame of point e... | finite-sample/incline | src/incline/ranking.py | .py | 686705939c38b7cc | 7.24 | 2 |
"""The result of a trend estimation.
Previously this was a naming convention: estimators appended columns named
``derivative_value``, ``smoothed_value`` and so on to a copy of the input frame,
and every consumer agreed to look for them. Nothing enforced the agreement, so
``naive_trend`` never produced ``smoothed_value... | finite-sample/incline | src/incline/result.py | .py | ede17bf9145ff901 | 7.24 | 2 |
"""Synthetic series with known derivatives, for testing estimators against truth.
A standard error is a claim about repeated sampling, so checking one means
simulating from a trend whose derivative you already know. These generators
supply that ground truth.
``noise_std`` means the same thing for every noise type her... | finite-sample/incline | src/incline/simulate.py | .py | f4e6116382954039 | 7.24 | 2 |
"""SiZer: which trend features survive being looked at from every scale.
A single bandwidth is a single opinion about what counts as signal. SiZer sweeps
the bandwidth and asks, at each scale and each point, whether the slope is
distinguishable from zero. Features that persist across many scales are real;
features tha... | finite-sample/incline | src/incline/sizer.py | .py | 3f23ead62db603e5 | 7.24 | 2 |
"""Incline's Monte Carlo helpers, on top of simcheck.
The generic machinery -- ``MonteCarloResult``, the binomial gates, the replicate
runner -- lives in `simcheck <https://github.com/finite-sample/simcheck>`_, which
was extracted from this file. What stays here is the part that is genuinely about
incline: driving a `... | finite-sample/incline | tests/_statistics.py | .py | df75e63a72722115 | 7.74 | 2 |
"""Tests for the functional surface.
These run over every public estimator at once. The facade is thin by design, so
what is worth testing here is that it is thin *uniformly*: the same schema, the
same option handling, the same behavior on awkward input, whichever estimator
you reach for.
"""
from __future__ import a... | finite-sample/incline | tests/test_api.py | .py | 21fad1335f56f218 | 7.74 | 2 |
"""Tests for the time axis.
Every estimator derives its x from here, so a mistake in this module is a
mistake in all of them. That is not hypothetical: the derivation used to be
copied across fifteen call sites, and one copy returned a pandas ``Index``
instead of an ndarray, which crashed ``local_polynomial_trend`` on... | finite-sample/incline | tests/test_axis.py | .py | 2e5db899f618039f | 7.74 | 2 |
"""Do the Bayesian estimators' credible intervals mean what they say?
Gaussian processes and state-space models are shrinkage estimators. They are
biased by construction -- pulling the fit toward the prior is the entire point --
so the unbiasedness and frequentist-coverage gates in ``test_econometrics.py``
do not appl... | finite-sample/incline | tests/test_bayesian_calibration.py | .py | 3fef22b49e875777 | 7.74 | 2 |
"""Does the estimator get better with more data, and does the knob work?
Two families of property that a single sample size cannot reveal.
**Consistency.** As the sample grows and the bandwidth shrinks appropriately,
bias and variance both go to zero. An estimator can be perfectly calibrated at
one n and still be wro... | finite-sample/incline | tests/test_consistency.py | .py | 94f22240d06dfbe3 | 7.74 | 2 |
"""Tests for the smoothers that are probability models.
A Gaussian process and a state-space model carry their own posterior variance,
so they bypass both the operator probe and the bootstrap. That makes them the
two places where a variance bug cannot be caught by the shared machinery, which
is why the numbers here ar... | finite-sample/incline | tests/test_process.py | .py | 50dd7f6c6ad74b32 | 7.74 | 2 |
"""Tests for ranking many series by trend strength.
This layer used to discard standard errors even where the estimator had
produced them, and derived significance by resampling the last k derivative
values as though they were independent draws -- they are adjacent points on one
smoothed curve. Most of what follows pi... | finite-sample/incline | tests/test_ranking.py | .py | f28a9f3e8c92f496 | 7.74 | 2 |
"""What happens when the Gaussian, constant-variance assumption is wrong?
Two very different answers, which is the point of separating them.
**Non-Gaussian noise barely matters.** A smoother's derivative is a weighted sum
of many observations, so the central limit theorem does the work: the sampling
distribution is c... | finite-sample/incline | tests/test_robustness.py | .py | ab1257afe556a1fb | 7.74 | 2 |
"""Tests for seasonal decomposition.
The schema tests carry the most weight. The previous implementation returned
``derivative_value`` from one code path and ``trend_derivative_value`` from
another, so what a caller had to index depended on whether seasonality happened
to be detected. Several tests below exist purely ... | finite-sample/incline | tests/test_seasonal.py | .py | d4207a2b7b0d4f92 | 7.74 | 2 |
"""Tests for the synthetic-series generators.
These generators are the ground truth the calibration suite measures against, so
a silent error here would quietly invalidate every coverage number in
``test_calibration.py``. Two properties matter most: the closed-form derivatives
really are the derivatives, and ``noise_s... | finite-sample/incline | tests/test_simulate.py | .py | 790faff3ee2e2d3a | 7.74 | 2 |
"""Tests for the scale sweep.
The property that matters is calibration on null data. The previous SiZer
carried its own variance formulas and the spline branch flagged roughly 90% of
pure noise as trending; the module docstring said so. SiZer no longer computes
standard errors at all, so the map inherits whatever the ... | finite-sample/incline | tests/test_sizer.py | .py | af70e5bc7225078e | 7.74 | 2 |
#!/usr/bin/python
# Copyright 2020, Red Hat, Inc.
#
# 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 ... | alvistack/ansible-role-ceph_rgw | library/ceph_mgr_module.py | .py | 451151063ab3bf45 | 7.15 | 1 |
"""behave hooks for the acceptance suite."""
import os
def before_all(context):
if not os.environ.get("OPENSPEC_ACCEPTANCE"):
raise RuntimeError(
"Run the suite via `python run_acceptance.py` (not plain `behave`).\n"
"The wrapper extracts Gherkin from openspec/**/spec.md and compo... | chrisime/CRooD | .agents/skills/acceptance-test-authoring/references/python/environment.py | .py | 40dd337489ad600b | 7.65 | 1 |
#!/usr/bin/env python3
"""
Minimal example of a file receiving service in python 2.7 using only built-ins intended for use in the
IntelliJ Code Exfiltration demonstration plugin. There is no error check or security, this is simply meant
to be abase/reference to quickly demonstrate the plugin.
Usage:
$ python mini... | ChrisCarini/intellij-code-exfiltration | python_post_server/minimal_upload_server.py | .py | de8b9480caabc559 | 7.24 | 2 |
import pytest
from unittest.mock import MagicMock, mock_open
from monitor.writer import DBConnection, MetricsWriter
from monitor.config import config as global_config
@pytest.fixture
def mock_postgres_config():
"""Returns a PostgreSQL configuration for DBConnection initialization."""
return {'postgres': {'ur... | skoenig/website-monitor | tests/test_writer.py | .py | f7d104980fbf0573 | 7.65 | 1 |
#!/usr/bin/env python3
import argparse
import asyncio
import atexit
import os
import struct
import socket
import signal
import sys
# Global verbose flag
VERBOSE = False
def log(msg):
"""Print debug message if verbose mode is enabled."""
if VERBOSE:
print(f"[host-address-advertiser] {msg}", file=sys.s... | ColOfAbRiX/role-wsl-config | files/wsl2/ubuntu-22/host-address.py | .py | 0d113d2c77367536 | 7 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.