Beispiel #1
0
def users():
    users = pd.read_csv("users.xlsx")
    hover = HoverTool(tooltips=[('Pct', '@pct')], mode='vline')
    users['']
    donut_from_df = bc.Donut(users['City'], level_spacing=[0.0, 0.01])
    '''    
    donut_from_df = Donut(df_users, label = "city",xlabel="city",ylabel="users",
                      values="count",
                      title="Users Per city",
                      title_text_font_size=str(32)+"pt",
                      level_spacing=[0.0, 0.01])'''
    #show(donut_from_df)
    script, div = components(donut_from_df)
    return """
    <!doctype html>
    <head>
     <title>Popular places</title>
     {bokeh_css}
    </head>
    <body>
     <h1>Most Popular Places visited by people!
     {div}
    
     {bokeh_js}
     {script}
    </body>
     """.format(script=script,
                div=div,
                bokeh_css=CDN.render_css(),
                bokeh_js=CDN.render_js())
Beispiel #2
0
def visualisation():
    # Build the dataframe
    df = pd.DataFrame({
        'x': 2 * np.pi * i / 100,
        'sin': np.sin(2 * np.pi * i / 100),
        'cos': np.cos(2 * np.pi * i / 100),
    } for i in range(0, 101))

    # Create the plot
    plot = bc.Line(title='Triganometric fun!', data=df, x='x', ylabel='y')

    # Generate the script and HTML for the plot
    script, div = components(plot)

    # Return the webpage
    return """
<!doctype html>
<head>
 <title>My wonderful trigonometric webpage</title>
 {bokeh_css}
</head>
<body>
 <h1>Everyone loves trig!
 {div}

 {bokeh_js}
 {script}
</body>
 """.format(script=script,
            div=div,
            bokeh_css=CDN.render_css(),
            bokeh_js=CDN.render_js())
Beispiel #3
0
def visualisation():
    current_city_name = request.args.get("city_name")
    if current_city_name == None:
        current_city_name = "Mumbai"
    subset = df_iplace[df_iplace['city'] == dropdown.value]
    #plot = create_figure(current_city_name)
    plot = bc.Bar(subset,
                  "placename",
                  values="placename",
                  agg="count",
                  plot_width=1000,
                  plot_height=1000,
                  title="Popular places")

    # Generate the script and HTML for the plot
    script, div = components(plot)

    # Return the webpage
    return """
    <!doctype html>
    <head>
     <title>Popular places</title>
     {bokeh_css}
    </head>
    <body>
     <h1>Most Popular Places visited by people!
     {div}
    
     {bokeh_js}
     {script}
    </body>
     """.format(script=script,
                div=div,
                bokeh_css=CDN.render_css(),
                bokeh_js=CDN.render_js())
Beispiel #4
0
def next_step():
    world = load_world()
    orders = dict()
    for sid, station in world.charging_stations.items():
        if "order_%s" % sid not in request.form:
            raise Exception("Missing order_%s in request." % sid)
        orders[sid] = int(request.form.get("order_%s" % sid))
    move_summary = world.next_step(orders)
    save_world(world)

    num_turns = len(world.solar_park.generation)
    available_tokens = [world.available_tokens(i) for i in range(num_turns)]
    max_tokens = int(max(available_tokens))
    turn_hours = [str(h).rjust(2, "0") for h in range(9, 9 + num_turns)]

    if world.current_step < num_turns:
        safe_js = make_custom_js(world.charging_stations, max_tokens,
                                 world.current_step)
    else:
        safe_js = ""
    data_plots_html, data_plots_js = build_game_data_plots(world)

    return render_template("board.html",
                           **dict(world=world),
                           num_turns=num_turns,
                           available_tokens=available_tokens,
                           max_tokens=max_tokens,
                           completed_a_move=True,
                           move_summary=move_summary,
                           turn_hours=turn_hours,
                           safe_js=safe_js,
                           bokeh_css_resources=CDN.render_css(),
                           bokeh_js_resources=CDN.render_js(),
                           data_plots_html=data_plots_html,
                           data_plots_js=data_plots_js)
Beispiel #5
0
def init(is_reset=False):
    if not os.path.exists("worlds"):
        raise Exception(
            "Admin, please create the 'worlds' directory to save worlds!")
    world = load_world()
    num_turns = len(world.solar_park.generation)
    available_tokens = [world.available_tokens(i) for i in range(num_turns)]
    max_tokens = int(max(available_tokens))
    turn_hours = [str(h).rjust(2, "0") for h in range(9, 9 + num_turns)]

    safe_js = make_custom_js(world.charging_stations, max_tokens,
                             world.current_step)
    data_plots_html, data_plots_js = build_game_data_plots(world)

    return render_template("board.html",
                           **dict(world=world),
                           num_turns=num_turns,
                           available_tokens=available_tokens,
                           max_tokens=max_tokens,
                           turn_hours=turn_hours,
                           safe_js=safe_js,
                           resetted_the_game=is_reset,
                           bokeh_css_resources=CDN.render_css(),
                           bokeh_js_resources=CDN.render_js(),
                           data_plots_html=data_plots_html,
                           data_plots_js=data_plots_js)
def visualisation():
 # Build the dataframe
 df = pd.DataFrame({
 'x': 2*np.pi*i/100,
 'sin': np.sin(2*np.pi*i/100),
 'cos': np.cos(2*np.pi*i/100),
 } for i in range(0,101))

 # Create the plot
 plot = bc.Line(title='Triganometric fun!',
 data=df, x='x', ylabel='y')

 # Generate the script and HTML for the plot
 script, div = components(plot)

 # Return the webpage
 return """
<!doctype html>
<head>
 <title>My wonderful trigonometric webpage</title>
 {bokeh_css}
</head>
<body>
 <h1>Everyone loves trig!
 {div}

 {bokeh_js}
 {script}
</body>
 """.format(script=script, div=div, bokeh_css=CDN.render_css(),
 bokeh_js=CDN.render_js())
Beispiel #7
0
def test_bokeh():
    from bokeh.io import output_notebook, show
    from bokeh.plotting import figure
    import ipyvolume.bokeh

    x, y, z = np.random.random((3, 100))

    p3.figure()
    scatter = p3.scatter(x, y, z)

    tools = "wheel_zoom,box_zoom,box_select,lasso_select,help,reset,"
    p = figure(title="E Lz space",
               tools=tools,
               webgl=True,
               width=500,
               height=500)
    r = p.circle(x, y, color="navy", alpha=0.2)
    ipyvolume.bokeh.link_data_source_selection_to_widget(
        r.data_source, scatter, 'selected')

    from bokeh.resources import CDN
    from bokeh.embed import components

    script, div = components(p)
    ipyvolume.embed.embed_html(
        "tmp/bokeh.html", [p3.gcc(), ipyvolume.bokeh.wmh],
        all=True,
        extra_script_head=script + CDN.render_js() + CDN.render_css(),
        body_pre="<h2>Do selections in 2d (bokeh)<h2>" + div +
        "<h2>And see the selection in ipyvolume<h2>")
Beispiel #8
0
def output_pweave():
    """
    Call this once in a Pweave document to include correct
    headers for Bokeh. Analogous to Bokeh's output_notebook
    """
    out = CDN.render_css()
    out += CDN.render_js()
    #display_markdown(out, raw=True)
    display_html(out, raw=True)
Beispiel #9
0
def root():

    print(
        render_template('diagrams/root.html',
                        resources=CDN.render(),
                        prefix=uri_prefix))
    return render_template('diagrams/root.html',
                           resources=CDN.render(),
                           prefix=uri_prefix)
Beispiel #10
0
def output_pweave():
    """
    Call this once in a Pweave document to include correct
    headers for Bokeh. Analogous to Bokeh's output_notebook
    """
    out = CDN.render_css()
    out += CDN.render_js()
    # display_markdown(out, raw=True)
    display_html(out, raw=True)
def visuals():

    plot = bc.Bar(data=top_ten_states_dataFrame, values='count', label='State')
    script, div = components(plot)

    error = None
    try:
        return '''
		<!DOCTYPE html>
		<html>
		<head>
			<title>Train Wreck Header</title>
			<meta charset="utf-8">
			<link rel="stylesheet" type="text/css" href="../static/css/bootstrap.min.css">
			<script type="text/javascript" href="../static/js/bootstrap.min.js"></script>
			<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
			{bokeh_css}
		</head>
		<header style="background-color: #e6e6e6;">
		<!--
			<p> started working </p> -->

			<nav class="navbar navbar-inverse" style="background-color: #4d4d4d;">
				<div class="container-fluid">

					<div class="navbar-header">
						<a class="navbar-brand" href="/" style="color: white;">Train Wreck Analysis</a>
					</div>

					<ul class="nav navbar-nav">
						<li><a href="/">Home</a></li>
						<li><a href="/map/">Map</a></li>
						<li><a href="/visuals/">Bar Chart</a></li>
					</ul>

				</div>
			</nav>
		</header>

		<body>
			<div class="container-fluid" style="margin-left: 20px; float:left; border: solid; border-style: groove; border-width: 5px; height: 650px; width: 700px; padding-top: 20px;">
			 {div}
			 {bokeh_js}
 			 {script}
			</div>
		</body>
		</html>
		'''.format(script=script,
             div=div,
             bokeh_css=CDN.render_css(),
             bokeh_js=CDN.render_js())

    except Exception as e:
        flash(e)
        return render_template('visuals.html', error=error)
def make_plot_code(df):
    fraud_file = pd.read_csv('plots/graphfraud.csv')
    not_fraud_file = pd.read_csv('plots/graphnotfraud.csv')
    df = df.drop(['has_header'], axis=1)
    with open('plots/pca.pkl') as f:
        pca = pickle.load(f)

    with open('plots/scaler.pkl') as f:
        scaler = pickle.load(f)
    print df.values
    try:
        df_ = df.fillna(0.)
        x = pca.transform(scaler.transform(df_.values))
    except:
        try:
            df_ = df.fillna(0)
            x = pca.transform(scaler.transform(df_.values))
        except:
            df_ = df.fillna(str(0))
            x = pca.transform(scaler.transform(df_.values))

    p = figure(title="Fraud Visualization", plot_width=400, plot_height=400)
    p.background_fill_color = "#eeeeee"

    p.scatter(not_fraud_file.values[:, 0],
              not_fraud_file.values[:, 1],
              marker='triangle',
              color='orange',
              legend='Not Fraud')
    p.scatter(fraud_file.values[:, 0],
              fraud_file.values[:, 1],
              marker='circle',
              color='red',
              legend='Fraud')
    p.scatter(x[0, 0],
              x[0, 1],
              color='blue',
              legend='Most recent event',
              marker='square',
              size=10)

    script, div = components(p)

    div = ast.literal_eval(json.dumps(div)).replace('\n', "")
    script = ast.literal_eval(json.dumps(script)).replace('\n', "")
    css = CDN.render_css()
    css = ast.literal_eval(json.dumps(css)).replace('\n', "")
    js = CDN.render_js()
    js = ast.literal_eval(json.dumps(js)).replace('\n', "")
    return div, script, css, js
Beispiel #13
0
def root():

    # get data
    fixed_url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&outputsize=compact&apikey=69N0R6WUDFW63EKD'
    ticker = dict(symbol=app.user_input['ticker'])

    try:
        tdata = requests.get(url=fixed_url, params=ticker)

        # format data
        tdata_dict = tdata.json()
        tdata_df = pd.DataFrame(tdata_dict['Time Series (Daily)'])
        tdata_df = tdata_df.transpose()
        tdata_df = tdata_df[['1. open', '4. close']]
        tdata_df.columns = ['open', 'close']
        tdata_df['open'] = tdata_df['open'].astype(float)
        tdata_df['close'] = tdata_df['close'].astype(float)

        # set data
        app.tdata = tdata_df
        app.user_input['req_fail'] == 'False'

        return render_template('plot_page.html', resources=CDN.render())

    except:
        app.user_input['req_fail'] == 'True'

        return redirect('/cantshow')
Beispiel #14
0
def submit_tick():

    # Save the form responses to the appvars attribute.
    appvars = {}
    appvars['start_date'] = request.form.get('start_date')
    appvars['end_date'] = request.form.get('end_date')
    appvars['stock_code'] = request.form.get('stock_code')

    try:
        # Retrieve ticker data, create plot
        tr = ticker_retrieval(appvars['stock_code'], appvars['start_date'],
                              appvars['end_date'], quandl_key)
        tr.get_ticker_data()
        p = tr.create_plot()
        # Stuff for embedding bokeh plot in webpage.
        script, div = components(p)
    except:
        # If data retrieval was unsuccessful, print an error in place of the plot!
        script = ""
        div = r"<div><p>Error! Stock code was entered incorrectly OR data is unavailable for the entered stock.</p></div>"

    return render_template('index.html',
                           script=script,
                           div=div,
                           bokeh_resources=CDN.render(),
                           st_date=appvars['start_date'],
                           ed_date=appvars['end_date'],
                           scode=appvars['stock_code'])
Beispiel #15
0
def index(search=None, num_videos = 0, **kwargs):
    print('/')
    return render_template("index.html", 
                           resources=CDN.render(), 
                           num_videos = num_videos, 
                           **kwargs
                          )
Beispiel #16
0
def predict():
    # loading data from current database connection
    data = cache.get('predictData')

    if data is None:
        data = db_to_pandas(g.cursor)
        cache.set('predictData', data, timeout=10600)

    # make predictions based on fetched data

    today_pred = cache.get('predictToday')

    if today_pred is None:
        today_pred = predict_today(data)
        cache.set('predictToday', today_pred, timeout=10600)

    # make plots from predictions
    script = cache.get('predictScript')
    divs = cache.get('predictDivs')

    if script is None:
        script, divs = graphics.create_all_buildings(today_pred.transpose())
        cache.set('predictScript', script, timeout=10600)
        cache.set('predictDivs', divs, timeout=10600)
    '''
    data = db_to_pandas(g.cursor)
    today_pred = predict_today(data)
    script, divs = graphics.create_all_buildings(today_pred.transpose())
    '''
    return render_template('predict.html',
                           divs=divs,
                           script=script,
                           css_script=CDN.render_js())
Beispiel #17
0
def show_plot():

    time_chooser = TimeForm.TimeForm(request.form)

    # By default show the last 72 hours of data
    interval = 72

    if time_chooser.validate_on_submit():
        #if time_chooser.the_time.data != 'all':
        interval = time_chooser.the_time.data
        current_app.logger.info('interval is %s', interval)
    current_app.logger.info('interval is %s', interval)

    # Get interval
    now = datetime.datetime.now()
    datetime_1 = (
        now - datetime.timedelta(hours=interval)).strftime('%Y-%m-%d %H:%M:%S')
    datetime_2 = now.strftime('%Y-%m-%d %H:%M:%S')

    plot_script, plot_div = make_range_plot(datetime_1, datetime_2)
    # CDN.render() has all of the information to get the javascript libraries
    # for Bokeh to work, loaded from a cdn somewhere.
    return render_template('temp_graph.html',
                           plot_div=plot_div,
                           plot_script=plot_script,
                           resources=CDN.render(),
                           form=time_chooser)
def savePlot(path, filename, country, r, cases, deaths, curve):
    p = figure(plot_height=350, plot_width=500, title=country, x_axis_label='Days (since 100 cases)', y_axis_label='',
            toolbar_location='right', tools = "hover",
            y_range=Range1d(0, int(1.05*max(cases)), bounds="auto"), x_range=Range1d(0, int(1.05*max(r)), bounds="auto"))

    hover = p.select(dict(type=HoverTool))
    hover.tooltips = [
            ('People', '$y'),
            ('Days (since 100 cases)' , '$index')
            ]

    p.vbar(r, top=cases, width=0.9, legend_label="Daily Cases", color = 'orange')

    p.vbar(r, top=deaths, width=0.9, legend_label="Daily Deaths", color = 'red', )

    p.line(r, curve, legend_label="Predicted Curve", line_width=2, line_color = 'red')

    script_bokeh, div_bokeh = components(p)
    resources_bokeh = CDN.render()

    html = template.render(resources=resources_bokeh,
                        script=script_bokeh,
                        div=div_bokeh)

    out_file_path = path + filename
    with io.open(out_file_path, mode='w') as f:
        f.write(html)
Beispiel #19
0
def srd():
  response=make_response(page2.render(resources=CDN.render()))
  response.headers['Access-Control-Allow-Origin'] = '*'
  response.headers['Access-Control-Allow-Methods'] = 'OPTIONS,HEAD,GET,POST'
  response.headers['Access-Control-Allow-Headers'] = 'x-requested-with'
  
  return response
Beispiel #20
0
def predict():
    # loading data from current database connection
    data = cache.get('predictData')

    if data is None:
        data = db_to_pandas(g.cursor)
        cache.set('predictData', data, timeout=10600)

    # make predictions based on fetched data

    today_pred = cache.get('predictToday')

    if today_pred is None:
        today_pred = predict_today(data)
        cache.set('predictToday', today_pred, timeout=10600)

    # make plots from predictions
    script = cache.get('predictScript')
    divs = cache.get('predictDivs')

    if script is None:
        script, divs = graphics.create_all_buildings(today_pred.transpose())
        cache.set('predictScript', script, timeout=10600)
        cache.set('predictDivs', divs, timeout=10600)
    '''
    data = db_to_pandas(g.cursor)
    today_pred = predict_today(data)
    script, divs = graphics.create_all_buildings(today_pred.transpose())
    '''
    return render_template('predict.html', divs=divs,
                           script=script, css_script=CDN.render_js())
Beispiel #21
0
def crypto(request):
    if request.user.is_authenticated:
        user = request.user
    else:
        user = False

    # do we have session data stored (avoiding too many api calls)
    try:
        print("Last data retrieved: ", request.session["timestamp"])
    except KeyError:
        request.session["timestamp"] = 0

    # sorting commands received in url or default
    try:
        sort_by = request.GET["sort_by"]
    except KeyError:
        sort_by = None

    coin_list, coin_data, market_data = retrieve_data_session_or_new_api(
        request)

    # sort data if needed (default order is by market_cap)
    if sort_by:
        print(f"Sorting data by {sort_by}...")
        rev_order = True
        if sort_by in ['symbol', 'name']:
            rev_order = False
        try:
            coin_data.sort(key=lambda x: x[sort_by], reverse=rev_order)
        except KeyError:
            print("Error sorting data!")

    resources = CDN.render()
    time_options = timeList.keys()
    currency_options = currencyList.keys()

    return render(
        request, "cryptoweb/crypto.html", {
            'resources': CDN.render(),
            'crypto_options': coin_list,
            'user': user,
            'time_options': time_options,
            'currency_options': currency_options,
            'coin_data': coin_data,
            'market_data': market_data
        })
def bokehPlot():
    company = app.vars['company']
    script, div = components(plot_price(company))
    return """
    <!doctype html>
    <head>
        {bokeh_css}
    </head>
    <body>
        {div}
        {bokeh_js}
        {script}
    </body>
    """.format(script=script,
               div=div,
               bokeh_css=CDN.render_css(),
               bokeh_js=CDN.render_js())
Beispiel #23
0
def data():
    # Solution to url_for in template not recognized: https://stackoverflow.com/questions/20843085/url-for-is-not-defined-in-flask
    main_url = url_for('main')
    logout_url = url_for('logout')
    if session['logged_in'] == True:
        return page.render(main_url=main_url, logout_url=logout_url, resources=CDN.render())
    else:
        return redirect(url_for('shop_login'))
def stockprice():
    if request.method == 'GET':
        return render_template('stocks.html')
    elif request.method == 'POST':
        theTicker = request.form['ticker']
        theOption = request.form.getlist('features')
        theDate = request.form['daterange']
        # call function to build graph
        plot = build_graph(theTicker, theOption, theDate)
        # get the plot components
        script, div = components(plot)
        # render plot on HTML page
        return render_template('stocks.html',
                               script=script,
                               div=div,
                               bokeh_css=CDN.render_css(),
                               bokeh_js=CDN.render_js())
Beispiel #25
0
def generate_sample_plot(h5file, dataset_path, dataset_index, dataset_name,
                         output_file, crt, cmz, plot_width, top_plot_height,
                         bottom_plot_height, use_global_max, global_max):
    sp_set = dataset_path + '/sp'
    if not (sp_set in h5file):
        printlog('Error! sp not found in %s ! Skipping...' % (dataset_path))
        return

    sp = np.array(h5file[sp_set])

    #sp_int = np.sum(sp, axis = 1);

    crt = np.array(crt)
    crt = crt / 60.0

    top_plot = _make_top_rt_plot(
        crt, sp, '%s. RT Integral profile, linear scale' % dataset_name,
        plot_width, top_plot_height, use_global_max, global_max)

    bottom_plot = _make_bottom_rt_plot(
        crt, cmz, sp, '%s. Full profile, log scale' % dataset_name, plot_width,
        bottom_plot_height, True, use_global_max, global_max)
    #bottom_plot2 = _make_bottom_rt_plot(crt, cmz, sp, '%s. Full profile, linear scale'%dataset_name, plot_width, bottom_plot_height, False, use_global_max, global_max);

    bottom_plot.x_range = top_plot.x_range
    #bottom_plot2.x_range = top_plot.x_range;
    #bottom_plot2.y_range = bottom_plot.y_range;

    script, div = components(
        gridplot([
            [top_plot],
            [bottom_plot],
            #[bottom_plot2]
        ]))

    with open(output_file, 'w') as fspec:

        fspec.write('\n'.join([
            '<!DOCTYPE html>',
            '<html lang="en">',
            '    <head>',
            '        <meta charset="utf-8">',
            '        <title>RT Spectrum for all peaks</title>',
            CDN.render(),
            '        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">',
            '    </head>',
            '    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>',
            '    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>',
            '    <body>',
            div,
            '    </body>',
            script,
            '<style>',
            '</style>',
            '    </html>',
        ]))
Beispiel #26
0
def main():
    p = argparse.ArgumentParser()
    p.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
    p.add_argument('outfile', nargs='?', default="site/index.html")
    p.add_argument('-t', '--template', default='template.jinja',
            help="""Jinja2 Tempate file[default: %(default)]""")
    p.add_argument('-v', '--view', default=False,
            help="""Launch browser to view output: %(default)]""")
    a = p.parse_args()

    df = pd.read_csv(a.infile)

    plots = mkplots(df)

    script, div = components(plots)
    
    js_resources = CDN.render_js()
    css_resources = CDN.render_css()
    env = Environment(loader=FileSystemLoader(THIS_DIR),
                          trim_blocks=True)
    # Alias str.format to strformat in template
    env.filters['strformat'] = str.format
    template = env.get_template(a.template)

    html = template.render( date=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                            command=" ".join(sys.argv),
                            workdir=os.getcwd(),
                            user=getpass.getuser(),
                            title="Santa Performance Plots",
                            js_resources=js_resources,
                            css_resources=css_resources,
                            script=script,
                            div=div)

    with open(a.outfile, "w") as f:
        f.write(html.encode('utf-8'))

    # to deploy to gh-pages, use the function `gh=deploy` defined in ~.bash_profile
    # first copy index.html tp the `site/` directory
    # Cribbed from https://gist.github.com/cobyism/4730490
    #    git subtree push --prefix site origin gh-pages
    if a.view:
        view(a.outfile)
Beispiel #27
0
    async def post(self, mode=None):
        """
        Retrieve unique user login statistics. The optional ``mode`` operator
        controls the output format. With mode ``raw`` the data is delivered
        with the requested content type (html, csv, text or json).

        Methods:
            POST /usage/login - deliver results

        Parameters:
            start (str): inclusive lower bound
            end (str): exclusive upper bound
            aggregate (chr): daily (d), weekly (w), monthly (m), quarterly (q)
                or yearly (y)
            content_type (str): force json, html, text

        Returns:
            data element with list of aggregation time interval and count of
            unique users who logged in

        Raises:
            401 Unauthorized:

        Examples:
            >>> GET http://devops:5001/usage/login?start=2017-01-01&aggregate=W
            >>> GET http://devops:5001/usage/login/raw?content_type=json
        """

        end = self.get_argument("end", as_type=datetime, default=now())
        start = self.get_argument("start",
                                  as_type=datetime,
                                  default=end - timedelta(days=90))
        aggregate = self.get_argument("aggregate", as_type=str, default="w")
        if mode in ("plot", "raw"):
            df = await self._query(start, end, aggregate)
            if mode == "raw":
                return self.reply(df)
            x = df.timestamp
            y = df.user
            p = figure(title="unique users",
                       x_axis_label='week',
                       sizing_mode="stretch_both",
                       y_axis_label='logins',
                       x_axis_type="datetime")
            p.line(x, y, line_width=4)
            p.title.text = "core usage by users"
            p.title.align = "left"
            p.title.text_font_size = "25px"
            return self.reply(json_item(p, "myplot"))
        return self.render("templates/usage.html",
                           rsc=CDN.render(),
                           start=start.date(),
                           end=end.date(),
                           aggregate=aggregate)
Beispiel #28
0
def render_html_col() -> str:
    """Render any of the versions"""
    # ip = request.ip.address
    record_visit()
    reload_tmpls()
    x_tools = request.args.get("xt", "")
    htmls = col.get_htmls()

    return TMPLS['col'].render(resources=CDN.render(),
                               x_tools=x_tools,
                               **htmls)
Beispiel #29
0
def home(request):
    temp = render_temperature_chart()
    weather_data = get_weather_data()
    pressao = render_pressao_chart()
    context = {
        'conditions': weather_data,
        'temperature': temp,
        'pressao': pressao,
        'bokehcdn': CDN.render()
    }
    return render(request, 'home.html', context)
Beispiel #30
0
def visualisation(session_type=None):
    global y_bottom
    global analyzer_log_dict
    global x
    global y

    # PARECERÍA QUE SE ENTRA UNA ÚNICA VEZ POR CLIENTE
    print("New Client Connected")
    plots = []
    plots.append(
        ajax_getplot(x=x,
                     y=y,
                     y_bottom=y_bottom,
                     ref_value=analyzer_log_dict["ref_level"]))
    #plots2 = []
    #plots2.append(get_ajax_plot2())
    return render_template("dashboard.html",
                           bokeh_css=CDN.render_css(),
                           bokeh_js=CDN.render_js(),
                           plots=plots)  #,plots2=plots2)
Beispiel #31
0
def root():
    global holdFileName
    global file
    arr = os.listdir(app.config['UPLOADED_DATA_DEST'])
    if request.method == 'POST':
        holdFileName = request.form.get('set')
    file = f'static/data/{holdFileName}'
    return page.render(resources=CDN.render(),
                       selected=holdFileName,
                       arr=arr,
                       holdFileName=holdFileName,
                       file=file)
Beispiel #32
0
def tickerTape_bokehPlot():
    ticker_str = app_tickerTape.vars['tickerSymbol']
    quandl.ApiConfig.api_key = 'rJS8aE3GNr2x5RBnFtr5'
    quandlData_df = getQuandlData(ticker_str)
    quandlPlot = plotQuandlData(ticker_str, quandlData_df)
    script, div = components(quandlPlot)
    return """
    <!doctype html>
    <head>
        {bokeh_css}
    </head>
    <body>
        {div}

        {bokeh_js}
        {script}
    </body>
    """.format(script=script,
               div=div,
               bokeh_css=CDN.render_css(),
               bokeh_js=CDN.render_js())
Beispiel #33
0
def graph():
    ticker = request.form.get('ticker')
    print(ticker)
    sdr = StockDataRetriever()
    stock_df = sdr.get_stock_data_in_dataframe_daily(ticker)
    boken_plotter = BokenPlotter(symbol=ticker, stock_df=stock_df)
    stock_plot_js, stock_plot_div = boken_plotter.create_plot_components()
    print(stock_plot_div)
    return render_template('graph.html',
                           resources=CDN.render(),
                           stock_plot_script=stock_plot_js,
                           plot_div=stock_plot_div)
Beispiel #34
0
def popular_places():
    try:
        db = mysql.connect()
        mycursor = db.cursor()
        mycursor.execute("select distinct(city) from placedetails")
        cities = []
        for row in mycursor:
            cities.append(row[0])
        form = AdminForm()
        form.city.choices = [(city, city) for city in cities]
        if request.method == 'POST' and form.validate_on_submit():
            cname = request.form['city']
            subset = df_iplace[df_iplace['city'] == cname]
            places = subset['placename'].value_counts().to_frame()
            plot = bc.Bar(places.iloc[0:5, ],
                          label="index",
                          values="placename",
                          plot_width=1000,
                          plot_height=700,
                          legend="top_right",
                          bar_width=0.3,
                          min_border=30,
                          xlabel="Places",
                          ylabel="Count")
            script, div = components(plot)
            return render_template(
                "admin.html",
                form=form,
                script=script,
                title_text="Top 5 Places visited by people in ",
                div=div,
                bokeh_css=CDN.render_css(),
                bokeh_js=CDN.render_js(),
                city=cname)
        return render_template("admin.html", form=form)
    except:
        print("Exception occured in admin")
    finally:
        db.close()
Beispiel #35
0
def root():
    return page.render(resources=CDN.render())
def hello_world():
    script = autoload_server(model=None,
                             url='http://localhost:5006/bkapp')
    return render_template("embed1.html", script=script,
                           resources=CDN.render())