Example #1
0
class StaticSelectElement(InteractiveElement):

    placeholder: PlainTextField
    action_id: str
    options: list[Option] = Factory(list)
    option_groups: list[OptionGroup] = Factory(list)
    initial_option: Option | None = None
    confirm: ConfirmationDialog | None = None
    type: str = field(default="static_select", init=False)
Example #2
0
class MemoryWormholeServer(object):
    """
    A factory for in-memory wormholes.

    :ivar _apps: Wormhole state arranged by the application id and relay URL
        it belongs to.

    :ivar _waiters: Observers waiting for a wormhole to be created for a
        specific application id and relay URL combination.
    """
    _apps: dict[ApplicationKey, _WormholeApp] = field(default=Factory(dict))
    _waiters: dict[ApplicationKey, Deferred] = field(default=Factory(dict))

    def create(
        self,
        appid,
        relay_url,
        reactor,
        versions={},
        delegate=None,
        journal=None,
        tor=None,
        timing=None,
        stderr=stderr,
        _eventual_queue=None,
        _enable_dilate=False,
    ):
        """
        Create a wormhole.  It will be able to connect to other wormholes created
        by this instance (and constrained by the normal appid/relay_url
        rules).
        """
        if tor is not None:
            raise ValueError("Cannot deal with Tor right now.")
        if _enable_dilate:
            raise ValueError("Cannot deal with dilation right now.")

        key = (relay_url, appid)
        wormhole = _MemoryWormhole(self._view(key))
        if key in self._waiters:
            self._waiters.pop(key).callback(wormhole)
        return wormhole

    def _view(self, key: ApplicationKey) -> _WormholeServerView:
        """
        Created a view onto this server's state that is limited by a certain
        appid/relay_url pair.
        """
        return _WormholeServerView(self, key)
Example #3
0
class Section(Block):
    """Section Block"""

    text: TextField
    type: str = field(default="section", init=False)
    fields: list[TextField] = Factory(list)
    accessory: Element | None = None
Example #4
0
class OverflowElement(InteractiveElement):

    placeholder: PlainTextField
    action_id: str
    options: list[Option] = Factory(list)
    confirm: ConfirmationDialog | None = None
    type: str = field(default="overflow", init=False)
Example #5
0
class _WormholeApp(object):
    """
    Represent a collection of wormholes that belong to the same
    appid/relay_url scope.
    """
    wormholes: dict[WormholeCode, IWormhole] = field(default=Factory(dict))
    _waiting: dict[WormholeCode, List[Deferred]] = field(default=Factory(dict))
    _counter: Iterator[int] = field(default=Factory(count))

    def allocate_code(self, wormhole: IWormhole,
                      code: Optional[WormholeCode]) -> WormholeCode:
        """
        Allocate a new code for the given wormhole.

        This also associates the given wormhole with the code for future
        lookup.

        Code generation logic is trivial and certainly not good enough for any
        real use.  It is sufficient for automated testing, though.
        """
        if code is None:
            code = "{}-persnickety-tardigrade".format(next(self._counter))
        self.wormholes.setdefault(code, []).append(wormhole)
        try:
            waiters = self._waiting.pop(code)
        except KeyError:
            pass
        else:
            for w in waiters:
                w.callback(wormhole)

        return code

    def wait_for_wormhole(self,
                          code: WormholeCode) -> Awaitable[_MemoryWormhole]:
        """
        Return a ``Deferred`` which fires with the next wormhole to be associated
        with the given code.  This is used to let the first end of a wormhole
        rendezvous with the second end.
        """
        d = Deferred()
        self._waiting.setdefault(code, []).append(d)
        return d
Example #6
0
class Attachment:
    """Slack Attachment"""

    fallback: str | None = None
    color: str | None = None
    pretext: str | None = None
    author_name: str | None = None
    author_link: str | None = None
    author_icon: str | None = None
    title: str | None = None
    title_link: str | None = None
    text: str | None = None
    blocks: list[Block] | None = None
    fields: list[Field] = Factory(list)
    actions: list[Action] | None = None
    image_url: str | None = None
    thumb_url: str | None = None
    footer: str | None = None
    footer_icon: str | None = None
    ts: int | None = None
    callback_id: str | None = None
Example #7
0
class OptionGroup:

    label: PlainTextField
    options: list[Option] = Factory(list)
Example #8
0
class Context(Block):
    """Context Block"""

    type: str = field(default="context", init=False)
    elements: list[TextField | ImageElement] = Factory(list)
Example #9
0
class Action(Block):

    elements: list[InteractiveElement] = Factory(list)
Example #10
0
class InjectionParametersGenerator:
    """
    Draw injection parameter samples from priors and return in dictionary format.

    Parameters
    ----------
    priors: dict
        Each key refers to one of the signal's parameters
        (following the PyFstat convention).
        Priors can be given as values in three formats
        (by order of evaluation):

        1. Callable without required arguments:
        `{"ParameterA": np.random.uniform}`.

        2. Dict containing numpy.random distribution as key and kwargs in a dict as value:
        `{"ParameterA": {"uniform": {"low": 0, "high":1}}}`.

        3. Constant value to be returned as is:
        `{"ParameterA": 1.0}`.

    seed: None, int
        Argument to be fed to numpy.random.default_rng,
        with all of its accepted types.

    _rng: np.random.Generator
        Alternatively, this class accepts an already-initialized np.Generator,
        in which case the `seed` argument will be ignored.
    """

    seed: Union[None, int] = field(default=None)
    _rng: np.random.Generator = field(
        default=Factory(lambda self: np.random.default_rng(self.seed), takes_self=True)
    )
    priors: dict = field(factory=dict)

    def __attrs_post_init__(self):
        self.priors = self._parse_priors(self.priors)

    def _parse_priors(self, priors_input_format):
        """Internal method to do the actual prior setup."""
        priors = {}

        for parameter_name, parameter_prior in priors_input_format.items():
            if callable(parameter_prior):
                priors[parameter_name] = parameter_prior
            elif isinstance(parameter_prior, dict):
                rng_function_name = next(iter(parameter_prior))
                rng_function = getattr(self._rng, rng_function_name)
                rng_kwargs = parameter_prior[rng_function_name]
                priors[parameter_name] = functools.partial(rng_function, **rng_kwargs)
            else:  # Assume it is something to be returned as is
                priors[parameter_name] = functools.partial(lambda x: x, parameter_prior)

        return priors

    def draw(self):
        """Draw a single multi-dimensional parameter space point from the given priors.

        Returns
        ----------
        injection_parameters: dict
            Dictionary with parameter names as keys and their numeric values.
        """
        injection_parameters = {
            parameter_name: parameter_prior()
            for parameter_name, parameter_prior in self.priors.items()
        }
        return injection_parameters
Example #11
0
class _MemoryWormhole(object):
    """
    Represent one side of a wormhole as conceived by ``MemoryWormholeServer``.
    """

    _view: _WormholeServerView
    _code: Optional[WormholeCode] = None
    _payload: DeferredQueue = field(default=Factory(DeferredQueue))
    _waiting_for_code: list[Deferred] = field(default=Factory(list))

    def allocate_code(self) -> None:
        if self._code is not None:
            raise ValueError(
                "allocate_code used with a wormhole which already has a code")
        self._code = self._view.allocate_code(self, None)
        waiters = self._waiting_for_code
        self._waiting_for_code = []
        for d in waiters:
            d.callback(self._code)

    def set_code(self, code: WormholeCode) -> None:
        if self._code is None:
            self._code = code
            self._view.allocate_code(self, code)
        else:
            raise ValueError(
                "set_code used with a wormhole which already has a code")

    def when_code(self) -> Deferred[WormholeCode]:
        if self._code is None:
            d = Deferred()
            self._waiting_for_code.append(d)
            return d
        return succeed(self._code)

    def get_welcome(self):
        return succeed("welcome")

    def send_message(self, payload: WormholeMessage) -> None:
        self._payload.put(payload)

    def when_received(self) -> Deferred[WormholeMessage]:
        if self._code is None:
            raise ValueError(
                "This implementation requires set_code or allocate_code "
                "before when_received.")
        d = self._view.wormhole_by_code(self._code, exclude=self)

        def got_wormhole(wormhole):
            msg = wormhole._payload.get()
            return msg

        d.addCallback(got_wormhole)
        return d

    get_message = when_received

    def close(self) -> None:
        pass

    # 0.9.2 compatibility
    def get_code(self) -> Deferred[WormholeCode]:
        if self._code is None:
            self.allocate_code()
        return self.when_code()

    get = when_received