Exemple #1
0
from Blueprint.Color import Color, ColorDict
from Blueprint.Entity import Entity, EntityDict, CurvedRailEntity
from Blueprint.Icon import Icon, IconDict
from Blueprint.Position import Position, PositionDict
from Blueprint.Schedule import Schedule, ScheduleDict
from Blueprint.Tile import Tile, TileDict

BlueprintDict = TypedDict(
    "BlueprintDict", {
        "entities": List[EntityDict],
        "item": str,
        "version": int,
        "label": str,
        "icons": List[IconDict],
        "label_color": ColorDict,
        "tiles": List[TileDict],
        "schedules": List[ScheduleDict],
        "description": str,
        "snap-to-grid": PositionDict,
        "position-relative-to-grid": PositionDict,
        "absolute-snapping": bool,
    })


class Blueprint(FactorioBlueprintObject):
    dict_type: Type[TypedDict] = BlueprintDict
    field_translation_map = {
        "snap_to_grid": "snap-to-grid",
        "position_relative_to_grid": "position-relative-to-grid",
        "absolute_snapping": "absolute-snapping",
Exemple #2
0
        if num == 0:
            return
        self.points.append((now, num))

    @property
    def value(self) -> int:
        """Get the summation of all non-expired points"""
        now = time.time()
        cutoff = now - self.window
        while self.points and self.points[0][0] < cutoff:
            self.points.pop(0)
        return sum([p[1] for p in self.points])


RemainingCapacity = TypedDict("RemainingCapacity", {
    "read": DecayingCapacityStore,
    "write": DecayingCapacityStore
})


class RateLimit(object):
    """
    Class for rate limiting requests to DynamoDB

    Parameters
    ----------
    total_read : float, optional
        The overall maximum read units per second
    total_write : float, optional
        The overall maximum write units per second
    total : :class:`~dynamo3.result.Capacity`, optional
        A Capacity object. You can provide this instead of ``total_read`` and
Exemple #3
0
    TypeVar,
    Union,
)
from urllib.parse import unquote

import lxml.html
from typing_extensions import TypedDict

MACOS = platform.system() == "Darwin"
LINUX = platform.system() == "Linux"
WSL = 'microsoft' in platform.release().lower()

StreamData = TypedDict(
    'StreamData', {
        'name': str,
        'id': int,
        'color': str,
        'invite_only': bool,
        'description': str,
    })

Message = TypedDict(
    'Message',
    {
        'id': int,
        'sender_id': int,
        'content': str,
        'recipient_id': int,
        'timestamp': int,
        'client': str,
        'subject': str,  # Only for stream msgs.
        'topic_links': List[str],
Exemple #4
0
    from typing_extensions import TypedDict

    from sentry_sdk.transport import Transport
    from sentry_sdk.integrations import Integration

    from sentry_sdk._types import Event, EventProcessor, BreadcrumbProcessor

    # Experiments are feature flags to enable and disable certain unstable SDK
    # functionality. Changing them from the defaults (`None`) in production
    # code is highly discouraged. They are not subject to any stability
    # guarantees such as the ones from semantic versioning.
    Experiments = TypedDict(
        "Experiments",
        {
            "max_spans": Optional[int],
            "record_sql_params": Optional[bool],
            "auto_enabling_integrations": Optional[bool],
        },
        total=False,
    )


# This type exists to trick mypy and PyCharm into thinking `init` and `Client`
# take these arguments (even though they take opaque **kwargs)
class ClientConstructor(object):
    def __init__(
        self,
        dsn=None,  # type: Optional[str]
        with_locals=True,  # type: bool
        max_breadcrumbs=100,  # type: int
        release=None,  # type: Optional[str]
Exemple #5
0
from asyncio import Semaphore
from contextlib import asynccontextmanager
from pathlib import Path
import json
from typing import Callable, Iterable, Sequence, Optional, NamedTuple, AsyncIterator, Any, Awaitable
from typing_extensions import TypedDict

from semver import VersionInfo

from dds_ports.port import Port, PackageID
from dds_ports import git, github, util

PackageJSON = TypedDict('PackageJSON', {
    'name': str,
    'namespace': str,
    'depends': Sequence[str],
})

LibraryJSON = TypedDict('LibraryJSON', {
    'name': str,
    'uses': Sequence[str],
})

FSTransformFn = Callable[[Path], Awaitable[None]]

BUILD_SEMAPHORE = Semaphore(1)


class SimpleGitHubAdaptingPort(NamedTuple):
    package_id: PackageID
    owner: str
Exemple #6
0
)
from rasa.shared.core.domain import Domain, State
from rasa.shared.core.slots import Slot

if TYPE_CHECKING:
    from typing_extensions import TypedDict

    from rasa.shared.core.training_data.structures import Story
    from rasa.shared.core.training_data.story_writer.story_writer import StoryWriter

    # precise type definition for `DialogueStateTracker.active_loop`
    TrackerActiveLoop = TypedDict(
        "TrackerActiveLoop",
        {
            LOOP_NAME: Optional[Text],
            LOOP_INTERRUPTED: bool,
            LOOP_REJECTED: bool,
            TRIGGER_MESSAGE: Dict,
        },
        total=False,
    )

logger = logging.getLogger(__name__)

# same as State but with Dict[...] substituted with FrozenSet[Tuple[...]]
FrozenState = FrozenSet[Tuple[Text, FrozenSet[Tuple[Text,
                                                    Tuple[Union[float,
                                                                Text]]]]]]


class EventVerbosity(Enum):
    """Filter on which events to include in tracker dumps."""
Exemple #7
0
    from sklearn.mixture import GaussianMixture
except ImportError as e:
    raise ImportError(
        "scikit-learn is required to use the stochastic_events module. "
        "Please install scikit-learn using\n"
        "\tpip install scikit-learn\n"
        "or install acnportal with extra options\n"
        "\tpip install acnportal[scikit-learn]"
    )


CapFnCallable = Callable[[float, float, float, float], Tuple[float, float]]

BatteryParams = TypedDict(
    "BatteryParams",
    {"type": Type[Battery], "capacity_fn": CapFnCallable, "kwargs": Dict[str, Any]},
    total=False,
)


class StochasticEvents:
    """ Base class for generating events from a stochastic model.

    Args:
        arrival_min (float): Clip arrive time at lower bound. Useful if you know that drivers should not arrive before a
            certain time. By default 0, meaning drivers do not arrive on the previous day. [hours since midnight]
        arrival_max (float): Clip arrive time at upper bound. Useful if you know drivers should not arrive after a
            certain time. My default 24, meaning drivers do not arrive the next day. [hours since midnight]
        duration_min (float): Clip duration to lower bound. Useful to limit session duration to a reasonable minimum.
            By default 0.0833 hours or 5 minutes. [hours]
        duration_max (float): Clip duration to upper bound. Useful to limit session duration to a reasonable maximum.
#
# 2. Comparing individually the conformity scores of the training points with
#    the conformity scores from the associated model for a new test point
#    (as presented in Romano et al. 2020 for the "cumulated_score" method)
#
# Let's explore the two possibilites with the "score" method using
# :class:`mapie.classification.MapieClassifier`.
#
# All we need to do is to provide with the `cv` argument a cross-validation
# object or an integer giving the number of folds.
# When estimating the prediction sets, we define how the scores are aggregated
# with the ``agg_scores`` attribute.

Params = TypedDict("Params", {
    "method": str,
    "cv": Optional[Union[int, str]],
    "random_state": Optional[int]
})
ParamsPredict = TypedDict("ParamsPredict", {
    "include_last_label": Union[bool, str],
    "agg_scores": str
})

kf = KFold(n_splits=5, shuffle=True)

STRATEGIES = {
    "score_cv_mean": (Params(method="score", cv=kf, random_state=42),
                      ParamsPredict(include_last_label=False,
                                    agg_scores="mean")),
    "score_cv_crossval": (Params(method="score", cv=kf, random_state=42),
                          ParamsPredict(include_last_label=False,
Exemple #9
0
from typing_extensions import TypedDict
from typing import Any

from pyobs.events import Event


class MoveEvent(Event):
    """Event to be sent when moving to a new target."""

    __module__ = "pyobs.events"
    pass


DataTypeRaDec = TypedDict("DataTypeRaDec", {"ra": float, "dec": float})


class MoveRaDecEvent(MoveEvent):
    """Event to be sent when moving to RA/Dec."""

    __module__ = "pyobs.events"

    def __init__(self, ra: float, dec: float, **kwargs: Any):
        MoveEvent.__init__(self)
        self.data: DataTypeRaDec = {"ra": ra, "dec": dec}

    @property
    def ra(self) -> float:
        return self.data["ra"]

    @property
    def dec(self) -> float:
Exemple #10
0
            self.mark_muted()

    def mark_muted(self) -> None:
        self.update_widget('M')

    # TODO: Handle event-based approach for topic-muting.


class UnreadPMButton(urwid.Button):
    def __init__(self, user_id: int, email: str) -> None:
        self.user_id = user_id
        self.email = email


DecodedStream = TypedDict('DecodedStream', {
    'stream_id': Optional[int],
    'stream_name': Optional[str],
})

ParsedNarrowLink = TypedDict('ParsedNarrowLink', {
    'narrow': str,
    'stream': DecodedStream,
    'topic_name': str,
    'message_id': Optional[int],
},
                             total=False)


class MessageLinkButton(urwid.Button):
    def __init__(self, controller: Any, caption: str, link: str,
                 display_attr: Optional[str]) -> None:
        self.controller = controller
Exemple #11
0
# An entry in the test data set.
# Each TestData is annotated with a 'type' as:
# * 'A': pre-transition where the UTC offset is different
# * 'B': post-transition where the UTC offset is different
# * 'a': pre-transition where only the DST offset is different
# * 'b': post-transition where only the DST offset is different
# * 'S': a monthly test sample
# * 'Y': end of year test sample
TestItem = TypedDict(
    "TestItem",
    {
        'epoch': int,  # seconds from AceTime epoch of 2000-01-01T00:00:00Z
        'total_offset': int,  # total UTC offset in seconds
        'dst_offset': int,  # DST offset in seconds
        'y': int,
        'M': int,
        'd': int,
        'h': int,
        'm': int,
        's': int,
        'abbrev': Optional[str],
        'type': str,
    })

# The test data set (epoch -> timezone info)
TestData = Dict[str, List[TestItem]]

# The top-level validation data collection. This can be serialized to JSON.
ValidationData = TypedDict(
    'ValidationData',
    {
Exemple #12
0
import re, subprocess, os, json, argparse, copy, shutil, inspect, sys
from typing_extensions import TypedDict
from datetime import datetime
from typing import *

scriptVersion: str = "2.3"

fsmName: str = "none"
context: str = "none"
initial: str = "none"
version: str = "none"

TransitionType = TypedDict(
    'TransitionType', {
        'event': str,
        'nextState': Optional[str],
        'guardList': List[str],
        'eventsSendList': List[str],
        'actionList': List[str]
    })
newTransition: TransitionType = {
    'event': "",
    'nextState': "",
    'guardList': [],
    'eventsSendList': [],
    'actionList': []
}

StateType = TypedDict(
    'StateType', {
        'parentState': str,
        'stateName': str,
Exemple #13
0

def select_row(view, row):
    """
    Select a `row` in an item view
    """
    selmodel = view.selectionModel()
    selmodel.select(view.model().index(row, 0),
                    QItemSelectionModel.ClearAndSelect)


if TYPE_CHECKING:
    # pylint: disable=used-before-assignment
    _ScriptData = TypedDict("_ScriptData", {
        "name": str,
        "script": str,
        "filename": Optional[str]
    })


class OWPythonScript(OWWidget):
    name = "Python Script"
    description = "Write a Python script and run it on input data or models."
    icon = "icons/PythonScript.svg"
    priority = 3150
    keywords = ["file", "program"]

    class Inputs:
        data = Input("Data",
                     Table,
                     replaces=["in_data"],
Exemple #14
0
from __future__ import annotations

from typing import Any, ClassVar, Dict, List, NoReturn, Optional, Union

from s3transfer.manager import TransferConfig
from typing_extensions import TypedDict

from .utils import human_readable_to_bytes

# If the user does not specify any overrides,
# these are the default values we use for the s3 transfer
# commands.
TransferConfigDict = TypedDict(
    "TransferConfigDict",
    max_bandwidth=Optional[Union[int, str]],
    max_concurrent_requests=int,
    max_queue_size=int,
    multipart_chunksize=Union[int, str],
    multipart_threshold=Union[int, str],
)

DEFAULTS: TransferConfigDict = {
    "max_bandwidth": None,
    "max_concurrent_requests": 10,
    "max_queue_size": 1000,
    "multipart_chunksize": 8 * (1024**2),
    "multipart_threshold": 8 * (1024**2),
}


class InvalidConfigError(Exception):
    """Invalid configuration."""
Exemple #15
0
from __future__ import annotations
from typing import Optional, Dict, Any
from typing_extensions import TypedDict

from pyobs.events.event import Event
from pyobs.utils.enums import ImageType

DataType = TypedDict("DataType", {
    "filename": str,
    "image_type": Optional[str],
    "raw": Optional[str]
})


class NewImageEvent(Event):
    """Event to be sent on a new image."""

    __module__ = "pyobs.events"

    def __init__(self,
                 filename: str,
                 image_type: Optional[ImageType] = None,
                 raw: Optional[str] = None,
                 **kwargs: Any):
        """Initializes new NewImageEvent.

        Args:
            filename: Name of new image file.
            image_type: Type of image.
            raw: Only for reduced images, references raw frame.
        """
Exemple #16
0
import re
import traceback
from typing import AbstractSet, List, Mapping, Optional, Sequence, Tuple

from typing_extensions import TypedDict

from zulint.printer import BLUE, ENDC, GREEN, MAGENTA, YELLOW, colors, print_err

Rule = TypedDict("Rule", {
    "bad_lines": Sequence[str],
    "description": str,
    "exclude": AbstractSet[str],
    "exclude_line": AbstractSet[Tuple[str, str]],
    "exclude_pattern": str,
    "good_lines": Sequence[str],
    "include_only": AbstractSet[str],
    "pattern": str,
    "strip": str,
    "strip_rule": str,
},
                 total=False)
LineTup = Tuple[int, str, str, str]


class RuleList:
    """Defines and runs custom linting rules for the specified language."""
    def __init__(
        self,
        langs: Sequence[str],
        rules: Sequence[Rule],
        max_length: Optional[int] = None,
Exemple #17
0
import anyio  # you would need to `pip install anyio`
import httpx  # you would need to `pip install httpx`
from typing_extensions import Final, TypedDict

from returns.context import RequiresContextFutureResultE
from returns.functions import tap
from returns.future import FutureResultE, future_safe
from returns.iterables import Fold
from returns.pipeline import managed
from returns.result import ResultE, safe

_URL: Final = 'https://jsonplaceholder.typicode.com/posts/{0}'
_Post = TypedDict('_Post', {
    'id': int,
    'userId': int,
    'title': str,
    'body': str,
})


def _close(
    client: httpx.AsyncClient,
    raw_value: ResultE[Sequence[str]],
) -> FutureResultE[None]:
    return future_safe(client.aclose)()


def _fetch_post(
    post_id: int,
) -> RequiresContextFutureResultE[_Post, httpx.AsyncClient]:
    context: RequiresContextFutureResultE[
Exemple #18
0
Event = TypedDict(
    'Event',
    {
        'type': str,
        # typing:
        'sender': Dict[str, Any],  # 'email', ...
        # typing & reaction:
        'op': str,
        # reaction:
        'user': Dict[str, Any],  # 'email', 'user_id', 'full_name'
        'reaction_type': str,
        'emoji_code': str,
        'emoji_name': str,
        # reaction & update_message:
        'message_id': int,
        # update_message:
        'rendered_content': str,
        # update_message_flags:
        'messages': List[int],
        'operation': str,
        'flag': str,
        'all': bool,
        # message:
        'message': Message,
        'flags': List[str],
        'subject': str,
        # subscription:
        'property': str,
        'user_id': int,  # Present when a streams subscribers are updated.
        'stream_id': int,
        'value': bool,
        'message_ids': List[int]  # Present when subject of msg(s) is updated
    },
    total=False)  # Each Event will only have a subset of these
Exemple #19
0
class RpcPeerResponse(TypedDict):
    enode: str
    id: str
    name: str
    caps: Sequence[str]
    network: RpcPeerNetworkResponse


RpcTransactionResponse = TypedDict('RpcTransactionResponse', {
    'hash': HexStr,
    'nonce': str,
    'gas': str,
    'gasPrice': str,
    # `from` being a reserved word forces us to use the alternate syntax for this type
    'from': HexStr,
    'to': HexStr,
    'value': str,
    'input': HexStr,
    'r': str,
    's': str,
    'v': str,
})


class RpcAccessList(TypedDict):
    address: str
    storageKeys: List[str]


class RpcBlockTransactionResponse(RpcTransactionResponse):
    blockNumber: str
Exemple #20
0
        elif stream_email_notify:
            notice['trigger'] = 'stream_email_notify'
        else:
            raise AssertionError("Unknown notification trigger!")
        notice['stream_name'] = stream_name
        if not already_notified.get("email_notified"):
            queue_json_publish("missedmessage_emails", notice,
                               lambda notice: None)
            notified['email_notified'] = True

    return notified


ClientInfo = TypedDict(
    'ClientInfo', {
        'client': ClientDescriptor,
        'flags': Optional[Iterable[str]],
        'is_sender': bool,
    })


def get_client_info_for_message_event(
        event_template: Mapping[str, Any],
        users: Iterable[Mapping[str, Any]]) -> Dict[str, ClientInfo]:
    '''
    Return client info for all the clients interested in a message.
    This basically includes clients for users who are recipients
    of the message, with some nuances for bots that auto-subscribe
    to all streams, plus users who may be mentioned, etc.
    '''

    send_to_clients = {}  # type: Dict[str, ClientInfo]
Exemple #21
0
from sqlalchemy.dialects import postgresql
from sqlalchemy.orm import Session
from sqlalchemy.sql import func
from sqlalchemy.sql.visitors import VisitableType
from typing_extensions import TypedDict

from superset import db

logger = logging.getLogger(__name__)

ColumnInfo = TypedDict(
    "ColumnInfo",
    {
        "name": str,
        "type": VisitableType,
        "nullable": bool,
        "default": Optional[Any],
        "autoincrement": str,
        "primary_key": int,
    },
)

example_column = {
    "name": "id",
    "type": sqlalchemy.sql.sqltypes.INTEGER(),
    "nullable": False,
    "default": None,
    "autoincrement": "auto",
    "primary_key": 1,
}
Exemple #22
0
from typing import Any, Optional, List, Dict, Tuple, Union
from typing_extensions import TypedDict, Literal


DagDef = TypedDict('DagDef', {
    "company": str,
    "default_input_key": Optional[str],
    "default_output_key": Optional[str],
    "high_priority": bool,
    "name": str,
    "nodes": List['NodeDef'],
    "queue_mng": Optional[str],
    "state": str,
})
NodeDef = TypedDict('NodeDef', {
    "blobs": Dict[str, str],
    "id": str,
    "inputs": Dict[str, Tuple[str, str]],
    "kind": str,
    "name": str,
    "params": Dict[str, Any],
}, total=False)
S3BucketSettings = TypedDict('S3BucketSettings', {
    "api_version": Optional[str],
    "aws_access_key_id": str,
    "aws_secret_access_key": str,
    "aws_session_token": Optional[str],
    "buckets": Dict[str, str],
    "endpoint_url": Optional[str],
    "region_name": Optional[str],
    "use_ssl": Optional[bool],
Exemple #23
0
class JiraVelocity(SourceCollector):
    """Collector to get sprint velocity from Jira."""

    Board = TypedDict("Board", {"id": int, "name": str})
    Points = TypedDict("Points", {"text": str, "value": float})
    Sprint = TypedDict("Sprint", {"id": int, "name": str, "goal": str})
    SprintPoints = dict[str, Points]

    async def _get_source_responses(self, *urls: URL) -> SourceResponses:
        """Extend to pass the Greenhopper velocity chart API."""
        board_id = await self.__board_id(urls[0])
        api_url = URL(
            f"{urls[0]}/rest/greenhopper/1.0/rapid/charts/velocity.json?rapidViewId={board_id}"
        )
        return await super()._get_source_responses(api_url)

    async def _parse_source_responses(
            self, responses: SourceResponses) -> SourceMeasurement:
        """Override to parse the sprint values from the responses."""
        api_url = await self._api_url()
        board_id = parse_qs(urlparse(str(
            responses.api_url)).query)["rapidViewId"][0]
        entity_url = URL(
            f"{api_url}/secure/RapidBoard.jspa?rapidView={board_id}&view=reporting&chart=sprintRetrospective&sprint="
        )
        json = await responses[0].json()
        # The JSON contains a list with sprints and a dict with the committed and completed points, indexed by sprint id
        sprints, points = json["sprints"], json["velocityStatEntries"]
        velocity_type = str(self._parameter("velocity_type"))
        nr_sprints = int(str(self._parameter("velocity_sprints")))
        # Get the points, either completed, committed, or completed minus committed, as determined by the velocity type
        sprint_values = [
            self.__velocity(points[str(sprint["id"])], velocity_type)
            for sprint in sprints[:nr_sprints]
        ]
        entities = [
            self.__entity(sprint, points[str(sprint["id"])], velocity_type,
                          entity_url) for sprint in sprints
        ]
        return SourceMeasurement(
            value=str(round(sum(sprint_values) /
                            len(sprint_values))) if sprint_values else "0",
            entities=entities)

    @staticmethod
    def __velocity(sprint_points: SprintPoints, velocity_type: str) -> float:
        """Return the points completed, points committed, or difference between the two for the sprint."""
        if velocity_type == "difference":
            return sprint_points["completed"]["value"] - sprint_points[
                "estimated"]["value"]
        return sprint_points[velocity_type]["value"]

    @staticmethod
    def __entity(sprint: Sprint, sprint_points: SprintPoints,
                 velocity_type: str, entity_url: URL) -> Entity:
        """Create a sprint entity."""
        sprint_id = str(sprint["id"])
        committed = sprint_points["estimated"]["text"]
        completed = sprint_points["completed"]["text"]
        difference = str(
            float(sprint_points["completed"]["value"] -
                  sprint_points["estimated"]["value"]))
        measured = dict(completed=completed,
                        estimated=committed,
                        difference=difference)[velocity_type]
        return Entity(
            key=sprint_id,
            name=sprint["name"],
            goal=sprint.get("goal") or "",
            points_completed=completed,
            points_committed=committed,
            points_measured=measured,
            points_difference=difference,
            url=str(entity_url) + sprint_id,
        )

    async def _landing_url(self, responses: SourceResponses) -> URL:
        """Override to create a link to the Greenhopper velocity chart."""
        api_url = await self._api_url()
        board_id = parse_qs(urlparse(str(
            responses.api_url)).query)["rapidViewId"][0]
        return URL(
            f"{api_url}/secure/RapidBoard.jspa?rapidView={board_id}&view=reporting&chart=velocityChart"
        )

    async def __board_id(self, api_url: URL) -> str:
        """Return the board id."""
        last = False
        start_at = 0
        boards: list[JiraVelocity.Board] = []
        while not last:
            url = URL(f"{api_url}/rest/agile/1.0/board?startAt={start_at}")
            response = (await super()._get_source_responses(url))[0]
            json = await response.json()
            boards.extend(json["values"])
            start_at += json["maxResults"]
            last = json["isLast"]
        board_name_or_id = str(self._parameter("board")).lower()
        matching_boards = [
            b for b in boards
            if board_name_or_id in (str(b["id"]), b["name"].lower().strip())
        ]
        if not matching_boards:
            message = f"Could not find a Jira board with id or name '{board_name_or_id}' at {api_url}"
            raise SourceCollectorException(message)
        return str(matching_boards[0]["id"])
from typing_extensions import TypedDict
from typing import Optional, List
from datetime import datetime
from enum import Enum

Todo = TypedDict(
    'Todo',
    {
        "todo_id": int,
        "due_date": Optional[datetime],
        "frequency": Optional[str],
        "task": str,  # Default to some string
        "timeSlot": Optional[int],
        "trackHabit": Optional[bool],
        "category": Optional[str],
        "remindBeforeDays": Optional[int]
    })

TodoLog = TypedDict('TodoLog', {"todo_id": int, "count": int, "action": str})

TodoCreatePayload = TypedDict(
    'TodoCreatePayload', {
        "todo_id": Optional[int],
        "due_date": Optional[datetime],
        "frequency": Optional[str],
        "task": Optional[str],
        "timeSlot": Optional[int],
        "trackHabit": Optional[bool],
        "category": Optional[str],
        "remindBeforeDays": Optional[int]
    })
Exemple #25
0
from enum import Enum

from .config import FALLBACK_COLOR, USER_COLORS_DIR

from typing import TYPE_CHECKING  # pylint: disable=wrong-import-order
if TYPE_CHECKING:
    from typing import List, Iterable, Optional, Callable  # noqa
    from typing_extensions import TypedDict  # noqa

    from .export_common import ExportDialog  # noqa
    from .preview import ThemePreview  # noqa
    from .preview_icons import IconThemePreview  # noqa

    from .theme_model import ThemeModelValue  # noqa
    from .theme_file_parser import ColorScheme  # noqa
    AboutLink = TypedDict('AboutLink', {'name': str, 'url': str})

PLUGIN_PATH_PREFIX = "__plugin__"


class OomoxPlugin(metaclass=ABCMeta):
    @property
    @abstractmethod
    def name(self) -> str:
        pass

    @property
    @abstractmethod
    def display_name(self) -> str:
        pass
Exemple #26
0
from .message import ETMMsg
from .msg_type import TGMsgType
from .utils import TelegramChatID, EFBChannelChatIDStr, TgChatMsgIDStr, message_id_to_str, \
    chat_id_to_str, OldMsgID, chat_id_str_to_id

if TYPE_CHECKING:
    from . import TelegramChannel
    from .chat import ETMChatMember, ETMChatType

database = SqliteDatabase(None)

PickledDict = TypedDict(
    'PickledDict', {
        "target": EFBChannelChatIDStr,
        "is_system": bool,
        "attributes": MessageAttribute,
        "commands": MessageCommands,
        "substitutions": Dict[Tuple[int, int], EFBChannelChatIDStr],
        "reactions": Dict[ReactionName, Collection[EFBChannelChatIDStr]]
    },
    total=False)
"""
Dict entries for ``pickle`` field of ``msglog`` log.

- ``target``: ``master_msg_id`` of the target message
- ``is_system``
- ``attributes``
- ``commands``
- ``substitutions``: ``Dict[Tuple[int, int], SlaveChatID]``
- ``reactions``: ``Dict[str, Collection[SlaveChatID]]``
"""
CONTAINER_ONLY: Final = 'container_only'
DESCRIPTION: Final = "description"
PATH_METHOD: Final = 'path'
COMMANDS: Final = 'commands'
SUCCESS: Final = 'success'
FAILURE: Final = 'failure'
COMMAND_NAME: Final = 'name'
COMMAND_DESCRIPTION: Final = 'description'

LEGACY_PATH_METHOD: Final = 'path_method'

TypeUserConfiguration = TypedDict('TypeUserConfiguration', {
    'name': str,
    'description': str,
    'container_only': bool,
    'path': str,
    'commands': List[str],
    'success': str,
    'failure': str,
},
                                  total=False)

TypeLegacyUserConfiguration = TypedDict('TypeLegacyUserConfiguration', {
    'name': str,
    'description': str,
    'container_only': bool,
    'path_method': str,
    'commands': List[str],
    'success': str,
    'failure': str,
},
                                        total=False)
    from sentry_sdk._types import (
        BreadcrumbProcessor,
        Event,
        EventProcessor,
        TracesSampler,
    )

    # Experiments are feature flags to enable and disable certain unstable SDK
    # functionality. Changing them from the defaults (`None`) in production
    # code is highly discouraged. They are not subject to any stability
    # guarantees such as the ones from semantic versioning.
    Experiments = TypedDict(
        "Experiments",
        {
            "max_spans": Optional[int],
            "record_sql_params": Optional[bool],
            "smart_transaction_trimming": Optional[bool],
            "propagate_tracestate": Optional[bool],
        },
        total=False,
    )

DEFAULT_QUEUE_SIZE = 100
DEFAULT_MAX_BREADCRUMBS = 100


# This type exists to trick mypy and PyCharm into thinking `init` and `Client`
# take these arguments (even though they take opaque **kwargs)
class ClientConstructor(object):
    def __init__(
        self,
        dsn=None,  # type: Optional[str]