We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Job Monitor fails in possible race condition
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Information

- **Qiskit Terra version**: 0.11.0.dev0+cf9c3f8
- **Python version**: Python 3.6.8
- **Operating system**: Linux 4.15.0-66-generic #75-Ubuntu SMP Tue Oct 1 05:24:09 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux 

### What is the current behavior?
Job monitor fails unrepeatably in a fashion suggesting that if the job has finished right at the instant the job monitor loops it ends up comparing `None` with an `int`.

```
Job Status: job is queuedTraceback (most recent call last):
  File "qyq.py", line 348, in <module>
    job_monitor(job_exp)
  File "/home/jax/work/QISKit/DEV/qiskit-terra/qiskit/tools/monitor/job_monitor.py", line 84, in job_monitor
    quiet=quiet, output=output)
  File "/home/jax/work/QISKit/DEV/qiskit-terra/qiskit/tools/monitor/job_monitor.py", line 49, in _text_checker
    interval = max(job.queue_position(), 2)
TypeError: '>' not supported between instances of 'int' and 'NoneType'
```
### Steps to reproduce the problem
Not reproduceable on-demand.
This occured on `ibmq_london`

### What is the expected behavior?
Job monitor survive any value returned by backend.


### Suggested solutions
None at present.



--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `qiskit/tools/jupyter/jupyter_magics.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 
3 # This code is part of Qiskit.
4 #
5 # (C) Copyright IBM 2017, 2018.
6 #
7 # This code is licensed under the Apache License, Version 2.0. You may
8 # obtain a copy of this license in the LICENSE.txt file in the root directory
9 # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
10 #
11 # Any modifications or derivative works of this code must retain this
12 # copyright notice, and modified files need to carry a notice indicating
13 # that they have been altered from the originals.
14 
15 """A module of magic functions"""
16 
17 import time
18 import threading
19 from IPython.display import display                              # pylint: disable=import-error
20 from IPython.core import magic_arguments                         # pylint: disable=import-error
21 from IPython.core.magic import (cell_magic, line_magic,
22                                 Magics, magics_class)            # pylint: disable=import-error
23 
24 try:
25     import ipywidgets as widgets                                 # pylint: disable=import-error
26 except ImportError:
27     raise ImportError('These functions  need ipywidgets. '
28                       'Run "pip install ipywidgets" before.')
29 import qiskit
30 from qiskit.tools.events.progressbar import TextProgressBar
31 from .progressbar import HTMLProgressBar
32 
33 
34 def _html_checker(job_var, interval, status, header,
35                   _interval_set=False):
36     """Internal function that updates the status
37     of a HTML job monitor.
38 
39     Args:
40         job_var (BaseJob): The job to keep track of.
41         interval (int): The status check interval
42         status (widget): HTML ipywidget for output ot screen
43         header (str): String representing HTML code for status.
44         _interval_set (bool): Was interval set by user?
45     """
46     job_status = job_var.status()
47     job_status_name = job_status.name
48     job_status_msg = job_status.value
49     status.value = header % (job_status_msg)
50     while job_status_name not in ['DONE', 'CANCELLED']:
51         time.sleep(interval)
52         job_status = job_var.status()
53         job_status_name = job_status.name
54         job_status_msg = job_status.value
55         if job_status_name == 'ERROR':
56             break
57         else:
58             if job_status_name == 'QUEUED':
59                 job_status_msg += ' (%s)' % job_var.queue_position()
60                 if not _interval_set:
61                     interval = max(job_var.queue_position(), 2)
62             else:
63                 if not _interval_set:
64                     interval = 2
65             status.value = header % (job_status_msg)
66 
67     status.value = header % (job_status_msg)
68 
69 
70 @magics_class
71 class StatusMagic(Magics):
72     """A class of status magic functions.
73     """
74     @cell_magic
75     @magic_arguments.magic_arguments()
76     @magic_arguments.argument(
77         '-i',
78         '--interval',
79         type=float,
80         default=None,
81         help='Interval for status check.'
82     )
83     def qiskit_job_status(self, line='', cell=None):
84         """A Jupyter magic function to check the status of a Qiskit job instance.
85         """
86         args = magic_arguments.parse_argstring(self.qiskit_job_status, line)
87 
88         if args.interval is None:
89             args.interval = 2
90             _interval_set = False
91         else:
92             _interval_set = True
93 
94         # Split cell lines to get LHS variables
95         cell_lines = cell.split('\n')
96         line_vars = []
97         for cline in cell_lines:
98             if '=' in cline and '==' not in cline:
99                 line_vars.append(cline.replace(' ', '').split('=')[0])
100             elif '.append(' in cline:
101                 line_vars.append(cline.replace(' ', '').split('(')[0])
102 
103         # Execute the cell
104         self.shell.ex(cell)
105 
106         # Look for all vars that are BaseJob instances
107         jobs = []
108         for var in line_vars:
109             iter_var = False
110             if '#' not in var:
111                 # The line var is a list or array, but we cannot parse the index
112                 # so just iterate over the whole array for jobs.
113                 if '[' in var:
114                     var = var.split('[')[0]
115                     iter_var = True
116                 elif '.append' in var:
117                     var = var.split('.append')[0]
118                     iter_var = True
119 
120                 if iter_var:
121                     for item in self.shell.user_ns[var]:
122                         if isinstance(item, qiskit.providers.basejob.BaseJob):
123                             jobs.append(item)
124                 else:
125                     if isinstance(self.shell.user_ns[var],
126                                   qiskit.providers.basejob.BaseJob):
127                         jobs.append(self.shell.user_ns[var])
128 
129         # Must have one job class
130         if not any(jobs):
131             raise Exception(
132                 "Cell must contain at least one variable of BaseJob type.")
133 
134         # List index of job if checking status of multiple jobs.
135         multi_job = False
136         if len(jobs) > 1:
137             multi_job = True
138 
139         job_checkers = []
140         # Loop over every BaseJob that was found.
141         for idx, job_var in enumerate(jobs):
142             style = "font-size:16px;"
143             if multi_job:
144                 idx_str = '[%s]' % idx
145             else:
146                 idx_str = ''
147             header = "<p style='{style}'>Job Status {id}: %s </p>".format(id=idx_str,
148                                                                           style=style)
149             status = widgets.HTML(
150                 value=header % job_var.status().value)
151 
152             thread = threading.Thread(target=_html_checker, args=(job_var, args.interval,
153                                                                   status, header,
154                                                                   _interval_set))
155             thread.start()
156             job_checkers.append(status)
157 
158         # Group all HTML widgets into single vertical layout
159         box = widgets.VBox(job_checkers)
160         display(box)
161 
162 
163 @magics_class
164 class ProgressBarMagic(Magics):
165     """A class of progress bar magic functions.
166     """
167     @line_magic
168     @magic_arguments.magic_arguments()
169     @magic_arguments.argument(
170         '-t',
171         '--type',
172         type=str,
173         default='html',
174         help="Type of progress bar, 'html' or 'text'."
175     )
176     def qiskit_progress_bar(self, line='', cell=None):  # pylint: disable=unused-argument
177         """A Jupyter magic function to generate progressbar.
178         """
179         args = magic_arguments.parse_argstring(self.qiskit_progress_bar, line)
180         if args.type == 'html':
181             pbar = HTMLProgressBar()
182         elif args.type == 'text':
183             pbar = TextProgressBar()
184         else:
185             raise qiskit.QiskitError('Invalid progress bar type.')
186 
187         return pbar
188
```

Path: `qiskit/tools/monitor/job_monitor.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 
3 # This code is part of Qiskit.
4 #
5 # (C) Copyright IBM 2017, 2018.
6 #
7 # This code is licensed under the Apache License, Version 2.0. You may
8 # obtain a copy of this license in the LICENSE.txt file in the root directory
9 # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
10 #
11 # Any modifications or derivative works of this code must retain this
12 # copyright notice, and modified files need to carry a notice indicating
13 # that they have been altered from the originals.
14 
15 
16 """A module for monitoring various qiskit functionality"""
17 
18 import sys
19 import time
20 
21 
22 def _text_checker(job, interval, _interval_set=False, quiet=False, output=sys.stdout):
23     """A text-based job status checker
24 
25     Args:
26         job (BaseJob): The job to check.
27         interval (int): The interval at which to check.
28         _interval_set (bool): Was interval time set by user?
29         quiet (bool): If True, do not print status messages.
30         output (file): The file like object to write status messages to.
31         By default this is sys.stdout.
32 
33     """
34     status = job.status()
35     msg = status.value
36     prev_msg = msg
37     msg_len = len(msg)
38 
39     if not quiet:
40         print('\r%s: %s' % ('Job Status', msg), end='', file=output)
41     while status.name not in ['DONE', 'CANCELLED', 'ERROR']:
42         time.sleep(interval)
43         status = job.status()
44         msg = status.value
45 
46         if status.name == 'QUEUED':
47             msg += ' (%s)' % job.queue_position()
48             if not _interval_set:
49                 interval = max(job.queue_position(), 2)
50         else:
51             if not _interval_set:
52                 interval = 2
53 
54         # Adjust length of message so there are no artifacts
55         if len(msg) < msg_len:
56             msg += ' ' * (msg_len - len(msg))
57         elif len(msg) > msg_len:
58             msg_len = len(msg)
59 
60         if msg != prev_msg and not quiet:
61             print('\r%s: %s' % ('Job Status', msg), end='', file=output)
62             prev_msg = msg
63     if not quiet:
64         print('', file=output)
65 
66 
67 def job_monitor(job, interval=None, quiet=False, output=sys.stdout):
68     """Monitor the status of a IBMQJob instance.
69 
70     Args:
71         job (BaseJob): Job to monitor.
72         interval (int): Time interval between status queries.
73         quiet (bool): If True, do not print status messages.
74         output (file): The file like object to write status messages to.
75         By default this is sys.stdout.
76     """
77     if interval is None:
78         _interval_set = False
79         interval = 5
80     else:
81         _interval_set = True
82 
83     _text_checker(job, interval, _interval_set,
84                   quiet=quiet, output=output)
85
```
--- 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/qiskit/tools/jupyter/jupyter_magics.py b/qiskit/tools/jupyter/jupyter_magics.py
--- a/qiskit/tools/jupyter/jupyter_magics.py
+++ b/qiskit/tools/jupyter/jupyter_magics.py
@@ -57,7 +57,9 @@
         else:
             if job_status_name == 'QUEUED':
                 job_status_msg += ' (%s)' % job_var.queue_position()
-                if not _interval_set:
+                if job_var.queue_position() is None:
+                    interval = 2
+                elif not _interval_set:
                     interval = max(job_var.queue_position(), 2)
             else:
                 if not _interval_set:
diff --git a/qiskit/tools/monitor/job_monitor.py b/qiskit/tools/monitor/job_monitor.py
--- a/qiskit/tools/monitor/job_monitor.py
+++ b/qiskit/tools/monitor/job_monitor.py
@@ -45,7 +45,9 @@
 
         if status.name == 'QUEUED':
             msg += ' (%s)' % job.queue_position()
-            if not _interval_set:
+            if job.queue_position() is None:
+                interval = 2
+            elif not _interval_set:
                 interval = max(job.queue_position(), 2)
         else:
             if not _interval_set:

{"golden_diff": "diff --git a/qiskit/tools/jupyter/jupyter_magics.py b/qiskit/tools/jupyter/jupyter_magics.py\n--- a/qiskit/tools/jupyter/jupyter_magics.py\n+++ b/qiskit/tools/jupyter/jupyter_magics.py\n@@ -57,7 +57,9 @@\n         else:\n             if job_status_name == 'QUEUED':\n                 job_status_msg += ' (%s)' % job_var.queue_position()\n-                if not _interval_set:\n+                if job_var.queue_position() is None:\n+                    interval = 2\n+                elif not _interval_set:\n                     interval = max(job_var.queue_position(), 2)\n             else:\n                 if not _interval_set:\ndiff --git a/qiskit/tools/monitor/job_monitor.py b/qiskit/tools/monitor/job_monitor.py\n--- a/qiskit/tools/monitor/job_monitor.py\n+++ b/qiskit/tools/monitor/job_monitor.py\n@@ -45,7 +45,9 @@\n \n         if status.name == 'QUEUED':\n             msg += ' (%s)' % job.queue_position()\n-            if not _interval_set:\n+            if job.queue_position() is None:\n+                interval = 2\n+            elif not _interval_set:\n                 interval = max(job.queue_position(), 2)\n         else:\n             if not _interval_set:\n", "issue": "Job Monitor fails in possible race condition\n<!-- \u26a0\ufe0f If you do not respect this template, your issue will be closed -->\r\n<!-- \u26a0\ufe0f Make sure to browse the opened and closed issues -->\r\n\r\n### Information\r\n\r\n- **Qiskit Terra version**: 0.11.0.dev0+cf9c3f8\r\n- **Python version**: Python 3.6.8\r\n- **Operating system**: Linux 4.15.0-66-generic #75-Ubuntu SMP Tue Oct 1 05:24:09 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux \r\n\r\n### What is the current behavior?\r\nJob monitor fails unrepeatably in a fashion suggesting that if the job has finished right at the instant the job monitor loops it ends up comparing `None` with an `int`.\r\n\r\n```\r\nJob Status: job is queuedTraceback (most recent call last):\r\n  File \"qyq.py\", line 348, in <module>\r\n    job_monitor(job_exp)\r\n  File \"/home/jax/work/QISKit/DEV/qiskit-terra/qiskit/tools/monitor/job_monitor.py\", line 84, in job_monitor\r\n    quiet=quiet, output=output)\r\n  File \"/home/jax/work/QISKit/DEV/qiskit-terra/qiskit/tools/monitor/job_monitor.py\", line 49, in _text_checker\r\n    interval = max(job.queue_position(), 2)\r\nTypeError: '>' not supported between instances of 'int' and 'NoneType'\r\n```\r\n### Steps to reproduce the problem\r\nNot reproduceable on-demand.\r\nThis occured on `ibmq_london`\r\n\r\n### What is the expected behavior?\r\nJob monitor survive any value returned by backend.\r\n\r\n\r\n### Suggested solutions\r\nNone at present.\r\n\r\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\n# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017, 2018.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"A module of magic functions\"\"\"\n\nimport time\nimport threading\nfrom IPython.display import display                              # pylint: disable=import-error\nfrom IPython.core import magic_arguments                         # pylint: disable=import-error\nfrom IPython.core.magic import (cell_magic, line_magic,\n                                Magics, magics_class)            # pylint: disable=import-error\n\ntry:\n    import ipywidgets as widgets                                 # pylint: disable=import-error\nexcept ImportError:\n    raise ImportError('These functions  need ipywidgets. '\n                      'Run \"pip install ipywidgets\" before.')\nimport qiskit\nfrom qiskit.tools.events.progressbar import TextProgressBar\nfrom .progressbar import HTMLProgressBar\n\n\ndef _html_checker(job_var, interval, status, header,\n                  _interval_set=False):\n    \"\"\"Internal function that updates the status\n    of a HTML job monitor.\n\n    Args:\n        job_var (BaseJob): The job to keep track of.\n        interval (int): The status check interval\n        status (widget): HTML ipywidget for output ot screen\n        header (str): String representing HTML code for status.\n        _interval_set (bool): Was interval set by user?\n    \"\"\"\n    job_status = job_var.status()\n    job_status_name = job_status.name\n    job_status_msg = job_status.value\n    status.value = header % (job_status_msg)\n    while job_status_name not in ['DONE', 'CANCELLED']:\n        time.sleep(interval)\n        job_status = job_var.status()\n        job_status_name = job_status.name\n        job_status_msg = job_status.value\n        if job_status_name == 'ERROR':\n            break\n        else:\n            if job_status_name == 'QUEUED':\n                job_status_msg += ' (%s)' % job_var.queue_position()\n                if not _interval_set:\n                    interval = max(job_var.queue_position(), 2)\n            else:\n                if not _interval_set:\n                    interval = 2\n            status.value = header % (job_status_msg)\n\n    status.value = header % (job_status_msg)\n\n\n@magics_class\nclass StatusMagic(Magics):\n    \"\"\"A class of status magic functions.\n    \"\"\"\n    @cell_magic\n    @magic_arguments.magic_arguments()\n    @magic_arguments.argument(\n        '-i',\n        '--interval',\n        type=float,\n        default=None,\n        help='Interval for status check.'\n    )\n    def qiskit_job_status(self, line='', cell=None):\n        \"\"\"A Jupyter magic function to check the status of a Qiskit job instance.\n        \"\"\"\n        args = magic_arguments.parse_argstring(self.qiskit_job_status, line)\n\n        if args.interval is None:\n            args.interval = 2\n            _interval_set = False\n        else:\n            _interval_set = True\n\n        # Split cell lines to get LHS variables\n        cell_lines = cell.split('\\n')\n        line_vars = []\n        for cline in cell_lines:\n            if '=' in cline and '==' not in cline:\n                line_vars.append(cline.replace(' ', '').split('=')[0])\n            elif '.append(' in cline:\n                line_vars.append(cline.replace(' ', '').split('(')[0])\n\n        # Execute the cell\n        self.shell.ex(cell)\n\n        # Look for all vars that are BaseJob instances\n        jobs = []\n        for var in line_vars:\n            iter_var = False\n            if '#' not in var:\n                # The line var is a list or array, but we cannot parse the index\n                # so just iterate over the whole array for jobs.\n                if '[' in var:\n                    var = var.split('[')[0]\n                    iter_var = True\n                elif '.append' in var:\n                    var = var.split('.append')[0]\n                    iter_var = True\n\n                if iter_var:\n                    for item in self.shell.user_ns[var]:\n                        if isinstance(item, qiskit.providers.basejob.BaseJob):\n                            jobs.append(item)\n                else:\n                    if isinstance(self.shell.user_ns[var],\n                                  qiskit.providers.basejob.BaseJob):\n                        jobs.append(self.shell.user_ns[var])\n\n        # Must have one job class\n        if not any(jobs):\n            raise Exception(\n                \"Cell must contain at least one variable of BaseJob type.\")\n\n        # List index of job if checking status of multiple jobs.\n        multi_job = False\n        if len(jobs) > 1:\n            multi_job = True\n\n        job_checkers = []\n        # Loop over every BaseJob that was found.\n        for idx, job_var in enumerate(jobs):\n            style = \"font-size:16px;\"\n            if multi_job:\n                idx_str = '[%s]' % idx\n            else:\n                idx_str = ''\n            header = \"<p style='{style}'>Job Status {id}: %s </p>\".format(id=idx_str,\n                                                                          style=style)\n            status = widgets.HTML(\n                value=header % job_var.status().value)\n\n            thread = threading.Thread(target=_html_checker, args=(job_var, args.interval,\n                                                                  status, header,\n                                                                  _interval_set))\n            thread.start()\n            job_checkers.append(status)\n\n        # Group all HTML widgets into single vertical layout\n        box = widgets.VBox(job_checkers)\n        display(box)\n\n\n@magics_class\nclass ProgressBarMagic(Magics):\n    \"\"\"A class of progress bar magic functions.\n    \"\"\"\n    @line_magic\n    @magic_arguments.magic_arguments()\n    @magic_arguments.argument(\n        '-t',\n        '--type',\n        type=str,\n        default='html',\n        help=\"Type of progress bar, 'html' or 'text'.\"\n    )\n    def qiskit_progress_bar(self, line='', cell=None):  # pylint: disable=unused-argument\n        \"\"\"A Jupyter magic function to generate progressbar.\n        \"\"\"\n        args = magic_arguments.parse_argstring(self.qiskit_progress_bar, line)\n        if args.type == 'html':\n            pbar = HTMLProgressBar()\n        elif args.type == 'text':\n            pbar = TextProgressBar()\n        else:\n            raise qiskit.QiskitError('Invalid progress bar type.')\n\n        return pbar\n", "path": "qiskit/tools/jupyter/jupyter_magics.py"}, {"content": "# -*- coding: utf-8 -*-\n\n# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017, 2018.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\n\"\"\"A module for monitoring various qiskit functionality\"\"\"\n\nimport sys\nimport time\n\n\ndef _text_checker(job, interval, _interval_set=False, quiet=False, output=sys.stdout):\n    \"\"\"A text-based job status checker\n\n    Args:\n        job (BaseJob): The job to check.\n        interval (int): The interval at which to check.\n        _interval_set (bool): Was interval time set by user?\n        quiet (bool): If True, do not print status messages.\n        output (file): The file like object to write status messages to.\n        By default this is sys.stdout.\n\n    \"\"\"\n    status = job.status()\n    msg = status.value\n    prev_msg = msg\n    msg_len = len(msg)\n\n    if not quiet:\n        print('\\r%s: %s' % ('Job Status', msg), end='', file=output)\n    while status.name not in ['DONE', 'CANCELLED', 'ERROR']:\n        time.sleep(interval)\n        status = job.status()\n        msg = status.value\n\n        if status.name == 'QUEUED':\n            msg += ' (%s)' % job.queue_position()\n            if not _interval_set:\n                interval = max(job.queue_position(), 2)\n        else:\n            if not _interval_set:\n                interval = 2\n\n        # Adjust length of message so there are no artifacts\n        if len(msg) < msg_len:\n            msg += ' ' * (msg_len - len(msg))\n        elif len(msg) > msg_len:\n            msg_len = len(msg)\n\n        if msg != prev_msg and not quiet:\n            print('\\r%s: %s' % ('Job Status', msg), end='', file=output)\n            prev_msg = msg\n    if not quiet:\n        print('', file=output)\n\n\ndef job_monitor(job, interval=None, quiet=False, output=sys.stdout):\n    \"\"\"Monitor the status of a IBMQJob instance.\n\n    Args:\n        job (BaseJob): Job to monitor.\n        interval (int): Time interval between status queries.\n        quiet (bool): If True, do not print status messages.\n        output (file): The file like object to write status messages to.\n        By default this is sys.stdout.\n    \"\"\"\n    if interval is None:\n        _interval_set = False\n        interval = 5\n    else:\n        _interval_set = True\n\n    _text_checker(job, interval, _interval_set,\n                  quiet=quiet, output=output)\n", "path": "qiskit/tools/monitor/job_monitor.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\n# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017, 2018.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"A module of magic functions\"\"\"\n\nimport time\nimport threading\nfrom IPython.display import display                              # pylint: disable=import-error\nfrom IPython.core import magic_arguments                         # pylint: disable=import-error\nfrom IPython.core.magic import (cell_magic, line_magic,\n                                Magics, magics_class)            # pylint: disable=import-error\n\ntry:\n    import ipywidgets as widgets                                 # pylint: disable=import-error\nexcept ImportError:\n    raise ImportError('These functions  need ipywidgets. '\n                      'Run \"pip install ipywidgets\" before.')\nimport qiskit\nfrom qiskit.tools.events.progressbar import TextProgressBar\nfrom .progressbar import HTMLProgressBar\n\n\ndef _html_checker(job_var, interval, status, header,\n                  _interval_set=False):\n    \"\"\"Internal function that updates the status\n    of a HTML job monitor.\n\n    Args:\n        job_var (BaseJob): The job to keep track of.\n        interval (int): The status check interval\n        status (widget): HTML ipywidget for output ot screen\n        header (str): String representing HTML code for status.\n        _interval_set (bool): Was interval set by user?\n    \"\"\"\n    job_status = job_var.status()\n    job_status_name = job_status.name\n    job_status_msg = job_status.value\n    status.value = header % (job_status_msg)\n    while job_status_name not in ['DONE', 'CANCELLED']:\n        time.sleep(interval)\n        job_status = job_var.status()\n        job_status_name = job_status.name\n        job_status_msg = job_status.value\n        if job_status_name == 'ERROR':\n            break\n        else:\n            if job_status_name == 'QUEUED':\n                job_status_msg += ' (%s)' % job_var.queue_position()\n                if job_var.queue_position() is None:\n                    interval = 2\n                elif not _interval_set:\n                    interval = max(job_var.queue_position(), 2)\n            else:\n                if not _interval_set:\n                    interval = 2\n            status.value = header % (job_status_msg)\n\n    status.value = header % (job_status_msg)\n\n\n@magics_class\nclass StatusMagic(Magics):\n    \"\"\"A class of status magic functions.\n    \"\"\"\n    @cell_magic\n    @magic_arguments.magic_arguments()\n    @magic_arguments.argument(\n        '-i',\n        '--interval',\n        type=float,\n        default=None,\n        help='Interval for status check.'\n    )\n    def qiskit_job_status(self, line='', cell=None):\n        \"\"\"A Jupyter magic function to check the status of a Qiskit job instance.\n        \"\"\"\n        args = magic_arguments.parse_argstring(self.qiskit_job_status, line)\n\n        if args.interval is None:\n            args.interval = 2\n            _interval_set = False\n        else:\n            _interval_set = True\n\n        # Split cell lines to get LHS variables\n        cell_lines = cell.split('\\n')\n        line_vars = []\n        for cline in cell_lines:\n            if '=' in cline and '==' not in cline:\n                line_vars.append(cline.replace(' ', '').split('=')[0])\n            elif '.append(' in cline:\n                line_vars.append(cline.replace(' ', '').split('(')[0])\n\n        # Execute the cell\n        self.shell.ex(cell)\n\n        # Look for all vars that are BaseJob instances\n        jobs = []\n        for var in line_vars:\n            iter_var = False\n            if '#' not in var:\n                # The line var is a list or array, but we cannot parse the index\n                # so just iterate over the whole array for jobs.\n                if '[' in var:\n                    var = var.split('[')[0]\n                    iter_var = True\n                elif '.append' in var:\n                    var = var.split('.append')[0]\n                    iter_var = True\n\n                if iter_var:\n                    for item in self.shell.user_ns[var]:\n                        if isinstance(item, qiskit.providers.basejob.BaseJob):\n                            jobs.append(item)\n                else:\n                    if isinstance(self.shell.user_ns[var],\n                                  qiskit.providers.basejob.BaseJob):\n                        jobs.append(self.shell.user_ns[var])\n\n        # Must have one job class\n        if not any(jobs):\n            raise Exception(\n                \"Cell must contain at least one variable of BaseJob type.\")\n\n        # List index of job if checking status of multiple jobs.\n        multi_job = False\n        if len(jobs) > 1:\n            multi_job = True\n\n        job_checkers = []\n        # Loop over every BaseJob that was found.\n        for idx, job_var in enumerate(jobs):\n            style = \"font-size:16px;\"\n            if multi_job:\n                idx_str = '[%s]' % idx\n            else:\n                idx_str = ''\n            header = \"<p style='{style}'>Job Status {id}: %s </p>\".format(id=idx_str,\n                                                                          style=style)\n            status = widgets.HTML(\n                value=header % job_var.status().value)\n\n            thread = threading.Thread(target=_html_checker, args=(job_var, args.interval,\n                                                                  status, header,\n                                                                  _interval_set))\n            thread.start()\n            job_checkers.append(status)\n\n        # Group all HTML widgets into single vertical layout\n        box = widgets.VBox(job_checkers)\n        display(box)\n\n\n@magics_class\nclass ProgressBarMagic(Magics):\n    \"\"\"A class of progress bar magic functions.\n    \"\"\"\n    @line_magic\n    @magic_arguments.magic_arguments()\n    @magic_arguments.argument(\n        '-t',\n        '--type',\n        type=str,\n        default='html',\n        help=\"Type of progress bar, 'html' or 'text'.\"\n    )\n    def qiskit_progress_bar(self, line='', cell=None):  # pylint: disable=unused-argument\n        \"\"\"A Jupyter magic function to generate progressbar.\n        \"\"\"\n        args = magic_arguments.parse_argstring(self.qiskit_progress_bar, line)\n        if args.type == 'html':\n            pbar = HTMLProgressBar()\n        elif args.type == 'text':\n            pbar = TextProgressBar()\n        else:\n            raise qiskit.QiskitError('Invalid progress bar type.')\n\n        return pbar\n", "path": "qiskit/tools/jupyter/jupyter_magics.py"}, {"content": "# -*- coding: utf-8 -*-\n\n# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017, 2018.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\n\"\"\"A module for monitoring various qiskit functionality\"\"\"\n\nimport sys\nimport time\n\n\ndef _text_checker(job, interval, _interval_set=False, quiet=False, output=sys.stdout):\n    \"\"\"A text-based job status checker\n\n    Args:\n        job (BaseJob): The job to check.\n        interval (int): The interval at which to check.\n        _interval_set (bool): Was interval time set by user?\n        quiet (bool): If True, do not print status messages.\n        output (file): The file like object to write status messages to.\n        By default this is sys.stdout.\n\n    \"\"\"\n    status = job.status()\n    msg = status.value\n    prev_msg = msg\n    msg_len = len(msg)\n\n    if not quiet:\n        print('\\r%s: %s' % ('Job Status', msg), end='', file=output)\n    while status.name not in ['DONE', 'CANCELLED', 'ERROR']:\n        time.sleep(interval)\n        status = job.status()\n        msg = status.value\n\n        if status.name == 'QUEUED':\n            msg += ' (%s)' % job.queue_position()\n            if job.queue_position() is None:\n                interval = 2\n            elif not _interval_set:\n                interval = max(job.queue_position(), 2)\n        else:\n            if not _interval_set:\n                interval = 2\n\n        # Adjust length of message so there are no artifacts\n        if len(msg) < msg_len:\n            msg += ' ' * (msg_len - len(msg))\n        elif len(msg) > msg_len:\n            msg_len = len(msg)\n\n        if msg != prev_msg and not quiet:\n            print('\\r%s: %s' % ('Job Status', msg), end='', file=output)\n            prev_msg = msg\n    if not quiet:\n        print('', file=output)\n\n\ndef job_monitor(job, interval=None, quiet=False, output=sys.stdout):\n    \"\"\"Monitor the status of a IBMQJob instance.\n\n    Args:\n        job (BaseJob): Job to monitor.\n        interval (int): Time interval between status queries.\n        quiet (bool): If True, do not print status messages.\n        output (file): The file like object to write status messages to.\n        By default this is sys.stdout.\n    \"\"\"\n    if interval is None:\n        _interval_set = False\n        interval = 5\n    else:\n        _interval_set = True\n\n    _text_checker(job, interval, _interval_set,\n                  quiet=quiet, output=output)\n", "path": "qiskit/tools/monitor/job_monitor.py"}]}