We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Panel show not working in chrome
![image](https://user-images.githubusercontent.com/18531147/96686273-9b76e700-137e-11eb-9904-6da02e2f8b31.png)

MRE:
```python
import panel as pn
pn.extension()

pn.widgets.FloatSlider().show()
```

tested on linux and windows 10

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `panel/io/notebook.py`
Content:
```
1 """
2 Various utilities for loading JS dependencies and rendering plots
3 inside the Jupyter notebook.
4 """
5 from __future__ import absolute_import, division, unicode_literals
6 
7 import json
8 import uuid
9 import sys
10 
11 from contextlib import contextmanager
12 from collections import OrderedDict
13 from six import string_types
14 
15 import bokeh
16 import bokeh.embed.notebook
17 
18 from bokeh.core.json_encoder import serialize_json
19 from bokeh.core.templates import MACROS
20 from bokeh.document import Document
21 from bokeh.embed import server_document
22 from bokeh.embed.bundle import bundle_for_objs_and_resources
23 from bokeh.embed.elements import div_for_render_item, script_for_render_items
24 from bokeh.embed.util import standalone_docs_json_and_render_items
25 from bokeh.embed.wrappers import wrap_in_script_tag
26 from bokeh.models import LayoutDOM, Model
27 from bokeh.resources import CDN, INLINE
28 from bokeh.settings import settings
29 from bokeh.util.serialization import make_id
30 from pyviz_comms import (
31     PYVIZ_PROXY, Comm, JupyterCommManager as _JupyterCommManager, nb_mime_js
32 )
33 
34 try:
35     from bokeh.util.string import escape
36 except Exception:
37     from html import escape
38 
39 from ..compiler import require_components
40 from .embed import embed_state
41 from .model import add_to_doc, diff
42 from .resources import _env
43 from .server import _server_url, _origin_url, get_server
44 from .state import state
45 
46 
47 #---------------------------------------------------------------------
48 # Private API
49 #---------------------------------------------------------------------
50 
51 LOAD_MIME = 'application/vnd.holoviews_load.v0+json'
52 EXEC_MIME = 'application/vnd.holoviews_exec.v0+json'
53 HTML_MIME = 'text/html'
54 
55 def push(doc, comm, binary=True):
56     """
57     Pushes events stored on the document across the provided comm.
58     """
59     msg = diff(doc, binary=binary)
60     if msg is None:
61         return
62     comm.send(msg.header_json)
63     comm.send(msg.metadata_json)
64     comm.send(msg.content_json)
65     for header, payload in msg.buffers:
66         comm.send(json.dumps(header))
67         comm.send(buffers=[payload])
68 
69 DOC_NB_JS = _env.get_template("doc_nb_js.js")
70 AUTOLOAD_NB_JS = _env.get_template("autoload_panel_js.js")
71 NB_TEMPLATE_BASE = _env.get_template('nb_template.html')
72 
73 def _autoload_js(bundle, configs, requirements, exports, skip_imports, ipywidget, load_timeout=5000):
74     return AUTOLOAD_NB_JS.render(
75         bundle    = bundle,
76         force     = True,
77         timeout   = load_timeout,
78         configs   = configs,
79         requirements = requirements,
80         exports   = exports,
81         skip_imports = skip_imports,
82         ipywidget = ipywidget
83     )
84 
85 
86 def html_for_render_items(docs_json, render_items, template=None, template_variables={}):
87     json_id = make_id()
88     json = escape(serialize_json(docs_json), quote=False)
89     json = wrap_in_script_tag(json, "application/json", json_id)
90 
91     script = wrap_in_script_tag(script_for_render_items(json_id, render_items))
92 
93     context = template_variables.copy()
94 
95     context.update(dict(
96         title = '',
97         plot_script = json + script,
98         docs = render_items,
99         base = NB_TEMPLATE_BASE,
100         macros = MACROS,
101     ))
102 
103     if len(render_items) == 1:
104         context["doc"] = context["docs"][0]
105         context["roots"] = context["doc"].roots
106 
107     if template is None:
108         template = NB_TEMPLATE_BASE
109     elif isinstance(template, string_types):
110         template = _env.from_string("{% extends base %}\n" + template)
111 
112     return template.render(context)
113 
114 
115 def render_template(document, comm=None, manager=None):
116     ref = document.roots[0].ref['id']
117     (docs_json, render_items) = standalone_docs_json_and_render_items(document, True)
118 
119     # We do not want the CommManager to appear in the roots because
120     # the custom template may not reference it
121     if manager:
122         item = render_items[0]
123         item.roots._roots = OrderedDict(list(item.roots._roots.items())[:-1])
124 
125     html = html_for_render_items(
126         docs_json, render_items, template=document.template,
127         template_variables=document.template_variables
128     )
129     return ({'text/html': html, EXEC_MIME: ''}, {EXEC_MIME: {'id': ref}})
130 
131 
132 def render_model(model, comm=None):
133     if not isinstance(model, Model):
134         raise ValueError("notebook_content expects a single Model instance")
135     from ..config import panel_extension as pnext
136 
137     target = model.ref['id']
138 
139     (docs_json, [render_item]) = standalone_docs_json_and_render_items([model], True)
140     div = div_for_render_item(render_item)
141     render_item = render_item.to_json()
142     requirements = [pnext._globals[ext] for ext in pnext._loaded_extensions
143                     if ext in pnext._globals]
144     ipywidget = 'ipywidgets_bokeh' in sys.modules
145 
146     script = DOC_NB_JS.render(
147         docs_json=serialize_json(docs_json),
148         render_items=serialize_json([render_item]),
149         requirements=requirements,
150         ipywidget=ipywidget
151     )
152     bokeh_script, bokeh_div = script, div
153     html = "<div id='{id}'>{html}</div>".format(id=target, html=bokeh_div)
154 
155     data = {'text/html': html, 'application/javascript': bokeh_script}
156     return ({'text/html': mimebundle_to_html(data), EXEC_MIME: ''},
157             {EXEC_MIME: {'id': target}})
158 
159 
160 def render_mimebundle(model, doc, comm, manager=None, location=None):
161     """
162     Displays bokeh output inside a notebook using the PyViz display
163     and comms machinery.
164     """
165     if not isinstance(model, LayoutDOM):
166         raise ValueError('Can only render bokeh LayoutDOM models')
167     add_to_doc(model, doc, True)
168     if manager is not None:
169         doc.add_root(manager)
170     if location is not None:
171         loc = location._get_model(doc, model, model, comm)
172         doc.add_root(loc)
173     return render_model(model, comm)
174 
175 
176 def mimebundle_to_html(bundle):
177     """
178     Converts a MIME bundle into HTML.
179     """
180     if isinstance(bundle, tuple):
181         data, metadata = bundle
182     else:
183         data = bundle
184     html = data.get('text/html', '')
185     if 'application/javascript' in data:
186         js = data['application/javascript']
187         html += '\n<script type="application/javascript">{js}</script>'.format(js=js)
188     return html
189 
190 #---------------------------------------------------------------------
191 # Public API
192 #---------------------------------------------------------------------
193 
194 
195 @contextmanager
196 def block_comm():
197     """
198     Context manager to temporarily block comm push
199     """
200     state._hold = True
201     try:
202         yield
203     finally:
204         state._hold = False
205 
206 
207 def load_notebook(inline=True, load_timeout=5000):
208     from IPython.display import publish_display_data
209 
210     resources = INLINE if inline else CDN
211     prev_resources = settings.resources()
212     try:
213         settings.resources = 'cdn'
214         bundle = bundle_for_objs_and_resources(None, resources)
215         configs, requirements, exports, skip_imports = require_components()
216         ipywidget = 'ipywidgets_bokeh' in sys.modules
217         bokeh_js = _autoload_js(bundle, configs, requirements, exports,
218                                 skip_imports, ipywidget, load_timeout)
219     finally:
220         settings.resources = prev_resources
221 
222     publish_display_data({
223         'application/javascript': bokeh_js,
224         LOAD_MIME: bokeh_js,
225     })
226     bokeh.io.notebook.curstate().output_notebook()
227 
228     # Publish comm manager
229     JS = '\n'.join([PYVIZ_PROXY, _JupyterCommManager.js_manager, nb_mime_js])
230     publish_display_data(data={LOAD_MIME: JS, 'application/javascript': JS})
231 
232 
233 def show_server(panel, notebook_url, port):
234     """
235     Displays a bokeh server inline in the notebook.
236 
237     Arguments
238     ---------
239     panel: Viewable
240       Panel Viewable object to launch a server for
241     notebook_url: str
242       The URL of the running Jupyter notebook server
243     port: int (optional, default=0)
244       Allows specifying a specific port
245     server_id: str
246       Unique ID to identify the server with
247 
248     Returns
249     -------
250     server: bokeh.server.Server
251     """
252     from IPython.display import publish_display_data
253 
254     if callable(notebook_url):
255         origin = notebook_url(None)
256     else:
257         origin = _origin_url(notebook_url)
258     server_id = uuid.uuid4().hex
259     server = get_server(panel, port=port, websocket_origin=origin,
260                         start=True, show=False, server_id=server_id)
261 
262     if callable(notebook_url):
263         url = notebook_url(server.port)
264     else:
265         url = _server_url(notebook_url, server.port)
266 
267     script = server_document(url, resources=None)
268 
269     publish_display_data({
270         HTML_MIME: script,
271         EXEC_MIME: ""
272     }, metadata={
273         EXEC_MIME: {"server_id": server_id}
274     })
275     return server
276 
277 
278 def show_embed(panel, max_states=1000, max_opts=3, json=False,
279                json_prefix='', save_path='./', load_path=None,
280                progress=True, states={}):
281     """
282     Renders a static version of a panel in a notebook by evaluating
283     the set of states defined by the widgets in the model. Note
284     this will only work well for simple apps with a relatively
285     small state space.
286 
287     Arguments
288     ---------
289     max_states: int
290       The maximum number of states to embed
291     max_opts: int
292       The maximum number of states for a single widget
293     json: boolean (default=True)
294       Whether to export the data to json files
295     json_prefix: str (default='')
296       Prefix for JSON filename
297     save_path: str (default='./')
298       The path to save json files to
299     load_path: str (default=None)
300       The path or URL the json files will be loaded from.
301     progress: boolean (default=False)
302       Whether to report progress
303     states: dict (default={})
304       A dictionary specifying the widget values to embed for each widget
305     """
306     from IPython.display import publish_display_data
307     from ..config import config
308 
309     doc = Document()
310     comm = Comm()
311     with config.set(embed=True):
312         model = panel.get_root(doc, comm)
313         embed_state(panel, model, doc, max_states, max_opts,
314                     json, json_prefix, save_path, load_path, progress,
315                     states)
316     publish_display_data(*render_model(model))
317 
318 
319 def ipywidget(obj, **kwargs):
320     """
321     Creates a root model from the Panel object and wraps it in
322     a jupyter_bokeh ipywidget BokehModel.
323 
324     Arguments
325     ---------
326     obj: object
327       Any Panel object or object which can be rendered with Panel
328     **kwargs: dict
329       Keyword arguments passed to the pn.panel utility function
330 
331     Returns
332     -------
333     Returns an ipywidget model which renders the Panel object.
334     """
335     from jupyter_bokeh import BokehModel
336     from ..pane import panel
337     model = panel(obj, **kwargs).get_root()
338     widget = BokehModel(model, combine_events=True)
339     if hasattr(widget, '_view_count'):
340         widget._view_count = 0
341         def view_count_changed(change, current=[model]):
342             new_model = None
343             if change['old'] > 0 and change['new'] == 0 and current:
344                 obj._cleanup(current[0])
345                 current[:] = []
346             elif (change['old'] == 0 and change['new'] > 0 and
347                   (not current or current[0] is not model)):
348                 if current:
349                     try:
350                         obj._cleanup(current[0])
351                     except Exception:
352                         pass
353                 new_model = obj.get_root()
354                 widget.update_from_model(new_model)
355                 current[:] = [new_model]
356         widget.observe(view_count_changed, '_view_count')
357     return widget
358
```
--- 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/panel/io/notebook.py b/panel/io/notebook.py
--- a/panel/io/notebook.py
+++ b/panel/io/notebook.py
@@ -25,7 +25,7 @@
 from bokeh.embed.wrappers import wrap_in_script_tag
 from bokeh.models import LayoutDOM, Model
 from bokeh.resources import CDN, INLINE
-from bokeh.settings import settings
+from bokeh.settings import settings, _Unset
 from bokeh.util.serialization import make_id
 from pyviz_comms import (
     PYVIZ_PROXY, Comm, JupyterCommManager as _JupyterCommManager, nb_mime_js
@@ -208,16 +208,20 @@
     from IPython.display import publish_display_data
 
     resources = INLINE if inline else CDN
-    prev_resources = settings.resources()
+    prev_resources = settings.resources(default="server")
+    user_resources = settings.resources._user_value is not _Unset
     try:
-        settings.resources = 'cdn'
+        settings.resources = 'inline' if inline else 'cdn'
         bundle = bundle_for_objs_and_resources(None, resources)
         configs, requirements, exports, skip_imports = require_components()
         ipywidget = 'ipywidgets_bokeh' in sys.modules
         bokeh_js = _autoload_js(bundle, configs, requirements, exports,
                                 skip_imports, ipywidget, load_timeout)
     finally:
-        settings.resources = prev_resources
+        if user_resources:
+            settings.resources = prev_resources
+        else:
+            settings.resources.unset_value()
 
     publish_display_data({
         'application/javascript': bokeh_js,

{"golden_diff": "diff --git a/panel/io/notebook.py b/panel/io/notebook.py\n--- a/panel/io/notebook.py\n+++ b/panel/io/notebook.py\n@@ -25,7 +25,7 @@\n from bokeh.embed.wrappers import wrap_in_script_tag\n from bokeh.models import LayoutDOM, Model\n from bokeh.resources import CDN, INLINE\n-from bokeh.settings import settings\n+from bokeh.settings import settings, _Unset\n from bokeh.util.serialization import make_id\n from pyviz_comms import (\n     PYVIZ_PROXY, Comm, JupyterCommManager as _JupyterCommManager, nb_mime_js\n@@ -208,16 +208,20 @@\n     from IPython.display import publish_display_data\n \n     resources = INLINE if inline else CDN\n-    prev_resources = settings.resources()\n+    prev_resources = settings.resources(default=\"server\")\n+    user_resources = settings.resources._user_value is not _Unset\n     try:\n-        settings.resources = 'cdn'\n+        settings.resources = 'inline' if inline else 'cdn'\n         bundle = bundle_for_objs_and_resources(None, resources)\n         configs, requirements, exports, skip_imports = require_components()\n         ipywidget = 'ipywidgets_bokeh' in sys.modules\n         bokeh_js = _autoload_js(bundle, configs, requirements, exports,\n                                 skip_imports, ipywidget, load_timeout)\n     finally:\n-        settings.resources = prev_resources\n+        if user_resources:\n+            settings.resources = prev_resources\n+        else:\n+            settings.resources.unset_value()\n \n     publish_display_data({\n         'application/javascript': bokeh_js,\n", "issue": "Panel show not working in chrome\n![image](https://user-images.githubusercontent.com/18531147/96686273-9b76e700-137e-11eb-9904-6da02e2f8b31.png)\r\n\r\nMRE:\r\n```python\r\nimport panel as pn\r\npn.extension()\r\n\r\npn.widgets.FloatSlider().show()\r\n```\r\n\r\ntested on linux and windows 10\n", "before_files": [{"content": "\"\"\"\nVarious utilities for loading JS dependencies and rendering plots\ninside the Jupyter notebook.\n\"\"\"\nfrom __future__ import absolute_import, division, unicode_literals\n\nimport json\nimport uuid\nimport sys\n\nfrom contextlib import contextmanager\nfrom collections import OrderedDict\nfrom six import string_types\n\nimport bokeh\nimport bokeh.embed.notebook\n\nfrom bokeh.core.json_encoder import serialize_json\nfrom bokeh.core.templates import MACROS\nfrom bokeh.document import Document\nfrom bokeh.embed import server_document\nfrom bokeh.embed.bundle import bundle_for_objs_and_resources\nfrom bokeh.embed.elements import div_for_render_item, script_for_render_items\nfrom bokeh.embed.util import standalone_docs_json_and_render_items\nfrom bokeh.embed.wrappers import wrap_in_script_tag\nfrom bokeh.models import LayoutDOM, Model\nfrom bokeh.resources import CDN, INLINE\nfrom bokeh.settings import settings\nfrom bokeh.util.serialization import make_id\nfrom pyviz_comms import (\n    PYVIZ_PROXY, Comm, JupyterCommManager as _JupyterCommManager, nb_mime_js\n)\n\ntry:\n    from bokeh.util.string import escape\nexcept Exception:\n    from html import escape\n\nfrom ..compiler import require_components\nfrom .embed import embed_state\nfrom .model import add_to_doc, diff\nfrom .resources import _env\nfrom .server import _server_url, _origin_url, get_server\nfrom .state import state\n\n\n#---------------------------------------------------------------------\n# Private API\n#---------------------------------------------------------------------\n\nLOAD_MIME = 'application/vnd.holoviews_load.v0+json'\nEXEC_MIME = 'application/vnd.holoviews_exec.v0+json'\nHTML_MIME = 'text/html'\n\ndef push(doc, comm, binary=True):\n    \"\"\"\n    Pushes events stored on the document across the provided comm.\n    \"\"\"\n    msg = diff(doc, binary=binary)\n    if msg is None:\n        return\n    comm.send(msg.header_json)\n    comm.send(msg.metadata_json)\n    comm.send(msg.content_json)\n    for header, payload in msg.buffers:\n        comm.send(json.dumps(header))\n        comm.send(buffers=[payload])\n\nDOC_NB_JS = _env.get_template(\"doc_nb_js.js\")\nAUTOLOAD_NB_JS = _env.get_template(\"autoload_panel_js.js\")\nNB_TEMPLATE_BASE = _env.get_template('nb_template.html')\n\ndef _autoload_js(bundle, configs, requirements, exports, skip_imports, ipywidget, load_timeout=5000):\n    return AUTOLOAD_NB_JS.render(\n        bundle    = bundle,\n        force     = True,\n        timeout   = load_timeout,\n        configs   = configs,\n        requirements = requirements,\n        exports   = exports,\n        skip_imports = skip_imports,\n        ipywidget = ipywidget\n    )\n\n\ndef html_for_render_items(docs_json, render_items, template=None, template_variables={}):\n    json_id = make_id()\n    json = escape(serialize_json(docs_json), quote=False)\n    json = wrap_in_script_tag(json, \"application/json\", json_id)\n\n    script = wrap_in_script_tag(script_for_render_items(json_id, render_items))\n\n    context = template_variables.copy()\n\n    context.update(dict(\n        title = '',\n        plot_script = json + script,\n        docs = render_items,\n        base = NB_TEMPLATE_BASE,\n        macros = MACROS,\n    ))\n\n    if len(render_items) == 1:\n        context[\"doc\"] = context[\"docs\"][0]\n        context[\"roots\"] = context[\"doc\"].roots\n\n    if template is None:\n        template = NB_TEMPLATE_BASE\n    elif isinstance(template, string_types):\n        template = _env.from_string(\"{% extends base %}\\n\" + template)\n\n    return template.render(context)\n\n\ndef render_template(document, comm=None, manager=None):\n    ref = document.roots[0].ref['id']\n    (docs_json, render_items) = standalone_docs_json_and_render_items(document, True)\n\n    # We do not want the CommManager to appear in the roots because\n    # the custom template may not reference it\n    if manager:\n        item = render_items[0]\n        item.roots._roots = OrderedDict(list(item.roots._roots.items())[:-1])\n\n    html = html_for_render_items(\n        docs_json, render_items, template=document.template,\n        template_variables=document.template_variables\n    )\n    return ({'text/html': html, EXEC_MIME: ''}, {EXEC_MIME: {'id': ref}})\n\n\ndef render_model(model, comm=None):\n    if not isinstance(model, Model):\n        raise ValueError(\"notebook_content expects a single Model instance\")\n    from ..config import panel_extension as pnext\n\n    target = model.ref['id']\n\n    (docs_json, [render_item]) = standalone_docs_json_and_render_items([model], True)\n    div = div_for_render_item(render_item)\n    render_item = render_item.to_json()\n    requirements = [pnext._globals[ext] for ext in pnext._loaded_extensions\n                    if ext in pnext._globals]\n    ipywidget = 'ipywidgets_bokeh' in sys.modules\n\n    script = DOC_NB_JS.render(\n        docs_json=serialize_json(docs_json),\n        render_items=serialize_json([render_item]),\n        requirements=requirements,\n        ipywidget=ipywidget\n    )\n    bokeh_script, bokeh_div = script, div\n    html = \"<div id='{id}'>{html}</div>\".format(id=target, html=bokeh_div)\n\n    data = {'text/html': html, 'application/javascript': bokeh_script}\n    return ({'text/html': mimebundle_to_html(data), EXEC_MIME: ''},\n            {EXEC_MIME: {'id': target}})\n\n\ndef render_mimebundle(model, doc, comm, manager=None, location=None):\n    \"\"\"\n    Displays bokeh output inside a notebook using the PyViz display\n    and comms machinery.\n    \"\"\"\n    if not isinstance(model, LayoutDOM):\n        raise ValueError('Can only render bokeh LayoutDOM models')\n    add_to_doc(model, doc, True)\n    if manager is not None:\n        doc.add_root(manager)\n    if location is not None:\n        loc = location._get_model(doc, model, model, comm)\n        doc.add_root(loc)\n    return render_model(model, comm)\n\n\ndef mimebundle_to_html(bundle):\n    \"\"\"\n    Converts a MIME bundle into HTML.\n    \"\"\"\n    if isinstance(bundle, tuple):\n        data, metadata = bundle\n    else:\n        data = bundle\n    html = data.get('text/html', '')\n    if 'application/javascript' in data:\n        js = data['application/javascript']\n        html += '\\n<script type=\"application/javascript\">{js}</script>'.format(js=js)\n    return html\n\n#---------------------------------------------------------------------\n# Public API\n#---------------------------------------------------------------------\n\n\n@contextmanager\ndef block_comm():\n    \"\"\"\n    Context manager to temporarily block comm push\n    \"\"\"\n    state._hold = True\n    try:\n        yield\n    finally:\n        state._hold = False\n\n\ndef load_notebook(inline=True, load_timeout=5000):\n    from IPython.display import publish_display_data\n\n    resources = INLINE if inline else CDN\n    prev_resources = settings.resources()\n    try:\n        settings.resources = 'cdn'\n        bundle = bundle_for_objs_and_resources(None, resources)\n        configs, requirements, exports, skip_imports = require_components()\n        ipywidget = 'ipywidgets_bokeh' in sys.modules\n        bokeh_js = _autoload_js(bundle, configs, requirements, exports,\n                                skip_imports, ipywidget, load_timeout)\n    finally:\n        settings.resources = prev_resources\n\n    publish_display_data({\n        'application/javascript': bokeh_js,\n        LOAD_MIME: bokeh_js,\n    })\n    bokeh.io.notebook.curstate().output_notebook()\n\n    # Publish comm manager\n    JS = '\\n'.join([PYVIZ_PROXY, _JupyterCommManager.js_manager, nb_mime_js])\n    publish_display_data(data={LOAD_MIME: JS, 'application/javascript': JS})\n\n\ndef show_server(panel, notebook_url, port):\n    \"\"\"\n    Displays a bokeh server inline in the notebook.\n\n    Arguments\n    ---------\n    panel: Viewable\n      Panel Viewable object to launch a server for\n    notebook_url: str\n      The URL of the running Jupyter notebook server\n    port: int (optional, default=0)\n      Allows specifying a specific port\n    server_id: str\n      Unique ID to identify the server with\n\n    Returns\n    -------\n    server: bokeh.server.Server\n    \"\"\"\n    from IPython.display import publish_display_data\n\n    if callable(notebook_url):\n        origin = notebook_url(None)\n    else:\n        origin = _origin_url(notebook_url)\n    server_id = uuid.uuid4().hex\n    server = get_server(panel, port=port, websocket_origin=origin,\n                        start=True, show=False, server_id=server_id)\n\n    if callable(notebook_url):\n        url = notebook_url(server.port)\n    else:\n        url = _server_url(notebook_url, server.port)\n\n    script = server_document(url, resources=None)\n\n    publish_display_data({\n        HTML_MIME: script,\n        EXEC_MIME: \"\"\n    }, metadata={\n        EXEC_MIME: {\"server_id\": server_id}\n    })\n    return server\n\n\ndef show_embed(panel, max_states=1000, max_opts=3, json=False,\n               json_prefix='', save_path='./', load_path=None,\n               progress=True, states={}):\n    \"\"\"\n    Renders a static version of a panel in a notebook by evaluating\n    the set of states defined by the widgets in the model. Note\n    this will only work well for simple apps with a relatively\n    small state space.\n\n    Arguments\n    ---------\n    max_states: int\n      The maximum number of states to embed\n    max_opts: int\n      The maximum number of states for a single widget\n    json: boolean (default=True)\n      Whether to export the data to json files\n    json_prefix: str (default='')\n      Prefix for JSON filename\n    save_path: str (default='./')\n      The path to save json files to\n    load_path: str (default=None)\n      The path or URL the json files will be loaded from.\n    progress: boolean (default=False)\n      Whether to report progress\n    states: dict (default={})\n      A dictionary specifying the widget values to embed for each widget\n    \"\"\"\n    from IPython.display import publish_display_data\n    from ..config import config\n\n    doc = Document()\n    comm = Comm()\n    with config.set(embed=True):\n        model = panel.get_root(doc, comm)\n        embed_state(panel, model, doc, max_states, max_opts,\n                    json, json_prefix, save_path, load_path, progress,\n                    states)\n    publish_display_data(*render_model(model))\n\n\ndef ipywidget(obj, **kwargs):\n    \"\"\"\n    Creates a root model from the Panel object and wraps it in\n    a jupyter_bokeh ipywidget BokehModel.\n\n    Arguments\n    ---------\n    obj: object\n      Any Panel object or object which can be rendered with Panel\n    **kwargs: dict\n      Keyword arguments passed to the pn.panel utility function\n\n    Returns\n    -------\n    Returns an ipywidget model which renders the Panel object.\n    \"\"\"\n    from jupyter_bokeh import BokehModel\n    from ..pane import panel\n    model = panel(obj, **kwargs).get_root()\n    widget = BokehModel(model, combine_events=True)\n    if hasattr(widget, '_view_count'):\n        widget._view_count = 0\n        def view_count_changed(change, current=[model]):\n            new_model = None\n            if change['old'] > 0 and change['new'] == 0 and current:\n                obj._cleanup(current[0])\n                current[:] = []\n            elif (change['old'] == 0 and change['new'] > 0 and\n                  (not current or current[0] is not model)):\n                if current:\n                    try:\n                        obj._cleanup(current[0])\n                    except Exception:\n                        pass\n                new_model = obj.get_root()\n                widget.update_from_model(new_model)\n                current[:] = [new_model]\n        widget.observe(view_count_changed, '_view_count')\n    return widget\n", "path": "panel/io/notebook.py"}], "after_files": [{"content": "\"\"\"\nVarious utilities for loading JS dependencies and rendering plots\ninside the Jupyter notebook.\n\"\"\"\nfrom __future__ import absolute_import, division, unicode_literals\n\nimport json\nimport uuid\nimport sys\n\nfrom contextlib import contextmanager\nfrom collections import OrderedDict\nfrom six import string_types\n\nimport bokeh\nimport bokeh.embed.notebook\n\nfrom bokeh.core.json_encoder import serialize_json\nfrom bokeh.core.templates import MACROS\nfrom bokeh.document import Document\nfrom bokeh.embed import server_document\nfrom bokeh.embed.bundle import bundle_for_objs_and_resources\nfrom bokeh.embed.elements import div_for_render_item, script_for_render_items\nfrom bokeh.embed.util import standalone_docs_json_and_render_items\nfrom bokeh.embed.wrappers import wrap_in_script_tag\nfrom bokeh.models import LayoutDOM, Model\nfrom bokeh.resources import CDN, INLINE\nfrom bokeh.settings import settings, _Unset\nfrom bokeh.util.serialization import make_id\nfrom pyviz_comms import (\n    PYVIZ_PROXY, Comm, JupyterCommManager as _JupyterCommManager, nb_mime_js\n)\n\ntry:\n    from bokeh.util.string import escape\nexcept Exception:\n    from html import escape\n\nfrom ..compiler import require_components\nfrom .embed import embed_state\nfrom .model import add_to_doc, diff\nfrom .resources import _env\nfrom .server import _server_url, _origin_url, get_server\nfrom .state import state\n\n\n#---------------------------------------------------------------------\n# Private API\n#---------------------------------------------------------------------\n\nLOAD_MIME = 'application/vnd.holoviews_load.v0+json'\nEXEC_MIME = 'application/vnd.holoviews_exec.v0+json'\nHTML_MIME = 'text/html'\n\ndef push(doc, comm, binary=True):\n    \"\"\"\n    Pushes events stored on the document across the provided comm.\n    \"\"\"\n    msg = diff(doc, binary=binary)\n    if msg is None:\n        return\n    comm.send(msg.header_json)\n    comm.send(msg.metadata_json)\n    comm.send(msg.content_json)\n    for header, payload in msg.buffers:\n        comm.send(json.dumps(header))\n        comm.send(buffers=[payload])\n\nDOC_NB_JS = _env.get_template(\"doc_nb_js.js\")\nAUTOLOAD_NB_JS = _env.get_template(\"autoload_panel_js.js\")\nNB_TEMPLATE_BASE = _env.get_template('nb_template.html')\n\ndef _autoload_js(bundle, configs, requirements, exports, skip_imports, ipywidget, load_timeout=5000):\n    return AUTOLOAD_NB_JS.render(\n        bundle    = bundle,\n        force     = True,\n        timeout   = load_timeout,\n        configs   = configs,\n        requirements = requirements,\n        exports   = exports,\n        skip_imports = skip_imports,\n        ipywidget = ipywidget\n    )\n\n\ndef html_for_render_items(docs_json, render_items, template=None, template_variables={}):\n    json_id = make_id()\n    json = escape(serialize_json(docs_json), quote=False)\n    json = wrap_in_script_tag(json, \"application/json\", json_id)\n\n    script = wrap_in_script_tag(script_for_render_items(json_id, render_items))\n\n    context = template_variables.copy()\n\n    context.update(dict(\n        title = '',\n        plot_script = json + script,\n        docs = render_items,\n        base = NB_TEMPLATE_BASE,\n        macros = MACROS,\n    ))\n\n    if len(render_items) == 1:\n        context[\"doc\"] = context[\"docs\"][0]\n        context[\"roots\"] = context[\"doc\"].roots\n\n    if template is None:\n        template = NB_TEMPLATE_BASE\n    elif isinstance(template, string_types):\n        template = _env.from_string(\"{% extends base %}\\n\" + template)\n\n    return template.render(context)\n\n\ndef render_template(document, comm=None, manager=None):\n    ref = document.roots[0].ref['id']\n    (docs_json, render_items) = standalone_docs_json_and_render_items(document, True)\n\n    # We do not want the CommManager to appear in the roots because\n    # the custom template may not reference it\n    if manager:\n        item = render_items[0]\n        item.roots._roots = OrderedDict(list(item.roots._roots.items())[:-1])\n\n    html = html_for_render_items(\n        docs_json, render_items, template=document.template,\n        template_variables=document.template_variables\n    )\n    return ({'text/html': html, EXEC_MIME: ''}, {EXEC_MIME: {'id': ref}})\n\n\ndef render_model(model, comm=None):\n    if not isinstance(model, Model):\n        raise ValueError(\"notebook_content expects a single Model instance\")\n    from ..config import panel_extension as pnext\n\n    target = model.ref['id']\n\n    (docs_json, [render_item]) = standalone_docs_json_and_render_items([model], True)\n    div = div_for_render_item(render_item)\n    render_item = render_item.to_json()\n    requirements = [pnext._globals[ext] for ext in pnext._loaded_extensions\n                    if ext in pnext._globals]\n    ipywidget = 'ipywidgets_bokeh' in sys.modules\n\n    script = DOC_NB_JS.render(\n        docs_json=serialize_json(docs_json),\n        render_items=serialize_json([render_item]),\n        requirements=requirements,\n        ipywidget=ipywidget\n    )\n    bokeh_script, bokeh_div = script, div\n    html = \"<div id='{id}'>{html}</div>\".format(id=target, html=bokeh_div)\n\n    data = {'text/html': html, 'application/javascript': bokeh_script}\n    return ({'text/html': mimebundle_to_html(data), EXEC_MIME: ''},\n            {EXEC_MIME: {'id': target}})\n\n\ndef render_mimebundle(model, doc, comm, manager=None, location=None):\n    \"\"\"\n    Displays bokeh output inside a notebook using the PyViz display\n    and comms machinery.\n    \"\"\"\n    if not isinstance(model, LayoutDOM):\n        raise ValueError('Can only render bokeh LayoutDOM models')\n    add_to_doc(model, doc, True)\n    if manager is not None:\n        doc.add_root(manager)\n    if location is not None:\n        loc = location._get_model(doc, model, model, comm)\n        doc.add_root(loc)\n    return render_model(model, comm)\n\n\ndef mimebundle_to_html(bundle):\n    \"\"\"\n    Converts a MIME bundle into HTML.\n    \"\"\"\n    if isinstance(bundle, tuple):\n        data, metadata = bundle\n    else:\n        data = bundle\n    html = data.get('text/html', '')\n    if 'application/javascript' in data:\n        js = data['application/javascript']\n        html += '\\n<script type=\"application/javascript\">{js}</script>'.format(js=js)\n    return html\n\n#---------------------------------------------------------------------\n# Public API\n#---------------------------------------------------------------------\n\n\n@contextmanager\ndef block_comm():\n    \"\"\"\n    Context manager to temporarily block comm push\n    \"\"\"\n    state._hold = True\n    try:\n        yield\n    finally:\n        state._hold = False\n\n\ndef load_notebook(inline=True, load_timeout=5000):\n    from IPython.display import publish_display_data\n\n    resources = INLINE if inline else CDN\n    prev_resources = settings.resources(default=\"server\")\n    user_resources = settings.resources._user_value is not _Unset\n    try:\n        settings.resources = 'inline' if inline else 'cdn'\n        bundle = bundle_for_objs_and_resources(None, resources)\n        configs, requirements, exports, skip_imports = require_components()\n        ipywidget = 'ipywidgets_bokeh' in sys.modules\n        bokeh_js = _autoload_js(bundle, configs, requirements, exports,\n                                skip_imports, ipywidget, load_timeout)\n    finally:\n        if user_resources:\n            settings.resources = prev_resources\n        else:\n            settings.resources.unset_value()\n\n    publish_display_data({\n        'application/javascript': bokeh_js,\n        LOAD_MIME: bokeh_js,\n    })\n    bokeh.io.notebook.curstate().output_notebook()\n\n    # Publish comm manager\n    JS = '\\n'.join([PYVIZ_PROXY, _JupyterCommManager.js_manager, nb_mime_js])\n    publish_display_data(data={LOAD_MIME: JS, 'application/javascript': JS})\n\n\ndef show_server(panel, notebook_url, port):\n    \"\"\"\n    Displays a bokeh server inline in the notebook.\n\n    Arguments\n    ---------\n    panel: Viewable\n      Panel Viewable object to launch a server for\n    notebook_url: str\n      The URL of the running Jupyter notebook server\n    port: int (optional, default=0)\n      Allows specifying a specific port\n    server_id: str\n      Unique ID to identify the server with\n\n    Returns\n    -------\n    server: bokeh.server.Server\n    \"\"\"\n    from IPython.display import publish_display_data\n\n    if callable(notebook_url):\n        origin = notebook_url(None)\n    else:\n        origin = _origin_url(notebook_url)\n    server_id = uuid.uuid4().hex\n    server = get_server(panel, port=port, websocket_origin=origin,\n                        start=True, show=False, server_id=server_id)\n\n    if callable(notebook_url):\n        url = notebook_url(server.port)\n    else:\n        url = _server_url(notebook_url, server.port)\n\n    script = server_document(url, resources=None)\n\n    publish_display_data({\n        HTML_MIME: script,\n        EXEC_MIME: \"\"\n    }, metadata={\n        EXEC_MIME: {\"server_id\": server_id}\n    })\n    return server\n\n\ndef show_embed(panel, max_states=1000, max_opts=3, json=False,\n               json_prefix='', save_path='./', load_path=None,\n               progress=True, states={}):\n    \"\"\"\n    Renders a static version of a panel in a notebook by evaluating\n    the set of states defined by the widgets in the model. Note\n    this will only work well for simple apps with a relatively\n    small state space.\n\n    Arguments\n    ---------\n    max_states: int\n      The maximum number of states to embed\n    max_opts: int\n      The maximum number of states for a single widget\n    json: boolean (default=True)\n      Whether to export the data to json files\n    json_prefix: str (default='')\n      Prefix for JSON filename\n    save_path: str (default='./')\n      The path to save json files to\n    load_path: str (default=None)\n      The path or URL the json files will be loaded from.\n    progress: boolean (default=False)\n      Whether to report progress\n    states: dict (default={})\n      A dictionary specifying the widget values to embed for each widget\n    \"\"\"\n    from IPython.display import publish_display_data\n    from ..config import config\n\n    doc = Document()\n    comm = Comm()\n    with config.set(embed=True):\n        model = panel.get_root(doc, comm)\n        embed_state(panel, model, doc, max_states, max_opts,\n                    json, json_prefix, save_path, load_path, progress,\n                    states)\n    publish_display_data(*render_model(model))\n\n\ndef ipywidget(obj, **kwargs):\n    \"\"\"\n    Creates a root model from the Panel object and wraps it in\n    a jupyter_bokeh ipywidget BokehModel.\n\n    Arguments\n    ---------\n    obj: object\n      Any Panel object or object which can be rendered with Panel\n    **kwargs: dict\n      Keyword arguments passed to the pn.panel utility function\n\n    Returns\n    -------\n    Returns an ipywidget model which renders the Panel object.\n    \"\"\"\n    from jupyter_bokeh import BokehModel\n    from ..pane import panel\n    model = panel(obj, **kwargs).get_root()\n    widget = BokehModel(model, combine_events=True)\n    if hasattr(widget, '_view_count'):\n        widget._view_count = 0\n        def view_count_changed(change, current=[model]):\n            new_model = None\n            if change['old'] > 0 and change['new'] == 0 and current:\n                obj._cleanup(current[0])\n                current[:] = []\n            elif (change['old'] == 0 and change['new'] > 0 and\n                  (not current or current[0] is not model)):\n                if current:\n                    try:\n                        obj._cleanup(current[0])\n                    except Exception:\n                        pass\n                new_model = obj.get_root()\n                widget.update_from_model(new_model)\n                current[:] = [new_model]\n        widget.observe(view_count_changed, '_view_count')\n    return widget\n", "path": "panel/io/notebook.py"}]}