Current File : //proc/self/root/usr/lib/python3/dist-packages/twisted/words/xish/utility.py
# -*- test-case-name: twisted.words.test.test_xishutil -*-
#
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Event Dispatching and Callback utilities.
"""


from twisted.python import log
from twisted.words.xish import xpath


class _MethodWrapper:
    """
    Internal class for tracking method calls.
    """

    def __init__(self, method, *args, **kwargs):
        self.method = method
        self.args = args
        self.kwargs = kwargs

    def __call__(self, *args, **kwargs):
        nargs = self.args + args
        nkwargs = self.kwargs.copy()
        nkwargs.update(kwargs)
        self.method(*nargs, **nkwargs)


class CallbackList:
    """
    Container for callbacks.

    Event queries are linked to lists of callables. When a matching event
    occurs, these callables are called in sequence. One-time callbacks
    are removed from the list after the first time the event was triggered.

    Arguments to callbacks are split spread across two sets. The first set,
    callback specific, is passed to C{addCallback} and is used for all
    subsequent event triggers.  The second set is passed to C{callback} and is
    event specific. Positional arguments in the second set come after the
    positional arguments of the first set. Keyword arguments in the second set
    override those in the first set.

    @ivar callbacks: The registered callbacks as mapping from the callable to a
                     tuple of a wrapper for that callable that keeps the
                     callback specific arguments and a boolean that signifies
                     if it is to be called only once.
    @type callbacks: C{dict}
    """

    def __init__(self):
        self.callbacks = {}

    def addCallback(self, onetime, method, *args, **kwargs):
        """
        Add callback.

        The arguments passed are used as callback specific arguments.

        @param onetime: If C{True}, this callback is called at most once.
        @type onetime: C{bool}
        @param method: The callback callable to be added.
        @param args: Positional arguments to the callable.
        @type args: C{list}
        @param kwargs: Keyword arguments to the callable.
        @type kwargs: C{dict}
        """

        if method not in self.callbacks:
            self.callbacks[method] = (_MethodWrapper(method, *args, **kwargs), onetime)

    def removeCallback(self, method):
        """
        Remove callback.

        @param method: The callable to be removed.
        """

        if method in self.callbacks:
            del self.callbacks[method]

    def callback(self, *args, **kwargs):
        """
        Call all registered callbacks.

        The passed arguments are event specific and augment and override
        the callback specific arguments as described above.

        @note: Exceptions raised by callbacks are trapped and logged. They will
               not propagate up to make sure other callbacks will still be
               called, and the event dispatching always succeeds.

        @param args: Positional arguments to the callable.
        @type args: C{list}
        @param kwargs: Keyword arguments to the callable.
        @type kwargs: C{dict}
        """

        for key, (methodwrapper, onetime) in list(self.callbacks.items()):
            try:
                methodwrapper(*args, **kwargs)
            except BaseException:
                log.err()

            if onetime:
                del self.callbacks[key]

    def isEmpty(self):
        """
        Return if list of registered callbacks is empty.

        @rtype: C{bool}
        """

        return len(self.callbacks) == 0


class EventDispatcher:
    """
    Event dispatching service.

    The C{EventDispatcher} allows observers to be registered for certain events
    that are dispatched. There are two types of events: XPath events and Named
    events.

    Every dispatch is triggered by calling L{dispatch} with a data object and,
    for named events, the name of the event.

    When an XPath type event is dispatched, the associated object is assumed to
    be an L{Element<twisted.words.xish.domish.Element>} instance, which is
    matched against all registered XPath queries. For every match, the
    respective observer will be called with the data object.

    A named event will simply call each registered observer for that particular
    event name, with the data object. Unlike XPath type events, the data object
    is not restricted to L{Element<twisted.words.xish.domish.Element>}, but can
    be anything.

    When registering observers, the event that is to be observed is specified
    using an L{xpath.XPathQuery} instance or a string. In the latter case, the
    string can also contain the string representation of an XPath expression.
    To distinguish these from named events, each named event should start with
    a special prefix that is stored in C{self.prefix}. It defaults to
    C{//event/}.

    Observers registered using L{addObserver} are persistent: after the
    observer has been triggered by a dispatch, it remains registered for a
    possible next dispatch. If instead L{addOnetimeObserver} was used to
    observe an event, the observer is removed from the list of observers after
    the first observed event.

    Observers can also be prioritized, by providing an optional C{priority}
    parameter to the L{addObserver} and L{addOnetimeObserver} methods. Higher
    priority observers are then called before lower priority observers.

    Finally, observers can be unregistered by using L{removeObserver}.
    """

    def __init__(self, eventprefix="//event/"):
        self.prefix = eventprefix
        self._eventObservers = {}
        self._xpathObservers = {}
        self._dispatchDepth = 0  # Flag indicating levels of dispatching
        # in progress
        self._updateQueue = []  # Queued updates for observer ops

    def _getEventAndObservers(self, event):
        if isinstance(event, xpath.XPathQuery):
            # Treat as xpath
            observers = self._xpathObservers
        else:
            if self.prefix == event[: len(self.prefix)]:
                # Treat as event
                observers = self._eventObservers
            else:
                # Treat as xpath
                event = xpath.internQuery(event)
                observers = self._xpathObservers

        return event, observers

    def addOnetimeObserver(self, event, observerfn, priority=0, *args, **kwargs):
        """
        Register a one-time observer for an event.

        Like L{addObserver}, but is only triggered at most once. See there
        for a description of the parameters.
        """
        self._addObserver(True, event, observerfn, priority, *args, **kwargs)

    def addObserver(self, event, observerfn, priority=0, *args, **kwargs):
        """
        Register an observer for an event.

        Each observer will be registered with a certain priority. Higher
        priority observers get called before lower priority observers.

        @param event: Name or XPath query for the event to be monitored.
        @type event: C{str} or L{xpath.XPathQuery}.
        @param observerfn: Function to be called when the specified event
                           has been triggered. This callable takes
                           one parameter: the data object that triggered
                           the event. When specified, the C{*args} and
                           C{**kwargs} parameters to addObserver are being used
                           as additional parameters to the registered observer
                           callable.
        @param priority: (Optional) priority of this observer in relation to
                         other observer that match the same event. Defaults to
                         C{0}.
        @type priority: C{int}
        """
        self._addObserver(False, event, observerfn, priority, *args, **kwargs)

    def _addObserver(self, onetime, event, observerfn, priority, *args, **kwargs):
        # If this is happening in the middle of the dispatch, queue
        # it up for processing after the dispatch completes
        if self._dispatchDepth > 0:
            self._updateQueue.append(
                lambda: self._addObserver(
                    onetime, event, observerfn, priority, *args, **kwargs
                )
            )
            return

        event, observers = self._getEventAndObservers(event)

        if priority not in observers:
            cbl = CallbackList()
            observers[priority] = {event: cbl}
        else:
            priorityObservers = observers[priority]
            if event not in priorityObservers:
                cbl = CallbackList()
                observers[priority][event] = cbl
            else:
                cbl = priorityObservers[event]

        cbl.addCallback(onetime, observerfn, *args, **kwargs)

    def removeObserver(self, event, observerfn):
        """
        Remove callable as observer for an event.

        The observer callable is removed for all priority levels for the
        specified event.

        @param event: Event for which the observer callable was registered.
        @type event: C{str} or L{xpath.XPathQuery}
        @param observerfn: Observer callable to be unregistered.
        """

        # If this is happening in the middle of the dispatch, queue
        # it up for processing after the dispatch completes
        if self._dispatchDepth > 0:
            self._updateQueue.append(lambda: self.removeObserver(event, observerfn))
            return

        event, observers = self._getEventAndObservers(event)

        emptyLists = []
        for priority, priorityObservers in observers.items():
            for query, callbacklist in priorityObservers.items():
                if event == query:
                    callbacklist.removeCallback(observerfn)
                    if callbacklist.isEmpty():
                        emptyLists.append((priority, query))

        for priority, query in emptyLists:
            del observers[priority][query]

    def dispatch(self, obj, event=None):
        """
        Dispatch an event.

        When C{event} is L{None}, an XPath type event is triggered, and
        C{obj} is assumed to be an instance of
        L{Element<twisted.words.xish.domish.Element>}. Otherwise, C{event}
        holds the name of the named event being triggered. In the latter case,
        C{obj} can be anything.

        @param obj: The object to be dispatched.
        @param event: Optional event name.
        @type event: C{str}
        """

        foundTarget = False

        self._dispatchDepth += 1

        if event != None:
            # Named event
            observers = self._eventObservers
            match = lambda query, obj: query == event
        else:
            # XPath event
            observers = self._xpathObservers
            match = lambda query, obj: query.matches(obj)

        priorities = list(observers.keys())
        priorities.sort()
        priorities.reverse()

        emptyLists = []
        for priority in priorities:
            for query, callbacklist in observers[priority].items():
                if match(query, obj):
                    callbacklist.callback(obj)
                    foundTarget = True
                    if callbacklist.isEmpty():
                        emptyLists.append((priority, query))

        for priority, query in emptyLists:
            del observers[priority][query]

        self._dispatchDepth -= 1

        # If this is a dispatch within a dispatch, don't
        # do anything with the updateQueue -- it needs to
        # wait until we've back all the way out of the stack
        if self._dispatchDepth == 0:
            # Deal with pending update operations
            for f in self._updateQueue:
                f()
            self._updateQueue = []

        return foundTarget


class XmlPipe:
    """
    XML stream pipe.

    Connects two objects that communicate stanzas through an XML stream like
    interface. Each of the ends of the pipe (sink and source) can be used to
    send XML stanzas to the other side, or add observers to process XML stanzas
    that were sent from the other side.

    XML pipes are usually used in place of regular XML streams that are
    transported over TCP. This is the reason for the use of the names source
    and sink for both ends of the pipe. The source side corresponds with the
    entity that initiated the TCP connection, whereas the sink corresponds with
    the entity that accepts that connection. In this object, though, the source
    and sink are treated equally.

    Unlike Jabber
    L{XmlStream<twisted.words.protocols.jabber.xmlstream.XmlStream>}s, the sink
    and source objects are assumed to represent an eternal connected and
    initialized XML stream. As such, events corresponding to connection,
    disconnection, initialization and stream errors are not dispatched or
    processed.

    @since: 8.2
    @ivar source: Source XML stream.
    @ivar sink: Sink XML stream.
    """

    def __init__(self):
        self.source = EventDispatcher()
        self.sink = EventDispatcher()
        self.source.send = lambda obj: self.sink.dispatch(obj)
        self.sink.send = lambda obj: self.source.dispatch(obj)
¿Qué es la limpieza dental de perros? - Clínica veterinaria


Es la eliminación del sarro y la placa adherida a la superficie de los dientes mediante un equipo de ultrasonidos que garantiza la integridad de las piezas dentales a la vez que elimina en profundidad cualquier resto de suciedad.

A continuación se procede al pulido de los dientes mediante una fresa especial que elimina la placa bacteriana y devuelve a los dientes el aspecto sano que deben tener.

Una vez terminado todo el proceso, se mantiene al perro en observación hasta que se despierta de la anestesia, bajo la atenta supervisión de un veterinario.

¿Cada cuánto tiempo tengo que hacerle una limpieza dental a mi perro?

A partir de cierta edad, los perros pueden necesitar una limpieza dental anual o bianual. Depende de cada caso. En líneas generales, puede decirse que los perros de razas pequeñas suelen acumular más sarro y suelen necesitar una atención mayor en cuanto a higiene dental.


Riesgos de una mala higiene


Los riesgos más evidentes de una mala higiene dental en los perros son los siguientes:

  • Cuando la acumulación de sarro no se trata, se puede producir una inflamación y retracción de las encías que puede descalzar el diente y provocar caídas.
  • Mal aliento (halitosis).
  • Sarro perros
  • Puede ir a más
  • Las bacterias de la placa pueden trasladarse a través del torrente circulatorio a órganos vitales como el corazón ocasionando problemas de endocarditis en las válvulas. Las bacterias pueden incluso acantonarse en huesos (La osteomielitis es la infección ósea, tanto cortical como medular) provocando mucho dolor y una artritis séptica).

¿Cómo se forma el sarro?

El sarro es la calcificación de la placa dental. Los restos de alimentos, junto con las bacterias presentes en la boca, van a formar la placa bacteriana o placa dental. Si la placa no se retira, al mezclarse con la saliva y los minerales presentes en ella, reaccionará formando una costra. La placa se calcifica y se forma el sarro.

El sarro, cuando se forma, es de color blanquecino pero a medida que pasa el tiempo se va poniendo amarillo y luego marrón.

Síntomas de una pobre higiene dental
La señal más obvia de una mala salud dental canina es el mal aliento.

Sin embargo, a veces no es tan fácil de detectar
Y hay perros que no se dejan abrir la boca por su dueño. Por ejemplo…

Recientemente nos trajeron a la clínica a un perro que parpadeaba de un ojo y decía su dueño que le picaba un lado de la cara. Tenía molestias y dificultad para comer, lo que había llevado a sus dueños a comprarle comida blanda (que suele ser un poco más cara y llevar más contenido en grasa) durante medio año. Después de una exploración oftalmológica, nos dimos cuenta de que el ojo tenía una úlcera en la córnea probablemente de rascarse . Además, el canto lateral del ojo estaba inflamado. Tenía lo que en humanos llamamos flemón pero como era un perro de pelo largo, no se le notaba a simple vista. Al abrirle la boca nos llamó la atención el ver una muela llena de sarro. Le realizamos una radiografía y encontramos una fístula que llegaba hasta la parte inferior del ojo.

Le tuvimos que extraer la muela. Tras esto, el ojo se curó completamente con unos colirios y una lentilla protectora de úlcera. Afortunadamente, la úlcera no profundizó y no perforó el ojo. Ahora el perro come perfectamente a pesar de haber perdido una muela.

¿Cómo mantener la higiene dental de tu perro?
Hay varias maneras de prevenir problemas derivados de la salud dental de tu perro.

Limpiezas de dientes en casa
Es recomendable limpiar los dientes de tu perro semanal o diariamente si se puede. Existe una gran variedad de productos que se pueden utilizar:

Pastas de dientes.
Cepillos de dientes o dedales para el dedo índice, que hacen más fácil la limpieza.
Colutorios para echar en agua de bebida o directamente sobre el diente en líquido o en spray.

En la Clínica Tus Veterinarios enseñamos a nuestros clientes a tomar el hábito de limpiar los dientes de sus perros desde que son cachorros. Esto responde a nuestro compromiso con la prevención de enfermedades caninas.

Hoy en día tenemos muchos clientes que limpian los dientes todos los días a su mascota, y como resultado, se ahorran el dinero de hacer limpiezas dentales profesionales y consiguen una mejor salud de su perro.


Limpiezas dentales profesionales de perros y gatos

Recomendamos hacer una limpieza dental especializada anualmente. La realizamos con un aparato de ultrasonidos que utiliza agua para quitar el sarro. Después, procedemos a pulir los dientes con un cepillo de alta velocidad y una pasta especial. Hacemos esto para proteger el esmalte.

La frecuencia de limpiezas dentales necesaria varía mucho entre razas. En general, las razas grandes tienen buena calidad de esmalte, por lo que no necesitan hacerlo tan a menudo e incluso pueden pasarse la vida sin requerir una limpieza. Sin embargo, razas pequeñas como el Yorkshire o el Maltés, deben hacérselas todos los años desde cachorros si se quiere conservar sus piezas dentales.

Otro factor fundamental es la calidad del pienso. Algunas marcas han diseñado croquetas que limpian la superficie del diente y de la muela al masticarse.

Ultrasonido para perros

¿Se necesita anestesia para las limpiezas dentales de perros y gatos?

La limpieza dental en perros no es una técnica que pueda practicarse sin anestesia general , aunque hay veces que los propietarios no quieren anestesiar y si tiene poco sarro y el perro es muy bueno se puede intentar…… , pero no se va a poder pulir ni acceder a todas la zona de la boca …. Además los limpiadores dentales van a irrigar agua y hay riesgo de aspiración a vías respiratorias si no se realiza una anestesia correcta con intubación traqueal . En resumen , sin anestesia no se va hacer una correcta limpieza dental.

Tampoco sirve la sedación ya que necesitamos que el animal esté totalmente quieto, y el veterinario tenga un acceso completo a todas sus piezas dentales y encías.

Alimentos para la limpieza dental

Hay que tener cierto cuidado a la hora de comprar determinados alimentos porque no todos son saludables. Algunos tienen demasiado contenido graso, que en exceso puede causar problemas cardiovasculares y obesidad.

Los mejores alimentos para los dientes son aquellos que están elaborados por empresas farmacéuticas y llevan componentes químicos con tratamientos específicos para el diente del perro. Esto implica no solo limpieza a través de la acción mecánica de morder sino también un tratamiento antibacteriano para prevenir el sarro.

Conclusión

Si eres como la mayoría de dueños, por falta de tiempo , es probable que no estés prestando la suficiente atención a la limpieza dental de tu perro. Por eso te animamos a que comiences a limpiar los dientes de tu perro y consideres atender a su higiene bucal con frecuencia.

Estas simples medidas pueden conllevar a que tu perro tenga una vida más larga y mucho más saludable.

Si te resulta imposible introducir un cepillo de dientes a tu perro en la boca, pásate con él por clínica Tus Veterinarios y te explicamos cómo hacerlo.

Necesitas hacer una limpieza dental profesional a tu mascota?
Llámanos al 622575274 o contacta con nosotros

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

¡Hola!