We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
raise StopIteration in generators is deprecated
```
...
/Users/Vic/projects/brain2/brain/utils/user_progress.py:686: DeprecationWarning: generator 'QuerySet._iter_results' raised StopIteration
  for action in actions:
/Users/Vic/projects/brain2/brain/utils/user_course_state.py:317: DeprecationWarning: generator 'QuerySet._iter_results' raised StopIteration
  PlayedTask(
/Users/Vic/projects/brain2/venv/lib/python3.6/site-packages/mongoengine/dereference.py:33: DeprecationWarning: generator 'QuerySet._iter_results' raised StopIteration
...
```
https://stackoverflow.com/questions/14183803/in-pythons-generators-what-is-the-difference-between-raise-stopiteration-and

https://github.com/MongoEngine/mongoengine/blob/5bdd35464b89dd2def1dcb0464e244322f1bc757/mongoengine/queryset/queryset.py#L95

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `mongoengine/queryset/queryset.py`
Content:
```
1 import six
2 
3 from mongoengine.errors import OperationError
4 from mongoengine.queryset.base import (BaseQuerySet, CASCADE, DENY, DO_NOTHING,
5                                        NULLIFY, PULL)
6 
7 __all__ = ('QuerySet', 'QuerySetNoCache', 'DO_NOTHING', 'NULLIFY', 'CASCADE',
8            'DENY', 'PULL')
9 
10 # The maximum number of items to display in a QuerySet.__repr__
11 REPR_OUTPUT_SIZE = 20
12 ITER_CHUNK_SIZE = 100
13 
14 
15 class QuerySet(BaseQuerySet):
16     """The default queryset, that builds queries and handles a set of results
17     returned from a query.
18 
19     Wraps a MongoDB cursor, providing :class:`~mongoengine.Document` objects as
20     the results.
21     """
22 
23     _has_more = True
24     _len = None
25     _result_cache = None
26 
27     def __iter__(self):
28         """Iteration utilises a results cache which iterates the cursor
29         in batches of ``ITER_CHUNK_SIZE``.
30 
31         If ``self._has_more`` the cursor hasn't been exhausted so cache then
32         batch. Otherwise iterate the result_cache.
33         """
34         self._iter = True
35 
36         if self._has_more:
37             return self._iter_results()
38 
39         # iterating over the cache.
40         return iter(self._result_cache)
41 
42     def __len__(self):
43         """Since __len__ is called quite frequently (for example, as part of
44         list(qs)), we populate the result cache and cache the length.
45         """
46         if self._len is not None:
47             return self._len
48 
49         # Populate the result cache with *all* of the docs in the cursor
50         if self._has_more:
51             list(self._iter_results())
52 
53         # Cache the length of the complete result cache and return it
54         self._len = len(self._result_cache)
55         return self._len
56 
57     def __repr__(self):
58         """Provide a string representation of the QuerySet"""
59         if self._iter:
60             return '.. queryset mid-iteration ..'
61 
62         self._populate_cache()
63         data = self._result_cache[:REPR_OUTPUT_SIZE + 1]
64         if len(data) > REPR_OUTPUT_SIZE:
65             data[-1] = '...(remaining elements truncated)...'
66         return repr(data)
67 
68     def _iter_results(self):
69         """A generator for iterating over the result cache.
70 
71         Also populates the cache if there are more possible results to
72         yield. Raises StopIteration when there are no more results.
73         """
74         if self._result_cache is None:
75             self._result_cache = []
76 
77         pos = 0
78         while True:
79 
80             # For all positions lower than the length of the current result
81             # cache, serve the docs straight from the cache w/o hitting the
82             # database.
83             # XXX it's VERY important to compute the len within the `while`
84             # condition because the result cache might expand mid-iteration
85             # (e.g. if we call len(qs) inside a loop that iterates over the
86             # queryset). Fortunately len(list) is O(1) in Python, so this
87             # doesn't cause performance issues.
88             while pos < len(self._result_cache):
89                 yield self._result_cache[pos]
90                 pos += 1
91 
92             # Raise StopIteration if we already established there were no more
93             # docs in the db cursor.
94             if not self._has_more:
95                 raise StopIteration
96 
97             # Otherwise, populate more of the cache and repeat.
98             if len(self._result_cache) <= pos:
99                 self._populate_cache()
100 
101     def _populate_cache(self):
102         """
103         Populates the result cache with ``ITER_CHUNK_SIZE`` more entries
104         (until the cursor is exhausted).
105         """
106         if self._result_cache is None:
107             self._result_cache = []
108 
109         # Skip populating the cache if we already established there are no
110         # more docs to pull from the database.
111         if not self._has_more:
112             return
113 
114         # Pull in ITER_CHUNK_SIZE docs from the database and store them in
115         # the result cache.
116         try:
117             for _ in six.moves.range(ITER_CHUNK_SIZE):
118                 self._result_cache.append(self.next())
119         except StopIteration:
120             # Getting this exception means there are no more docs in the
121             # db cursor. Set _has_more to False so that we can use that
122             # information in other places.
123             self._has_more = False
124 
125     def count(self, with_limit_and_skip=False):
126         """Count the selected elements in the query.
127 
128         :param with_limit_and_skip (optional): take any :meth:`limit` or
129             :meth:`skip` that has been applied to this cursor into account when
130             getting the count
131         """
132         if with_limit_and_skip is False:
133             return super(QuerySet, self).count(with_limit_and_skip)
134 
135         if self._len is None:
136             self._len = super(QuerySet, self).count(with_limit_and_skip)
137 
138         return self._len
139 
140     def no_cache(self):
141         """Convert to a non-caching queryset
142 
143         .. versionadded:: 0.8.3 Convert to non caching queryset
144         """
145         if self._result_cache is not None:
146             raise OperationError('QuerySet already cached')
147 
148         return self._clone_into(QuerySetNoCache(self._document,
149                                                 self._collection))
150 
151 
152 class QuerySetNoCache(BaseQuerySet):
153     """A non caching QuerySet"""
154 
155     def cache(self):
156         """Convert to a caching queryset
157 
158         .. versionadded:: 0.8.3 Convert to caching queryset
159         """
160         return self._clone_into(QuerySet(self._document, self._collection))
161 
162     def __repr__(self):
163         """Provides the string representation of the QuerySet
164 
165         .. versionchanged:: 0.6.13 Now doesnt modify the cursor
166         """
167         if self._iter:
168             return '.. queryset mid-iteration ..'
169 
170         data = []
171         for _ in six.moves.range(REPR_OUTPUT_SIZE + 1):
172             try:
173                 data.append(self.next())
174             except StopIteration:
175                 break
176 
177         if len(data) > REPR_OUTPUT_SIZE:
178             data[-1] = '...(remaining elements truncated)...'
179 
180         self.rewind()
181         return repr(data)
182 
183     def __iter__(self):
184         queryset = self
185         if queryset._iter:
186             queryset = self.clone()
187         queryset.rewind()
188         return queryset
189 
190 
191 class QuerySetNoDeRef(QuerySet):
192     """Special no_dereference QuerySet"""
193 
194     def __dereference(items, max_depth=1, instance=None, name=None):
195         return items
196
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/mongoengine/queryset/queryset.py b/mongoengine/queryset/queryset.py
--- a/mongoengine/queryset/queryset.py
+++ b/mongoengine/queryset/queryset.py
@@ -92,7 +92,7 @@
             # Raise StopIteration if we already established there were no more
             # docs in the db cursor.
             if not self._has_more:
-                raise StopIteration
+                return
 
             # Otherwise, populate more of the cache and repeat.
             if len(self._result_cache) <= pos:

{"golden_diff": "diff --git a/mongoengine/queryset/queryset.py b/mongoengine/queryset/queryset.py\n--- a/mongoengine/queryset/queryset.py\n+++ b/mongoengine/queryset/queryset.py\n@@ -92,7 +92,7 @@\n             # Raise StopIteration if we already established there were no more\n             # docs in the db cursor.\n             if not self._has_more:\n-                raise StopIteration\n+                return\n \n             # Otherwise, populate more of the cache and repeat.\n             if len(self._result_cache) <= pos:\n", "issue": "raise StopIteration in generators is deprecated\n```\r\n...\r\n/Users/Vic/projects/brain2/brain/utils/user_progress.py:686: DeprecationWarning: generator 'QuerySet._iter_results' raised StopIteration\r\n  for action in actions:\r\n/Users/Vic/projects/brain2/brain/utils/user_course_state.py:317: DeprecationWarning: generator 'QuerySet._iter_results' raised StopIteration\r\n  PlayedTask(\r\n/Users/Vic/projects/brain2/venv/lib/python3.6/site-packages/mongoengine/dereference.py:33: DeprecationWarning: generator 'QuerySet._iter_results' raised StopIteration\r\n...\r\n```\r\nhttps://stackoverflow.com/questions/14183803/in-pythons-generators-what-is-the-difference-between-raise-stopiteration-and\r\n\r\nhttps://github.com/MongoEngine/mongoengine/blob/5bdd35464b89dd2def1dcb0464e244322f1bc757/mongoengine/queryset/queryset.py#L95\n", "before_files": [{"content": "import six\n\nfrom mongoengine.errors import OperationError\nfrom mongoengine.queryset.base import (BaseQuerySet, CASCADE, DENY, DO_NOTHING,\n                                       NULLIFY, PULL)\n\n__all__ = ('QuerySet', 'QuerySetNoCache', 'DO_NOTHING', 'NULLIFY', 'CASCADE',\n           'DENY', 'PULL')\n\n# The maximum number of items to display in a QuerySet.__repr__\nREPR_OUTPUT_SIZE = 20\nITER_CHUNK_SIZE = 100\n\n\nclass QuerySet(BaseQuerySet):\n    \"\"\"The default queryset, that builds queries and handles a set of results\n    returned from a query.\n\n    Wraps a MongoDB cursor, providing :class:`~mongoengine.Document` objects as\n    the results.\n    \"\"\"\n\n    _has_more = True\n    _len = None\n    _result_cache = None\n\n    def __iter__(self):\n        \"\"\"Iteration utilises a results cache which iterates the cursor\n        in batches of ``ITER_CHUNK_SIZE``.\n\n        If ``self._has_more`` the cursor hasn't been exhausted so cache then\n        batch. Otherwise iterate the result_cache.\n        \"\"\"\n        self._iter = True\n\n        if self._has_more:\n            return self._iter_results()\n\n        # iterating over the cache.\n        return iter(self._result_cache)\n\n    def __len__(self):\n        \"\"\"Since __len__ is called quite frequently (for example, as part of\n        list(qs)), we populate the result cache and cache the length.\n        \"\"\"\n        if self._len is not None:\n            return self._len\n\n        # Populate the result cache with *all* of the docs in the cursor\n        if self._has_more:\n            list(self._iter_results())\n\n        # Cache the length of the complete result cache and return it\n        self._len = len(self._result_cache)\n        return self._len\n\n    def __repr__(self):\n        \"\"\"Provide a string representation of the QuerySet\"\"\"\n        if self._iter:\n            return '.. queryset mid-iteration ..'\n\n        self._populate_cache()\n        data = self._result_cache[:REPR_OUTPUT_SIZE + 1]\n        if len(data) > REPR_OUTPUT_SIZE:\n            data[-1] = '...(remaining elements truncated)...'\n        return repr(data)\n\n    def _iter_results(self):\n        \"\"\"A generator for iterating over the result cache.\n\n        Also populates the cache if there are more possible results to\n        yield. Raises StopIteration when there are no more results.\n        \"\"\"\n        if self._result_cache is None:\n            self._result_cache = []\n\n        pos = 0\n        while True:\n\n            # For all positions lower than the length of the current result\n            # cache, serve the docs straight from the cache w/o hitting the\n            # database.\n            # XXX it's VERY important to compute the len within the `while`\n            # condition because the result cache might expand mid-iteration\n            # (e.g. if we call len(qs) inside a loop that iterates over the\n            # queryset). Fortunately len(list) is O(1) in Python, so this\n            # doesn't cause performance issues.\n            while pos < len(self._result_cache):\n                yield self._result_cache[pos]\n                pos += 1\n\n            # Raise StopIteration if we already established there were no more\n            # docs in the db cursor.\n            if not self._has_more:\n                raise StopIteration\n\n            # Otherwise, populate more of the cache and repeat.\n            if len(self._result_cache) <= pos:\n                self._populate_cache()\n\n    def _populate_cache(self):\n        \"\"\"\n        Populates the result cache with ``ITER_CHUNK_SIZE`` more entries\n        (until the cursor is exhausted).\n        \"\"\"\n        if self._result_cache is None:\n            self._result_cache = []\n\n        # Skip populating the cache if we already established there are no\n        # more docs to pull from the database.\n        if not self._has_more:\n            return\n\n        # Pull in ITER_CHUNK_SIZE docs from the database and store them in\n        # the result cache.\n        try:\n            for _ in six.moves.range(ITER_CHUNK_SIZE):\n                self._result_cache.append(self.next())\n        except StopIteration:\n            # Getting this exception means there are no more docs in the\n            # db cursor. Set _has_more to False so that we can use that\n            # information in other places.\n            self._has_more = False\n\n    def count(self, with_limit_and_skip=False):\n        \"\"\"Count the selected elements in the query.\n\n        :param with_limit_and_skip (optional): take any :meth:`limit` or\n            :meth:`skip` that has been applied to this cursor into account when\n            getting the count\n        \"\"\"\n        if with_limit_and_skip is False:\n            return super(QuerySet, self).count(with_limit_and_skip)\n\n        if self._len is None:\n            self._len = super(QuerySet, self).count(with_limit_and_skip)\n\n        return self._len\n\n    def no_cache(self):\n        \"\"\"Convert to a non-caching queryset\n\n        .. versionadded:: 0.8.3 Convert to non caching queryset\n        \"\"\"\n        if self._result_cache is not None:\n            raise OperationError('QuerySet already cached')\n\n        return self._clone_into(QuerySetNoCache(self._document,\n                                                self._collection))\n\n\nclass QuerySetNoCache(BaseQuerySet):\n    \"\"\"A non caching QuerySet\"\"\"\n\n    def cache(self):\n        \"\"\"Convert to a caching queryset\n\n        .. versionadded:: 0.8.3 Convert to caching queryset\n        \"\"\"\n        return self._clone_into(QuerySet(self._document, self._collection))\n\n    def __repr__(self):\n        \"\"\"Provides the string representation of the QuerySet\n\n        .. versionchanged:: 0.6.13 Now doesnt modify the cursor\n        \"\"\"\n        if self._iter:\n            return '.. queryset mid-iteration ..'\n\n        data = []\n        for _ in six.moves.range(REPR_OUTPUT_SIZE + 1):\n            try:\n                data.append(self.next())\n            except StopIteration:\n                break\n\n        if len(data) > REPR_OUTPUT_SIZE:\n            data[-1] = '...(remaining elements truncated)...'\n\n        self.rewind()\n        return repr(data)\n\n    def __iter__(self):\n        queryset = self\n        if queryset._iter:\n            queryset = self.clone()\n        queryset.rewind()\n        return queryset\n\n\nclass QuerySetNoDeRef(QuerySet):\n    \"\"\"Special no_dereference QuerySet\"\"\"\n\n    def __dereference(items, max_depth=1, instance=None, name=None):\n        return items\n", "path": "mongoengine/queryset/queryset.py"}], "after_files": [{"content": "import six\n\nfrom mongoengine.errors import OperationError\nfrom mongoengine.queryset.base import (BaseQuerySet, CASCADE, DENY, DO_NOTHING,\n                                       NULLIFY, PULL)\n\n__all__ = ('QuerySet', 'QuerySetNoCache', 'DO_NOTHING', 'NULLIFY', 'CASCADE',\n           'DENY', 'PULL')\n\n# The maximum number of items to display in a QuerySet.__repr__\nREPR_OUTPUT_SIZE = 20\nITER_CHUNK_SIZE = 100\n\n\nclass QuerySet(BaseQuerySet):\n    \"\"\"The default queryset, that builds queries and handles a set of results\n    returned from a query.\n\n    Wraps a MongoDB cursor, providing :class:`~mongoengine.Document` objects as\n    the results.\n    \"\"\"\n\n    _has_more = True\n    _len = None\n    _result_cache = None\n\n    def __iter__(self):\n        \"\"\"Iteration utilises a results cache which iterates the cursor\n        in batches of ``ITER_CHUNK_SIZE``.\n\n        If ``self._has_more`` the cursor hasn't been exhausted so cache then\n        batch. Otherwise iterate the result_cache.\n        \"\"\"\n        self._iter = True\n\n        if self._has_more:\n            return self._iter_results()\n\n        # iterating over the cache.\n        return iter(self._result_cache)\n\n    def __len__(self):\n        \"\"\"Since __len__ is called quite frequently (for example, as part of\n        list(qs)), we populate the result cache and cache the length.\n        \"\"\"\n        if self._len is not None:\n            return self._len\n\n        # Populate the result cache with *all* of the docs in the cursor\n        if self._has_more:\n            list(self._iter_results())\n\n        # Cache the length of the complete result cache and return it\n        self._len = len(self._result_cache)\n        return self._len\n\n    def __repr__(self):\n        \"\"\"Provide a string representation of the QuerySet\"\"\"\n        if self._iter:\n            return '.. queryset mid-iteration ..'\n\n        self._populate_cache()\n        data = self._result_cache[:REPR_OUTPUT_SIZE + 1]\n        if len(data) > REPR_OUTPUT_SIZE:\n            data[-1] = '...(remaining elements truncated)...'\n        return repr(data)\n\n    def _iter_results(self):\n        \"\"\"A generator for iterating over the result cache.\n\n        Also populates the cache if there are more possible results to\n        yield. Raises StopIteration when there are no more results.\n        \"\"\"\n        if self._result_cache is None:\n            self._result_cache = []\n\n        pos = 0\n        while True:\n\n            # For all positions lower than the length of the current result\n            # cache, serve the docs straight from the cache w/o hitting the\n            # database.\n            # XXX it's VERY important to compute the len within the `while`\n            # condition because the result cache might expand mid-iteration\n            # (e.g. if we call len(qs) inside a loop that iterates over the\n            # queryset). Fortunately len(list) is O(1) in Python, so this\n            # doesn't cause performance issues.\n            while pos < len(self._result_cache):\n                yield self._result_cache[pos]\n                pos += 1\n\n            # Raise StopIteration if we already established there were no more\n            # docs in the db cursor.\n            if not self._has_more:\n                return\n\n            # Otherwise, populate more of the cache and repeat.\n            if len(self._result_cache) <= pos:\n                self._populate_cache()\n\n    def _populate_cache(self):\n        \"\"\"\n        Populates the result cache with ``ITER_CHUNK_SIZE`` more entries\n        (until the cursor is exhausted).\n        \"\"\"\n        if self._result_cache is None:\n            self._result_cache = []\n\n        # Skip populating the cache if we already established there are no\n        # more docs to pull from the database.\n        if not self._has_more:\n            return\n\n        # Pull in ITER_CHUNK_SIZE docs from the database and store them in\n        # the result cache.\n        try:\n            for _ in six.moves.range(ITER_CHUNK_SIZE):\n                self._result_cache.append(self.next())\n        except StopIteration:\n            # Getting this exception means there are no more docs in the\n            # db cursor. Set _has_more to False so that we can use that\n            # information in other places.\n            self._has_more = False\n\n    def count(self, with_limit_and_skip=False):\n        \"\"\"Count the selected elements in the query.\n\n        :param with_limit_and_skip (optional): take any :meth:`limit` or\n            :meth:`skip` that has been applied to this cursor into account when\n            getting the count\n        \"\"\"\n        if with_limit_and_skip is False:\n            return super(QuerySet, self).count(with_limit_and_skip)\n\n        if self._len is None:\n            self._len = super(QuerySet, self).count(with_limit_and_skip)\n\n        return self._len\n\n    def no_cache(self):\n        \"\"\"Convert to a non-caching queryset\n\n        .. versionadded:: 0.8.3 Convert to non caching queryset\n        \"\"\"\n        if self._result_cache is not None:\n            raise OperationError('QuerySet already cached')\n\n        return self._clone_into(QuerySetNoCache(self._document,\n                                                self._collection))\n\n\nclass QuerySetNoCache(BaseQuerySet):\n    \"\"\"A non caching QuerySet\"\"\"\n\n    def cache(self):\n        \"\"\"Convert to a caching queryset\n\n        .. versionadded:: 0.8.3 Convert to caching queryset\n        \"\"\"\n        return self._clone_into(QuerySet(self._document, self._collection))\n\n    def __repr__(self):\n        \"\"\"Provides the string representation of the QuerySet\n\n        .. versionchanged:: 0.6.13 Now doesnt modify the cursor\n        \"\"\"\n        if self._iter:\n            return '.. queryset mid-iteration ..'\n\n        data = []\n        for _ in six.moves.range(REPR_OUTPUT_SIZE + 1):\n            try:\n                data.append(self.next())\n            except StopIteration:\n                break\n\n        if len(data) > REPR_OUTPUT_SIZE:\n            data[-1] = '...(remaining elements truncated)...'\n\n        self.rewind()\n        return repr(data)\n\n    def __iter__(self):\n        queryset = self\n        if queryset._iter:\n            queryset = self.clone()\n        queryset.rewind()\n        return queryset\n\n\nclass QuerySetNoDeRef(QuerySet):\n    \"\"\"Special no_dereference QuerySet\"\"\"\n\n    def __dereference(items, max_depth=1, instance=None, name=None):\n        return items\n", "path": "mongoengine/queryset/queryset.py"}]}