
    df=J                       d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Zddl
mZ ddlmZ ddlmZ ddlmZmZ ddlmZmZmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddl m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z* ddl+m,Z, dZ-	 ddl.Z.dZ0d Z1d Z2 G d d      Z3 G d de3      Z4 G d de4      Z5 G d d      Z6 G d de3      Z7 G d d e4      Z8 G d! d"e4      Z9 G d# d$e3      Z: G d% d&e:      Z; G d' d(e;      Z< G d) d*e:      Z= G d+ d,e=      Z> G d- d.      Z? G d/ d0e=      Z@ G d1 d2e3      ZA G d3 d4e3      ZBy# e/$ r dZ.dZ-Y w xY w)5zEFramework-agnostic core of Motor, an asynchronous driver for MongoDB.    N)ChangeStream)ClientSession)
Collection)CommandCursorRawBatchCommandCursor)_QUERY_OPTIONSCursorRawBatchCursor)Database)
DriverInfo)ClientEncryption   )
docstrings)version)
AsyncCommand	AsyncRead
AsyncWriteDelegateMethodMotorCursorChainingMethodReadOnlyPropertycoroutine_annotationcreate_class_with_frameworkunwrap_args_sessionunwrap_kwargs_session)callback_type_errorTFx   c                 >    t        j                         | z
  t        k  S )z/Are we within the with_transaction retry limit?)time	monotonic"_WITH_TRANSACTION_RETRY_TIME_LIMIT)
start_times    C/home/api-vastappli/venv/lib/python3.12/site-packages/motor/core.py_within_time_limitr#   A   s    >>j(+MMM    c                 l    t        | t        j                  j                        xr | j                  dk(  S )z/Return true if exc is a MaxTimeMSExpired error.2   )
isinstancepymongoerrorsOperationFailurecode)excs    r"   _max_time_expired_errorr-   F   s&    c7>>::;NBNr$   c                       e Zd Zd Zd Zd Zy)AgnosticBasec                     t        || j                        r1t        | d      r%t        |d      r| j                  |j                  k(  S t        S )Ndelegate)r'   	__class__hasattrr1   NotImplemented)selfothers     r"   __eq__zAgnosticBase.__eq__L   s=    udnn-j)z*==ENN22r$   c                     || _         y Nr1   )r5   r1   s     r"   __init__zAgnosticBase.__init__U   s	     r$   c                 N    | j                   j                   d| j                  dS )N())r2   __name__r1   r5   s    r"   __repr__zAgnosticBase.__repr__X   s%    ..))*!DMM+<A>>r$   N)r?   
__module____qualname__r7   r;   rA    r$   r"   r/   r/   K   s    !?r$   r/   c                   D    e Zd Z e       Z e       Z e       Z e       Zy)AgnosticBasePropertiesN)r?   rB   rC   r   codec_optionsread_preferenceread_concernwrite_concernrD   r$   r"   rF   rF   \   s"    $&M&(O#%L$&Mr$   rF   c                       e Zd ZdZej
                  j                  Z e       Z	 e       Z
 e       Z e       Z e       j                  d      Z e       Z eej&                        j)                  e      Z eej.                        j)                  e      Z e       Z e       Z e       Z e       j)                  e      Z e       Z e       Z  e       Z! e       Z" e       Z# e       Z$ e       Z% e       Z& eejN                        j)                  e(      Z) fdZ*e+d        Z,d Z-	 	 	 	 	 	 	 	 	 	 	 	 ddZ.d Z/d	 Z0d
 Z xZ1S )AgnosticClientMotorClientMotorDatabasedocc                    d|v r-|j                  d      }| j                  j                  |       nd}|| _        |j	                  dd       t        dt        | j                  j                               }|j                  d      r|j                  d      }t        |t
              st        dt        |       d      |j                  rd	|j                   nd
}|j                  rd	|j                   nd
}t        |j                   d	|j                   |j                   | |j                   |       }||d<    | j                  |i |}t         	| E  |       y)a9  Create a new connection to a single MongoDB instance at *host:port*.

        Takes the same constructor arguments as
        :class:`~pymongo.mongo_client.MongoClient`, as well as:

        :Parameters:
          - `io_loop` (optional): Special event loop
            instance to use instead of default.
        io_loopNconnectFMotordriverzIncorrect type for `driver` z7; expected value of type pymongo.driver_info.DriverInfo| )pop
_frameworkcheck_event_loop_io_loop
setdefaultr   motor_versionplatform_infogetr'   	TypeErrortyper   platformname__delegate_class__superr;   )
r5   argskwargsrR   driver_infoprovided_infoadded_versionadded_platformr1   r2   s
            r"   r;   zAgnosticClient.__init__}   sk    jj+GOO,,W5G)U+ -9V9V9XY::h"JJx0MmZ8243F2G HM M  <I;P;Pa 5 567VXM=J=S=Sq!7!7 89Y[N$##$Am&8&8%9:&&'7''((89K 'x*4**D;F;"r$   c                 p    | j                   | j                  j                         | _         | j                   S r9   r[   rY   get_event_loopr@   s    r"   rR   zAgnosticClient.io_loop   *    ==  OO::<DM}}r$   c                     | j                   S r9   rR   r@   s    r"   get_io_loopzAgnosticClient.get_io_loop       ||r$   c                 t    t        t        | j                  | j                        } || |||||||||	|
||      S )aR  Watch changes on this cluster.

        Returns a :class:`~MotorChangeStream` cursor which iterates over changes
        on all databases in this cluster. Introduced in MongoDB 4.0.

        See the documentation for :meth:`MotorCollection.watch` for more
        details and examples.

        :Parameters:
          - `pipeline` (optional): A list of aggregation pipeline stages to
            append to an initial ``$changeStream`` stage. Not all
            pipeline stages are valid after a ``$changeStream`` stage, see the
            MongoDB documentation on change streams for the supported stages.
          - `full_document` (optional): The fullDocument option to pass
            to the ``$changeStream`` stage. Allowed values: 'updateLookup'.
            When set to 'updateLookup', the change notification for partial
            updates will include both a delta describing the changes to the
            document, as well as a copy of the entire document that was
            changed from some time after the change occurred.
          - `resume_after` (optional): A resume token. If provided, the
            change stream will start returning changes that occur directly
            after the operation specified in the resume token. A resume token
            is the _id value of a change document.
          - `max_await_time_ms` (optional): The maximum time in milliseconds
            for the server to wait for changes before responding to a getMore
            operation.
          - `batch_size` (optional): The maximum number of documents to return
            per batch.
          - `collation` (optional): The :class:`~pymongo.collation.Collation`
            to use for the aggregation.
          - `start_at_operation_time` (optional): If provided, the resulting
            change stream will only return changes that occurred at or after
            the specified :class:`~bson.timestamp.Timestamp`. Requires
            MongoDB >= 4.0.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `start_after` (optional): The same as `resume_after` except that
            `start_after` can resume notifications after an invalidate event.
            This option and `resume_after` are mutually exclusive.
          - `comment` (optional): A user-provided comment to attach to this
            command.
          - `full_document_before_change`: Allowed values: `whenAvailable` and `required`. Change
            events may now result in a `fullDocumentBeforeChange` response field.
          - `show_expanded_events` (optional): Include expanded events such as DDL events like
            `dropIndexes`.

        :Returns:
          A :class:`~MotorChangeStream`.

        .. versionchanged:: 3.2
           Added ``show_expanded_events`` parameter.

        .. versionchanged:: 3.1
           Added ``full_document_before_change`` parameter.

        .. versionchanged:: 3.0
           Added ``comment`` parameter.

        .. versionchanged:: 2.1
           Added the ``start_after`` parameter.

        .. versionadded:: 2.0

        .. mongodoc:: changeStreams
        r   AgnosticChangeStreamrY   rB   r5   pipelinefull_documentresume_aftermax_await_time_ms
batch_size	collationstart_at_operation_timesessionstart_aftercommentfull_document_before_changeshow_expanded_eventscursor_classs                 r"   watchzAgnosticClient.watch   T    ` 3 $//4??

 #' 
 	
r$   c           
          |j                  d      r+t        | j                  j                   d|d| d| d      | |   S )N_ has no attribute . To access the z database, use client[''].
startswithAttributeErrorr2   r?   r5   rc   s     r"   __getattr__zAgnosticClient.__getattr__  sU    ??3 >>**++=dXEUVZU[)$s4 
 Dzr$   c                 ^    t        t        | j                  | j                        } || |      S r9   )r   AgnosticDatabaserY   rB   )r5   rc   db_classs      r"   __getitem__zAgnosticClient.__getitem__  s)    ./?RVRaRabd##r$   c                    |j                   t        k(  r:t        t        | j                  | j
                        } || |j                  |      S |j                   t        k(  r.t        t        | j                  | j
                        } |||       S |j                   t        k(  r.t        t        | j                  | j
                        } |||       S y N	_delegate)r2   r   r   r   rY   rB   rc   r   AgnosticCommandCursorr   AgnosticClientSession)r5   objr   command_cursor_classsession_classs        r"   wrapzAgnosticClient.wrap"  s    ==H$2 $//4??H D#((c::]]m+#>%t$  (T22]]m+7%tM !d++ ,r$   NNNNNNNNNNNN)2r?   rB   rC   __motor_class_name__r(   mongo_clientMongoClientrd   r   addressarbitersr   close__hash__r   unwrapdrop_databaseoptionsr   get_database_docr   r   get_databaseget_default_database_docget_default_databaseHOST	is_mongos
is_primaryr   r   list_databaseslist_database_namesnodesPORTprimaryrI   secondariesserver_infotopology_descriptionstart_session_docr   start_sessionr;   propertyrR   rr   r   r   r   __classcell__r2   s   @r"   rL   rL   c   sm   ( --99 G!HEH N))/:M G!j&A&ABGGQL)j.Q.QRWWX`aD "I!#J[%%m4N#+ED G#%L"$K+K+- Z%A%ABGGVM'#R  

  $$(!c
J$
,r$   rL   c                   "    e Zd ZdZd Zd Zd Zy)_MotorTransactionContextz;Internal transaction context manager for start_transaction.c                     || _         y r9   )_session)r5   r   s     r"   r;   z!_MotorTransactionContext.__init__:  s	    r$   c                    K   | S wr9   rD   r@   s    r"   
__aenter__z#_MotorTransactionContext.__aenter__=          c                    K   | j                   j                  rH|#| j                   j                          d {    y | j                   j                          d {    y y 7 )7 wr9   )r   in_transactioncommit_transactionabort_transactionr5   exc_typeexc_valexc_tbs       r"   	__aexit__z"_MotorTransactionContext.__aexit__@  sP     ==''mm66888mm55777	 (87s!   6A&A""A&A$A&$A&N)r?   rB   rC   __doc__r;   r   r   rD   r$   r"   r   r   7  s    E 8r$   r   c                       e Zd ZdZdZeZ e       Z e       Z	 e       Z
 e       Z e       Z e       Z e       Z e       Z e       Z e       Z e       Zd Zd Z	 	 	 	 ddZ	 ddZed        Zd	 Zd
 Zd Zd Zy)r   a  A session for ordering sequential operations.

    Do not create an instance of :class:`MotorClientSession` directly; use
    :meth:`MotorClient.start_session`:

    .. code-block:: python3

      collection = client.db.collection

      async with await client.start_session() as s:
          async with s.start_transaction():
              await collection.delete_one({"x": 1}, session=s)
              await collection.insert_one({"x": 2}, session=s)

    .. versionadded:: 2.0
    MotorClientSessionc                 @    t         j                  | |       || _        y )Nr:   )r/   r;   _client)r5   r1   motor_clients      r"   r;   zAgnosticClientSession.__init__i  s    dX6#r$   c                 6    | j                   j                         S r9   r   rr   r@   s    r"   rr   z!AgnosticClientSession.get_io_loopm      ||''))r$   Nc                 D  K   t        j                         }	 | j                  ||||      4 d{    	  ||        d{   }ddd      d{    | j                  sS 	 	 | j                          d{    S 7 O7 @# t        $ r}| j                  r| j                          d{  7   t        |t        j                  j                        r2|j                  d      r!t        |      rY d}~ddd      d{  7    d}~ww xY w7 # 1 d{  7  sw Y   xY w7 # t        j                  j                  $ rT}|j                  d      rt        |      rt        |      sY d}~|j                  d      rt        |      rY d}~n	 d}~ww xY ww)a  Executes an awaitable in a transaction.

        This method starts a transaction on this session, awaits ``coro``
        once, and then commits the transaction. For example::

          async def coro(session):
              orders = session.client.db.orders
              inventory = session.client.db.inventory
              inserted_id = await orders.insert_one(
                  {"sku": "abc123", "qty": 100}, session=session)
              await inventory.update_one(
                  {"sku": "abc123", "qty": {"$gte": 100}},
                  {"$inc": {"qty": -100}}, session=session)
              return inserted_id

          async with await client.start_session() as session:
              inserted_id = await session.with_transaction(coro)

        To pass arbitrary arguments to the ``coro``, wrap it with a
        ``lambda`` like this::

          async def coro(session, custom_arg, custom_kwarg=None):
              # Transaction operations...

          async with await client.start_session() as session:
              await session.with_transaction(
                  lambda s: coro(s, "custom_arg", custom_kwarg=1))

        In the event of an exception, ``with_transaction`` may retry the commit
        or the entire transaction, therefore ``coro`` may be awaited
        multiple times by a single call to ``with_transaction``. Developers
        should be mindful of this possibility when writing a ``coro`` that
        modifies application state or has any other side-effects.
        Note that even when the ``coro`` is invoked multiple times,
        ``with_transaction`` ensures that the transaction will be committed
        at-most-once on the server.

        The ``coro`` should not attempt to start new transactions, but
        should simply run operations meant to be contained within a
        transaction. The ``coro`` should also not commit the transaction;
        this is handled automatically by ``with_transaction``. If the
        ``coro`` does commit or abort the transaction without error,
        however, ``with_transaction`` will return without taking further
        action.

        When ``coro`` raises an exception, ``with_transaction``
        automatically aborts the current transaction. When ``coro`` or
        :meth:`~ClientSession.commit_transaction` raises an exception that
        includes the ``"TransientTransactionError"`` error label,
        ``with_transaction`` starts a new transaction and re-executes
        the ``coro``.

        When :meth:`~ClientSession.commit_transaction` raises an exception with
        the ``"UnknownTransactionCommitResult"`` error label,
        ``with_transaction`` retries the commit until the result of the
        transaction is known.

        This method will cease retrying after 120 seconds has elapsed. This
        timeout is not configurable and any exception raised by the
        ``coro`` or by :meth:`ClientSession.commit_transaction` after the
        timeout is reached will be re-raised. Applications that desire a
        different timeout duration should not use this method.

        :Parameters:
          - `coro`: The coroutine to run inside a transaction. The coroutine must
            accept a single argument, this session. Note, under certain error
            conditions the coroutine may be run multiple times.
          - `read_concern` (optional): The
            :class:`~pymongo.read_concern.ReadConcern` to use for this
            transaction.
          - `write_concern` (optional): The
            :class:`~pymongo.write_concern.WriteConcern` to use for this
            transaction.
          - `read_preference` (optional): The read preference to use for this
            transaction. If ``None`` (the default) the :attr:`read_preference`
            of this :class:`Database` is used. See
            :mod:`~pymongo.read_preferences` for options.

        :Returns:
          The return value of the ``coro``.

        .. versionadded:: 2.1
        NTransientTransactionErrorUnknownTransactionCommitResult)r   r   start_transaction	Exceptionr   r   r'   r(   r)   PyMongoErrorhas_error_labelr#   r   r-   )	r5   cororI   rJ   rH   max_commit_time_msr!   retr,   s	            r"   with_transactionz&AgnosticClientSession.with_transactionp  s    v ^^%
--m_>P   $T
*C	 " &&
11333$ 
S +  
**"44666"3(C(CD//0KL.z: !   
   . 4~~22 ++,LM.z: 7 < !**+FGL^"M 3 s   .F B F DBBBF DF &D* 9D(:D* >F B	DD	,B/-AD	2D6F DF D		DDF D%DD%!F (D* *F'F.F 4FF FFF c                 V    | j                   j                  ||||       t        |       S )a  Start a multi-statement transaction.

        Takes the same arguments as
        :class:`~pymongo.client_session.TransactionOptions`.

        Best used in a context manager block:

        .. code-block:: python3

          # Use "await" for start_session, but not for start_transaction.
          async with await client.start_session() as s:
              async with s.start_transaction():
                  await collection.delete_one({"x": 1}, session=s)
                  await collection.insert_one({"x": 2}, session=s)

        )rI   rJ   rH   r   )r1   r   r   )r5   rI   rJ   rH   r   s        r"   r   z'AgnosticClientSession.start_transaction  s4    & 	''%'+1	 	( 	
 (--r$   c                     | j                   S )z8The :class:`~MotorClient` this session was created from.r   r@   s    r"   clientzAgnosticClientSession.client       ||r$   c                    K   | S wr9   rD   r@   s    r"   r   z AgnosticClientSession.__aenter__  r   r   c                 F   K   | j                   j                  |||       y wr9   )r1   __exit__r   s       r"   r   zAgnosticClientSession.__aexit__  s     x&9s   !c                     t        d      )NzMUse Motor sessions like 'async with await client.start_session()', not 'with')r   r@   s    r"   	__enter__zAgnosticClientSession.__enter__  s    [
 	
r$   c                      y r9   rD   r   s       r"   r   zAgnosticClientSession.__exit__#      r$   )NNNN)r?   rB   rC   r   r   r   rd   r   r   r   end_sessionr   cluster_time	has_endedr   r   operation_time
session_idr   advance_cluster_timeadvance_operation_timer;   rr   r   r   r   r   r   r   r   r   rD   r$   r"   r   r   H  s    " 0&%$.K#%L "I%'N G%'N!#J)++-$* FR _c.6  :

r$   r   c                   ,    e Zd ZdZeZ e       Z e       Z e	e
j                        Z e	       j                  e      Z e       Z e	       j%                  d      Z e       j                  e      Z ee
j*                        Z e       j                  e      Z e       Z e       j%                  d      Z e       j                  e      Z ed      Z fdZd Z	 	 	 	 	 	 	 	 	 	 	 	 ddZ 	 	 	 	 	 	 dd	Z!e"d
        Z#d Z$d Z%d Z&d Zd Z' xZ(S )r   rN   rO   MotorCollection	aggregate	attr_namec                     || _         |j                  d      }||nt        |j                  |fi |}t        |   |       y )Nr   )r   r_   r   r1   re   r;   )r5   r   rc   rg   r   r1   r2   s         r"   r;   zAgnosticDatabase.__init__:  sC    JJ{+	 ) 598FOOUY;d]c;d"r$   c                     t        t        | j                  | j                        } || d   | j                  |gt        |      i t        |      S )aS	  Execute an aggregation pipeline on this database.

        Introduced in MongoDB 3.6.

        The aggregation can be run on a secondary if the client is connected
        to a replica set and its ``read_preference`` is not :attr:`PRIMARY`.
        The :meth:`aggregate` method obeys the :attr:`read_preference` of this
        :class:`MotorDatabase`, except when ``$out`` or ``$merge`` are used, in
        which case  :attr:`PRIMARY` is used.

        All optional `aggregate command`_ parameters should be passed as
        keyword arguments to this method. Valid options include, but are not
        limited to:

          - `allowDiskUse` (bool): Enables writing to temporary files. When set
            to True, aggregation stages can write data to the _tmp subdirectory
            of the --dbpath directory. The default is False.
          - `maxTimeMS` (int): The maximum amount of time to allow the operation
            to run in milliseconds.
          - `batchSize` (int): The maximum number of documents to return per
            batch. Ignored if the connected mongod or mongos does not support
            returning aggregate results using a cursor.
          - `collation` (optional): An instance of
            :class:`~pymongo.collation.Collation`.
          - `let` (dict): A dict of parameter names and values. Values must be
            constant or closed expressions that do not reference document
            fields. Parameters can then be accessed as variables in an
            aggregate expression context (e.g. ``"$$var"``). This option is
            only supported on MongoDB >= 5.0.

        Returns a :class:`MotorCommandCursor` that can be iterated like a
        cursor from :meth:`find`::

           async def f():
               # Lists all operations currently running on the server.
               pipeline = [{"$currentOp": {}}]
               async for operation in client.admin.aggregate(pipeline):
                   print(operation)

        .. note:: This method does not support the 'explain' option. Please
           use :meth:`MotorDatabase.command` instead.

        .. note:: The :attr:`MotorDatabase.write_concern` of this database is
           automatically applied to this operation.

        .. versionadded:: 2.1

        .. _aggregate command:
            https://www.mongodb.com/docs/manual/reference/command/aggregate/
        z$cmd.aggregater   AgnosticLatentCommandCursorrY   rB   _async_aggregater   r   r5   rx   rf   rg   r   s        r"   r   zAgnosticDatabase.aggregateA  s`    f 3'$//

 !"!!
 !&	

 $F+
 	
r$   c                 t    t        t        | j                  | j                        } || |||||||||	|
||      S )aD  Watch changes on this database.

        Returns a :class:`~MotorChangeStream` cursor which iterates over changes
        on this database. Introduced in MongoDB 4.0.

        See the documentation for :meth:`MotorCollection.watch` for more
        details and examples.

        :Parameters:
          - `pipeline` (optional): A list of aggregation pipeline stages to
            append to an initial ``$changeStream`` stage. Not all
            pipeline stages are valid after a ``$changeStream`` stage, see the
            MongoDB documentation on change streams for the supported stages.
          - `full_document` (optional): The fullDocument option to pass
            to the ``$changeStream`` stage. Allowed values: 'updateLookup'.
            When set to 'updateLookup', the change notification for partial
            updates will include both a delta describing the changes to the
            document, as well as a copy of the entire document that was
            changed from some time after the change occurred.
          - `resume_after` (optional): A resume token. If provided, the
            change stream will start returning changes that occur directly
            after the operation specified in the resume token. A resume token
            is the _id value of a change document.
          - `max_await_time_ms` (optional): The maximum time in milliseconds
            for the server to wait for changes before responding to a getMore
            operation.
          - `batch_size` (optional): The maximum number of documents to return
            per batch.
          - `collation` (optional): The :class:`~pymongo.collation.Collation`
            to use for the aggregation.
          - `start_at_operation_time` (optional): If provided, the resulting
            change stream will only return changes that occurred at or after
            the specified :class:`~bson.timestamp.Timestamp`. Requires
            MongoDB >= 4.0.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `start_after` (optional): The same as `resume_after` except that
            `start_after` can resume notifications after an invalidate event.
            This option and `resume_after` are mutually exclusive.
          - `comment` (optional): A user-provided comment to attach to this
            command.
          - `full_document_before_change`: Allowed values: `whenAvailable` and `required`. Change
             events may now result in a `fullDocumentBeforeChange` response field.
          - `show_expanded_events` (optional): Include expanded events such as DDL events like
            `dropIndexes`.

        :Returns:
          A :class:`~MotorChangeStream`.

        .. versionchanged:: 3.2
           Added ``show_expanded_events`` parameter.

        .. versionchanged:: 3.1
           Added ``full_document_before_change`` parameter.

        .. versionchanged:: 3.0
           Added ``comment`` parameter.

        .. versionchanged:: 2.1
           Added the ``start_after`` parameter.

        .. versionadded:: 2.0

        .. mongodoc:: changeStreams
        ru   rw   s                 r"   r   zAgnosticDatabase.watch  r   r$   c                 (   K   |f|d<   |d<   |d<   |d<   |d<   |d<    fd}	 j                         }
 j                  j                  |
|	       d{   }t        t         j                   j
                        } ||       S 7 2w)	a.
  Issue a MongoDB command and parse the response as a cursor.

        If the response from the server does not include a cursor field, an error will be thrown.

        Otherwise, behaves identically to issuing a normal MongoDB command.

        :Parameters:
          - `command`: document representing the command to be issued,
            or the name of the command (for simple commands only).

            .. note:: the order of keys in the `command` document is
               significant (the "verb" must come first), so commands
               which require multiple keys (e.g. `findandmodify`)
               should use an instance of :class:`~bson.son.SON` or
               a string and kwargs instead of a Python `dict`.

          - `value` (optional): value to use for the command verb when
            `command` is passed as a string
          - `read_preference` (optional): The read preference for this
            operation. See :mod:`~pymongo.read_preferences` for options.
            If the provided `session` is in a transaction, defaults to the
            read preference configured for the transaction.
            Otherwise, defaults to
            :attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`.
          - `codec_options`: A :class:`~bson.codec_options.CodecOptions`
            instance.
          - `session` (optional): A
            :class:`MotorClientSession`.
          - `comment` (optional): A user-provided comment to attach to future getMores for this
            command.
          - `max_await_time_ms` (optional): The number of ms to wait for more data on future
            getMores for this command.
          - `**kwargs` (optional): additional keyword arguments will
            be added to the command document before it is sent

        .. note:: :meth:`command` does **not** obey this Database's
           :attr:`read_preference` or :attr:`codec_options`. You must use the
           ``read_preference`` and ``codec_options`` parameters instead.

        .. note:: :meth:`command` does **not** apply any custom TypeDecoders
           when decoding the command response.

        .. note:: If this client has been configured to use MongoDB Stable
           API (see :ref:`versioned-api-ref`), then :meth:`command` will
           automatically add API versioning options to the given command.
           Explicitly adding API versioning options in the command and
           declaring an API version on the client is not supported.

        .. seealso:: The MongoDB documentation on `commands <https://dochub.mongodb.org/core/commands>`_.
        valuerH   rG   r   r   r{   c                  `     j                   j                  t               i t              S r9   )r1   cursor_commandr   r   )rf   rg   r5   s   r"   innerz.AgnosticDatabase.cursor_command.<locals>.inner+  s1    /4==//$T*.CF.K r$   N)rr   rY   run_on_executorr   r   rB   )r5   commandr  rH   rG   r   r   r{   rg   r  loopcursorr   rf   s   `       `    @r"   r  zAgnosticDatabase.cursor_command  s     z zw$3 !"/#y#y&7"#	
 !66tUCC2!4??DOO
 FD)) Ds   ABB3Bc                     | j                   S )z*This MotorDatabase's :class:`MotorClient`.r   r@   s    r"   r   zAgnosticDatabase.client9  r   r$   c                 ~    |j                  d      r(t        | j                  j                   d|d| d      | |   S )Nr   r   r   z$ collection, use database['{name}'].r   r   s     r"   r   zAgnosticDatabase.__getattr__>  sO    ??3 >>**++=dXEUVZU[67 
 Dzr$   c                 ^    t        t        | j                  | j                        } || |      S r9   )r   AgnosticCollectionrY   rB   r5   rc   collection_classs      r"   r   zAgnosticDatabase.__getitem__G  s+    6
  d++r$   c                     | j                   j                  }| j                  j                  j                  }|dk(  rt        | d      t        d| d| d      )N	open_synczA.open_sync() is unnecessary Motor 0.2, see changelog for details.z@MotorDatabase object is not callable. If you meant to call the 'z' method on a z4 object it is failing because no such method exists.)r1   rc   r   r2   r?   r`   )r5   rf   rg   database_nameclient_class_names        r"   __call__zAgnosticDatabase.__call__N  sx    ** LL22;;K'$% &- - 
 &~6G5H I55
 	
r$   c                    |j                   t        u r:t        t        | j                  | j
                        } || |j                  |      S |j                   t        u r(| j                  | j                  |j                  |      S |j                   t        u r.t        t        | j                  | j
                        } |||       S |S r   )r2   r   r   r  rY   rB   rc   r   r   r   r   )r5   r   klassr   s       r"   r   zAgnosticDatabase.wrap]  s    ==J&/"DOOT__E sxx377]]h&>>$,,C>HH]]m+#>%t$  (T22Jr$   c                 6    | j                   j                         S r9   r   r@   s    r"   rr   zAgnosticDatabase.get_io_loopo  r   r$   r   )r   NNNNN))r?   rB   rC   r   r   rd   r   r   __bool__r   r   cmd_docr  r   r   create_collectionr   dereferencer   drop_collectionget_collectionlist_collection_names_doclist_collection_namesr   list_collectionsr   rc   validate_collectionwith_optionsr   r;   r   r   r  r   r   r   r   r  rr   r   r   s   @r"   r   r   '  sM   *!HHz112G$++J7+K"n++,=>O#%**:6N%**N*NO {''6D#+,,->?!#((2L ;7#>
D  $$(!c
P Q*f  ,
$*r$   r   c                   <    e Zd ZdZeZ e       Z e       Z e	e
j                        Z e       Z e	e
j                        Z e	e
j"                        Z e	       Z e	       Z e	e
j*                        Z e	e
j.                        Z e       Z e	e
j4                        Z e	       Z e	       Z e	       Z e	       Z ee
j@                        Z! e	e
jD                        Z# e	e
jH                        Z% e	e
jL                        Z' e(       Z) ee
jT                        Z+ e,e
jZ                        Z. e	e
j^                        Z0 e(       Z1 e       Z2 e	       Z3 e	e
jh                        Z5 e	e
jl                        Z7 e	e
jp                        Z9 e	       Z: e       jw                  e      Z< ed      Z= ed      Z> ed      Z? ed      Z@	 	 	 	 	 d fd	ZAd	 ZBd
 ZCd ZDd ZEd ZFd ZGd ZH	 	 	 	 	 	 	 	 	 	 	 	 ddZIddZJd ZKd Z;d ZL xZMS )r  r   rO   r   r   aggregate_raw_batcheslist_indexeslist_search_indexesc                     t        t        | j                  | j                        }t	        ||      st        d|z        ||nt        |j                  |||||      }	t        
| %  |	       || _
        y )Nz?First argument to MotorCollection must be MotorDatabase, not %r)rG   rH   rJ   rI   )r   r   rY   rB   r'   r`   r   r1   re   r;   database)r5   r)  rc   rG   rH   rJ   rI   r   r   r1   r2   s             r"   r;   zAgnosticCollection.__init__  s     //?RVRaRab(H-QT\\  $ !!+ /+) 	 	" r$   c           
          |j                  d      r<| j                   d| }t        | j                  j                   d|d| d| d      | |   S )Nr   .r   r   z collection, use database['r   )r   rc   r   r2   r?   )r5   rc   	full_names      r"   r   zAgnosticCollection.__getattr__  si    ??399+Qtf-I >>**++=dXEUV_U`-i[= 
 Dzr$   c                     t        t        | j                  | j                        } || j                  | j
                  dz   |z   | j                  |         S )Nr+  r   )r   r  rY   rB   r)  rc   r1   r  s      r"   r   zAgnosticCollection.__getitem__  sL    6
  MM499s?T1T]]4=P
 	
r$   c                 F    t        d| j                  j                  z        )NzMotorCollection object is not callable. If you meant to call the '%s' method on a MotorCollection object it is failing because no such method exists.)r`   r1   rc   r5   rf   rg   s      r"   r  zAgnosticCollection.__call__  s'    57;}}7I7IJ
 	
r$   c                      | j                   j                  t        |      i t        |      }t	        t
        | j                  | j                        } |||       S )a  Create a :class:`MotorCursor`. Same parameters as for
        PyMongo's :meth:`~pymongo.collection.Collection.find`.

        Note that ``find`` does not require an ``await`` expression, because
        ``find`` merely creates a
        :class:`MotorCursor` without performing any operations on the server.
        ``MotorCursor`` methods such as :meth:`~MotorCursor.to_list`
        perform actual operations.
        )r1   findr   r   r   AgnosticCursorrY   rB   r5   rf   rg   r
  r   s        r"   r1  zAgnosticCollection.find  sR     $##%8%>`BWX^B_`2>4??TXTcTcdFD))r$   c                      | j                   j                  t        |      i t        |      }t	        t
        | j                  | j                        } |||       S )a  Query the database and retrieve batches of raw BSON.

        Similar to the :meth:`find` method but returns each batch as bytes.

        This example demonstrates how to work with raw batches, but in practice
        raw batches should be passed to an external library that can decode
        BSON into another data type, rather than used with PyMongo's
        :mod:`bson` module.

        .. code-block:: python3

          async def get_raw():
              cursor = db.test.find_raw_batches()
              async for batch in cursor:
                  print(bson.decode_all(batch))

        Note that ``find_raw_batches`` does not support sessions.

        .. versionadded:: 2.0
        )r1   find_raw_batchesr   r   r   AgnosticRawBatchCursorrY   rB   r3  s        r"   r5  z#AgnosticCollection.find_raw_batches  sY    * 0// &
*?*G
 3"DOOT__
 FD))r$   c                     t        t        | j                  | j                        } || | j                  |gt        |      i t        |      S )a  Execute an aggregation pipeline on this collection.

        The aggregation can be run on a secondary if the client is connected
        to a replica set and its ``read_preference`` is not :attr:`PRIMARY`.

        :Parameters:
          - `pipeline`: a single command or list of aggregation commands
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`, created with
            :meth:`~MotorClient.start_session`.
          - `**kwargs`: send arbitrary parameters to the aggregate command

        All optional `aggregate command`_ parameters should be passed as
        keyword arguments to this method. Valid options include, but are not
        limited to:

          - `allowDiskUse` (bool): Enables writing to temporary files. When set
            to True, aggregation stages can write data to the _tmp subdirectory
            of the --dbpath directory. The default is False.
          - `maxTimeMS` (int): The maximum amount of time to allow the operation
            to run in milliseconds.
          - `batchSize` (int): The maximum number of documents to return per
            batch. Ignored if the connected mongod or mongos does not support
            returning aggregate results using a cursor.
          - `collation` (optional): An instance of
            :class:`~pymongo.collation.Collation`.
          - `let` (dict): A dict of parameter names and values. Values must be
            constant or closed expressions that do not reference document
            fields. Parameters can then be accessed as variables in an
            aggregate expression context (e.g. ``"$$var"``). This option is
            only supported on MongoDB >= 5.0.

        Returns a :class:`MotorCommandCursor` that can be iterated like a
        cursor from :meth:`find`::

          async def f():
              pipeline = [{'$project': {'name': {'$toUpper': '$name'}}}]
              async for doc in collection.aggregate(pipeline):
                  print(doc)

        Note that this method returns a :class:`MotorCommandCursor` which
        lazily runs the aggregate command when first iterated. In order to run
        an aggregation with ``$out`` or ``$merge`` the application needs to
        iterate the cursor, for example::

           cursor = motor_coll.aggregate([{'$out': 'out'}])
           # Iterate the cursor to run the $out (or $merge) operation.
           await cursor.to_list(length=None)
           # Or more succinctly:
           await motor_coll.aggregate([{'$out': 'out'}]).to_list(length=None)
           # Or:
           async for _ in motor_coll.aggregate([{'$out': 'out'}]):
               pass

        :class:`MotorCommandCursor` does not allow the ``explain`` option. To
        explain MongoDB's query plan for the aggregation, use
        :meth:`MotorDatabase.command`::

          async def f():
              plan = await db.command(
                  'aggregate', 'COLLECTION-NAME',
                  pipeline=[{'$project': {'x': 1}}],
                  explain=True)

              print(plan)

        .. versionchanged:: 2.1
           This collection's read concern is now applied to pipelines
           containing the `$out` stage when connected to MongoDB >= 4.2.

        .. versionchanged:: 1.0
           :meth:`aggregate` now **always** returns a cursor.

        .. versionchanged:: 0.5
           :meth:`aggregate` now returns a cursor by default,
           and the cursor is returned immediately without an ``await``.
           See :ref:`aggregation changes in Motor 0.5 <aggregate_changes_0_5>`.

        .. versionchanged:: 0.2
           Added cursor support.

        .. _aggregate command:
            https://mongodb.com/docs/manual/applications/aggregation

        r   r   s        r"   r   zAgnosticCollection.aggregate  sZ    l 3'$//

 !!
 !&	

 $F+
 	
r$   c                     t        t        | j                  | j                        } || | j                  |fi t        |      S )a  Perform an aggregation and retrieve batches of raw BSON.

        Similar to the :meth:`aggregate` method but returns each batch as bytes.

        This example demonstrates how to work with raw batches, but in practice
        raw batches should be passed to an external library that can decode
        BSON into another data type, rather than used with PyMongo's
        :mod:`bson` module.

        .. code-block:: python3

          async def get_raw():
              cursor = db.test.aggregate_raw_batches()
              async for batch in cursor:
                  print(bson.decode_all(batch))

        Note that ``aggregate_raw_batches`` does not support sessions.

        .. versionadded:: 2.0
        )r   r   rY   rB   _async_aggregate_raw_batchesr   )r5   rx   rg   r   s       r"   r%  z(AgnosticCollection.aggregate_raw_batchesi  sG    * 3'$//

 $33X
AVW]A^
 	
r$   c                 t    t        t        | j                  | j                        } || |||||||||	|
||      S )a  Watch changes on this collection.

        Performs an aggregation with an implicit initial ``$changeStream``
        stage and returns a :class:`~MotorChangeStream` cursor which
        iterates over changes on this collection.

        Introduced in MongoDB 3.6.

        A change stream continues waiting indefinitely for matching change
        events. Code like the following allows a program to cancel the change
        stream and exit.

        .. code-block:: python3

          change_stream = None


          async def watch_collection():
              global change_stream

              # Using the change stream in an "async with" block
              # ensures it is canceled promptly if your code breaks
              # from the loop or throws an exception.
              async with db.collection.watch() as change_stream:
                  async for change in change_stream:
                      print(change)


          # Tornado
          from tornado.ioloop import IOLoop


          def main():
              loop = IOLoop.current()
              # Start watching collection for changes.
              try:
                  loop.run_sync(watch_collection)
              except KeyboardInterrupt:
                  if change_stream:
                      loop.run_sync(change_stream.close)


          # asyncio
          try:
              asyncio.run(watch_collection())
          except KeyboardInterrupt:
              pass

        The :class:`~MotorChangeStream` async iterable blocks
        until the next change document is returned or an error is raised. If
        the :meth:`~MotorChangeStream.next` method encounters
        a network error when retrieving a batch from the server, it will
        automatically attempt to recreate the cursor such that no change
        events are missed. Any error encountered during the resume attempt
        indicates there may be an outage and will be raised.

        .. code-block:: python3

            try:
                pipeline = [{"$match": {"operationType": "insert"}}]
                async with db.collection.watch(pipeline) as stream:
                    async for change in stream:
                        print(change)
            except pymongo.errors.PyMongoError:
                # The ChangeStream encountered an unrecoverable error or the
                # resume attempt failed to recreate the cursor.
                logging.error("...")

        For a precise description of the resume process see the
        `change streams specification`_.

        :Parameters:
          - `pipeline` (optional): A list of aggregation pipeline stages to
            append to an initial ``$changeStream`` stage. Not all
            pipeline stages are valid after a ``$changeStream`` stage, see the
            MongoDB documentation on change streams for the supported stages.
          - `full_document` (optional): The fullDocument option to pass
            to the ``$changeStream`` stage. Allowed values: 'updateLookup'.
            When set to 'updateLookup', the change notification for partial
            updates will include both a delta describing the changes to the
            document, as well as a copy of the entire document that was
            changed from some time after the change occurred.
          - `resume_after` (optional): A resume token. If provided, the
            change stream will start returning changes that occur directly
            after the operation specified in the resume token. A resume token
            is the _id value of a change document.
          - `max_await_time_ms` (optional): The maximum time in milliseconds
            for the server to wait for changes before responding to a getMore
            operation.
          - `batch_size` (optional): The maximum number of documents to return
            per batch.
          - `collation` (optional): The :class:`~pymongo.collation.Collation`
            to use for the aggregation.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `start_after` (optional): The same as `resume_after` except that
            `start_after` can resume notifications after an invalidate event.
            This option and `resume_after` are mutually exclusive.
          - `comment` (optional): A user-provided comment to attach to this
            command.
          - `full_document_before_change`: Allowed values: `whenAvailable` and `required`.
            Change events may now result in a `fullDocumentBeforeChange` response field.
          - `show_expanded_events` (optional): Include expanded events such as DDL events
            like `dropIndexes`.

        :Returns:
          A :class:`~MotorChangeStream`.

        See the :ref:`tornado_change_stream_example`.

        .. versionchanged:: 3.2
           Added ``show_expanded_events`` parameter.

        .. versionchanged:: 3.1
           Added ``full_document_before_change`` parameter.

        .. versionchanged:: 3.0
           Added ``comment`` parameter.

        .. versionchanged:: 2.1
           Added the ``start_after`` parameter.

        .. versionadded:: 1.2

        .. mongodoc:: changeStreams

        .. _change streams specification:
            https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.rst
        ru   rw   s                 r"   r   zAgnosticCollection.watch  sT    ` 3 $//4??

 #' 
 	
r$   c                 x    t        t        | j                  | j                        } || | j                  fd|i|S )a^  Get a cursor over the index documents for this collection. ::

          async def print_indexes():
              async for index in db.test.list_indexes():
                  print(index)

        If the only index is the default index on ``_id``, this might print::

            SON([('v', 1), ('key', SON([('_id', 1)])), ('name', '_id_')])
        r   )r   r   rY   rB   _async_list_indexes)r5   r   rg   r   s       r"   r&  zAgnosticCollection.list_indexes,  s<     3'$//

 D$":":VGVvVVr$   c                 z    t        t        | j                  | j                        } || | j                  g|i |S )z?Return a cursor over search indexes for the current collection.)r   r   rY   rB   _async_list_search_indexes)r5   rf   rg   r   s       r"   r'  z&AgnosticCollection.list_search_indexes>  s:    2'$//

 D$"A"ASDSFSSr$   c                    |j                   t        u r(| j                  | j                  |j                  |      S |j                   t        u rt        ||       S |j                   t        u r.t        t        | j                  | j                        } |||       S |j                   t        u r.t        t        | j                  | j                        } |||       S |S r   )r2   r   r)  rc   r	   r2  r   r   r   rY   rB   r   rv   )r5   r   r   change_stream_classs       r"   r   zAgnosticCollection.wrapG  s    ==J&>>$--S>II]]f$!#t,,]]m+#>%t$  (T22]]l*"=$doot# 'sD11Jr$   c                 6    | j                   j                         S r9   )r)  rr   r@   s    r"   rr   zAgnosticCollection.get_io_loop\  s    }}((**r$   )NNNNNr   r9   )Nr?   rB   rC   r   r   rd   r   r   r  r   r   bulk_write_doc
bulk_writer   count_documentscreate_index_doccreate_indexcreate_indexes_doccreate_indexescreate_search_indexcreate_search_indexesdelete_many_docdelete_manydelete_one_doc
delete_onedistinctdrop_docdrop
drop_indexdrop_search_indexdrop_indexesestimated_document_countfind_one_docfind_onefind_one_and_delete_docfind_one_and_deletefind_one_and_replace_docfind_one_and_replacefind_one_and_update_docfind_one_and_updater   r,  index_information_docindex_informationr   insert_many_docinsert_manyinsert_one_doc
insert_onerc   r   renamereplace_one_docreplace_oneupdate_many_docupdate_manyupdate_one_doc
update_oneupdate_search_indexr   r#  r   r9  r<  r>  r;   r   r   r  r1  r5  r   r%  r   r&  r'  rr   r   r   s   @r"   r  r  s  sF   ,#HH*";";<JkOJ$?$?@L!j&C&CDN&.(N:#=#=>K*";";<J{HJ//0DJ$>L+~Z445H&:+M+MN'J,O,OP&:+M+MN "I!j&F&FG!;!;<K*";";<JDkG^F:#=#=>K:#=#=>K*";";<J&.!#((4L ;7#,7N#O #n=!*5J!K !B	

**<a
F
@  $$(!c
JW$T*+r$   r  c                       e Zd ZdZ ed      Z e       Z e       Z e       Z	 e       Z
 e       Z fdZd Zd ZeZd Zd Zd	 Zeed
               Zd Zd Zd Zed        Zd Zd Zd Zd Zd Zd Zd Z d Z! xZ"S )AgnosticBaseCursorz7Base class for AgnosticCursor and AgnosticCommandCursorr   r   c                 P    t         |   |       || _        d| _        d| _        y)a  Don't construct a cursor yourself, but acquire one from methods like
        :meth:`MotorCollection.find` or :meth:`MotorCollection.aggregate`.

        .. note::
          There is no need to manually close cursors; they are closed
          by the server after being fully iterated
          with :meth:`to_list`, :meth:`each`, or `async for`, or
          automatically closed by the client when the :class:`MotorCursor` is
          cleaned up by the garbage collector.
        r:   FN)re   r;   
collectionstartedclosed)r5   r
  ro  r2   s      r"   r;   zAgnosticBaseCursor.__init__j  s*     	&)$r$   c                     | S r9   rD   r@   s    r"   	__aiter__zAgnosticBaseCursor.__aiter__|      r$   c                    K   | j                   r=| j                         s| j                          d{   rt        | j                        S t
        7 w)z;Advance the cursor.

        .. versionadded:: 2.2
        N)alive_buffer_size	_get_morenextr1   StopAsyncIterationr@   s    r"   ry  zAgnosticBaseCursor.next  sD     
 ::4,,.8H2H2H&&   3Is   0AA Ac                    K   | S wr9   rD   r@   s    r"   r   zAgnosticBaseCursor.__aenter__  r   r   c                 Z   K   | j                   r| j                          d {    y y 7 wr9   r1   r   r   s       r"   r   zAgnosticBaseCursor.__aexit__  $     ==**,     +)+c                     | j                   st        j                  j                  d      d| _        | j                         S )z+Initial query or getMore. Returns a Future.zICan't call get_more() on a MotorCursor that has been exhausted or killed.T)rv  r(   r)   InvalidOperationrp  _refreshr@   s    r"   rx  zAgnosticBaseCursor._get_more  s8    zz..11[  }}r$   c                    t        j                  dt        d       | j                         s| j                  r| j                         S | j                         r<| j                  j                  | j                               }|j                  d       |S | j                  j                  | j                               }|j                  d       |S )a  **DEPRECATED** - A Future used with `gen.coroutine`_ to
        asynchronously retrieve the next document in the result set,
        fetching a batch of documents from the server if necessary.
        Resolves to ``False`` if there are no more documents, otherwise
        :meth:`next_object` is guaranteed to return a document:

        .. doctest:: fetch_next
           :hide:

           >>> _ = MongoClient().test.test_collection.delete_many({})
           >>> collection = MotorClient().test.test_collection

        .. attention:: The :attr:`fetch_next` property is deprecated and will
           be removed in Motor 3.0. Use `async for` to iterate elegantly and
           efficiently over :class:`MotorCursor` objects instead.:

           .. doctest:: fetch_next

              >>> async def f():
              ...     await collection.drop()
              ...     await collection.insert_many([{"_id": i} for i in range(5)])
              ...     async for doc in collection.find():
              ...         sys.stdout.write(str(doc["_id"]) + ", ")
              ...     print("done")
              ...
              >>> IOLoop.current().run_sync(f)
              0, 1, 2, 3, 4, done

        While it appears that fetch_next retrieves each document from
        the server individually, the cursor actually fetches documents
        efficiently in `large batches`_. Example usage:

        .. doctest:: fetch_next

           >>> async def f():
           ...     await collection.drop()
           ...     await collection.insert_many([{"_id": i} for i in range(5)])
           ...     cursor = collection.find().sort([("_id", 1)])
           ...     while await cursor.fetch_next:
           ...         doc = cursor.next_object()
           ...         sys.stdout.write(str(doc["_id"]) + ", ")
           ...     print("done")
           ...
           >>> IOLoop.current().run_sync(f)
           0, 1, 2, 3, 4, done

        .. versionchanged:: 2.2
           Deprecated.

        .. _`large batches`: https://www.mongodb.com/docs/manual/tutorial/iterate-a-cursor/#cursor-batches
        .. _`gen.coroutine`: http://tornadoweb.org/en/stable/gen.html
        zThe fetch_next property is deprecated and may be removed in a future major release. Use `async for` to iterate over Cursor objects instead.   
stacklevelTF)
warningswarnDeprecationWarningrw  rv  rx  rY   
get_futurerr   
set_result)r5   futures     r"   
fetch_nextzAgnosticBaseCursor.fetch_next  s    n 	+ 	
   "tzz>>## __//0@0@0BCFd#M __//0@0@0BCFe$Mr$   c                     t        j                  dt        d       | j                         syt	        | j
                        S )aw  **DEPRECATED** - Get a document from the most recently fetched
        batch, or ``None``. See :attr:`fetch_next`.

        The :meth:`next_object` method is deprecated and may be removed
        in a future major release. Use `async for` to elegantly iterate over
        :class:`MotorCursor` objects instead.

        .. versionchanged:: 2.2
           Deprecated.
        zThe next_object method is deprecated and may be removed in a future major release.  Use `async for` to iterate over Cursor objects instead.r  r  N)r  r  r  rw  ry  r1   r@   s    r"   next_objectzAgnosticBaseCursor.next_object  s=     	+ 	
   "DMM""r$   c                 J    t        |      st        | j                  |d       y)a  Iterates over all the documents for this cursor.

        :meth:`each` returns immediately, and `callback` is executed asynchronously
        for each document. `callback` is passed ``(None, None)`` when iteration
        is complete.

        Cancel iteration early by returning ``False`` from the callback. (Only
        ``False`` cancels iteration: returning ``None`` or 0 does not.)

        .. testsetup:: each

           from tornado.ioloop import IOLoop

           MongoClient().test.test_collection.delete_many({})
           MongoClient().test.test_collection.insert_many([{"_id": i} for i in range(5)])

           collection = MotorClient().test.test_collection

        .. doctest:: each

           >>> def each(result, error):
           ...     if error:
           ...         raise error
           ...     elif result:
           ...         sys.stdout.write(str(result["_id"]) + ", ")
           ...     else:
           ...         # Iteration complete
           ...         IOLoop.current().stop()
           ...         print("done")
           ...
           >>> cursor = collection.find().sort([("_id", 1)])
           >>> cursor.each(callback=each)
           >>> IOLoop.current().start()
           0, 1, 2, 3, 4, done

        .. note:: Unlike other Motor methods, ``each`` requires a callback and
           does not return a Future, so it cannot be used in a coroutine.
           ``async for`` and :meth:`to_list` are much easier to use.

        :Parameters:
         - `callback`: function taking (document, error)
        N)callabler   _each_got_more)r5   callbacks     r"   eachzAgnosticBaseCursor.each  s#    V !%%Hd+r$   c                 b   |r	 |j                          | j                         dkD  rBt        | j                        } ||d       du ry | j
                  ry | j                         dkD  rB| j                  r]| j                  s| j                  sE| j                  j                  | j                         | j                         | j                  |       y | j                  j                  | j                         t        j                   |d d              y # t        $ r} |d |       Y d }~y d }~ww xY w)Nr   F)resultr   rw  ry  r1   rq  rv  	cursor_idrp  rY   
add_futurerr   rx  r  	call_soon	functoolspartial)r5   r  r  errorrP   s        r"   r  z!AgnosticBaseCursor._each_got_more.  s    
 !A%t}}%C T"e+ {{ !A% ::4>>OO&&  "DNN$4d6I6I8
 OO%%d&6&6&8):K:KHVZ\`:ab-  u%s   D 	D.	D))D.c                    |.t        |t              st        d|z        |dk  rt        d      | j	                         t
        d   z  rt        j                  j                  d      | j                  j                  | j                               }| j                  s|j                  g        |S g }| j                  j                  | j                         | j                         | j                   |||       |S )a  Get a list of documents.

        .. testsetup:: to_list

          MongoClient().test.test_collection.delete_many({})
          MongoClient().test.test_collection.insert_many([{"_id": i} for i in range(4)])

          from tornado import ioloop

        .. doctest:: to_list

          >>> from motor.motor_tornado import MotorClient
          >>> collection = MotorClient().test.test_collection
          >>>
          >>> async def f():
          ...     cursor = collection.find().sort([("_id", 1)])
          ...     docs = await cursor.to_list(length=2)
          ...     while docs:
          ...         print(docs)
          ...         docs = await cursor.to_list(length=2)
          ...     print("done")
          ...
          >>> ioloop.IOLoop.current().run_sync(f)
          [{'_id': 0}, {'_id': 1}]
          [{'_id': 2}, {'_id': 3}]
          done

        :Parameters:
         - `length`: maximum number of documents to return for this call, or
           None

         Returns a Future.

        .. versionchanged:: 2.0
           No longer accepts a callback argument.

        .. versionchanged:: 0.2
           `callback` must be passed as a keyword argument, like
           ``to_list(10, callback=callback)``, and the
           `length` parameter is no longer optional.
        zlength must be an int, not %rr   zlength must be non-negativetailable_cursorz%Can't call to_list on tailable cursor)r'   intr`   
ValueError_query_flagsr   r(   r)   r  rY   r  rr   rv  r  r  rx  _to_list)r5   lengthr  the_lists       r"   to_listzAgnosticBaseCursor.to_listJ  s    V fc* ?& HII! !>??0A!BB..112YZZ++D,<,<,>?zzb!  HOO&&  "  r$   c                 h   	 |j                         }|j                         ry ||}nt        |t        |      z
  |      }t	        |      D ]/  }|j                  | j                         j                                1 |d uxr t        |      |k\  }|s| j                  s|j                  |       y | j                  j                  | j                         | j                         | j                  |||       y # t        $ r0}	|j                         s|j!                  |	       Y d }	~	y Y d }	~	y d }	~	ww xY wr9   )r  doneminlenrangeappend_datapopleftrv  r  rY   r  rr   rx  r  r   set_exception)
r5   r  r  r  get_more_resultr  nr   reached_lengthr,   s
             r"   r  zAgnosticBaseCursor._to_list  s   	*$++-F{{}~X.71X 8

 4 4 678 $4/KCMV4KNTZZ!!(+**$$&(8$--QY[a  	*;;=$$S)) !	*s$    C8 BC8 1AC8 8	D1!D,,D1c                 6    | j                   j                         S r9   )ro  rr   r@   s    r"   rr   zAgnosticBaseCursor.get_io_loop  s    **,,r$   c                 h   K   | j                   s d| _         | j                          d{    yy7 w)zkExplicitly kill this cursor on the server.

        Call like::

            await cursor.close()

        TN)rq  _async_closer@   s    r"   r   zAgnosticBaseCursor.close  s0      {{DK##%%% %s   '202c                 <    | j                   j                  |       | S r9   )r1   r|   r5   r|   s     r"   r|   zAgnosticBaseCursor.batch_size  s      ,r$   c                 4    t        | j                               S r9   )r  r  r@   s    r"   rw  zAgnosticBaseCursor._buffer_size  s    4::<  r$   c                     t         r9   NotImplementedErrorr@   s    r"   r  zAgnosticBaseCursor._query_flags      !!r$   c                     t         r9   r  r@   s    r"   r  zAgnosticBaseCursor._data  r  r$   c                     t         r9   r  r@   s    r"   _killedzAgnosticBaseCursor._killed  r  r$   )#r?   rB   rC   r   r   r  r  r   r   r  rv  r   r;   rs  ry  	__anext__r   r   rx  r   r   r  r  r  r  r  r  rr   r   r|   rw  r  r  r  r   r   s   @r"   rm  rm  `  s    Aw/L{H G "IE G$! I H  HT#..,`c8 B BH*8-
&!"""r$   rm  c                   x   e Zd ZdZeZ e       Z e       Z	 e
       Z e
       Z e       Z e       Z e       Z e       Z e       Z eej&                        Z e       Z eej,                        Z e       Z e       Z e       Z e       Z e       Z e       Z e
       Zd Zd Z d Z!d Z"d Z#d Z$d	 Z%y
)r2  MotorCursorrO   c                 H    | j                   j                          d| _        | S )z,Rewind this cursor to its unevaluated state.F)r1   rewindrp  r@   s    r"   r  zAgnosticCursor.rewind  s    r$   c                 j    | j                  | j                  j                         | j                        S )zGet a clone of this cursor.)r2   r1   clonero  r@   s    r"   r  zAgnosticCursor.clone  s$    ~~dmm113T__EEr$   c                 j    | j                  | j                  j                         | j                        S r9   )r2   r1   __copy__ro  r@   s    r"   r  zAgnosticCursor.__copy__  s$    ~~dmm446HHr$   c                 l    | j                  | j                  j                  |      | j                        S r9   )r2   r1   __deepcopy__ro  )r5   memos     r"   r  zAgnosticCursor.__deepcopy__  s&    ~~dmm88>PPr$   c                 .    | j                   j                  S r9   )r1   _Cursor__query_flagsr@   s    r"   r  zAgnosticCursor._query_flags      }}111r$   c                 .    | j                   j                  S r9   )r1   _Cursor__datar@   s    r"   r  zAgnosticCursor._data  s    }}***r$   c                 .    | j                   j                  S r9   )r1   _Cursor__killedr@   s    r"   r  zAgnosticCursor._killed  s    }},,,r$   N)&r?   rB   rC   r   r	   rd   r   r   r   r}   r   rO  explain
add_optionremove_optionlimitskipmax_scanr   cursor_sort_docsorthint	where_docwherer{   max_time_msr  maxr   allow_disk_use_Cursor__dier  r  r  r  r  r  r  rD   r$   r"   r2  r2    s    ( G)+I{HkG*,J-/M%'E$&D(*H$)C)CDD$&D%**>*>?E13+-K
#
%C
#
%C')G.0N;LFIQ2+-r$   r2  c                       e Zd ZdZeZy)r6  MotorRawBatchCursorN)r?   rB   rC   r   r
   rd   rD   r$   r"   r6  r6    s    0'r$   r6  c                   :    e Zd ZdZeZ e       Zd Zd Z	d Z
d Zy)r   MotorCommandCursorc                     K    fd} j                         } j                  j                  ||       d{   S 7 w)a^  Advance the cursor without blocking indefinitely.

        This method returns the next document without waiting
        indefinitely for data.

        If no document is cached locally then this method runs a single
        getMore command. If the getMore yields any documents, the next
        document is returned, otherwise, if the getMore returns no documents
        (because there is no additional data) then ``None`` is returned.

        :Returns:
          The next document or ``None`` when no document is available
          after running a single getMore or when the cursor is closed.
        c                  8     j                   j                         S r9   )r1   try_nextr@   s   r"   r  z-AgnosticCommandCursor.try_next.<locals>.inner  s    ==))++r$   N)rr   rY   r  )r5   r  r	  s   `  r"   r  zAgnosticCommandCursor.try_next	  s9      	, !__44T5AAAAs   5?=?c                      y)Nr   rD   r@   s    r"   r  z"AgnosticCommandCursor._query_flags  s    r$   c                 .    | j                   j                  S r9   )r1   _CommandCursor__datar@   s    r"   r  zAgnosticCommandCursor._data"  r  r$   c                 .    | j                   j                  S r9   )r1   _CommandCursor__killedr@   s    r"   r  zAgnosticCommandCursor._killed%  s    }}333r$   N)r?   rB   rC   r   r   rd   r   _CommandCursor__dier  r  r  r  rD   r$   r"   r   r     s+    /&#+B,24r$   r   c                       e Zd ZdZeZy)AgnosticRawBatchCommandCursorMotorRawBatchCommandCursorN)r?   rB   rC   r   r   rd   rD   r$   r"   r  r  )  s    7.r$   r  c                   N    e Zd ZdZdZg ZdZdZdZdZ	dZ
dZd Zd Zd Zd Zd	 Zy)
_LatentCursorzCTake the place of a PyMongo CommandCursor until aggregate() begins.TNFc                 &    |j                   | _        y r9   )r1   _CommandCursor__collection)r5   ro  s     r"   r;   z_LatentCursor.__init__:  s    *4*=*='r$   c                      y r9   rD   r/  s      r"   _CommandCursor__end_sessionz)_LatentCursor._CommandCursor__end_session=  r   r$   c                      y r9   rD   r/  s      r"   r  z!_LatentCursor._CommandCursor__die@  r   r$   c                 ,    t        | j                        S r9   )r  r  r@   s    r"   r  z_LatentCursor.cloneC  s    T<<==r$   c                      y r9   rD   r@   s    r"   r  z_LatentCursor.rewindF  r   r$   )r?   rB   rC   r   rv  r  _CommandCursor__idr  _CommandCursor__sock_mgr_CommandCursor__session _CommandCursor__explicit_sessionr  r;   r  r  r  r  rD   r$   r"   r  r  .  sL    ME"#"'+$I>>r$   r  c                   <     e Zd ZdZ fdZd Z fdZ fdZ xZS )r   MotorLatentCommandCursorc                 b    t         |   t        |      |       || _        || _        || _        y r9   )re   r;   r  startrf   rg   )r5   ro  r  rf   rg   r2   s        r"   r;   z$AgnosticLatentCommandCursor.__init__M  s.     	z2J?
	r$   c                 $    || j                   d<   | S )N	batchSize)rg   r  s     r"   r|   z&AgnosticLatentCommandCursor.batch_size[  s    #-K r$   c                 ~   | j                   sd| _         | j                  j                  | j                               } | j                  | j
                  i | j                  }d x| _        x| _        | _        | j                  j                  | j                         || j                  |       |S t        | )         S )NT)rp  rY   r  rr   r  rf   rg   r  _on_startedre   rx  )r5   original_futurer  r2   s      r"   rx  z%AgnosticLatentCommandCursor._get_more_  s    ||DL"oo889I9I9KLOTZZ:dkk:F377DJ7T[OO&&  "FD,<,<o #"w ""r$   c                    	 |j                         }|| _        |j                         ry | j                  j                  s| j                  j                  s/|j                  t        | j                  j                               y t        | !         }| j                  j                  ||       y # t        $ r0}|j                         s|j                  |       Y d }~y Y d }~y d }~ww xY wr9   )r  r1   r  r  rv  r  r  re   rx  rY   chain_futurer   r  )r5   r  r  pymongo_cursorr,   r2   s        r"   r  z'AgnosticLatentCommandCursor._on_startedo  s    	F $]]_N*DM ##%}}119L9L**3t}}/Q/Q+RS *,,,V_E  	3"'')--c22 *	3s   B1 1	C*:!C%%C*)	r?   rB   rC   r   r;   r|   rx  r  r   r   s   @r"   r   r   J  s$    5# F Fr$   r   c                        e Zd ZdZeZdZ ed      Z e	       Z
 fdZd Zd Zed        Zd	 Zd
 Zd Zd ZeZd Zd Zd Zd Zd Z xZS )rv   zA change stream cursor.

    Should not be called directly by application developers. See
    :meth:`~MotorCollection.watch` for example usage.

    .. versionadded: 1.2
    .. mongodoc:: changeStreams
    MotorChangeStreamr   r   c                 \    t         |   d        || _        ||||||||	|
|||d| _        y )Nr:   )rx   ry   rz   r{   r|   r}   r~   r   r   r   r   r   )re   r;   _target_kwargs)r5   targetrx   ry   rz   r{   r|   r}   r~   r   r   r   r   r   r2   s                 r"   r;   zAgnosticChangeStream.__init__  sI      	$' *(!2$"'>&+F$8
r$   c                     | j                   s? | j                  j                   j                  di t        | j                        | _         y y )NrD   )r1   r  r   r   r  r@   s    r"   
_lazy_initzAgnosticChangeStream._lazy_init  s<    }}7DLL1177^:OPTP\P\:]^DM r$   c                 V    | j                          | j                  j                         S r9   )r  r1   r  r@   s    r"   	_try_nextzAgnosticChangeStream._try_next  s    }}%%''r$   c                 H    | j                   sy| j                   j                  S )zDoes this cursor have the potential to return more data?

        .. note:: Even if :attr:`alive` is ``True``, :meth:`next` can raise
            :exc:`StopAsyncIteration` and :meth:`try_next` can return ``None``.

        T)r1   rv  r@   s    r"   rv  zAgnosticChangeStream.alive  s     }}}}"""r$   c                    K   | j                   r)| j                          d{   }||S | j                   r)t               7 w)ap  Advance the cursor.

        This method blocks until the next change document is returned or an
        unrecoverable error is raised. This method is used when iterating over
        all changes in the cursor. For example::

            async def watch_collection():
                resume_token = None
                pipeline = [{'$match': {'operationType': 'insert'}}]
                try:
                    async with db.collection.watch(pipeline) as stream:
                        async for insert_change in stream:
                            print(insert_change)
                            resume_token = stream.resume_token
                except pymongo.errors.PyMongoError:
                    # The ChangeStream encountered an unrecoverable error or the
                    # resume attempt failed to recreate the cursor.
                    if resume_token is None:
                        # There is no usable resume token because there was a
                        # failure during ChangeStream initialization.
                        logging.error('...')
                    else:
                        # Use the interrupted ChangeStream's resume token to
                        # create a new ChangeStream. The new stream will
                        # continue from the last seen insert change without
                        # missing any events.
                        async with db.collection.watch(
                                pipeline, resume_after=resume_token) as stream:
                            async for insert_change in stream:
                                print(insert_change)

        Raises :exc:`StopAsyncIteration` if this change stream is closed.

        In addition to using an "async for" loop as shown in the code
        example above, you can also iterate the change stream by calling
        ``await change_stream.next()`` repeatedly.
        N)rv  r  rz  )r5   rP   s     r"   ry  zAgnosticChangeStream.next  sA     L jj'C
 jj
 !""	 (s    AAAAc                    K   | j                         }| j                  j                  || j                         d{   S 7 w)a  Advance the cursor without blocking indefinitely.

        This method returns the next change document without waiting
        indefinitely for the next change. If no changes are available,
        it returns None. For example:

        .. code-block:: python3

          while change_stream.alive:
              change = await change_stream.try_next()
              # Note that the ChangeStream's resume token may be updated
              # even when no changes are returned.
              print("Current resume token: %r" % (change_stream.resume_token,))
              if change is not None:
                  print("Change document: %r" % (change,))
                  continue
              # We end up here when there are no recent changes.
              # Sleep for a while before trying again to avoid flooding
              # the server with getMore requests when no changes are
              # available.
              await asyncio.sleep(10)

        If no change document is cached locally then this method runs a single
        getMore command. If the getMore yields any documents, the next
        document is returned, otherwise, if the getMore returns no documents
        (because there have been no changes) then ``None`` is returned.

        :Returns:
          The next change document or ``None`` when no document is available
          after running a single getMore or when the cursor is closed.

        .. versionadded:: 2.1
        N)rr   rY   r  r  r5   r	  s     r"   r  zAgnosticChangeStream.try_next  s8     D !__44T4>>JJJJs   :AAAc                 Z   K   | j                   r| j                          d{    yy7 w)zaClose this change stream.

        Stops any "async for" loops using this change stream.
        N)r1   _closer@   s    r"   r   zAgnosticChangeStream.close!  s&     
 ==++- r  c                     | S r9   rD   r@   s    r"   rs  zAgnosticChangeStream.__aiter__)  rt  r$   c                    K   | j                   s>| j                         }| j                  j                  || j                         d {    | S 7 wr9   )r1   rr   rY   r  r  r  s     r"   r   zAgnosticChangeStream.__aenter__.  sD     }}##%D//11$HHH Is   AAA	Ac                 Z   K   | j                   r| j                          d {    y y 7 wr9   r}  r   s       r"   r   zAgnosticChangeStream.__aexit__4  r~  r  c                 6    | j                   j                         S r9   )r  rr   r@   s    r"   rr   z AgnosticChangeStream.get_io_loop8  r   r$   c                     t        d      )Nz/Use a change stream in "async with", not "with")RuntimeErrorr@   s    r"   r   zAgnosticChangeStream.__enter__;  s    LMMr$   c                      y r9   rD   r   s       r"   r   zAgnosticChangeStream.__exit__>  r   r$   )r?   rB   rC   r   r   rd   r   r   r  r   resume_tokenr;   r  r  r   rv  ry  r  r   rs  r  r   r   rr   r   r   r   r   s   @r"   rv   rv     s     &.G,F#%L 
D_(
 
# 
#+#Z#KJ  I*Nr$   rv   c                   :    e Zd ZdZdZeZ eej                        Z
 e       Z e       Z e       Z eej                        Z e       Z e       Z e       Z e       Z e       Z e       Z	 	 d fd	Zed        Zd Zd Zd Zd	 Zd
 Zd Z	 	 ddZ xZ S )AgnosticClientEncryptionz,Explicit client-side field level encryption.MotorClientEncryptionrO   c                     |r| j                   j                  |       nd}|j                  }| j                  |||||      }t        	|   |       || _        y)a#  Explicit client-side field level encryption.

        Takes the same constructor arguments as
        :class:`pymongo.encryption.ClientEncryption`, as well as:

        :Parameters:
          - `io_loop` (optional): Special event loop
            instance to use instead of default.
        N)rY   rZ   r1   rd   re   r;   r[   )
r5   kms_providerskey_vault_namespacekey_vault_clientrG   rR   kms_tls_optionssync_clientr1   r2   s
            r"   r;   z!AgnosticClientEncryption.__init__V  s\    $ OO,,W5G&//**.]O
 	"r$   c                 p    | j                   | j                  j                         | _         | j                   S r9   rm   r@   s    r"   rR   z AgnosticClientEncryption.io_loops  ro   r$   c                     | j                   S r9   rq   r@   s    r"   rr   z$AgnosticClientEncryption.get_io_loopy  rs   r$   c                    K   | S wr9   rD   r@   s    r"   r   z#AgnosticClientEncryption.__aenter__|  r   r   c                 Z   K   | j                   r| j                          d {    y y 7 wr9   r}  r   s       r"   r   z"AgnosticClientEncryption.__aexit__  r~  r  c                 H    t        d| j                  j                   d      )NzUse z in "async with", not "with")r  r2   r?   r@   s    r"   r   z"AgnosticClientEncryption.__enter__  s"    T$.."9"9!::VWXXr$   c                      y r9   rD   r   s       r"   r   z!AgnosticClientEncryption.__exit__  r   r$   c                    K   t        t        | j                  | j                        } || j                  j                         |       S wr9   )r   r2  rY   rB   r1   get_keys)r5   r   s     r"   r2  z!AgnosticClientEncryption.get_keys  s9     2>4??TXTcTcdDMM224d;;s   AA	c           	      @  K   t        t        | j                  | j                        }| j	                         } | j                  j
                  || j                  j                  f|j                  ||||d| d{   \  }	}
 |||	j                  |	      |
fS 7 w)a	  Create a collection with encryptedFields.

        .. warning::
            This function does not update the encryptedFieldsMap in the client's
            AutoEncryptionOpts, thus the user must create a new client after calling
            this function with the encryptedFields returned.

        Normally collection creation is automatic. This method should
        only be used to specify options on
        creation. :class:`~pymongo.errors.EncryptionError` will be
        raised if the collection already exists.

        :Parameters:
          - `database`: the database in which to create a collection
          - `name`: the name of the collection to create
          - `encrypted_fields` (dict): Document that describes the encrypted fields for
            Queryable Encryption. For example::

              {
                "escCollection": "enxcol_.encryptedCollection.esc",
                "ecocCollection": "enxcol_.encryptedCollection.ecoc",
                "fields": [
                    {
                        "path": "firstName",
                        "keyId": Binary.from_uuid(UUID('00000000-0000-0000-0000-000000000000')),
                        "bsonType": "string",
                        "queries": {"queryType": "equality"}
                    },
                    {
                        "path": "ssn",
                        "keyId": Binary.from_uuid(UUID('04104104-1041-0410-4104-104104104104')),
                        "bsonType": "string"
                    }
                  ]
              }

            The "keyId" may be set to ``None`` to auto-generate the data keys.
          - `kms_provider` (optional): the KMS provider to be used
          - `master_key` (optional): Identifies a KMS-specific key used to encrypt the
            new data key. If the kmsProvider is "local" the `master_key` is
            not applicable and may be omitted.
          - `**kwargs` (optional): additional keyword arguments are the same as "create_collection".

        All optional `create collection command`_ parameters should be passed
        as keyword arguments to this method.
        See the documentation for :meth:`~pymongo.database.Database.create_collection`
        for all valid options.

        :Raises:
          - :class:`~pymongo.errors.EncryptedCollectionError`: When either data-key creation or
            creating the collection fails.

        .. versionadded:: 3.2

        .. _create collection command:
            https://mongodb.com/docs/manual/reference/command/create

        )r)  rc   encrypted_fieldskms_provider
master_keyNr   )	r   r  rY   rB   rr   r  r1   create_encrypted_collectionrc   )r5   r)  rc   r4  r5  r6  rg   r  r	  collefs              r"   r7  z4AgnosticClientEncryption.create_encrypted_collection  s     F 7
 !888MM55	
 &&-%!	
 	
 	
b  $))tDbHH	
s   A;B=B>B)NN)!r?   rB   rC   r   r   r   rd   r   r   create_data_key_doccreate_data_keyencryptencrypt_expressiondecrypt	close_docr   rewrap_many_data_key
delete_keyget_keyadd_key_alt_nameget_key_by_alt_nameremove_key_alt_namer;   r   rR   rr   r   r   r   r   r2  r7  r   r   s   @r"   r#  r#  B  s    62)"z'E'EFOnG%nGZ112E (>JnG#~&.&.  :  
Y< QIr$   r#  )Cr   r  r   r  r(   pymongo.authpymongo.commonpymongo.databasepymongo.errorspymongo.mongo_clientpymongo.change_streamr   pymongo.client_sessionr   pymongo.collectionr   pymongo.command_cursorr   r   pymongo.cursorr   r	   r
   r   pymongo.driver_infor   pymongo.encryptionr   rW   r   r   r]   metaprogrammingr   r   r   r   r   r   r   r   r   r   motor_commonr   HAS_SSLsslImportErrorr    r#   r-   r/   rF   rL   r   r   r   r  rm  r2  r6  r   r  r  r   rv   r#  rD   r$   r"   <module>rW     su   L          . 0 ) G A A % * /  &   .
 &) "N
O
? ?"'\ 'Q,+ Q,h8 8"\L \~I*- I*X
j+/ j+Zi" i"X/-' /-d(^ (
#4. #4L/$9 /
 89F"7 9Fxy< yx\I| \IY@  
CGs   
E 	EE