We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Components on multiple objects duplicates objects in all_models
This can causes models to be initialized more than once, which causes errors. Need to protect on both the python and JS sides. 


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `bokeh/embed.py`
Content:
```
1 ''' This module provides functions for embedding Bokeh plots in various
2 different ways.
3 
4 There are a number of different combinations of options when embedding
5 Bokeh plots. The data for the plot can be contained in the document,
6 or on a Bokeh server, or in a sidecar JavaScript file. Likewise, BokehJS
7 may be inlined in the document, or loaded from CDN or a Bokeh server.
8 
9 The functions in ``bokeh.embed`` provide functionality to embed in all
10 these different cases.
11 
12 '''
13 
14 from __future__ import absolute_import
15 
16 from warnings import warn
17 import uuid
18 
19 from .protocol import serialize_json
20 from .resources import Resources
21 from .templates import (
22     AUTOLOAD, AUTOLOAD_SERVER, AUTOLOAD_STATIC, FILE,
23     NOTEBOOK_DIV, PLOT_DIV, PLOT_JS, PLOT_SCRIPT, RESOURCES
24 )
25 from .util.string import encode_utf8
26 
27 from .plot_object import PlotObject
28 from collections import Sequence
29 from six import string_types
30 
31 def _wrap_in_function(code):
32     # Indent and wrap Bokeh function def around
33     code = "\n".join([ "    " + line for line in code.split("\n") ])
34     return 'Bokeh.$(function() {\n%s\n});' % code
35 
36 
37 def components(plot_objects, resources=None):
38     ''' Return HTML components to embed a Bokeh plot.
39 
40     The data for the plot is stored directly in the returned HTML.
41 
42     .. note:: The returned components assume that BokehJS resources
43               are **already loaded**.
44 
45     Args:
46         plot_objects (PlotObject|list|dict|tuple) :
47         The |components| function takes either a single PlotObject, a list/tuple of
48         PlotObjects, or a dictionary of keys and PlotObjects. Each returns
49         a corresponding data structure of script and div pairs.
50 
51         The following illustrates how different input types correlate to outputs:
52 
53             components(plot)
54             #=> (script, plot_div)
55 
56             components((plot_1, plot_2))
57             #=> (script, (plot_1_div, plot_2_div))
58 
59             components({"Plot 1": plot_1, "Plot 2": plot_2})
60             #=> (script, {"Plot 1": plot_1_div, "Plot 2": plot_2_div})
61 
62         An example can be found in examples/embed/embed_multiple.py
63 
64         resources : Deprecated argument
65 
66     Returns:
67         (script, div[s]): UTF-8 encoded
68     '''
69     from .document import Document
70     if isinstance(plot_objects, (PlotObject, Document)):
71         plot_objects = [plot_objects]
72     if resources is not None:
73         warn('Because the ``resources`` argument is no longer needed, '
74              'it is deprecated and will be removed in'
75              'a future version.', DeprecationWarning, stacklevel=2)
76     all_models = []
77     plots = []
78     if isinstance(plot_objects, Sequence) and all(isinstance(x, (PlotObject, Document)) for x in plot_objects):
79         divs = []
80         for idx, plot_object in enumerate(plot_objects):
81             elementid = str(uuid.uuid4())
82             _append_plot(all_models, plots, plot_object, elementid)
83             divs = _append_div(elementid, divs)
84         if len(divs) == 1:
85             divs = divs[0]
86         else:
87             divs = tuple(divs)
88         return _component_pair(all_models, plots, divs)
89     elif isinstance(plot_objects, dict) and \
90          all(isinstance(x, string_types) for x in plot_objects.keys()) and \
91          all(isinstance(x, (PlotObject, Document)) for x in plot_objects.values()):
92         divs = {}
93         for key in plot_objects.keys():
94             elementid = str(uuid.uuid4())
95             _append_plot(all_models, plots, plot_objects[key], elementid)
96             divs = _append_div(elementid, divs, key)
97         return _component_pair(all_models, plots, divs)
98     else:
99         raise ValueError('Input must be a PlotObject, a Sequence of PlotObjects, or a mapping of string to PlotObjects')
100 
101 def _component_pair(all_models, plots, divs):
102     js = PLOT_JS.render(
103         all_models = serialize_json(all_models),
104         plots = plots
105     )
106     script = PLOT_SCRIPT.render(
107         plot_js = _wrap_in_function(js),
108     )
109     return encode_utf8(script), divs
110 
111 def _append_plot(all_models, plots, plot_object, elementid):
112     ref = plot_object.ref
113     all_models.extend(plot_object.dump())
114     plots.append({
115         'modelid': ref["id"],
116         'elementid': '#' + elementid,
117         'modeltype': ref["type"]
118     })
119 
120 def _append_div(elementid, divs=None, key=None):
121     div = PLOT_DIV.render(
122         elementid = elementid
123     )
124     if isinstance(divs, list):
125         divs.append(encode_utf8(div))
126         return divs
127     elif isinstance(divs, dict):
128         divs[key] = encode_utf8(div)
129         return divs
130     else:
131         return encode_utf8(div)
132 
133 def notebook_div(plot_object):
134     ''' Return HTML for a div that will display a Bokeh plot in an
135     IPython Notebook
136 
137     The data for the plot is stored directly in the returned HTML.
138 
139     Args:
140         plot_object (PlotObject) : Bokeh object to render
141             typically a Plot or PlotContext
142 
143     Returns:
144         div : UTF-8 encoded HTML text
145 
146     .. note::
147         Assumes ``bokeh.load_notebook()`` or the equivalent has already
148         been executed.
149 
150     '''
151     ref = plot_object.ref
152     elementid = str(uuid.uuid4())
153 
154     plots = [{
155         'modelid': ref["id"],
156         'elementid': '#' + elementid,
157         'modeltype': ref["type"]
158     }]
159 
160     js = PLOT_JS.render(
161         all_models = serialize_json(plot_object.dump()),
162         plots = plots
163     )
164     script = PLOT_SCRIPT.render(
165         plot_js = _wrap_in_function(js),
166     )
167     div = PLOT_DIV.render(elementid=elementid)
168     html = NOTEBOOK_DIV.render(
169         plot_script = script,
170         plot_div = div,
171     )
172     return encode_utf8(html)
173 
174 
175 def file_html(plot_object, resources, title, template=FILE, template_variables=None):
176     ''' Return an HTML document that embeds a Bokeh plot.
177 
178     The data for the plot is stored directly in the returned HTML.
179 
180     Args:
181         plot_object (PlotObject) : Bokeh object to render
182             typically a Plot or PlotContext
183         resources (Resources) : a resource configuration for BokehJS assets
184         title (str) : a title for the HTML document ``<title>`` tags
185         template (Template, optional) : HTML document template (default: FILE)
186             A Jinja2 Template, see bokeh.templates.FILE for the required
187             template parameters
188         template_variables (dict, optional) : variables to be used in the Jinja2
189             template. If used, the following variable names will be overwritten:
190             title, plot_resources, plot_script, plot_div
191 
192     Returns:
193         html : standalone HTML document with embedded plot
194 
195     '''
196     from .document import Document
197     if not isinstance(plot_object, (PlotObject, Document)):
198         raise ValueError('plot_object must be a single PlotObject')
199 
200     plot_resources = RESOURCES.render(
201         js_raw = resources.js_raw,
202         css_raw = resources.css_raw,
203         js_files = resources.js_files,
204         css_files = resources.css_files,
205     )
206     script, div = components(plot_object)
207     template_variables_full = \
208         template_variables.copy() if template_variables is not None else {}
209     template_variables_full.update(
210         {
211             'title': title,
212             'plot_resources': plot_resources,
213             'plot_script': script,
214             'plot_div': div,
215         }
216     )
217     html = template.render(template_variables_full)
218     return encode_utf8(html)
219 
220 
221 def autoload_static(plot_object, resources, script_path):
222     ''' Return JavaScript code and a script tag that can be used to embed
223     Bokeh Plots.
224 
225     The data for the plot is stored directly in the returned JavaScript code.
226 
227     Args:
228         plot_object (PlotObject) :
229         resources (Resources) :
230         script_path (str) :
231 
232     Returns:
233         (js, tag) :
234             JavaScript code to be saved at ``script_path`` and a ``<script>``
235             tag to load it
236 
237     Raises:
238         ValueError
239 
240     '''
241     if resources.mode == 'inline':
242         raise ValueError("autoload_static() requires non-inline resources")
243 
244     if resources.dev:
245         raise ValueError("autoload_static() only works with non-dev resources")
246 
247     elementid = str(uuid.uuid4())
248 
249     js = AUTOLOAD.render(
250         all_models = serialize_json(plot_object.dump()),
251         js_url = resources.js_files[0],
252         css_files = resources.css_files,
253         elementid = elementid,
254     )
255 
256     tag = AUTOLOAD_STATIC.render(
257         src_path = script_path,
258         elementid = elementid,
259         modelid = plot_object._id,
260         modeltype = plot_object.__view_model__,
261         loglevel = resources.log_level,
262     )
263 
264     return encode_utf8(js), encode_utf8(tag)
265 
266 
267 def autoload_server(plot_object, session, public=False):
268     ''' Return a script tag that can be used to embed Bokeh Plots from
269     a Bokeh Server.
270 
271     The data for the plot is stored on the Bokeh Server.
272 
273     Args:
274         plot_object (PlotObject) :
275         session (Session) :
276 
277     Returns:
278         tag :
279             a ``<script>`` tag that will execute an autoload script
280             loaded from the Bokeh Server
281 
282     '''
283     elementid = str(uuid.uuid4())
284     resources = Resources(root_url=session.root_url, mode="server")
285     tag = AUTOLOAD_SERVER.render(
286         src_path = resources._autoload_path(elementid),
287         elementid = elementid,
288         modelid = plot_object._id,
289         root_url = resources.root_url,
290         docid =  session.docid,
291         docapikey = session.apikey,
292         loglevel = resources.log_level,
293         public = public
294     )
295 
296     return encode_utf8(tag)
297
```

Path: `examples/plotting/file/ajax_source_realtime.py`
Content:
```
1 import numpy as np
2 
3 from bokeh.plotting import figure, show, output_file
4 from bokeh.models.sources import AjaxDataSource
5 
6 output_file("ajax_source_realtime.html", title="ajax_source_realtime.py example")
7 source = AjaxDataSource(data_url='http://localhost:5050/data', mode="append",
8                         if_modified=True, polling_interval=1000, max_size=125)
9 p = figure()
10 p.line('x', 'y', source=source)
11 show(p)
12 
13 import time
14 from threading import Thread
15 from collections import namedtuple, deque
16 
17 Entry = namedtuple('Entry', ['x', 'y', 'creation'])
18 
19 entries = deque(maxlen=120)
20 
21 def gen_entry():
22     global entries
23     x = 0
24     while True:
25         last_entry = Entry(x, np.sin(x*np.pi/10), time.time())
26         entries.append(last_entry)
27         print("Entry generated: %s" % str(last_entry))
28         x += 1
29         if x > entries.maxlen and x % 10 == 0:
30             time.sleep(2)
31 
32 t = Thread(target=gen_entry)
33 t.daemon = True
34 t.start()
35 
36 import json
37 from flask import Flask, Response, request
38 from bokeh.server.crossdomain import crossdomain
39 
40 app = Flask(__name__)
41 
42 @app.route('/data', methods=['GET', 'OPTIONS'])
43 @crossdomain(origin="*", methods=['GET', 'POST'])
44 def hello_world():
45     global entries
46     try:
47         modified_since = float(request.headers.get('If-Modified-Since'))
48     except TypeError:
49         modified_since = 0
50 
51     new_entries = [e for e in entries if e.creation > modified_since]
52     js = json.dumps({'x':[e.x for e in new_entries], 'y':[e.y for e in new_entries]})
53     resp = Response(js, status=200, mimetype='application/json')
54 
55     if new_entries:
56         resp.headers['Last-Modified'] = new_entries[-1].creation
57     elif modified_since:
58         resp.headers['Last-Modified'] = modified_since
59 
60     return resp
61 
62 if __name__ ==  "__main__":
63     app.run(port=5050)
64
```
--- 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/bokeh/embed.py b/bokeh/embed.py
--- a/bokeh/embed.py
+++ b/bokeh/embed.py
@@ -73,7 +73,7 @@
         warn('Because the ``resources`` argument is no longer needed, '
              'it is deprecated and will be removed in'
              'a future version.', DeprecationWarning, stacklevel=2)
-    all_models = []
+    all_models = dict()
     plots = []
     if isinstance(plot_objects, Sequence) and all(isinstance(x, (PlotObject, Document)) for x in plot_objects):
         divs = []
@@ -85,7 +85,7 @@
             divs = divs[0]
         else:
             divs = tuple(divs)
-        return _component_pair(all_models, plots, divs)
+        return _component_pair(list(all_models.values()), plots, divs)
     elif isinstance(plot_objects, dict) and \
          all(isinstance(x, string_types) for x in plot_objects.keys()) and \
          all(isinstance(x, (PlotObject, Document)) for x in plot_objects.values()):
@@ -94,7 +94,7 @@
             elementid = str(uuid.uuid4())
             _append_plot(all_models, plots, plot_objects[key], elementid)
             divs = _append_div(elementid, divs, key)
-        return _component_pair(all_models, plots, divs)
+        return _component_pair(list(all_models.values()), plots, divs)
     else:
         raise ValueError('Input must be a PlotObject, a Sequence of PlotObjects, or a mapping of string to PlotObjects')
 
@@ -110,7 +110,8 @@
 
 def _append_plot(all_models, plots, plot_object, elementid):
     ref = plot_object.ref
-    all_models.extend(plot_object.dump())
+    for item in plot_object.dump():
+        all_models[item['id']] = item
     plots.append({
         'modelid': ref["id"],
         'elementid': '#' + elementid,
diff --git a/examples/plotting/file/ajax_source_realtime.py b/examples/plotting/file/ajax_source_realtime.py
--- a/examples/plotting/file/ajax_source_realtime.py
+++ b/examples/plotting/file/ajax_source_realtime.py
@@ -24,7 +24,6 @@
     while True:
         last_entry = Entry(x, np.sin(x*np.pi/10), time.time())
         entries.append(last_entry)
-        print("Entry generated: %s" % str(last_entry))
         x += 1
         if x > entries.maxlen and x % 10 == 0:
             time.sleep(2)

{"golden_diff": "diff --git a/bokeh/embed.py b/bokeh/embed.py\n--- a/bokeh/embed.py\n+++ b/bokeh/embed.py\n@@ -73,7 +73,7 @@\n         warn('Because the ``resources`` argument is no longer needed, '\n              'it is deprecated and will be removed in'\n              'a future version.', DeprecationWarning, stacklevel=2)\n-    all_models = []\n+    all_models = dict()\n     plots = []\n     if isinstance(plot_objects, Sequence) and all(isinstance(x, (PlotObject, Document)) for x in plot_objects):\n         divs = []\n@@ -85,7 +85,7 @@\n             divs = divs[0]\n         else:\n             divs = tuple(divs)\n-        return _component_pair(all_models, plots, divs)\n+        return _component_pair(list(all_models.values()), plots, divs)\n     elif isinstance(plot_objects, dict) and \\\n          all(isinstance(x, string_types) for x in plot_objects.keys()) and \\\n          all(isinstance(x, (PlotObject, Document)) for x in plot_objects.values()):\n@@ -94,7 +94,7 @@\n             elementid = str(uuid.uuid4())\n             _append_plot(all_models, plots, plot_objects[key], elementid)\n             divs = _append_div(elementid, divs, key)\n-        return _component_pair(all_models, plots, divs)\n+        return _component_pair(list(all_models.values()), plots, divs)\n     else:\n         raise ValueError('Input must be a PlotObject, a Sequence of PlotObjects, or a mapping of string to PlotObjects')\n \n@@ -110,7 +110,8 @@\n \n def _append_plot(all_models, plots, plot_object, elementid):\n     ref = plot_object.ref\n-    all_models.extend(plot_object.dump())\n+    for item in plot_object.dump():\n+        all_models[item['id']] = item\n     plots.append({\n         'modelid': ref[\"id\"],\n         'elementid': '#' + elementid,\ndiff --git a/examples/plotting/file/ajax_source_realtime.py b/examples/plotting/file/ajax_source_realtime.py\n--- a/examples/plotting/file/ajax_source_realtime.py\n+++ b/examples/plotting/file/ajax_source_realtime.py\n@@ -24,7 +24,6 @@\n     while True:\n         last_entry = Entry(x, np.sin(x*np.pi/10), time.time())\n         entries.append(last_entry)\n-        print(\"Entry generated: %s\" % str(last_entry))\n         x += 1\n         if x > entries.maxlen and x % 10 == 0:\n             time.sleep(2)\n", "issue": "Components on multiple objects duplicates objects in all_models\nThis can causes models to be initialized more than once, which causes errors. Need to protect on both the python and JS sides. \n\n", "before_files": [{"content": "''' This module provides functions for embedding Bokeh plots in various\ndifferent ways.\n\nThere are a number of different combinations of options when embedding\nBokeh plots. The data for the plot can be contained in the document,\nor on a Bokeh server, or in a sidecar JavaScript file. Likewise, BokehJS\nmay be inlined in the document, or loaded from CDN or a Bokeh server.\n\nThe functions in ``bokeh.embed`` provide functionality to embed in all\nthese different cases.\n\n'''\n\nfrom __future__ import absolute_import\n\nfrom warnings import warn\nimport uuid\n\nfrom .protocol import serialize_json\nfrom .resources import Resources\nfrom .templates import (\n    AUTOLOAD, AUTOLOAD_SERVER, AUTOLOAD_STATIC, FILE,\n    NOTEBOOK_DIV, PLOT_DIV, PLOT_JS, PLOT_SCRIPT, RESOURCES\n)\nfrom .util.string import encode_utf8\n\nfrom .plot_object import PlotObject\nfrom collections import Sequence\nfrom six import string_types\n\ndef _wrap_in_function(code):\n    # Indent and wrap Bokeh function def around\n    code = \"\\n\".join([ \"    \" + line for line in code.split(\"\\n\") ])\n    return 'Bokeh.$(function() {\\n%s\\n});' % code\n\n\ndef components(plot_objects, resources=None):\n    ''' Return HTML components to embed a Bokeh plot.\n\n    The data for the plot is stored directly in the returned HTML.\n\n    .. note:: The returned components assume that BokehJS resources\n              are **already loaded**.\n\n    Args:\n        plot_objects (PlotObject|list|dict|tuple) :\n        The |components| function takes either a single PlotObject, a list/tuple of\n        PlotObjects, or a dictionary of keys and PlotObjects. Each returns\n        a corresponding data structure of script and div pairs.\n\n        The following illustrates how different input types correlate to outputs:\n\n            components(plot)\n            #=> (script, plot_div)\n\n            components((plot_1, plot_2))\n            #=> (script, (plot_1_div, plot_2_div))\n\n            components({\"Plot 1\": plot_1, \"Plot 2\": plot_2})\n            #=> (script, {\"Plot 1\": plot_1_div, \"Plot 2\": plot_2_div})\n\n        An example can be found in examples/embed/embed_multiple.py\n\n        resources : Deprecated argument\n\n    Returns:\n        (script, div[s]): UTF-8 encoded\n    '''\n    from .document import Document\n    if isinstance(plot_objects, (PlotObject, Document)):\n        plot_objects = [plot_objects]\n    if resources is not None:\n        warn('Because the ``resources`` argument is no longer needed, '\n             'it is deprecated and will be removed in'\n             'a future version.', DeprecationWarning, stacklevel=2)\n    all_models = []\n    plots = []\n    if isinstance(plot_objects, Sequence) and all(isinstance(x, (PlotObject, Document)) for x in plot_objects):\n        divs = []\n        for idx, plot_object in enumerate(plot_objects):\n            elementid = str(uuid.uuid4())\n            _append_plot(all_models, plots, plot_object, elementid)\n            divs = _append_div(elementid, divs)\n        if len(divs) == 1:\n            divs = divs[0]\n        else:\n            divs = tuple(divs)\n        return _component_pair(all_models, plots, divs)\n    elif isinstance(plot_objects, dict) and \\\n         all(isinstance(x, string_types) for x in plot_objects.keys()) and \\\n         all(isinstance(x, (PlotObject, Document)) for x in plot_objects.values()):\n        divs = {}\n        for key in plot_objects.keys():\n            elementid = str(uuid.uuid4())\n            _append_plot(all_models, plots, plot_objects[key], elementid)\n            divs = _append_div(elementid, divs, key)\n        return _component_pair(all_models, plots, divs)\n    else:\n        raise ValueError('Input must be a PlotObject, a Sequence of PlotObjects, or a mapping of string to PlotObjects')\n\ndef _component_pair(all_models, plots, divs):\n    js = PLOT_JS.render(\n        all_models = serialize_json(all_models),\n        plots = plots\n    )\n    script = PLOT_SCRIPT.render(\n        plot_js = _wrap_in_function(js),\n    )\n    return encode_utf8(script), divs\n\ndef _append_plot(all_models, plots, plot_object, elementid):\n    ref = plot_object.ref\n    all_models.extend(plot_object.dump())\n    plots.append({\n        'modelid': ref[\"id\"],\n        'elementid': '#' + elementid,\n        'modeltype': ref[\"type\"]\n    })\n\ndef _append_div(elementid, divs=None, key=None):\n    div = PLOT_DIV.render(\n        elementid = elementid\n    )\n    if isinstance(divs, list):\n        divs.append(encode_utf8(div))\n        return divs\n    elif isinstance(divs, dict):\n        divs[key] = encode_utf8(div)\n        return divs\n    else:\n        return encode_utf8(div)\n\ndef notebook_div(plot_object):\n    ''' Return HTML for a div that will display a Bokeh plot in an\n    IPython Notebook\n\n    The data for the plot is stored directly in the returned HTML.\n\n    Args:\n        plot_object (PlotObject) : Bokeh object to render\n            typically a Plot or PlotContext\n\n    Returns:\n        div : UTF-8 encoded HTML text\n\n    .. note::\n        Assumes ``bokeh.load_notebook()`` or the equivalent has already\n        been executed.\n\n    '''\n    ref = plot_object.ref\n    elementid = str(uuid.uuid4())\n\n    plots = [{\n        'modelid': ref[\"id\"],\n        'elementid': '#' + elementid,\n        'modeltype': ref[\"type\"]\n    }]\n\n    js = PLOT_JS.render(\n        all_models = serialize_json(plot_object.dump()),\n        plots = plots\n    )\n    script = PLOT_SCRIPT.render(\n        plot_js = _wrap_in_function(js),\n    )\n    div = PLOT_DIV.render(elementid=elementid)\n    html = NOTEBOOK_DIV.render(\n        plot_script = script,\n        plot_div = div,\n    )\n    return encode_utf8(html)\n\n\ndef file_html(plot_object, resources, title, template=FILE, template_variables=None):\n    ''' Return an HTML document that embeds a Bokeh plot.\n\n    The data for the plot is stored directly in the returned HTML.\n\n    Args:\n        plot_object (PlotObject) : Bokeh object to render\n            typically a Plot or PlotContext\n        resources (Resources) : a resource configuration for BokehJS assets\n        title (str) : a title for the HTML document ``<title>`` tags\n        template (Template, optional) : HTML document template (default: FILE)\n            A Jinja2 Template, see bokeh.templates.FILE for the required\n            template parameters\n        template_variables (dict, optional) : variables to be used in the Jinja2\n            template. If used, the following variable names will be overwritten:\n            title, plot_resources, plot_script, plot_div\n\n    Returns:\n        html : standalone HTML document with embedded plot\n\n    '''\n    from .document import Document\n    if not isinstance(plot_object, (PlotObject, Document)):\n        raise ValueError('plot_object must be a single PlotObject')\n\n    plot_resources = RESOURCES.render(\n        js_raw = resources.js_raw,\n        css_raw = resources.css_raw,\n        js_files = resources.js_files,\n        css_files = resources.css_files,\n    )\n    script, div = components(plot_object)\n    template_variables_full = \\\n        template_variables.copy() if template_variables is not None else {}\n    template_variables_full.update(\n        {\n            'title': title,\n            'plot_resources': plot_resources,\n            'plot_script': script,\n            'plot_div': div,\n        }\n    )\n    html = template.render(template_variables_full)\n    return encode_utf8(html)\n\n\ndef autoload_static(plot_object, resources, script_path):\n    ''' Return JavaScript code and a script tag that can be used to embed\n    Bokeh Plots.\n\n    The data for the plot is stored directly in the returned JavaScript code.\n\n    Args:\n        plot_object (PlotObject) :\n        resources (Resources) :\n        script_path (str) :\n\n    Returns:\n        (js, tag) :\n            JavaScript code to be saved at ``script_path`` and a ``<script>``\n            tag to load it\n\n    Raises:\n        ValueError\n\n    '''\n    if resources.mode == 'inline':\n        raise ValueError(\"autoload_static() requires non-inline resources\")\n\n    if resources.dev:\n        raise ValueError(\"autoload_static() only works with non-dev resources\")\n\n    elementid = str(uuid.uuid4())\n\n    js = AUTOLOAD.render(\n        all_models = serialize_json(plot_object.dump()),\n        js_url = resources.js_files[0],\n        css_files = resources.css_files,\n        elementid = elementid,\n    )\n\n    tag = AUTOLOAD_STATIC.render(\n        src_path = script_path,\n        elementid = elementid,\n        modelid = plot_object._id,\n        modeltype = plot_object.__view_model__,\n        loglevel = resources.log_level,\n    )\n\n    return encode_utf8(js), encode_utf8(tag)\n\n\ndef autoload_server(plot_object, session, public=False):\n    ''' Return a script tag that can be used to embed Bokeh Plots from\n    a Bokeh Server.\n\n    The data for the plot is stored on the Bokeh Server.\n\n    Args:\n        plot_object (PlotObject) :\n        session (Session) :\n\n    Returns:\n        tag :\n            a ``<script>`` tag that will execute an autoload script\n            loaded from the Bokeh Server\n\n    '''\n    elementid = str(uuid.uuid4())\n    resources = Resources(root_url=session.root_url, mode=\"server\")\n    tag = AUTOLOAD_SERVER.render(\n        src_path = resources._autoload_path(elementid),\n        elementid = elementid,\n        modelid = plot_object._id,\n        root_url = resources.root_url,\n        docid =  session.docid,\n        docapikey = session.apikey,\n        loglevel = resources.log_level,\n        public = public\n    )\n\n    return encode_utf8(tag)\n", "path": "bokeh/embed.py"}, {"content": "import numpy as np\n\nfrom bokeh.plotting import figure, show, output_file\nfrom bokeh.models.sources import AjaxDataSource\n\noutput_file(\"ajax_source_realtime.html\", title=\"ajax_source_realtime.py example\")\nsource = AjaxDataSource(data_url='http://localhost:5050/data', mode=\"append\",\n                        if_modified=True, polling_interval=1000, max_size=125)\np = figure()\np.line('x', 'y', source=source)\nshow(p)\n\nimport time\nfrom threading import Thread\nfrom collections import namedtuple, deque\n\nEntry = namedtuple('Entry', ['x', 'y', 'creation'])\n\nentries = deque(maxlen=120)\n\ndef gen_entry():\n    global entries\n    x = 0\n    while True:\n        last_entry = Entry(x, np.sin(x*np.pi/10), time.time())\n        entries.append(last_entry)\n        print(\"Entry generated: %s\" % str(last_entry))\n        x += 1\n        if x > entries.maxlen and x % 10 == 0:\n            time.sleep(2)\n\nt = Thread(target=gen_entry)\nt.daemon = True\nt.start()\n\nimport json\nfrom flask import Flask, Response, request\nfrom bokeh.server.crossdomain import crossdomain\n\napp = Flask(__name__)\n\n@app.route('/data', methods=['GET', 'OPTIONS'])\n@crossdomain(origin=\"*\", methods=['GET', 'POST'])\ndef hello_world():\n    global entries\n    try:\n        modified_since = float(request.headers.get('If-Modified-Since'))\n    except TypeError:\n        modified_since = 0\n\n    new_entries = [e for e in entries if e.creation > modified_since]\n    js = json.dumps({'x':[e.x for e in new_entries], 'y':[e.y for e in new_entries]})\n    resp = Response(js, status=200, mimetype='application/json')\n\n    if new_entries:\n        resp.headers['Last-Modified'] = new_entries[-1].creation\n    elif modified_since:\n        resp.headers['Last-Modified'] = modified_since\n\n    return resp\n\nif __name__ ==  \"__main__\":\n    app.run(port=5050)\n", "path": "examples/plotting/file/ajax_source_realtime.py"}], "after_files": [{"content": "''' This module provides functions for embedding Bokeh plots in various\ndifferent ways.\n\nThere are a number of different combinations of options when embedding\nBokeh plots. The data for the plot can be contained in the document,\nor on a Bokeh server, or in a sidecar JavaScript file. Likewise, BokehJS\nmay be inlined in the document, or loaded from CDN or a Bokeh server.\n\nThe functions in ``bokeh.embed`` provide functionality to embed in all\nthese different cases.\n\n'''\n\nfrom __future__ import absolute_import\n\nfrom warnings import warn\nimport uuid\n\nfrom .protocol import serialize_json\nfrom .resources import Resources\nfrom .templates import (\n    AUTOLOAD, AUTOLOAD_SERVER, AUTOLOAD_STATIC, FILE,\n    NOTEBOOK_DIV, PLOT_DIV, PLOT_JS, PLOT_SCRIPT, RESOURCES\n)\nfrom .util.string import encode_utf8\n\nfrom .plot_object import PlotObject\nfrom collections import Sequence\nfrom six import string_types\n\ndef _wrap_in_function(code):\n    # Indent and wrap Bokeh function def around\n    code = \"\\n\".join([ \"    \" + line for line in code.split(\"\\n\") ])\n    return 'Bokeh.$(function() {\\n%s\\n});' % code\n\n\ndef components(plot_objects, resources=None):\n    ''' Return HTML components to embed a Bokeh plot.\n\n    The data for the plot is stored directly in the returned HTML.\n\n    .. note:: The returned components assume that BokehJS resources\n              are **already loaded**.\n\n    Args:\n        plot_objects (PlotObject|list|dict|tuple) :\n        The |components| function takes either a single PlotObject, a list/tuple of\n        PlotObjects, or a dictionary of keys and PlotObjects. Each returns\n        a corresponding data structure of script and div pairs.\n\n        The following illustrates how different input types correlate to outputs:\n\n            components(plot)\n            #=> (script, plot_div)\n\n            components((plot_1, plot_2))\n            #=> (script, (plot_1_div, plot_2_div))\n\n            components({\"Plot 1\": plot_1, \"Plot 2\": plot_2})\n            #=> (script, {\"Plot 1\": plot_1_div, \"Plot 2\": plot_2_div})\n\n        An example can be found in examples/embed/embed_multiple.py\n\n        resources : Deprecated argument\n\n    Returns:\n        (script, div[s]): UTF-8 encoded\n    '''\n    from .document import Document\n    if isinstance(plot_objects, (PlotObject, Document)):\n        plot_objects = [plot_objects]\n    if resources is not None:\n        warn('Because the ``resources`` argument is no longer needed, '\n             'it is deprecated and will be removed in'\n             'a future version.', DeprecationWarning, stacklevel=2)\n    all_models = dict()\n    plots = []\n    if isinstance(plot_objects, Sequence) and all(isinstance(x, (PlotObject, Document)) for x in plot_objects):\n        divs = []\n        for idx, plot_object in enumerate(plot_objects):\n            elementid = str(uuid.uuid4())\n            _append_plot(all_models, plots, plot_object, elementid)\n            divs = _append_div(elementid, divs)\n        if len(divs) == 1:\n            divs = divs[0]\n        else:\n            divs = tuple(divs)\n        return _component_pair(list(all_models.values()), plots, divs)\n    elif isinstance(plot_objects, dict) and \\\n         all(isinstance(x, string_types) for x in plot_objects.keys()) and \\\n         all(isinstance(x, (PlotObject, Document)) for x in plot_objects.values()):\n        divs = {}\n        for key in plot_objects.keys():\n            elementid = str(uuid.uuid4())\n            _append_plot(all_models, plots, plot_objects[key], elementid)\n            divs = _append_div(elementid, divs, key)\n        return _component_pair(list(all_models.values()), plots, divs)\n    else:\n        raise ValueError('Input must be a PlotObject, a Sequence of PlotObjects, or a mapping of string to PlotObjects')\n\ndef _component_pair(all_models, plots, divs):\n    js = PLOT_JS.render(\n        all_models = serialize_json(all_models),\n        plots = plots\n    )\n    script = PLOT_SCRIPT.render(\n        plot_js = _wrap_in_function(js),\n    )\n    return encode_utf8(script), divs\n\ndef _append_plot(all_models, plots, plot_object, elementid):\n    ref = plot_object.ref\n    for item in plot_object.dump():\n        all_models[item['id']] = item\n    plots.append({\n        'modelid': ref[\"id\"],\n        'elementid': '#' + elementid,\n        'modeltype': ref[\"type\"]\n    })\n\ndef _append_div(elementid, divs=None, key=None):\n    div = PLOT_DIV.render(\n        elementid = elementid\n    )\n    if isinstance(divs, list):\n        divs.append(encode_utf8(div))\n        return divs\n    elif isinstance(divs, dict):\n        divs[key] = encode_utf8(div)\n        return divs\n    else:\n        return encode_utf8(div)\n\ndef notebook_div(plot_object):\n    ''' Return HTML for a div that will display a Bokeh plot in an\n    IPython Notebook\n\n    The data for the plot is stored directly in the returned HTML.\n\n    Args:\n        plot_object (PlotObject) : Bokeh object to render\n            typically a Plot or PlotContext\n\n    Returns:\n        div : UTF-8 encoded HTML text\n\n    .. note::\n        Assumes ``bokeh.load_notebook()`` or the equivalent has already\n        been executed.\n\n    '''\n    ref = plot_object.ref\n    elementid = str(uuid.uuid4())\n\n    plots = [{\n        'modelid': ref[\"id\"],\n        'elementid': '#' + elementid,\n        'modeltype': ref[\"type\"]\n    }]\n\n    js = PLOT_JS.render(\n        all_models = serialize_json(plot_object.dump()),\n        plots = plots\n    )\n    script = PLOT_SCRIPT.render(\n        plot_js = _wrap_in_function(js),\n    )\n    div = PLOT_DIV.render(elementid=elementid)\n    html = NOTEBOOK_DIV.render(\n        plot_script = script,\n        plot_div = div,\n    )\n    return encode_utf8(html)\n\n\ndef file_html(plot_object, resources, title, template=FILE, template_variables=None):\n    ''' Return an HTML document that embeds a Bokeh plot.\n\n    The data for the plot is stored directly in the returned HTML.\n\n    Args:\n        plot_object (PlotObject) : Bokeh object to render\n            typically a Plot or PlotContext\n        resources (Resources) : a resource configuration for BokehJS assets\n        title (str) : a title for the HTML document ``<title>`` tags\n        template (Template, optional) : HTML document template (default: FILE)\n            A Jinja2 Template, see bokeh.templates.FILE for the required\n            template parameters\n        template_variables (dict, optional) : variables to be used in the Jinja2\n            template. If used, the following variable names will be overwritten:\n            title, plot_resources, plot_script, plot_div\n\n    Returns:\n        html : standalone HTML document with embedded plot\n\n    '''\n    from .document import Document\n    if not isinstance(plot_object, (PlotObject, Document)):\n        raise ValueError('plot_object must be a single PlotObject')\n\n    plot_resources = RESOURCES.render(\n        js_raw = resources.js_raw,\n        css_raw = resources.css_raw,\n        js_files = resources.js_files,\n        css_files = resources.css_files,\n    )\n    script, div = components(plot_object)\n    template_variables_full = \\\n        template_variables.copy() if template_variables is not None else {}\n    template_variables_full.update(\n        {\n            'title': title,\n            'plot_resources': plot_resources,\n            'plot_script': script,\n            'plot_div': div,\n        }\n    )\n    html = template.render(template_variables_full)\n    return encode_utf8(html)\n\n\ndef autoload_static(plot_object, resources, script_path):\n    ''' Return JavaScript code and a script tag that can be used to embed\n    Bokeh Plots.\n\n    The data for the plot is stored directly in the returned JavaScript code.\n\n    Args:\n        plot_object (PlotObject) :\n        resources (Resources) :\n        script_path (str) :\n\n    Returns:\n        (js, tag) :\n            JavaScript code to be saved at ``script_path`` and a ``<script>``\n            tag to load it\n\n    Raises:\n        ValueError\n\n    '''\n    if resources.mode == 'inline':\n        raise ValueError(\"autoload_static() requires non-inline resources\")\n\n    if resources.dev:\n        raise ValueError(\"autoload_static() only works with non-dev resources\")\n\n    elementid = str(uuid.uuid4())\n\n    js = AUTOLOAD.render(\n        all_models = serialize_json(plot_object.dump()),\n        js_url = resources.js_files[0],\n        css_files = resources.css_files,\n        elementid = elementid,\n    )\n\n    tag = AUTOLOAD_STATIC.render(\n        src_path = script_path,\n        elementid = elementid,\n        modelid = plot_object._id,\n        modeltype = plot_object.__view_model__,\n        loglevel = resources.log_level,\n    )\n\n    return encode_utf8(js), encode_utf8(tag)\n\n\ndef autoload_server(plot_object, session, public=False):\n    ''' Return a script tag that can be used to embed Bokeh Plots from\n    a Bokeh Server.\n\n    The data for the plot is stored on the Bokeh Server.\n\n    Args:\n        plot_object (PlotObject) :\n        session (Session) :\n\n    Returns:\n        tag :\n            a ``<script>`` tag that will execute an autoload script\n            loaded from the Bokeh Server\n\n    '''\n    elementid = str(uuid.uuid4())\n    resources = Resources(root_url=session.root_url, mode=\"server\")\n    tag = AUTOLOAD_SERVER.render(\n        src_path = resources._autoload_path(elementid),\n        elementid = elementid,\n        modelid = plot_object._id,\n        root_url = resources.root_url,\n        docid =  session.docid,\n        docapikey = session.apikey,\n        loglevel = resources.log_level,\n        public = public\n    )\n\n    return encode_utf8(tag)\n", "path": "bokeh/embed.py"}, {"content": "import numpy as np\n\nfrom bokeh.plotting import figure, show, output_file\nfrom bokeh.models.sources import AjaxDataSource\n\noutput_file(\"ajax_source_realtime.html\", title=\"ajax_source_realtime.py example\")\nsource = AjaxDataSource(data_url='http://localhost:5050/data', mode=\"append\",\n                        if_modified=True, polling_interval=1000, max_size=125)\np = figure()\np.line('x', 'y', source=source)\nshow(p)\n\nimport time\nfrom threading import Thread\nfrom collections import namedtuple, deque\n\nEntry = namedtuple('Entry', ['x', 'y', 'creation'])\n\nentries = deque(maxlen=120)\n\ndef gen_entry():\n    global entries\n    x = 0\n    while True:\n        last_entry = Entry(x, np.sin(x*np.pi/10), time.time())\n        entries.append(last_entry)\n        x += 1\n        if x > entries.maxlen and x % 10 == 0:\n            time.sleep(2)\n\nt = Thread(target=gen_entry)\nt.daemon = True\nt.start()\n\nimport json\nfrom flask import Flask, Response, request\nfrom bokeh.server.crossdomain import crossdomain\n\napp = Flask(__name__)\n\n@app.route('/data', methods=['GET', 'OPTIONS'])\n@crossdomain(origin=\"*\", methods=['GET', 'POST'])\ndef hello_world():\n    global entries\n    try:\n        modified_since = float(request.headers.get('If-Modified-Since'))\n    except TypeError:\n        modified_since = 0\n\n    new_entries = [e for e in entries if e.creation > modified_since]\n    js = json.dumps({'x':[e.x for e in new_entries], 'y':[e.y for e in new_entries]})\n    resp = Response(js, status=200, mimetype='application/json')\n\n    if new_entries:\n        resp.headers['Last-Modified'] = new_entries[-1].creation\n    elif modified_since:\n        resp.headers['Last-Modified'] = modified_since\n\n    return resp\n\nif __name__ ==  \"__main__\":\n    app.run(port=5050)\n", "path": "examples/plotting/file/ajax_source_realtime.py"}]}