text stringlengths 185 73.3k | repo stringlengths 7 100 | path stringlengths 4 146 | language stringclasses 7
values | hash stringlengths 16 16 | score float64 7 8.5 | stars int64 0 237k |
|---|---|---|---|---|---|---|
import json
import os
from os import path
import click
class Cursor:
def __init__(self, location):
self._location = location
self._name = path.basename(location)
@property
def name(self):
return self._name
@property
def value(self):
with open(self._location) as f... | code42/incydr_python | src/_incydr_cli/cursor.py | .py | 61bdd21b1774f242 | 7.5 | 9 |
import os
import click
from click._compat import get_text_stderr
from _incydr_cli import ERROR_LOG_FILE_NAME
from _incydr_cli import get_user_project_path
class IncydrCLIException(click.ClickException):
"""Wrapper class for Incydr CLI exceptions. The `message` param automatically gets logged to error file and p... | code42/incydr_python | src/_incydr_cli/exceptions.py | .py | 3d42222253aa8470 | 7.5 | 9 |
import chardet
import click
class AutoDecodedFile(click.File):
"""Attempts to autodetect file's encoding prior to normal click.File processing."""
def convert(self, value, param, ctx):
try:
with open(value, "rb") as file:
self.encoding = chardet.detect(file.read())["encodi... | code42/incydr_python | src/_incydr_cli/file_readers.py | .py | 730675131fd54a3b | 7.5 | 9 |
import logging
from threading import Lock
import click
from click import BadOptionUsage
from _incydr_cli.logger.enums import ServerProtocol
from _incydr_cli.logger.handlers import NoPrioritySysLogHandler
# prevent loggers from printing stacks to stderr if a pipe is broken
logging.raiseExceptions = False
logger_de... | code42/incydr_python | src/_incydr_cli/logger/__init__.py | .py | 3279b8450ab63e2b | 7.5 | 9 |
import sys
from csv import DictWriter
from datetime import datetime
from io import TextIOWrapper
from itertools import chain
from typing import Iterable
from typing import List
from typing import Type
from pydantic import BaseModel
from rich.console import Console
from rich.console import ConsoleRenderable
from rich.c... | code42/incydr_python | src/_incydr_cli/render.py | .py | 8f630d1eda8006d5 | 7.5 | 9 |
from datetime import datetime
from itertools import count
from typing import Union
import requests
from ..exceptions import IncydrException
from .models import Actor
from .models import ActorFamily
from .models import ActorsPage
from .models import QueryActorsRequest
from _incydr_sdk.exceptions import DateParseError
... | code42/incydr_python | src/_incydr_sdk/actors/client.py | .py | 338db46458b286fb | 7.5 | 9 |
from typing import List
from typing import Optional
from pydantic import BaseModel
from pydantic import Field
from _incydr_sdk.core.models import ResponseModel
class QueryActorsRequest(BaseModel):
nameStartsWith: Optional[str] = None
nameEndsWith: Optional[str] = None
active: Optional[bool] = None
p... | code42/incydr_python | src/_incydr_sdk/actors/models.py | .py | b9d81db5678086a6 | 7.5 | 9 |
from itertools import count
from typing import Iterator
from typing import List
from typing import Optional
from typing import Union
import requests
from ..enums import SortDirection
from .models import Agent
from .models import AgentsPage
from .models import AgentType
from .models import AgentUpdateRequest
from .mod... | code42/incydr_python | src/_incydr_sdk/agents/client.py | .py | baf8548daf51e149 | 7.5 | 9 |
from __future__ import annotations
from datetime import datetime
from typing import List
from typing import Optional
from typing import Union
from pydantic import BaseModel
from pydantic import Field
from pydantic import field_validator
from _incydr_sdk.core.models import ResponseModel
from _incydr_sdk.enums import ... | code42/incydr_python | src/_incydr_sdk/agents/models.py | .py | 6158391a10fc73ce | 7.5 | 9 |
"""Graphdb CIM sparql client."""
from __future__ import annotations
import json
import os
from copy import deepcopy
from dataclasses import dataclass, field
from enum import StrEnum
from http import HTTPStatus
from pathlib import Path
from typing import TYPE_CHECKING, TypedDict, TypeVar
import httpx
import pandas as... | statnett/cimsparql | src/cimsparql/graphdb.py | .py | 3c108f012305609d | 7.52 | 10 |
"""Pydantic model for sparql result."""
from __future__ import annotations
from typing import TYPE_CHECKING
from polyfactory.decorators import post_generated
from polyfactory.factories import pydantic_factory
from pydantic import BaseModel, ConfigDict, Field
if TYPE_CHECKING:
from typing import Any, Self
clas... | statnett/cimsparql | src/cimsparql/sparql_result_json.py | .py | bf374b97b9be94d1 | 7.52 | 10 |
"""Type mapper functionality for graphdb data."""
from __future__ import annotations
import dataclasses
from contextlib import contextmanager
from decimal import Decimal
from typing import TYPE_CHECKING, Any
import pandas as pd
from cimsparql.templates import TYPE_MAPPER_QUERY
if TYPE_CHECKING:
from collection... | statnett/cimsparql | src/cimsparql/type_mapper.py | .py | 6f80fc8c41dc9bd8 | 7.52 | 10 |
"""Functions used to configure GraphDB client.
Will handle authenticated instances of GraphDB where user and password is given in environment
variables ("GRAPHDB_USER" & "GRAPHDB_USER_PASSWD").
"""
def service(repo: str | None = None, server: str = "127.0.0.1:7200", protocol: str = "https", path: str = "") -> str:
... | statnett/cimsparql | src/cimsparql/url.py | .py | 20353c1e70cefd09 | 7.52 | 10 |
"""Provide value mappers."""
import pandas as pd
class ValueMapper:
"""Base value mapper."""
def map(self, df: pd.DataFrame) -> pd.DataFrame:
_ = self
return df
class MridMapper(ValueMapper):
"""Mrid mapper.
Replaces all matches of uri_regex with an empty string in columns which c... | statnett/cimsparql | src/cimsparql/value_mapper.py | .py | 558573af80656f37 | 7.52 | 10 |
from __future__ import annotations
import asyncio
import os
from dataclasses import dataclass
from string import Template
from typing import TYPE_CHECKING
import pytest
import tests.t_utils.common as t_common
import tests.t_utils.custom_models as t_custom
import tests.t_utils.entsoe_models as t_entsoe
if TYPE_CHECK... | statnett/cimsparql | tests/test_model_properties.py | .py | 69c4976d39971aa4 | 8.02 | 10 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sys import stderr
import re
import audiofile
import config
def warn(msg):
"""print message to stderr"""
print(msg, file=stderr)
def probe(path):
"""Read sample metadata, or None if the file is unreadable"""
try:
return {
'channe... | porzione/wavescan | libwavescan.py | .py | 2917ea6a35e608ff | 7.63 | 17 |
import sys
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent
FIXTURES = Path(__file__).resolve().parent / "fixtures"
sys.path.insert(0, str(REPO))
import pytest # noqa: E402
class FakeEnt:
"""Stands in for an os.DirEntry"""
def __init__(self, path):
self.path = path
se... | porzione/wavescan | tests/conftest.py | .py | 0963aeae3fd68389 | 8.13 | 17 |
"""Tests for WSNote.guess() — the file-name-to-drum heuristic"""
import pytest
from libwavescan import WSNote
from conftest import FakeArgs, FakeEnt
@pytest.fixture(scope="module")
def wsnote():
return WSNote(FakeArgs())
# hand-picked cases, including regressions for fixed config bugs
KNOWN = [
("Kick_909... | porzione/wavescan | tests/test_guess.py | .py | 85666f21d61c3483 | 8.13 | 17 |
import math
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, Tuple
import numpy as np
if TYPE_CHECKING:
from readimc.data.panorama import Panorama
from readimc.data.slide import Slide
class AcquisitionBase(ABC):
... | BodenmillerGroup/readimc | readimc/data/acquisition.py | .py | 07e29be5ebd7a556 | 7.66 | 20 |
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple
from readimc.data.acquisition import Acquisition
if TYPE_CHECKING:
from readimc.data.slide import Slide
@dataclass
class Panorama:
"""Panorama metadata (only for panoramas with panorama image data)"""
... | BodenmillerGroup/readimc | readimc/data/panorama.py | .py | b473a87230ec7975 | 7.66 | 20 |
from dataclasses import dataclass, field
from typing import Dict, List, Optional
from readimc.data.acquisition import Acquisition
from readimc.data.panorama import Panorama
@dataclass
class Slide:
"""Slide metadata"""
id: int
"""Slide ID"""
metadata: Dict[str, str]
"""Full slide metadata"""
... | BodenmillerGroup/readimc | readimc/data/slide.py | .py | cc225f403e021125 | 7.66 | 20 |
from abc import ABC, abstractmethod
from os import PathLike
from pathlib import Path
from typing import Optional, Union
import numpy as np
from .data import Acquisition
class IMCFile(ABC):
"""Shared IMC file interface"""
def __init__(self, path: Union[str, PathLike]) -> None:
super().__init__()
... | BodenmillerGroup/readimc | readimc/imc_file.py | .py | dd2554a33e8d041f | 7.66 | 20 |
import mmap
import tempfile
from os import W_OK, PathLike, access, path
from pathlib import Path
from typing import BinaryIO, List, Optional, Sequence, Tuple, Union
from warnings import warn
import numpy as np
from imageio.v2 import imread
from .data import Acquisition, Panorama, Slide
from .imc_file import IMCFile
f... | BodenmillerGroup/readimc | readimc/mcd_file.py | .py | d68977df5af2fff3 | 7.66 | 20 |
import logging
import os
from datetime import datetime, timedelta, timezone
import discord
from discord import app_commands
from discord.ext import commands
from settings import GUILD_ID
from libs.http_client import HTTPClient, handle_api_error
from libs.logging import DiscordBotHandler
LOG_TEXT_CHANNEL_ID = os.envi... | pistachiostudio/takohachi | src/cogs/apex_tracker.py | .py | cb6ac6e0df296c7a | 7.42 | 6 |
import os
from discord.ext import commands
from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive
class DeleteImage(commands.Cog):
"""画像を削除するやつですが、動作しないので調整中です"""
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.Cog.listener()
async def on_raw_reaction_cl... | pistachiostudio/takohachi | src/cogs/delete_image.py | .py | 8818a5fcbd2bd60c | 7.42 | 6 |
import os
from pathlib import Path
from typing import Dict, List, Optional
import gspread
from oauth2client.service_account import ServiceAccountCredentials
DIC_KEY = os.environ["DIC_KEY"]
class TriggerRepository:
def __init__(self, addssl_json_keyfile: Path):
# 2つのAPIを記述しないとリフレッシュトークンを3600秒毎に発行し続けなければな... | pistachiostudio/takohachi | src/cogs/repository.py | .py | 086a74cfe62f0dbe | 7.42 | 6 |
import discord
from libs.utils import get_now_timestamp_jst
# 共通で利用するカスタム embed を返します
def get_custum_embed() -> discord.Embed:
embed = discord.Embed()
embed.timestamp = get_now_timestamp_jst()
return embed
def create_embed(
title: str | None = None,
description: str | None = None,
color: d... | pistachiostudio/takohachi | src/libs/embed.py | .py | 9a1b28f0bdb37a79 | 7.42 | 6 |
"""
HTTPクライアント関連の共通処理を提供するモジュール
"""
import logging
import httpx
import tenacity
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential
logger = logging.getLogger(__name__)
class APIError(Exception):
"""API関連のエラーの基底クラス"""
def __init__(
self, messa... | pistachiostudio/takohachi | src/libs/http_client.py | .py | 6ac4248e2e635dbb | 7.42 | 6 |
import os
import re
from datetime import datetime, timedelta, timezone
from random import randint
from urllib import parse
import httpx
import yfinance as yf
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential
from yfinance.exceptions import YFRateLimitError
from libs.http_client... | pistachiostudio/takohachi | src/libs/utils.py | .py | e538c6f4c628da2f | 7.42 | 6 |
#!/usr/bin/env python3
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import minimize
import argparse
def build_parser():
"""
Build options for parser
"""
parser = argparse.ArgumentParser()
txt = "file containg phi angle, QM, and MM energies in 1st, 2nd... | emanuelefalbo/HessFit | hessfit/fit4dihe-boltz.py | .py | 144e83ddec72862e | 7.5 | 9 |
#!/usr/bin/env python3
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import minimize
import argparse
def build_parser():
"""
Build options for parser
"""
parser = argparse.ArgumentParser()
txt = "file containg phi angle, QM, and MM energies in 1st, 2nd... | emanuelefalbo/HessFit | hessfit/fit4dihe-nonlin-phase.py | .py | 0bcb3a6ffdd8220a | 7.5 | 9 |
#!/usr/bin/env python3
import re
import argparse
import pandas as pd
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
'''
alist.sort(key=natural_keys) sorts in human order
http://nedbatchelder.com/blog/200712/human_sorting.html
(See Toothy's implementation in t... | emanuelefalbo/HessFit | hessfit/get_mm_energy.py | .py | 98e1dc659a829555 | 7.5 | 9 |
#!/usr/bin/env python3
import argparse
import os
def dir_path(string):
if os.path.isdir(string):
return string
else:
raise NotADirectoryError(string)
def commandline_parser():
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-f1','-... | emanuelefalbo/HessFit | hessfit/log2topol.py | .py | 9e853a0c990fac33 | 7.5 | 9 |
#!/usr/bin/env python3
import os
import get_amass
import guessBO
def build_dihe_folder(fname, type_list, charges):
# Function to store force field strings, and
# atomtype-charges for the GauScan2log function
folder = 'dihedrals'
if not os.path.exists(folder):
os.makedirs(folder)
wi... | emanuelefalbo/HessFit | hessfit/print_top.py | .py | 84ebe9b430e9de46 | 7.5 | 9 |
def gaff_vdw_parameters():
"""
Returns GAFF/AMBER van der Waals parameters:
Radius = Rmin/2 (Å)
Well-depth = epsilon (kcal/mol)
"""
return {
# ---- CARBON ----
"c": (1.9080, 0.0860),
"c2": (1.9080, 0.0860),
"c3": (1.9080, 0.1094),
"ca": (1.9080, 0.0860)... | emanuelefalbo/HessFit | hessfit/vdwparms.py | .py | b0c658e8eb64d1e2 | 7.5 | 9 |
#!/usr/bin/env python3
"""
xTB conformational prescreening for HessFit.
xTB is used only to optimize candidate conformers and obtain
relative energies.
The resulting structures are subsequently used as starting
geometries for the high-level Gaussian Opt + Freq calculations.
The canonical HessFit RIC definition is N... | emanuelefalbo/HessFit | hessfit/xtb_screening.py | .py | 515ae595a1a85892 | 7.5 | 9 |
#!/usr/bin/env python3
# this_file: opentype_hinting_freezer/hintingfreezer.py
"""Bake a font's hinting into its outlines at a chosen pixel size."""
from __future__ import annotations
import io
import warnings
from collections.abc import Iterator, KeysView, Mapping
from pathlib import Path
from typing import Any
fro... | twardoch/fonttools-opentype-hinting-freezer | opentype_hinting_freezer/hintingfreezer.py | .py | e4b7308f30e3dd4c | 7.42 | 6 |
# this_file: tests/conftest.py
"""
Pytest configuration and fixtures for OpenType Hinting Freezer tests.
"""
import pytest
from pathlib import Path
import tempfile
import shutil
import subprocess
import sys
from typing import Generator
# Test directories
TEST_DIR = Path(__file__).parent
DATA_DIR = TEST_DIR / "data"
O... | twardoch/fonttools-opentype-hinting-freezer | tests/conftest.py | .py | 18fb87729c67d285 | 7.92 | 6 |
import pytest
from pathlib import Path
import subprocess
import sys
# Helper to get the path to the pyfthintfreeze executable script
# This might need adjustment depending on how the CLI is installed/run in test env
# For an editable install, `pyfthintfreeze` should be on the PATH within the venv.
CLI_EXECUTABLE = "py... | twardoch/fonttools-opentype-hinting-freezer | tests/test_cli_integration.py | .py | 1609e060249834ba | 7.92 | 6 |
# this_file: tests/test_error_handling.py
"""
Tests for error handling in OpenType Hinting Freezer.
"""
import pytest
from pathlib import Path
import tempfile
from opentype_hinting_freezer.hintingfreezer import freezehinting, read_from_path
def test_read_from_path_nonexistent_file():
"""Test that reading a non-e... | twardoch/fonttools-opentype-hinting-freezer | tests/test_error_handling.py | .py | 887cafd96fecb8cf | 7.92 | 6 |
#!/usr/bin/env python3
# this_file: gimeltra/gimeltra.py
"""Abjad transliteration engine.
Scripts are named by their ISO 15924 code (``Hebr``, ``Arab``, ``Latn``, ...).
The rules live in ``gimeltra_data.json``, compiled from ``gimeltra.tsv`` by
``update.py``. Latin (``Latn``) is the pivot: any pair that lacks a direct... | twardoch/gimeltra | gimeltra/gimeltra.py | .py | 20e215b1e7ed21c2 | 7.62 | 16 |
#!/usr/bin/env python3
# this_file: tests/test_gimeltra.py
"""Tests for the Gimeltra transliteration engine."""
import subprocess
import sys
import pytest
from fontTools import unicodedata as ucd
import gimeltra
from gimeltra import Transliterator, tr
def _nfkc(s: str) -> str:
# Fold presentation-form ligature... | twardoch/gimeltra | tests/test_gimeltra.py | .py | 9e340ba6f29771cd | 8.12 | 16 |
# bencode structured encoding
#
# Written by Petru Paler
#
# 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,... | breezy-team/fastbencode | fastbencode/_bencode_py.py | .py | b1018cbf021f1890 | 7.62 | 16 |
# Copyright (C) 2007, 2009, 2010, 2016 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program ... | breezy-team/fastbencode | tests/test_bencode.py | .py | ad8706925b349393 | 7.12 | 16 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# @created: 27.12.2024
# @author: Aleksey Komissarov
# @contact: ad3002@gmail.com
"""
Batch check TRF consistency for multiple genome assemblies.
This script iterates through directories containing genome assemblies and runs
TRF consistency checks on each one. If issue... | aglabx/satellome | scripts/batch_check_trf_consistency.py | .py | f0d3e48c0357a50d | 7.45 | 7 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# @created: 27.12.2024
# @author: Aleksey Komissarov
# @contact: ad3002@gmail.com
"""
Check TRF results consistency.
This script verifies that TRF analysis completed successfully for all contigs/scaffolds
above a certain size threshold. It's expected that contigs large... | aglabx/satellome | scripts/check_trf_consistency.py | .py | 2991584b0b358408 | 7.45 | 7 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @created: 2025-11-15
# @author: Claude Code
# @contact: noreply@anthropic.com
"""
Custom exception classes for Satellome.
This module defines a hierarchy of exception classes for better error handling
and debugging throughout the Satellome pipeline. Using specific exc... | aglabx/satellome | src/satellome/core_functions/exceptions.py | .py | 8ea0aa1ddb8d45ad | 7.45 | 7 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @created: 05.06.2011
# @author: Aleksey Komissarov
# @contact: ad3002@gmail.com
"""
Classes:
- AbstractBlockFileIO(AbstractFileIO)
"""
from satellome.core_functions.io.abstract_reader import AbstractFileIO
class AbstractBlockFileIO(AbstractFileIO):
"""... | aglabx/satellome | src/satellome/core_functions/io/block_file.py | .py | 8d654f746932471a | 7.45 | 7 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @created: 14.06.2011
# @author: Aleksey Komissarov
# @contact: ad3002@gmail.com
import json
import logging
logger = logging.getLogger(__name__)
class AbstractModel(object):
"""
Abstract base class for data model objects with automatic attribut... | aglabx/satellome | src/satellome/core_functions/models/abstract_model.py | .py | bebabde1ea2f96a9 | 7.45 | 7 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @created: 06.09.2011
# @author: Aleksey Komissarov
# @contact: ad3002@gmail.com
"""
satellome settings loader.
"""
import os
import platform
import yaml
import satellome
satellome_path = satellome.__path__[0]
SETTINGS_FILENAME = os.path.join(satellome_path, "setting... | aglabx/satellome | src/satellome/core_functions/settings.py | .py | 7fb0bde45349e13c | 7.45 | 7 |
"""Atomic publication of pipeline output files.
Why this exists
---------------
Every satellome output used to be written *in place*: ``open(path, 'w')`` on the
final path, then streamed for minutes (a ``.sat`` for a T2T genome is
gigabytes). That has two consequences, both observed in production:
1. A concurrent rea... | aglabx/satellome | src/satellome/core_functions/tools/atomic_io.py | .py | 1ff322404dd51705 | 7.45 | 7 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @created: 14.02.2023
# @author: Aleksey Komissarov
# @contact: ad3002@gmail.com
"""
Graph-based clustering utilities for tandem repeat analysis.
Provides network-based clustering using sequence similarity distances,
with annotation by taxon presence and motif size dist... | aglabx/satellome | src/satellome/core_functions/tools/clusterization.py | .py | a64657742f5c7eb2 | 7.45 | 7 |
"""Exclusive lock on an output directory.
Why this exists
---------------
Two satellome runs pointed at the same ``-o`` directory (a pool worker and a
retry of the same genome, say) overwrite each other's files mid-write. The
second run's ``open(path, 'w')`` truncates an artifact the first run already
finished, and bo... | aglabx/satellome | src/satellome/core_functions/tools/dir_lock.py | .py | 8687f205b7d700f7 | 7.45 | 7 |
import logging
import time
from http import HTTPStatus
from typing import Optional, Tuple
import email.utils
import requests
from devcycle_python_sdk.api.backoff import exponential_backoff
from devcycle_python_sdk.options import DevCycleLocalOptions
from devcycle_python_sdk.exceptions import (
APIClientError,
... | DevCycleHQ/python-server-sdk | devcycle_python_sdk/api/config_client.py | .py | ef769002ad77d2b4 | 7.64 | 18 |
import json
import logging
import time
from typing import Optional, List
import requests
from devcycle_python_sdk.api.backoff import exponential_backoff
from devcycle_python_sdk.options import DevCycleLocalOptions
from devcycle_python_sdk.exceptions import (
APIClientError,
NotFoundError,
APIClientUnautho... | DevCycleHQ/python-server-sdk | devcycle_python_sdk/api/event_client.py | .py | 5b192e57a81e102f | 7.64 | 18 |
import logging
import random
import time
import json
from pathlib import Path
from threading import Lock
from typing import Any, cast, Optional, List, Tuple
import wasmtime
from wasmtime import (
Engine,
Func,
FuncType,
Linker,
Memory,
Module,
Store,
ValType,
)
import devcycle_python_... | DevCycleHQ/python-server-sdk | devcycle_python_sdk/api/local_bucketing.py | .py | 9178205e1bf63c34 | 7.64 | 18 |
import logging
import platform
from typing import Any, Dict
from devcycle_python_sdk import DevCycleCloudOptions, AbstractDevCycleClient
from devcycle_python_sdk.api.bucketing_client import BucketingAPIClient
from devcycle_python_sdk.exceptions import (
NotFoundError,
CloudClientUnauthorizedError,
)
from devc... | DevCycleHQ/python-server-sdk | devcycle_python_sdk/cloud_client.py | .py | 751db27b6f54a7af | 7.64 | 18 |
import json
import logging
import uuid
from numbers import Real
from typing import Any, Dict, Union, Optional
from devcycle_python_sdk import DevCycleLocalOptions, AbstractDevCycleClient
from devcycle_python_sdk.api.local_bucketing import LocalBucketing
from devcycle_python_sdk.managers.config_manager import Environme... | DevCycleHQ/python-server-sdk | devcycle_python_sdk/local_client.py | .py | 1db1c818b788c3d7 | 7.64 | 18 |
import json
import logging
import threading
import time
from datetime import datetime
from typing import Optional
import ld_eventsource.actions
from devcycle_python_sdk.api.config_client import ConfigAPIClient
from devcycle_python_sdk.api.local_bucketing import LocalBucketing
from devcycle_python_sdk.exceptions impor... | DevCycleHQ/python-server-sdk | devcycle_python_sdk/managers/config_manager.py | .py | b6df43fd5de42f02 | 7.64 | 18 |
from typing import List, Optional
from devcycle_python_sdk.models.eval_hook import EvalHook
from devcycle_python_sdk.models.eval_hook_context import HookContext
from devcycle_python_sdk.models.variable import Variable
from devcycle_python_sdk.models.variable_metadata import VariableMetadata
from devcycle_python_sdk.op... | DevCycleHQ/python-server-sdk | devcycle_python_sdk/managers/eval_hooks_manager.py | .py | 60e2e3d08bcd16a0 | 7.64 | 18 |
from dataclasses import dataclass
from typing import Optional
class EvalReasons:
"""Evaluation reasons constants"""
DEFAULT = "DEFAULT"
class DefaultReasonDetails:
"""Default reason details constants"""
MISSING_CONFIG = "Missing Config"
USER_NOT_TARGETED = "User Not Targeted"
TYPE_MISMATCH... | DevCycleHQ/python-server-sdk | devcycle_python_sdk/models/eval_reason.py | .py | a1b063216b7c6548 | 7.64 | 18 |
# ruff: noqa: N815
from dataclasses import dataclass, field
from typing import Dict, Optional, Any, List
from datetime import datetime, timezone
from .user import DevCycleUser
class EventType:
VariableEvaluated = "variableEvaluated"
AggVariableEvaluated = "aggVariableEvaluated"
VariableDefaulted = "varia... | DevCycleHQ/python-server-sdk | devcycle_python_sdk/models/event.py | .py | 4a3dde128a6e3e9f | 7.64 | 18 |
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from devcycle_python_sdk import (
DevCycleCloudClient,
DevCycleCloudOptions,
DevCycleLocalClient,
DevCycleLocalOptions,
)
def devcycle_cloud_middleware(get_response):
"""
This middleware adds the DevCycle ... | DevCycleHQ/python-server-sdk | example/django-app/devcycle_test/middleware.py | .py | d801baeb0ee20bbc | 7.14 | 18 |
from django.contrib import admin
from django.contrib.auth.admin import GroupAdmin as BaseGroupAdmin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import Group
from django.contrib.sessions.models import Session
from django.utils import timezone
from django.utils.safestr... | ig-rudenko/ecstasy | apps/accounting/admin.py | .py | 0e03387e4e3c3fc7 | 7.54 | 11 |
"""
Admin configuration for platform settings models.
"""
from django import forms
from django.contrib import admin
from django_celery_beat.admin import ClockedScheduleAdmin as BaseClockedScheduleAdmin
from django_celery_beat.admin import CrontabScheduleAdmin as BaseCrontabScheduleAdmin
from django_celery_beat.admin i... | ig-rudenko/ecstasy | apps/app_settings/admin.py | .py | 93a4cafdc4604ac4 | 7.54 | 11 |
from celery import shared_task
from django.contrib.sessions.models import Session
from rest_framework_simplejwt.token_blacklist.models import OutstandingToken
from rest_framework_simplejwt.utils import aware_utcnow
@shared_task
def flush_expired_tokens():
"""Flushes any expired tokens in the outstanding token lis... | ig-rudenko/ecstasy | apps/app_settings/tasks.py | .py | c935e2482e21bb46 | 7.54 | 11 |
from django.db import connection
from django.db.migrations.executor import MigrationExecutor
from django.test import TransactionTestCase
class TracerouteConfigMigrationTest(TransactionTestCase):
"""Проверка переименования настроек трассировки без потери данных."""
migrate_from = ("app_settings", "0004_access... | ig-rudenko/ecstasy | apps/app_settings/tests/test_migrations.py | .py | 799ef1ccd3756a50 | 8.04 | 11 |
from django.test import TestCase
from django_celery_beat.models import CrontabSchedule, PeriodicTask
from apps.app_settings.apps import register_task
class PeriodicTaskRegistrationTests(TestCase):
"""Тесты регистрации периодических задач приложения."""
def test_register_task_handles_crontab_schedules_with_s... | ig-rudenko/ecstasy | apps/app_settings/tests/test_periodic_tasks.py | .py | 755e0323fc19b430 | 8.04 | 11 |
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from django.core.cache import cache
from django.test import SimpleTestCase, TestCase
from requests import RequestException
from apps.app_settings.models import ZabbixConfig
from apps.app_settings.zabbix_config_cache import (
ZABBIX_CONFI... | ig-rudenko/ecstasy | apps/app_settings/tests/test_zabbix_api_connector.py | .py | a2f6f0e6ff64ffb1 | 7.04 | 11 |
from django.contrib.auth.models import AbstractUser, AnonymousUser
from django.db.models import Q
from rest_framework import permissions
from rest_framework.request import Request
from ..models import DeviceMedia, Devices, InterfacesComments
def has_user_access_to_device(user: AbstractUser | AnonymousUser, device: D... | ig-rudenko/ecstasy | apps/check/api/permissions.py | .py | 28668c127a6f287f | 7.54 | 11 |
from decimal import Decimal
from re import findall
from typing import Any
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from apps.gathering.models import Vlan, VlanPort
from ..models import (
AuthGroup,
BulkDeviceCommandExecution,
BulkDeviceCommandExecutionR... | ig-rudenko/ecstasy | apps/check/api/serializers.py | .py | bc333750aea6b1a8 | 7.54 | 11 |
# pylint: disable=missing-module-docstring,wrong-import-position
import logging
import os
import socket
import sys
import time
if "_3SCALE_TESTS_DEBUG" in os.environ:
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)... | 3scale-qe/3scale-tests | testsuite/__init__.py | .py | a4c6f6219ba35af3 | 7 | 9 |
"""
Custom Auth0 resources for testsuite
"""
import http.client
import json
from testsuite.config import settings
def auth0_token():
"""
Token for Auth0 API
"""
auth = settings["auth0"]
conn = http.client.HTTPSConnection(auth["domain"])
payload = (
"{" + f"\"client_id\":\"{auth['clie... | 3scale-qe/3scale-tests | testsuite/auth0/__init__.py | .py | 467f84aa87ed6159 | 7 | 9 |
"""APIs for Stripe and Braintree"""
import backoff
import braintree
import stripe
from braintree.exceptions.request_timeout_error import RequestTimeoutError
from braintree.exceptions.service_unavailable_error import ServiceUnavailableError
from threescale_api.resources import InvoiceState
class Stripe:
"""API fo... | 3scale-qe/3scale-tests | testsuite/billing.py | .py | 0c79ba5497a18443 | 8 | 9 |
"""This module is where most of the capability providers should be to not have them scattered around"""
from openshift_client import Missing
from weakget import weakget
from testsuite import gateways
from testsuite.capabilities import Capability, CapabilityRegistry
from testsuite.config import settings
from testsuite... | 3scale-qe/3scale-tests | testsuite/capabilities/providers.py | .py | ec7a74de6fdf245f | 8 | 9 |
"""Collection of classes for working with different ssl certificate tools."""
from abc import ABC, abstractmethod
from typing import Dict, List, Optional, Tuple
from testsuite.certificates.persist import TmpFilePersist
# Type alias for Names field in certification csrs
CertificateNames = List[Dict[str, str]]
class... | 3scale-qe/3scale-tests | testsuite/certificates/__init__.py | .py | 262822107abd82e5 | 8 | 9 |
"""CFSSL certificate implementation."""
from typing import Optional
import cfssl
from testsuite.certificates import Certificate, SigningProvider, UnsignedKey
class CFSSLRESTProvider(SigningProvider): # pylint: disable=too-few-public-methods
"""Class for signing keys with remote CFSSL instance."""
def sig... | 3scale-qe/3scale-tests | testsuite/certificates/cfssl/rest.py | .py | 8d93b08ec1f8485a | 8 | 9 |
"""Module that helps certificates with temporary persistence"""
import os
import shutil
import tempfile
from abc import ABC, abstractmethod
from typing import Dict
class TmpFilePersist(ABC):
"""Persists data into files so it can be used in commands that require files"""
def __init__(self) -> None:
s... | 3scale-qe/3scale-tests | testsuite/certificates/persist.py | .py | faf6dcd00bf4deb2 | 8 | 9 |
"""CertificateStore concrete classes."""
import os
import tempfile
from abc import ABC
from typing import Dict
from testsuite.certificates import Certificate, CertificateStore
def _persist(path, name: str, ext: str, content: str):
with open(os.path.join(path, f"{name}.{ext}"), "w", encoding="utf8") as file:
... | 3scale-qe/3scale-tests | testsuite/certificates/stores.py | .py | dd0e2b78b8a3a098 | 8 | 9 |
"""Module responsible for processing configuration"""
import inspect
from typing import Any, Dict, Mapping
from weakget import weakget
from testsuite.capabilities import Singleton
from testsuite.config import settings
from testsuite.openshift.client import OpenShiftClient
def openshift(server="default", project="t... | 3scale-qe/3scale-tests | testsuite/configuration.py | .py | 3bfeb0ea194d9d61 | 8 | 9 |
"""
Custom loader for dynaconf
Some values can be gathered from openshift deployment of 3scale from relevant
configmaps, secrets, routes, etc. These values should be used as
default/fallback in case they aren't defined in config or by env variables.
dynaconf provides interface to custom loader that can be used to gat... | 3scale-qe/3scale-tests | testsuite/dynaconf_loader.py | .py | d63b035f0d85a24b | 8 | 9 |
"""
Shadow request classes to unify workflow over different backends
e.g httpbin-go returns headers 'Host': ["httpbingo.org"], but httpbin returns 'Host': "httpbin.org"
"""
# pylint: disable=too-few-public-methods
import urllib.parse
import requests
from requests.structures import CaseInsensitiveDict
class EchoedR... | 3scale-qe/3scale-tests | testsuite/echoed_request.py | .py | 842ea11cc470ee06 | 8 | 9 |
"""Pytest plugin for collecting gateway logs"""
import logging
from datetime import datetime, timezone
import pytest
from _pytest.outcomes import Skipped
from testsuite.gateways.gateways import Capability
log = logging.getLogger(__name__)
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_setup(... | 3scale-qe/3scale-tests | testsuite/gateway_logs.py | .py | a3f6b60ff758254e | 8 | 9 |
"""
Sets up gateway defined in testsuite settings
"""
import importlib
import inspect
import logging
import pkgutil
from typing import Type, Union
from testsuite.config import settings
from testsuite.gateways.gateways import AbstractGateway, Gateway, new_gateway
log = logging.getLogger(__name__)
# walk through all ... | 3scale-qe/3scale-tests | testsuite/gateways/__init__.py | .py | ff62e4a16b478e37 | 7 | 9 |
"""Module containing all APIcast gateways"""
import logging
from abc import ABC, abstractmethod
from datetime import datetime
from typing import Dict, List, Optional, Tuple
from openshift_client import OpenShiftPythonException
from threescale_api.resources import Service
from testsuite import utils
from testsuite.ca... | 3scale-qe/3scale-tests | testsuite/gateways/apicast/__init__.py | .py | e935de4d91cbb96a | 8 | 9 |
"""Collection of gateways that run in containerized environment"""
from typing import Dict
from threescale_api.resources import Service
from testsuite.capabilities import Capability
from testsuite.gateways.apicast import AbstractApicast
from testsuite.openshift.env import Properties
class ContainerizedApicast(Abst... | 3scale-qe/3scale-tests | testsuite/gateways/apicast/containers.py | .py | 4d09f0987f3a3fb1 | 8 | 9 |
"""Apicast deployed with ApicastOperator"""
import re
import time
from typing import Any, Callable, Dict, Match, Pattern, Union
from openshift_client import OpenShiftPythonException
from weakget import weakget
from testsuite import settings
from testsuite.capabilities import Capability, CapabilityRegistry
from tests... | 3scale-qe/3scale-tests | testsuite/gateways/apicast/operator.py | .py | c2b7fccd0513b24c | 8 | 9 |
"""Self-managed APIcast already deployed somewhere in OpenShift"""
import inspect
import logging
from typing import Type, Union
from weakget import weakget
from testsuite.capabilities import Capability
from testsuite.gateways.apicast import AbstractApicast, OpenshiftApicast
from testsuite.gateways.gateways import Ga... | 3scale-qe/3scale-tests | testsuite/gateways/apicast/selfmanaged.py | .py | a82204d5b692f60e | 8 | 9 |
"""System Apicast that comes deployed with 3scale"""
from typing import TYPE_CHECKING
import backoff
from openshift_client import OpenShiftPythonException
from testsuite.capabilities import Capability
from testsuite.gateways.apicast import AbstractApicast
from testsuite.openshift.env import Properties
from testsuite... | 3scale-qe/3scale-tests | testsuite/gateways/apicast/system.py | .py | 42185f4dd75e78a4 | 8 | 9 |
"""Apicast with TLS certificates configured"""
import logging
from datetime import datetime
from typing import Optional
from threescale_api.resources import Application, Service
from testsuite.openshift.objects import Routes, SecretKinds
from ... import settings
from ...capabilities import Capability
from ...certif... | 3scale-qe/3scale-tests | testsuite/gateways/apicast/tls.py | .py | d66d2b8fb3b78e9c | 8 | 9 |
"""SystemApicast variant for deployments where zync is disabled"""
from typing import TYPE_CHECKING
from urllib.parse import urlparse
from threescale_api.resources import Service
from testsuite.gateways.apicast.system import SystemApicast
from testsuite.openshift.objects import Routes
if TYPE_CHECKING:
from typ... | 3scale-qe/3scale-tests | testsuite/gateways/apicast/zyncless.py | .py | 3dd892078e63ccfb | 8 | 9 |
"""Module containing all basic gateways"""
from abc import ABC, abstractmethod
from typing import Set, Type, TypeVar, Union
from testsuite.capabilities import Capability
from testsuite.configuration import SettingsParser
from testsuite.lifecycle_hook import LifecycleHook
from testsuite.openshift.env import Properties... | 3scale-qe/3scale-tests | testsuite/gateways/gateways.py | .py | eed08eb4a12dd505 | 8 | 9 |
"""Service mesh gateway"""
from typing import Dict
from threescale_api.resources import Application, Service
from testsuite.capabilities import Capability
from testsuite.gateways.gateways import AbstractGateway
from testsuite.gateways.service_mesh.client import ServiceMeshHttpClient
from testsuite.gateways.service_m... | 3scale-qe/3scale-tests | testsuite/gateways/service_mesh/__init__.py | .py | 50902bd768a4f871 | 8 | 9 |
"""HttpClient for Service mesh"""
from typing import Iterable
import requests
from threescale_api.utils import HttpClient
class ServiceMeshHttpClient(HttpClient):
"""HttpClient for Service mesh"""
# pylint: disable=too-many-arguments
def __init__(
self,
openshift,
root_url,
... | 3scale-qe/3scale-tests | testsuite/gateways/service_mesh/client.py | .py | b46c65b458558b66 | 8 | 9 |
"""Objects for managing Httpbin deployments"""
import importlib_resources as resources
from testsuite.openshift.client import OpenShiftClient
from testsuite.rhsso.rhsso import RHSSOServiceConfiguration
class Httpbin:
"""Class for manipulation Httpbin deployment in service mesh environment"""
def __init__(s... | 3scale-qe/3scale-tests | testsuite/gateways/service_mesh/httpbin.py | .py | 5c034163d153d99f | 8 | 9 |
"""Objects for managing ServiceMesh deployments"""
from contextlib import ExitStack
from typing import List
from urllib.parse import urlparse, urlunparse
from openshift_client import Selector
from testsuite.openshift.client import OpenShiftClient
from testsuite.openshift.env import Properties
class ServiceMesh:
... | 3scale-qe/3scale-tests | testsuite/gateways/service_mesh/mesh.py | .py | b545cc2ed9b983ca | 8 | 9 |
"""Module containing WASMGateway and its dependencies"""
from typing import Dict
from urllib.parse import urlparse
import importlib_resources as resources
from threescale_api.resources import Application, Service
from testsuite.capabilities import Capability
from testsuite.gateways import AbstractGateway
from testsu... | 3scale-qe/3scale-tests | testsuite/gateways/wasm/__init__.py | .py | 56da576e25612848 | 8 | 9 |
"""Module containing WASMExtension"""
import importlib_resources as resources
from threescale_api.resources import Service
from testsuite.openshift.client import OpenShiftClient
# pylint: disable=too-many-instance-attributes
class WASMExtension:
"""Class representing once instance of WASMExtension, including de... | 3scale-qe/3scale-tests | testsuite/gateways/wasm/extension.py | .py | d9dacff81f74ee77 | 8 | 9 |
"""Http client with HTTPX library supporting HTTP/1.1 and HTTP/2"""
import functools
import logging
from typing import Generator, Iterable
import backoff
import httpx
from httpx import (
URL,
USE_CLIENT_DEFAULT,
Auth,
Client,
Request,
Response,
create_ssl_context,
)
from threescale_api.res... | 3scale-qe/3scale-tests | testsuite/httpx.py | .py | a3870c826354b430 | 7 | 9 |
"""
A simple interface to get data from Jaeger using the rest http api
Note: jaeger http rest api is not officially supported and may be a subject of a change
"""
from string import Template
from urllib.parse import urlparse
import backoff
import importlib_resources as resources
import requests
class Jaeger:
""... | 3scale-qe/3scale-tests | testsuite/jaeger.py | .py | 3266d07107ca5a42 | 8 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.