예제 #1
0
파일: slideshow.py 프로젝트: chakas/bokeh
def render_plot():
    dist_plot = distribution()

    anim_plot = animated()

    pop = Population(curdoc())

    return render_template(
        'app_plot.html',
        tag1=autoload_server(dist_plot),
        tag2=autoload_server(anim_plot),
        tag3=autoload_server(pop.layout)
    )
예제 #2
0
def make_snippet(kind, plot, session=None, target=None):
    if kind == "plot":
        tag = autoload_server(plot, session)
        thread = Thread()
        thread.start()
    if kind == "animated":
        tag = autoload_server(plot, session)
        thread = Thread(target=target, args=(plot, session))
        thread.start()
    elif kind == "widget":
        tag = autoload_server(plot, session)
        thread = Thread(target=target, args=(pop,))
        thread.start()

    return tag, plot._id
예제 #3
0
def standalone(*tunnels, plots=None, remote_only=False, bokeh_port=5006,
               mon_port=8080):
    execs = make_tunnels(tunnels, (not remote_only))
    plot_args = {'plot_list': plots} if plots else dict()
    plots, monitors, change_streams = generate_plots(execs, **plot_args)

    p_bokeh, session = start_bokeh(mon_port, bokeh_port, change_streams)

    def kill_bokeh():
        if isinstance(p_bokeh, Popen):
            p_bokeh.terminate()

    try:
        print(session.id)
        scr = autoload_server(plots, session_id=session.id)
        print(scr)
        scr = re.sub('http://localhost:{0}'.format(bokeh_port), '', scr)
        scr = TEMPLATE.format(script=scr).encode()

        loop = asyncio.get_event_loop()
        start_tornado(loop, bokeh_port, mon_port, scr)
        loop.run_until_complete(asyncio.gather(
            *(mon() for mon in monitors),
            *(changes.start() for changes in change_streams)
        ))
    finally:
        kill_bokeh()
예제 #4
0
파일: test_embed.py 프로젝트: chakas/bokeh
 def test_script_attrs_no_session_id_provided(self):
     r = embed.autoload_server(None)
     self.assertFalse('bokeh-session-id' in r)
     html = bs4.BeautifulSoup(r)
     scripts = html.findAll(name='script')
     self.assertEqual(len(scripts), 1)
     attrs = scripts[0].attrs
     self.assertTrue(set(attrs), set([
         'src',
         'data-bokeh-doc-id',
         'data-bokeh-model-id',
         'data-bokeh-log-level',
         'async',
         'id'
     ]))
     divid = attrs['id']
     src = "%s/autoload.js?bokeh-autoload-element=%s" % \
           ("http://localhost:5006", divid)
     self.assertDictEqual({ 'async' : 'false',
                            'data-bokeh-doc-id' : '',
                            'data-bokeh-model-id' : '',
                            'data-bokeh-log-level' : 'info',
                            'id' : divid,
                            'src' : src },
                          attrs)
예제 #5
0
 def test_script_attrs(self):
     r = embed.autoload_server(_embed_test_plot, self.sess)
     html = bs4.BeautifulSoup(r)
     scripts = html.findAll(name='script')
     self.assertEqual(len(scripts), 1)
     attrs = scripts[0].attrs
     self.assertTrue(set(attrs), set([
         'src',
         'data-bokeh-docid',
         'data-bokeh-docapikey',
         'data-bokeh-modeltype',
         'data-bokeh-modelid',
         'data-bokeh-root-url',
         'async',
         'id',
         'data-bokeh-data',
         'data-bokeh-conn-string'
     ]))
     self.assertEqual(attrs['async'], 'true')
     self.assertEqual(attrs['data-bokeh-data'], 'server')
     self.assertEqual(attrs['data-bokeh-docapikey'], 'apikey123')
     self.assertEqual(attrs['data-bokeh-docid'], 'docid10')
     self.assertEqual(attrs['data-bokeh-modelid'], str(_embed_test_plot._id))
     self.assertEqual(attrs['data-bokeh-modeltype'], 'Plot')
     self.assertEqual(attrs['data-bokeh-root-url'], "http://foo/")
     self.assertEqual(attrs['data-bokeh-conn-string'], 'ws://foo/bokeh/sub')
     divid = attrs['id']
     self.assertEqual(attrs['src'], "%s/bokeh/autoload.js/%s" % ("http://foo", divid))
예제 #6
0
def init_plot(crawl_name):
    session = Session()
    document = Document()
    session.use_doc(crawl_name)
    session.load_document(document)

    if document.context.children:
        plot = document.context.children[0]
    else:
        output_server(crawl_name)
        # TODO: Remove these when Bokeh is upgraded
        # placeholders or Bokeh can't inject properly
        current = np.datetime64(datetime.now())
        xdr = Range1d(current, current + 1)
        ydr = ["urls"]

        # styling suggested by Bryan
        plot = figure(title="Crawler Monitor", tools="hover",
                      x_axis_type="datetime", y_axis_location="right", x_range=xdr, y_range=ydr,
                      width=1200, height=600)
        plot.toolbar_location = None
        plot.xgrid.grid_line_color = None

    document.add(plot)
    session.store_document(document)
    script = autoload_server(plot, session)

    #TODO: Looks like a Bokeh bug, probably not repeatable with current code
    script = script.replace("'modelid': u'", "'modelid': '")
    return script
예제 #7
0
 def get_bokeh_script(self, suffix):
     assert hasattr(self, 'object')
     bokeh_session = pull_session(session_id=None, url='http://localhost:5006/%s/' % suffix)
     # We want to make this less cumbersome see https://github.com/bokeh/bokeh/issues/3349
     user_source = bokeh_session.document.get_model_by_name('user_pk_source')
     user_source.data = dict(user_pk=[self.object.pk])
     script = autoload_server(None, app_path='/%s' % suffix, session_id=bokeh_session.id)
     return script
예제 #8
0
def factexplorer():
    # session = pull_session(url="http://localhost:5006/factexplorer")
    script = autoload_server(model=None, app_path="/factexplorer", url="http://localhost")
    return render_template(
        "description.html",
        script = script,
        title = "Exploring timeseries of selected facts",
        summary = summary, description = "The facts can be selected by user input. If no fact can be found, the graph will not change."
    )
예제 #9
0
def journals():
    # session = pull_session(url="http://localhost:5006/journals")
    script = autoload_server(model=None, app_path="/journals", url="http://localhost:5006")
    return render_template(
        "description.html",
        script = script,
        title = "Exploring paper distribution across journals",
        summary = summary, description = "This graph shows the distribution of papers over journals, with absolute counts on the left hand scale, and cumulative percentage on the right hand scale."
    )
예제 #10
0
def cooccurrences():
    # session = pull_session(url="https://contentmine-demo-staging.herokuapp.com/cooccurrences")
    script = autoload_server(model=None, app_path="/cooccurrences", url="https://contentmine-demo-staging.herokuapp.com")
    return render_template(
        "description.html",
        script = script,
        title = "Exploring co-occurrences of facts",
        summary = summary, description = "The plot shows the count of co-occurrences of facts with other facts of their dictionary, in a range of top 5 to top 25. Co-occurrence between two facts is defined as appearing together in the same publication."
    )
예제 #11
0
def trending():
    # session = pull_session(url="http://127.0.0.1:5006/trending")
    script = autoload_server(model=None, app_path="/trending", url="http://127.0.0.1:5006")
    return render_template(
        "description.html",
        title = "Exploring most frequent and uptrending facts",
        summary = summary, description = "The left column shows the top 10 facts, determined by absolute counts over the whole period. The right column shows the top 10 uptrending facts, determined by the sum of percentage changes of daily counts.",
        script = script
    )
예제 #12
0
def dictionaries():
    # session = pull_session(url="http://0.0.0.0:5006/dictionaries")
    script = autoload_server(model=None, app_path="/dictionaries", url="http://0.0.0.0:5006")
    return render_template(
        "description.html",
        script = script,
        title = "Exploring aggregated counts of facts over dictionaries",
        summary = summary, description = "The upper time series shows the absolute counts of facts, aggregated by their source dictionary. The lower time series shows the relative share of facts per dictionary, as a fraction of the daily total count."
    )
예제 #13
0
def index():
    plot = figure()
    plot.circle([1,2], [3,4])
    document = Document()
    document.add_root(plot)

    session = push_session(document)
    script = autoload_server(None, session_id=session.id)

    return render_template('index.html', bokeh_script=script)
예제 #14
0
    def apply(self,target_df):
        self.init_func(target_df, *self.args, **self.kwargs)

        self.session = push_session(curdoc())
        tag = autoload_server(self.p,session_id=self.session.id)
        target_df._top_df._plots.append(tag)

        thread = Thread(target = self._continuous_wrapper, args=(target_df,))
        thread.start()
        return thread
예제 #15
0
    def content(self):
        plot, session = self.create_plot()
        divs = autoload_server(plot, session)

        for var in self.variables:
            thread = threading.Thread(target=self.update_plot,
                                      args=(plot, session, var))
            thread.start()

        return render_template('bokeh_linechart.html', divs=divs,
                               variables=self.variables, viewid=self.viewid)
예제 #16
0
def pages_timeseries(response):
    parse_datetime = lambda x: datetime.datetime.strptime(x, "%Y-%m-%dT%H:%M:%S.%f")
    parsed_dates = [parse_datetime(x[1]) for x in response]
    dates = sorted(parsed_dates)
    plot = figure(plot_width=584, x_axis_type="datetime", x_axis_label="Dates",
            y_axis_label="Number Fetched")
    plot.line(x=dates, y=range(len(dates)))

    button = Button(label="Press Me")

    session = push_session(curdoc())
    script = autoload_server(vplot(plot, button), session_id=session.id)
    return script
예제 #17
0
def embed_bokeh(request, bokeh_app):
    """Render the requested app from the bokeh server"""

    # http://bokeh.pydata.org/en/0.12.3/docs/reference/embed.html

    # TODO: test if bokeh server is reachable
    bokeh_script = autoload_server(None, app_path="/{}".format(bokeh_app),
                                   url=bokeh_url)

    context = {'bokeh_script': bokeh_script,
               'bokeh_app': bokeh_app}

    return render(request, "dashboard/embed_bokeh.html", context)
예제 #18
0
def get_bokeh_script(user, plot, suffix):
    from .models import UserSession

    document = Document()
    document.add_root(plot)
    document.title = suffix

    with closing(push_session(document)) as session:
        # Save the session id to a UserSession
        UserSession.objects.create(user=user, bokeh_session_id=session.id)
        # Get the script to pass into the template
        script = autoload_server(None, session_id=session.id)

    return script
예제 #19
0
def render_plot():
    """
    Get the script tags from each plot object and "insert" them into the template.

    This also starts different threads for each update function, so you can have
    a non-blocking update.
    """
    dist_plot, dist_session = distribution()
    dist_tag = autoload_server(dist_plot, dist_session)

    anim_plot, anim_session = animated()
    anim_tag = autoload_server(anim_plot, anim_session)
    # for update_animation as target we need to pass the anim_plot and anim_session as args
    thread = Thread(target=update_animation, args=(anim_plot, anim_session))
    thread.start()

    pop = Population()
    pop_tag = autoload_server(pop.layout, pop.session)
    # for update_population as target we need to pass the pop instance as args
    thread = Thread(target=update_population, args=(pop,))
    thread.start()

    return render_template('app_plot.html', tag1=dist_tag, tag2=anim_tag, tag3=pop_tag)
예제 #20
0
파일: bokeh_utils.py 프로젝트: linea-it/qlf
def get_bokeh_script(plot):

    from .models import UserSession

    document = Document()
    document.add_root(plot)

    with closing(push_session(document, url=bokeh_url)) as session:
        # Save the session id
        UserSession.objects.create(user=User.objects.get(),
                                   bokehSessionId=session.id)
        # Get the script to pass into the template
        script = autoload_server(None, session_id=session.id, url=bokeh_url)

    return script
예제 #21
0
def root():
    """ Returns the web interface to the estuary model """

    bokeh_div = autoload_server(None, session_id=None,
                                app_path='/app', url='')
    left, right = bokeh_div.split('src="')
    bokeh_div = left + 'src="http://yavinprime.mit.edu:5006' + right

    html = flask.render_template(
        'app.html',
        # bokeh=autoload_server(None, session_id=None,
        #                       app_path='/app', url=''),
        bokeh=bokeh_div,
    )
    return encode_utf8(html)
예제 #22
0
파일: app.py 프로젝트: ViDA-NYU/memex
def render_dashboard():
    #dashboard = DashBoard()
    #tag = autoload_server(dashboard.layout, dashboard.session)
    tag = autoload_server(dashboard.layout, dashboard.session)

    html = """
    <html>
    <head></head>
    <body>
    %s
    </body>
    </html>
    """
    html = html % (tag)
    #render_template('demo.html', tag=tag)

    return render_template('demo.html', tag=tag)
예제 #23
0
파일: pluginutils.py 프로젝트: Afey/bokeh
        def wrapper(*args, **kwargs):
            docname = prefix + str(uuid.uuid4())
            session = Session(name=url, root_url=url)
            session.use_doc(docname)
            session.load_document(curdoc())
            curdoc().autoadd = False
            curdoc().autostore = False

            obj = func(*args, **kwargs)
            tag = embed.autoload_server(obj, session)
            obj.tag = tag

            curdoc().add(obj)
            changed = session.store_document(curdoc())

            logger.debug("stored: %s", str(changed))

            return obj
예제 #24
0
파일: views.py 프로젝트: along528/insight
def input():

  hover = HoverTool( tooltips=[ ('Agency','<font color="#000000"> @agency, @city, @state</font>')])
  plot = format(figure(title="Hit Rate vs Search Rate Split by Race",plot_width=800, plot_height=400,tools=[hover,"pan","wheel_zoom","box_zoom","reset"]))
  plot.circle('black_search_rate','black_hit_rate',color="#dd3439",size=10,source=source_rates,legend="Black Drivers",alpha=0.7)
  plot.circle('white_search_rate','white_hit_rate',color="#257bf8",size=10,source=source_rates,legend="White Drivers",alpha=0.7)
  plot.xaxis.axis_label = "Searches / Stops"
  plot.yaxis.axis_label = "Hits / Searches"

  curdoc().add_root(plot)
  session = push_session(curdoc())
  bokeh_script = autoload_server(plot, session_id=session.id, url=url)
  bokeh_id = bokeh_script.split()[2].split('"')[1]
  print "script:"
  print bokeh_script
  print "id:"
  print bokeh_id
  return render_template("input.html",
		bokeh_script=bokeh_script)
예제 #25
0
파일: test_embed.py 프로젝트: eachan/bokeh
 def test_script_attrs_session_id_provided(self):
     r = embed.autoload_server(_embed_test_plot, session_id='fakesession')
     self.assertTrue('bokeh-session-id=fakesession' in r)
     html = bs4.BeautifulSoup(r)
     scripts = html.findAll(name='script')
     self.assertEqual(len(scripts), 1)
     attrs = scripts[0].attrs
     self.assertTrue(set(attrs), set([
         'src',
         'data-bokeh-doc-id',
         'data-bokeh-model-id',
         'id'
     ]))
     divid = attrs['id']
     src = "%s/autoload.js?bokeh-autoload-element=%s&bokeh-session-id=fakesession" % \
           ("http://localhost:5006", divid)
     self.assertDictEqual({ 'data-bokeh-doc-id' : '',
                            'data-bokeh-model-id' : str(_embed_test_plot._id),
                            'id' : divid,
                            'src' : src },
                          attrs)
예제 #26
0
    def root():
        """ Returns the web interface to the estuary model """

        # Over-write url if in deployment; else, accept default.
        autoload_kws = dict(app_path="/app", session_id=None)
        if args.deploy:
            autoload_kws['url'] = ''
        bokeh_div = autoload_server(None, **autoload_kws)
        if args.deploy:
            left, right = bokeh_div.split('src="')
            deployment_src = 'src="http://{:s}:{:d}'.format(
                args.host, args.bokeh_port
            )
            bokeh_div = left + deployment_src + right

        html = flask.render_template(
            'app.html',
            # bokeh=autoload_server(None, session_id=None,
            #                       app_path='/app', url=''),
            bokeh=bokeh_div,
        )
        return encode_utf8(html)
예제 #27
0
def line_scratch():

    line_width = 4

    line1 = [(0, 1, 2, 3, 4, 5), (0, 1, 2, 3, 4, 5)]
    line2 = [(0, 1, 2, 3, 4, 5), (0, 5, 1, 4, 2, 3)]
    line3 = [(5, 4, 3, 2, 1), (5, 4, 3, 2, 1)]

    plot = figure()
    red = plot.line(x=line1[0], y=line1[1], line_width=line_width, color="crimson")
    blue = plot.line(x=line2[0], y=line2[1], line_width=line_width)
    # purple = plot.line(x=line3[0], y=line3[1], line_width=line_width, color="purple")

    button = Button(label="Add Line")
    button.on_click(add_line)

    curdoc().add_root(vplot(plot, button))
    session = push_session(curdoc())

    script = autoload_server(model=None, session_id=session.id)

    # script, div = components(vplot(plot, button))
    return script
예제 #28
0
def embed_bokeh(request, bokeh_app):
    """Render the requested app from the bokeh server"""

    # http://bokeh.pydata.org/en/0.12.3/docs/reference/embed.html

    # TODO: test if bokeh server is reachable
    bokeh_script = autoload_server(None, app_path="/{}".format(bokeh_app),
                                   url=bokeh_url)

    template = loader.get_template('dashboard/embed_bokeh.html')

    context = {'bokeh_script': bokeh_script,
               'bokeh_app': bokeh_app}

    response = HttpResponse(template.render(context, request))

    # Save full url path in the HTTP response, so that the bokeh
    # app can use this info, e.g:
    # http://localhost:8000/dashboard/AMx/?metric=AM1&ci_dataset=cfht&ci_id=452

    response.set_cookie('django_full_path', request.get_full_path())

    return response
예제 #29
0
파일: plotter.py 프로젝트: locuslab/dreaml
    def init_func(self,target_df,f,title,
                  legend=None,interval=1,colors=None,**kwargs):
        # self.connect_to_server()
        self.p = figure(plot_width=400, plot_height=400,title=title)
        (y0,x0) = f(**kwargs)
        target_df["x/","val/"].set_matrix(np.array(x0).reshape(1,len(x0)))
        target_df["y/","val/"].set_matrix(np.array(y0).reshape(1,len(y0)))

        if len(legend)==0:
            for i in range(len(y0)):
                legend.append(str(i))
        if len(colors)==0:
            for i in range(len(y0)):
                color = "#%06x" % randint(0, 0xFFFFFF)
                colors.append(color)

        if len(y0)!= len(x0):
            raise ValueError("f must return two lists of equal length, equal\
                to the number of lines to be plotted.")
        if len(y0)!= len(legend):
            raise ValueError("length of legend must match number of\
                lines plotted")
        if len(y0) != len(colors):
            raise ValueError("length of list of colors must much number of\
                lines plotted")

        for i in range(len(legend)):
            self.p.line([],
                        [],
                        name=legend[i],
                        legend=legend[i],
                        color=colors[i])

        self.session = push_session(curdoc())
        tag = autoload_server(self.p,session_id=self.session.id)
        target_df._top_df._plots.append(tag)
예제 #30
0
    degree_normal = round(degree_rad*180./pi)
    plot.title = titlevalue + str(degree_normal)

    source.data = dict(x=x, y=y)

for w in [mu, tau]:
    w.on_change('value', update_data)


# Set up layouts and add to document
inputs = VBoxForm(children=[mu, tau])

layout = HBox(children=[inputs, plot], width=800)

html = """
<html>
    <head>Yolo</head>
    <body>
        %s
    </body>
</html>
""" % autoload_server(layout, session_id=session.id)

with open("motion.html", "w+") as f:
    f.write(html)
    
document.add_root(layout)
if __name__ == "__main__":
    print("\npress ctrl-C to exit")
    session.loop_until_closed()
예제 #31
0
def somepath():
    script = autoload_server(model=None, url="http://localhost:5006/generator")
    return render_template('slide.html', bokS=script)
async def test(request):
    script = autoload_server(model=None, url='http://localhost:5116/bkapp')
    with open("templates/embed.html") as tmp:
        templt = tmp.read()
    return html(Template(templt).render(script=script))
예제 #33
0
        shifted = groups[1:] + [groups[-1] + 5]

        self.source_pyramid.data = dict(
            groups=groups,
            shifted=shifted,
            male=male_percent,
            female=female_percent,
        )


import bokeh.embed as embed

pop = Population()
pop.render()

tag = embed.autoload_server(pop.layout)

html = """
<html>
<head></head>
<body>
%s
</body>
</html>
"""
html = html % (tag)
with open("population_embed.html", "w+") as f:
    f.write(html)

print("""
To view this example, run
예제 #34
0
 def test_return_type(self):
     r = embed.autoload_server(_embed_test_plot, self.sess)
     self.assertTrue(isinstance(r, str))
예제 #35
0
from bokeh.plotting import *
from bokeh.session import Session
from bokeh import embed
Session().register('testuser', 'testpassword')
N = 80
x = np.linspace(0, 4*np.pi, N)
y = np.sin(x)
output_server("line_animate")
TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select"
p = figure(tools=TOOLS)
p.circle(x, y, color="#3333ee", name="sin")
push()
renderer = p.select(dict(name="sin"))
ds = renderer[0].data_source
cursession().publish()
tag = embed.autoload_server(p, cursession(), public=True)
html = """
<html>
<head></head>
<body>
%s
</body>
</html>
"""
html = html % (tag)

with open("publishing.html", "w+") as f:
    f.write(html)

print("""
To view this example, run
예제 #36
0

if __name__ == '__main__':
    # create a plot and style its properties
    model1 = get_forecast_data(model1_file)
    model2 = get_forecast_data(model2_file)
    i = 0

    plots = []
    new_pts = []
    for city in ['denver', 'ny', 'chicago', 'seattle', 'sf']:
        for cartype in ['uberX', 'uberXL', 'uberBLACK', 'uberSUV']:
            p, ds = create_plots(model1, model2, city, cartype)
            plots.append(p)
            new_pts.append(ds)
    vp = vplot(*plots)
    ip = load(urlopen('http://jsonip.com'))['ip']
    session = cursession()
    session.publish()
    tag = autoload_server(vp, session, public=True)

    html = """
    {%% extends "base.html" %%}
    {%% block bokeh %%}
    %s
    {%% endblock %%}
    """ % tag

    with open('templates/index.html', 'w+') as f:
        f.write(html)
예제 #37
0
def run_chart(exchange, asset, limit):
    client = pymongo.MongoClient()
    db = client['bitpredict_'+exchange]
    collection = db[asset_+'_predictions']

    def get_data():
        if (limit)
            cursor = collection.find()
        else
            cursor = collection.find().limit(limit)
        data = pd.DataFrame(list(cursor))
        data = data.set_index('_id')
        data = data.sort_index(ascending=True)
        timestamps = pd.to_datetime(data.index, unit='s').to_series()
        returns = data.returns.cumsum()*100
        return timestamps, returns

    timestamps, returns = get_data()
    output_server('bitpredict_'+exchange+'_performance')

    background = '#f2f2f2'
    ylabel_standoff = 0
    xformatter = DatetimeTickFormatter(formats=dict(hours=["%H:%M"]))
    yformatter = PrintfTickFormatter(format="%8.1f")
    p = figure(title=None,
                plot_width=750,
                plot_height=500,
                x_axis_type='datetime',
                min_border_top=5,
                min_border_bottom=10,
                background_fill=background,
                x_axis_label='Date',
                tools='',
                toolbar_location=None)
    p.line(x=timestamps,
            y=returns,
            name='returns',
            color='#8959a8',
            line_width=1,
            legend='Cumulative Return',
            line_cap='round',
            line_join='round')
    p.legend.orientation = 'top_left'
    p.legend.border_line_color = background
    p.outline_line_color = None
    p.xgrid.grid_line_color = 'white'
    p.ygrid.grid_line_color = 'white'
    p.axis.axis_line_color = None
    p.axis.major_tick_line_color = None
    p.axis.minor_tick_line_color = None
    p.yaxis.axis_label = 'Percent'
    p.yaxis.axis_label_standoff = ylabel_standoff
    p.xaxis.formatter = xformatter
    p.yaxis.formatter = yformatter
    p.xaxis.axis_label_standoff = 12
    p.yaxis.major_label_text_font = 'courier'
    p.xaxis.major_label_text_font = 'courier'

    push()
    ip = load(urlopen('http://jsonip.com'))['ip']
    ssn = cursession()
    ssn.publish()
    tag = embed.autoload_server(p, ssn, public=True)
    renderer = p.select(dict(name='returns'))
    ds_returns = renderer[0].data_source

    while True:
        timestamps, returns = get_data()
        ds_returns.data['x'] = timestamps
        ds_returns.data['y'] = returns
        ssn.store_objects(ds_returns)
        time.sleep(300)
예제 #38
0
    controls = row(children=[year_select, location_select])
    layout = column(children=[controls, pyramid(), population()])

    return layout


layout = create_layout()

update_data()

html = """
<html>
    <head></head>
    <body>
        %s
    </body>
</html>
""" % autoload_server(layout, session_id=session.id, relative_urls=False)

with io.open("widget.html", mode='w+', encoding='utf-8') as f:
    f.write(html)

print(__doc__)

document.add_root(layout)

if __name__ == "__main__":
    print("\npress ctrl-C to exit")
    session.loop_until_closed()
예제 #39
0
p.annular_wedge(
    0,
    0,
    rmin,
    rmax,
    theta[:-1],
    theta[1:],
    inner_radius_units="data",
    outer_radius_units="data",
    fill_color=colors,
    line_color="black",
)

push()

tag = embed.autoload_server(p, cursession())
html = """
<html>
  <head></head>
  <body>
    %s
  </body>
</html>
"""
html = html % (tag)
with open("animated_embed.html", "w+") as f:
    f.write(html)

print("""
To view this example, run
    python -m SimpleHTTPServer (or http.server on python 3)
        shifted = groups[1:] + [groups[-1] + 5]

        self.source_pyramid.data = dict(
            groups=groups,
            shifted=shifted,
            male=male_percent,
            female=female_percent,
        )
        self.session.store_document(self.document)

import bokeh.embed as embed

pop = Population()
pop.render()

tag = embed.autoload_server(pop.layout, pop.session)

html = """
<html>
<head></head>
<body>
%s
</body>
</html>
"""
html = html % (tag)
with open("population_embed.html", "w+") as f:
    f.write(html)

print("""
To view this example, run
예제 #41
0
def index():
    script = autoload_server(model=None, url=url, app_path="/sliders")
    return render_template('index.html', bokeh_script=script)
예제 #42
0
p3.axis.minor_tick_line_color = None
p3.yaxis.axis_label = 'Basis Points'
p3.yaxis.axis_label_standoff = ylabel_standoff
p3.xaxis.formatter = xformatter
p3.yaxis.formatter = yformatter
p3.xaxis.axis_label_standoff = 12
p3.yaxis.major_label_text_font = 'courier'
p3.xaxis.major_label_text_font = 'courier'
p3.x_range = p1.x_range

vp = vplot(p1, p2, p3)
push()
ip = load(urlopen('http://jsonip.com'))['ip']
ssn = cursession()
ssn.publish()
tag = embed.autoload_server(vp, ssn, public=True).replace('localhost', ip)
html = """
{%% extends "layout.html" %%}
{%% block bokeh %%}
%s
{%% endblock %%}
""" % tag
with open('templates/extended.html', 'w+') as f:
    f.write(html)

renderer = p1.select(dict(name='prices'))
ds_prices = renderer[0].data_source
renderer = p2.select(dict(name='predictions'))
ds_predictions = renderer[0].data_source
renderer = p3.select(dict(name='returns'))
ds_returns = renderer[0].data_source
예제 #43
0
파일: uhcsdb.py 프로젝트: yupengyan/uhcsdb
def bokeh_plot():
    bokeh_script = autoload_server(None,
                                   app_path="/visualize",
                                   url="http://rsfern.materials.cmu.edu")
    return render_template('visualize.html', bokeh_script=bokeh_script)
예제 #44
0
def update_data(attrname, old, new):

    #a = aperture.value
    m = magnitude.value
    e = exptime.value

    luvoir.aperture = aperture.value
    hdi.set_pixel_sizes(luvoir)  # adaptively set the pixel sizes

    wave = hdi.pivotwave
    snr = phot_etc.compute_snr(luvoir, hdi, e, m)
    source.data = dict(x=wave[2:-3], y=snr[2:-3], desc=hdi.bandnames[2:-3])
    source2.data = dict(x=hdi.pivotwave[0:2],
                        y=snr[0:2],
                        desc=hdi.bandnames[0:2])
    source3.data = dict(x=hdi.pivotwave[-3:],
                        y=snr[-3:],
                        desc=hdi.bandnames[-3:])


for w in [aperture, exptime, magnitude]:  # iterate on changes to parameters
    w.on_change('value', update_data)

# Set up layouts and add to document
inputs = WidgetBox(children=[aperture, exptime, magnitude])
curdoc().add_root(row(children=[inputs, snr_plot]))
script = autoload_server(model=None,
                         app_path="/simple_etc",
                         url="pancho.local:5006")
#print(script)
예제 #45
0
from bokeh.embed import autoload_server
script = autoload_server("http://localhost:5008/vbar_example")
예제 #46
0
파일: animated.py 프로젝트: zjffdu/bokeh
                    fill_color=colors, line_color="white")

# add the plot to curdoc
curdoc().add_root(p)

# open a session which will keep our local doc in sync with server
session = push_session(curdoc())

html = """
<html>
  <head></head>
  <body>
    %s
  </body>
</html>
""" % autoload_server(p, session_id=session.id)

with io.open("animated.html", mode='w+', encoding='utf-8') as f:
    f.write(html)

print(__doc__)

ds = r.data_source

def update():
    rmin = roll(ds.data["inner_radius"], 1)
    rmax = roll(ds.data["outer_radius"], -1)
    ds.data.update(inner_radius=rmin, outer_radius=rmax)

curdoc().add_periodic_callback(update, 30)
예제 #47
0
df = pd.DataFrame(data)
df = df.set_index(['x'])


def stacked(df, categories):
    areas = OrderedDict()
    last = np.zeros(len(df[categories[0]]))
    for cat in categories:
        next = last + df[cat]
        areas[cat] = np.hstack((last[::-1], next))
        last = next
    return areas


output_server("brewer")

figure(plot_width=300, plot_height=300)

areas = stacked(df, categories)

colors = brewer["Spectral"][len(areas)]

x2 = np.hstack((data['x'][::-1], data['x']))
patches([x2 for a in areas],
        list(areas.values()),
        color=colors,
        alpha=0.8,
        line_color=None)

tag = embed.autoload_server(curplot(), cursession())
예제 #48
0
 def get(self):
     template = env.get_template('embed.html')
     script = autoload_server(model=None,
                              url='http://localhost:5006/bkapp',
                              relative_urls=False)
     self.write(template.render(script=script, template="Tornado"))
예제 #49
0
#	'Long EMA(%smin)' % ((n1 * 15) / 60) : x0,
#	'Short EMA(%smin)' % ((n2 * 15) / 60): x2
#	}

#d1 = max(data_obj_2['Short EMA(%smin)' % ((n2 * 15) / 60)])
#d2 = min(data_obj_2['Short EMA(%smin)' % ((n2 * 15) / 60)])
#a1 = abs(int(d1)-int(d2))
#y_r = max(data_obj_2['Recorded Usage']) + 5
x = 1
y = 1
p = figure()
p.line(x, y)

push()

tag = embed.autoload_server(p, cursession())
html = """
<html>
  <head></head>
  <body>
    %s
  </body>
</html>
"""
with open("animated_embed.html", "w+") as f:
    f.write(html)

renderer = p.select(dict(type=GlyphRenderer))
ds = renderer[0].data_source

t = 0
예제 #50
0
        self.figure.toolbar_location = None
        self.figure.min_border_right = 0


thrustdisplay = ThrustDisplay()
x = np.linspace(0, 10, 20)
y = np.random.rand()*10 * x
thrustdisplay.initdatafields(x, y)

@linear(m=1, b=0)
def update(step):
    step = step / 4
    x = np.array(step)
    y = np.random.rand() * 10 * x
    thrustdisplay.updateData(x, y)

    
# open a session to keep our local document in sync with server
session = push_session(curdoc())
curdoc().add_periodic_callback(update, 10)

#currently configured to print a script to the console and thats it
script = autoload_server(thrustdisplay.figure, session_id=session.id)
print(script)
script2, div = components(thrustdisplay.figure)
print(script2)
print(div)
#session.show() # open the document in a browser
#session.loop_until_closed() # run forever'''