示例#1
0
    def show_news_list(self, zipcode="21029", radius=70):
        try:
            news_list = self.get_local_news_by_zipcode(zipcode, radius)
        except BaseException as ex:
            print('-' * 60)
            traceback.print_exc(file=sys.stdout)
            print('-' * 60)
            news_list = []

        try:
            return html.Ol([
                html.Li([
                    html.A(x['title'], href=x['url'], target='_blank'),
                    html.Div(x['publishedAt'],
                             style={
                                 'size': 1,
                                 'color': "blue"
                             })
                ]) for x in news_list
            ])

        except BaseException:
            print('-' * 60)
            traceback.print_exc(file=sys.stdout)
            print('-' * 60)
            return html.Ol("API call limit")
示例#2
0
def Text():
    return [
        [
            html.Label('Markdown'),
            dcc.Markdown(dedent('''
                #### Dash and Markdown

                Dash supports [Markdown](http://commonmark.org/help).

                Markdown is a simple way to write and format text.
                It includes a syntax for things like **bold text** and
                *italics*,
                [links](http://commonmark.org/help), inline `code` snippets,
                lists, quotes, and more.

                > Don't forget blockquotes!
                > Blockquotes have a simple left border and an indent,
                > there is nothing too fancy here.
                > These styles are meant to be familiar with GitHub markdown.
            '''))
        ],

        [
            html.H1('Heading 1'),
            html.H2('Heading 2'),
            html.H3('Heading 3'),
            html.H4('Heading 4'),
            html.H5('Heading 5'),
            html.H6('Heading 6'),
        ],

        [
            html.Ul([
                html.Li('Unordered Lists have basic styles'),
                html.Li('They use the circle list style'),
                html.Li([
                    'Also, ',
                    html.Ul([
                        html.Li('nested lists feel right'),
                        html.Li('This could be a Ul or a Ol'),
                    ])
                ])
            ])
        ],

        [
            html.Ol([
                html.Li('Ordered Lists have basic styles too'),
                html.Li('They use the decimal list style'),
                html.Li([
                    'And also',
                    html.Ol([
                        html.Li('ordered lists can be nested too'),
                        html.Li('As could unordered lists'),
                    ])
                ])
            ])
        ]
    ]
示例#3
0
def display_app(pathname):
    if pathname == "/" or pathname is None:
        return html.Div(
            className="container",
            children=[
                html.H1("Dash Table Review App"),
                html.Ol([
                    html.Li(
                        dcc.Link(
                            name.replace("app_", "").replace("_", " "),
                            href="/{}".format(
                                name.replace("app_", "").replace("_", "-")),
                        )) for name in apps
                ]),
            ],
        )

    app_name = pathname.replace("/", "").replace("-", "_")
    if app_name in apps:
        return html.Div([
            html.H3(app_name.replace("-", " ")),
            html.Div(id="waitfor"),
            html.Div(apps[app_name].layout()),
        ])
    else:
        return """
            App not found.
            You supplied "{}" and these are the apps that exist:
            {}
        """.format(app_name, list(apps.keys()))
示例#4
0
    def show_news_list(self, zipcode="21029", radius=70):
        colors = ['primary', 'secondary', 'success', 'warning', 'danger', 'info']
        color_cycle = cycle(colors)
        try:
            news_list = self.get_local_news_by_zipcode(zipcode, radius)
        except BaseException as ex:
            print('-' * 60)
            traceback.print_exc(file=sys.stdout)
            print('-' * 60)
            news_list = []

        try:
            # return html.Ol([
            #     html.Li([
            #         html.A(x['title'], href=x['url'], target='_blank'),
            #         html.Div(x['publishedAt'], style={'size': 1, 'color': "blue"})
            #     ])
            #     for x in news_list])
            return dbc.ListGroup(
                [
                    dbc.ListGroupItem(
                        [
                            dbc.ListGroupItemHeading(html.H5(x['title'])),
                            dbc.ListGroupItemText(html.H6(x['publishedAt'])),
                        ],
                        href=x['url'], target='_blank', color=next(color_cycle)
                    ) for x in news_list
                ]
            )

        except BaseException:
            print('-' * 60)
            traceback.print_exc(file=sys.stdout)
            print('-' * 60)
            return html.Ol("API call limit")
示例#5
0
def build_nav_stack(stack):
    children = []
    for site in stack:
        children.append(
            html.Li(html.A(site.name, href=site.url), className='crumb'))
    return html.Div(
        children=[html.Nav(children=html.Ol(children), className='crumbs')])
示例#6
0
def component_leaderboard_4col(series_list):

    leaderboard_counts = get_leaderboard_df(series_list).iloc[:10, :]

    body = []

    for index, row in leaderboard_counts.iterrows():
        body.append(html.Li(
            index,
            className="lead",
        ))

    return dbc.Col(
        [
            html.H3("Leaderboard"),
            html.P(
                "Ranked by number of times each method was selected as the best performer",
                className="subtitle text-muted",
            ),
            html.Ol(body),
            html.A(
                html.P("View full leaderboard"),
                href="/leaderboard",
            ),
        ],
        lg=4,
    )
示例#7
0
def rec_table(n, input_val):
    # read data from cloud sql
    con = pymysql.connect(host="34.87.57.222",
                          user="******",
                          passwd="",
                          db="movies")
    query = "SELECT * FROM reco"
    rec_df_small = pd.read_sql(query, con)

    # build vectorizer
    cv = CountVectorizer(stop_words="english"
                         )  # set up a count vectorizer and remove stop words
    cv_corpus = cv.fit_transform(rec_df_small["corpus"])
    cossim_matrix = cosine_similarity(cv_corpus, cv_corpus)

    # Create a mapping of movie title to index
    indices = pd.Series(rec_df_small.index,
                        index=rec_df_small.title.values).to_dict()

    res = get_reco(input_val, cossim_matrix, indices, rec_df_small)

    children = html.Div([
        html.H4("The top 10 movies are:"),
        html.Ol(id="reco-list", children=[html.Li(i) for i in res]),
    ])
    con.close()
    return children
示例#8
0
文件: app.py 项目: dgilros/DataViz
def update_facts(pax_category):
    category = int(pax_category) if pax_category else 0
    title = Assets.CATEGORIES[category]['title']
    facts = Assets.CATEGORIES[category]['facts']
    return html.Div([
        html.H5(title),
        html.Ol([html.Li(fact) for fact in facts],
                className="list-numbered", style={"padding": "5px"})
    ])
示例#9
0
 def description_about_app(self):
     """
     :return:Retorna la visualización de las intrucciones para el aplicativo
     """
     return dbc.Card([
         dbc.CardHeader("Sobre KTMath"),
         dbc.CardBody(
             [html.Div([
                 html.H1('¿Por qué usar KtMath?', className="card-title"),
                 html.Br( ),
                 html.H2('Gestión del conocimiento con inteligencia matemática'),
                 html.Ol('- ¿Fugas en transferencia de conocimiento en tu empresa?'),
                 html.Ol('- ¿Identificas el contexto que debes analizar?'),
                 html.Ol('- ¿Quisieras reconocer de manera cuantitativa este tipo de problemáticas?'),
                 html.Ol('- ¿Generar un control de la gestión del conocimiento'),
                 html.Br( ),
                 html.H2('¿Qué es KTmath?', className="card-subtitle"),
                 html.P('KTmath es una herramienta diseñada para facilitar a las empresas y a '
                        'personas dedicadas a la gestión del conocimiento el diagnostico de problematicas '
                        'que se encuentran en la transferencia de conocimiento utilizando herramientas estadísticas'
                        ' y de machine learning para mejorar su precisión.',
                        className="card-text"),
                 html.Br( ),
                 html.H2('¿En que información se basa KTmat?', className="card-subtitle"),
                 html.P('KTmath se basa en un conjunto de variables de entrada o variables X que fueron recolectadas'
                        ' a partir de diferentes fuentes de artículos en repositorios indexados donde los autores'
                        ' realizaron análisis sobre las causas de fugas en gestión del conocimiento tales como miedo'
                        ' al reemplazo, desvinculación, cultura de documentación.'
                        'Las variables se califican de 0 a 5 por parte de encuestados que pueden ser trabajadores de '
                        'una empresa, sector entre otros y se tiene como hipotesis al final reconocer si tiene o no '
                        'tiene gestión del conocimiento formal.',
                        className="card-text"),
                 html.Br( ),
                 html.H2('¿Qué proceso realiza KTmat?', className="card-subtitle"),
                 html.P('A partir de información recolectada por medio de encuestas que cumplen una estructura '
                        'especifica de la que se extraen las posibles problemáticas de la empresa, *KTmat* utiliza'
                        ' herramientas estadisticas para filtrar dichas variables y encontrar su correlación para p'
                        'osteriormente evaluar por medio del algoritmo de machine learning llamada Maquina de vectores'
                        ' de soporte si la empresa tiene o no gestión del conocimiento y si las variables generan un '
                        'patrón definido.', className="card-text"),
             ])]
         )
     ], color="info", inverse=True, style={"width": "100%", 'marginTop': '30px', 'justify': 'center'}, )
示例#10
0
def serve_layout(_, user_key, __):
    builder = AnnotationBuilder(local=True)
    my_annotations = builder.get_annotations(user=user_key)
    children = []
    for annotation in my_annotations:
        children.append(html.Li([
            html.Span([token["text"] + " " for token in annotation.tokens[0]], style={"fontWeight": "bold"}),
            html.Br(),
            html.Span(annotation.doi),
            html.Span(" "),
            serve_ann_options(quote(annotation.doi, safe="")),
            html.Br(),
            html.Span(str(annotation.labels))
        ]))

    return html.Div([html.H5("My Annotated Abstracts"),
                    html.Ol(children)])
示例#11
0
def generate_carousel():
    logger.debug("generate carousel")
    headline_services = app_controller.get_club_headline_service(CLUB_NAME)
    if not headline_services:
        print("no headline")
        return html.Div()
    service_count = len(headline_services)
    logger.debug("generate carouse al")
    logger.debug("service count " + str(service_count))

    carousel = html.Div(**{"data-ride": "carousel"},
                        id="carouselExampleIndicators",
                        className="carousel slide",
                        children=[
        html.Ol(className="carousel-indicators", children=[
            html.Li(**{"data-target":"#carouselExampleIndicators", "data-slide-to":str(i)}, className="active" if i ==0 else "") for i in range(service_count)
        ]),
        html.Div(className="carousel-inner", children=[
            html.Div(className="carousel-item active" if i ==0 else "carousel-item", children=[
                html.Div(className="d-flex", children=[
                    dcc.Link(className="col",href="/service/book/{}".format(service.id), children=[
                        html.Img(className="img-fluid",
                                src=filestore.get_service_img_link(service.id, MAJOR_IMG),
                                alt="Second slide")

                    ]),
                    dcc.Link(className="col",href="/service/book/{}".format(service.id), children=[
                        html.Img(className="img-fluid",
                                src=filestore.get_service_img_link_alt(service.id),
                                alt="Second slide")
                    ])
                ])
            ]) for i, service in enumerate(headline_services)
        ]),
        html.A(**{"data-slide":"prev"}, className="carousel-control-prev", href="#carouselExampleIndicators", role="button", children=[
            html.Span(**{"aria-hidden":"true"}, className="carousel-control-prev-icon"),
            html.Span("Previous", className="sr-only")
        ]),
        html.A(**{"data-slide":"next"}, className="carousel-control-next", href="#carouselExampleIndicators", role="button", children=[
            html.Span(**{"aria-hidden":"true"}, className="carousel-control-next-icon"),
            html.Span("Next", className="sr-only")
        ]),
    ])
    logger.debug("return carousel")
    return carousel
示例#12
0
    def makeAbbr(self):
        title = html.H3("Abbreviations")
        text1 = dcc.Markdown(
            '''If your text is interlinearized, you can provide a list of abbreviations in plain 
        text (UTF-8) format; these will be displayed in small caps. The abbreviations file must be formatted as follows:'''
        )
        text2 = html.Ol(children=[
            html.
            Li('''List each abbreviation on a separate line. Do not include definitions. Give 
        abbreviations in ALL CAPS if that is how they appear in the ELAN file;'''
               ),
            html.Li(children=[
                '''List each part of an abbreviation that comes separated by punctuation on a separate line 
        (e.g., if you have “''',
                html.Span("pl.poss", className="smallCaps"), '''” and “''',
                html.Span("pfv:past", className="smallCaps"), '''”, list “''',
                html.Span("pl”, “poss”, “pfv”, “past”", className="smallCaps"),
                ''' separately);'''
            ]),
            html.Li(children=[
                '''Don’t include numbers for grammatical person—if you have things like “3A” or “1''',
                html.Span("pl", className="smallCaps"),
                '''”, include “A” and “''',
                html.Span("pl", className="smallCaps"),
                '''” in your list, but not “3A”, “1''',
                html.Span("pl",
                          className="smallCaps"), '''” or “1”, “2”, “3”;'''
            ]),
            html.Li(children=[
                '''Abbreviations that include subparts in superscript or subscript should be included in 
            the list along with HTML tags for super- or subscripting—for example, “''',
                html.Span(className="smallCaps",
                          children=['pl', html.Sub('excl')]),
                '''” would be listed as “pl<sub>excl</sub>”. Use “<sup></sup>” tags for superscripting in the same way.'''
            ])
        ])
        text3 = dcc.Markdown(
            '''Super/subscripting for lexical items rather than grammatical abbreviations may 
        have to be applied manually in the ELAN or HTML file itself.''')

        abbr = html.Div(className='aboutContents',
                        children=[title, text1, text2, text3])
        return abbr
示例#13
0
def update_output(n_clicks, value):
    indexer = Indexer()
    results = indexer.search(value)

    li_children = []
    for no, result in enumerate(results, 1):
        url, title, snippet = result

        if title:
            li = html.Li(children=[
                                html.A(title, href=url),
                                dcc.Markdown(children=snippet),
                            ])

            li_children.append(li)

    ol = html.Ol(children=li_children)

    return ol
示例#14
0
def set_col4_children(selected_rate):
    col4_children = [html.Hr(),
            html.H3(" "),
            html.P("""
            The model uses a time-dependent transmission/spreading rate following the assumption that a signicant change in transmission rate
            may occur at certain points over the course of a pandemic. This is modelled though change points which corresponds to Government policy
            interventions and events that could affect the transmission rate. The current model includes the following change points"""),
            html.Ol([
                html.Li("10 March 2020: Universities and schools close until further notice."),
                html.Li("18 March 2020: Border restriction including restrictions on inbound passengers."),
                html.Li("23 April 2020: Beginning of Ramadan."),
                html.Li("26 April 2020: Masks made compulsory for all shoppers, service sector and construction sector employees."),
                html.Li("17 May 2020: Masks made compulsory for all individuals going out in public."),
                html.Li("19 May 2020: Eid precautionary measures including suspending most commercial activities and travel restrictions. In effect till May 31 but this wasn't added as a change point because it's close to another change point.."),
                html.Li("22 May 2020: Ehtheraz contact tracing app made mandatory for public. Change point wasn't added following the previous reason."),
                html.Li("15 June 2020: Phase 1 of reopening measures. This change point has been added to the model."),
                html.Li("1 July 2020: Phase 2 of reopening measures."),
                ]
            ),
            html.H5("""
            When the effective growth rate goes below 0, we will see reduction in new infections and eventually eradicate the pandemic.
            Effective growth rate has been on a steady decline below 0 but a second wave is a possibility..
            """)
            ]
    if selected_rate=="Reproduction Rate":
        col4_children = [html.Hr(),
            html.H3(" "),
            html.P("""
            The effective reproductive number provides a one number summary for the state of an epidemic at a given time.
            It is defined as the number of people who become infected per infectious person at a given time. The higher the
            reproductive number, the more it is spreading. We want this number to be close to 0 and definitely under 1. Beyond 1,
            the viral transmission is in a growth phase and is infecting more and more people everyday."""),
            html.P("""
            Knowing the current reproductive number is essential as it is a good indicator of where we stand in terms of
            eradicating the pandemic. The graph on the left is derived from a Bayesian approach to estimate and track the reproductive number
            on a daily basis. Use the drop-down box to see the result of estimating a similar statistic by keeping the reproductive number
            static given a change point. Whereas the graph to the left is mostly for monitoring the present, the other graph
            derived from the SIR model is for retrospection into the interventions and providing an estimate of the growth of the pandemic
            in the future.
            """)
            ]
    return col4_children
示例#15
0
    def get_page_content(self):
        '''
        Generates the dashboard page content
        '''

        return [html.Section(className='content-header',children=[
                    html.H1(children='Gabbard Diagram'),
                    html.Ol(className='breadcrumb',children=[
                        html.Li(children=[html.I(className='fa fa-dashboard'),' Home']),
                        html.Li(className='active',children='Gabbard Diagram'),
                    ])
                ]),
                html.Section(className='content',children=[
                    html.Div(className='row',children=[
                        html.Div(className='col-md-12',children=[
                            html.Div(className='box',children=[
                                html.Div(className='box-header with-border',children=[
                                    html.H3(className='box-title',children='History of LEO till January 2021')
                                ]),
                                html.Div(className='box-body',children=[
                                    html.P("John Gabbard developed a diagram for illustrating the orbital changes and the orbital decay of debris fragments. A Gabbard diagram is a scatter plot of orbit altitude versus orbital period. Since all orbits are elliptical, a Gabbard diagram plots two points for each satellite: the apogee and perigee. Each pair of points will share the same orbital period and thus will be vertically aligned."),
                                    html.P(children=[
                                        html.Ul(children=[
                                            html.Li(html.A(href=self.base_url + '?autoplay=1&loop=1&rel=0&fs=1&start=45&end=56', target="gabbard_video", children="October 1970 - Cosmos 374 & 375 Deliberate Self-Destruct")),
                                            html.Li(html.A(href=self.base_url + '?autoplay=1&loop=1&rel=0&fs=1&start=104&end=115', target="gabbard_video", children="September 1985 - P-78/Solwind Destroyed by Anti-Satellite Weapon")),
                                            html.Li(html.A(href=self.base_url + '?autoplay=1&loop=1&rel=0&fs=1&start=147&end=159', target="gabbard_video", children="June 1996 - Step II Rocket Body Propulsion System Failure")),
                                            html.Li(html.A(href=self.base_url + '?autoplay=1&loop=1&rel=0&fs=1&start=190&end=201', target="gabbard_video", children="January 2007 - Fengyun 1C Destroyed by Anti-Satellite Weapon")),
                                            html.Li(html.A(href=self.base_url + '?autoplay=1&loop=1&rel=0&fs=1&start=199&end=210', target="gabbard_video", children="February 2009 - Iridium 33 & Cosmos 2251 Collision")),
                                            html.Li(html.A(href=self.base_url + '?autoplay=1&loop=1&rel=0&fs=1&start=240&end=251', target="gabbard_video", children="March 2019 - Microsat-R Destroyed by Anti-Satellite Weapon")),
                                        ])
                                    ]),
                                    html.Iframe(id='igabbard', name='gabbard_video', width="800", height="500", src=self.base_url + "?autoplay=1&loop=1&rel=0&fs=1", style=dict(border=0))
                                ])
                            ])
                        ])
                    ])
                ])
            ]
示例#16
0
def breadcrumb_layout(crumbs):

    return dbc.Nav(
        [
            html.Ol(
                [
                    html.Li(
                        html.A(crumb[0], href=crumb[1]),
                        className="breadcrumb-item",
                    )
                    for crumb in crumbs[:-1]
                ]
                + [
                    html.Li(
                        crumbs[-1][0],
                        id="breadcrumb",
                        className="breadcrumb-item active",
                    )
                ],
                className="breadcrumb",
            )
        ],
        navbar=True,
    )
示例#17
0
from .common import bokeh_url

about = """
Upload your AiiDA database and compare it to existing data using automated plots.
"""
about_html = [html.P(i) for i in about.split("\n\n")]

layout = [
    html.Div(
        [
            html.Div(html.H1(app.title), id="maintitle"),
            html.H2("About"),
            html.Div(about_html, className="info-container"),
            html.H2("Steps"),
            html.Div(
                html.Ol([
                    html.Li(html.A('Upload AiiDA database', href='upload/')),
                    html.Li(
                        html.A(
                            'Plot performance of all MOFs',
                            href=bokeh_url + '/figure',
                            target="_blank")),
                ]),
                className="sycolinks"),
        ],
        id="container",
        # tag for iframe resizer
        #**{'data-iframe-height': ''},
    )
]
示例#18
0
文件: app.py 项目: Futile21/heroku3
        # html.H1(children='Wind Energy Calculator',),
        dbc.Jumbotron([
            html.H3(children='Instructions', ),
            html.
            P(children=
              "The map of South Africa displays an estimated capacity factor or wind power of a "
              "specific turbine over a year at a particular height. The data entered below will "
              "be plotted on the map."),
            html.Ol([
                html.
                Li(children=
                   "Select one of the four turbine options (the different turbines with their "
                   "corresponding maximum power outputs are displayed in the table below to the"
                   " left)."),
                html.Li(
                    children="Select one of the four required hub heights."),
                html.
                Li(children=
                   "Select the type of estimate required, namely capacity factor or wind power."
                   ),
                html.Li(
                    children=
                    "To submit the requirements, click the “Plot” button."),
            ], ),
            html.
            P(children=
              "The card to right of the selection criteria displays an estimate of the capacity "
              "factor and wind power at a specific point selected on the map."
              ),
        ])
    ], )
示例#19
0
app.css.append_css({"external_url": 'https://codepen.io/chriddyp/pen/bWLwgP.css'})

app.layout=html.Div([

	html.Div([html.H1(children="Homework 3", style={"color":"maroon", "text-align":"center", "font-family":"cursive", "font-weight":"bold", "font-size":"40px"})], className="twelve columns"),

	#row1

	html.Div([
		html.Div([html.P("Homework 3 assumes the development of this web application using Dash and Plotly in Python.You are required to develop 6 plots (including one table) with the given layout. Subtle differences related to styling (colors etc) are allowed, yet the general layout must be kept to perceive same information as this website does. Quandl is used as a data source for 4 plots among 6, while the other 2 are based on user provided data. Some of the Quandl based plots require minor analysis using pandas. You are encouraged to follow below mentioned steps to complete the HW:",
			style={"text-align":"justify","padding-left":"10",}),
			
			html.Ol(
				[html.Li("Start from first developing the 6 plots in Jupyter Notebook,"),
				html.Li("Once plots are ready post them into the Dash app,"),
				html.Li("Add HTML components (website heading etc.),"),
				html.Li("Structure the layout of the dashboard.")], style={"padding-left":"25",}

				)], className="four columns"),

		html.Div([html.P("Graph 1", style={"font-weight":"bold", "font-size":"18px"}), html.P("The graph on the right hand side is showing correlations of different variables (call them from x1 to x8) with employee churn. Data is artificial, manually inputted by the developer. Recreate the graph. Small coloring or corelation value differences will be neglected."),
			], className="four columns"),

		html.Div([
		dcc.Graph(id="Graph1", figure=f1)],
		className="four columns")

		], className="twelve columns"),


	#row2
示例#20
0
 ),
 html.Div(html.Br()),
 html.Div("B. Jenis informasi yang dikumpulkan"),
 html.Div(html.Br()),
 html.P(
         "Jenis informasi pribadi pengguna yang kami kumpulkan baik langsung maupun melalui pihak ketiga antara lain: "
 ),
 html.Ol(
     [
         html.Li(html.Div("Nama pengguna")),
         html.Li(html.Div("Username")),
         html.Li(html.Div("Password")),
         html.Li(html.Div("Alamat email")),
         html.Li(html.Div("IP Address")),
         html.Li(html.Div("Browser")),
         html.Li(html.Div("Jaringan")),
         html.Li(html.Div("Informasi lokasi")),
         html.Li(html.Div("Pageview/hit")),
         html.Li(html.Div("Sesi")),
         html.Li(html.Div("Informasi OS")),
         html.Li(html.Div("Tipe device")),
         html.Li(html.Div("Referer"))
     ]
 ),
 html.P(
         "Sebagian besar informasi tersebut dikumpulkan dan digunakan untuk kepentingan agregasi statistik laman "
         "dan tidak dipergunakan untuk kepentingan selain operasional akun pengguna dalam penggunaan layanan "
         "laman rippleet.com."
 ),
 html.Div(html.Br()),
 html.Div("C. Bagaimana kami mengumpulkan informasi pengguna"),
示例#21
0
     html.Div(html.H1(app.title), id="maintitle"),
     html.H2("About"),
     html.Img(src="assets/images/logo.png", className="sycologo"),
     html.Img(src="assets/images/schema.png", className="sycoschema"),
     html.Div(about_html + [
         html.P(
             html.A(html.B("Watch the tutorial on Youtube"),
                    href='https://youtu.be/i8i4HmEEw4Y',
                    target='_blank')),
     ],
              className="info-container"),
     html.H2("Steps"),
     html.Div(html.Ol([
         html.Li(html.A('Compute diverse set', href='maxdiv/')),
         html.Li(
             html.A('Genetic Algorithm: compute next generation',
                    href='ga/')),
         html.Li(html.A('Determine importance of variables',
                        href='ml/')),
     ]),
              className="sycolinks"),
     html.H2("Changelog"),
     html.Ul([
         html.Li([html.B(k + " "), html.Span(v)]) for k, v in changelog
     ], ),
     html.P([
         "Find the code ",
         html.A("on github",
                href="https://github.com/ltalirz/sycofinder",
                target='_blank'), "."
     ]),
 ],
示例#22
0
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

df = get_dataframe()

app.layout = html.Div(children=[
    html.H1('Brand or App Name', style= {'color': "pink", 'backgroundColor': "grey",
    'padding': '50px', 'fontSize': '70px',
    'border': '3px solid green'}),
    html.H2('put tagline or branding here'),

    html.Ol([
        html.Li('Select your product category'),
        html.Li('Now select the profile that reflects your skin care lifestyle'),
        html.Li('Click the button to receive your recommended products'),
        
        ]),
    
    html.Label('Select Category'),
    dcc.Dropdown(id='category_drop',
        options=[
            {'label': 'Mositurizer', 'value': 'More Mositurizer'},
            {'label': 'Cleansers', 'value': 'More Cleanser'},
            {'label': 'Anti-Aging', 'value': 'More Anti-Aging'},
            {'label': 'Eye Treatments', 'value': 'More Eye Treatments'},
            {'label': 'Acne Control', 'value': 'More Blemish + Acne Control'},
            {'label': 'Toners', 'value': 'More Toners, Astringents'},
            {'label': 'Nightime', 'value': 'More Night Cream'},
            {'label': 'Sun Protection', 'value': 'More Sun Protection '}
        ],
示例#23
0
 html.Ol([
     html.Li([
         'Fristly, we consider a) the arithmetic average of bond yields across different maturities ' +\
         'and b) the prices of a stock index. While the market is not open,we retrieve the past N days of data' + \
         " for:",
         html.Ul([
             html.Li("IVV: daily open, high, low, & close prices"),
             html.Li(
                 "US Treasury CMT Rates for 1 mo, 2 mo, 3 mo, 6 mo, " + \
                 "1 yr and 2 yr maturities and we consider the arithmetic average."
             )
         ])
     ]),
     html.Li([
         'As bond and stock prices display a well known inverse relationship,'+\
         'we regress stock prices over bond yields to obtain a OLS fitting model in the last '+\
         'n days. Furthermore, we compute some additional statistical features : correlation coefficient'+\
         'of the two time series and confidence intervals of the regression coefficient. We will perform orders'+\
         'only when the two following conditions are satisfied:',
         html.Ul([
             html.Li('The regression coefficient is negative with a 95% CI.'),
             html.Li(' The absolute value of the correlatio coefficient is greater or equal than a value rho, which can also be modified as a parameter.'),
             html.Li('Despite the user is free to change the value of the correlation coefficient. The economic intuition behind the model lies in the negative relationship '+\
                     'between the bond yield curve and teh stock market. Therefore a negative correlation of at least 0.5 is suggested,'+\
                     'although this may result in a limited number of trades')
         ]),
     ]),
     html.Li(
         'We perform a buy order on the stock index when the Bond Yield is rising and a Sell ' +\
         'order when the bond yield is decreasing. We only perform an order if the magnitude of the change is' +\
         'significant. To compute this, we regress the bond yields of the previous 5 days to predict the '+\
         'future value. Assuming that the Bond yield follows a normal distribution, whose parameters are given'+\
         'by the mean and standard deviation of the regression coefficient, we execute and order only if the'+\
         'shift is greater than a given confidence interval, which can be modified to fit different trading styles'+\
         '(defensive trading strategies will choose a higher confidence interval, aggressive trading strategies a lower one). ''Repeat 2. for past CMT data to create a FEATURES ' + \
         'dataframe containing historical values of a, b, and R^2 '
     ),
     html.Li(
         'We always enter with a market order. We then place a limit order with threshold alpha, which can be modified as parameter'+\
         'Finally, if after n days the order is not closed yet, the limit oerder is cancelled and the market oder closed.'
     ),
     html.Li(
         'Given the macroeconomic intuition behind it, the model is more suited for position trading, considering a threshold'+\
         'rho of at least 0.5 in absolute value and therefore implementing a limited number of trades.'
     )
 ])
示例#24
0
def recommend(n_clicks, num_recs, upperlimit, lowerlimit, input_box):
    """ Wrapped function which takes user input in a text box, a slider and 2 on-off switches
    and returns a set of citation recommendations based on these parameters.
    ARGUMENTS: n_clicks: a parameter of the HTML button which indicates it has 
               been clicked
               input_box: the content of the text area in which the user has 
               entered a citation context.
               num_recs: no. of recommendations to return
               lowerlimit: if selected, the MAG50 model is used. MAG model is used by default
               upperlimit: if selected, recommendations with >500 citations are discarded.

    RETURNS:   list of recommendations with titles displayed, abstract, no. of citations and year
               in tooltip. Each recommendation links to the corresponding MAG page"""

    context = clean_text(input_box)
    print(upperlimit, num_recs, n_clicks)
    if context != '':
        if lowerlimit:
            hd2vrecommendations = hd2v_wvindvout_recommend(
                context, hd2vreducedmodel)
            bm25recommendations = solr_recommend(context, 'mag_en_cs_50_all')
            citedbm25_recommendations = solr_cited_recommend(
                context, 'mag_en_cs_50_cited_all')
            if not hd2vrecommendations or not bm25recommendations or not citedbm25_recommendations:
                return html.Div([
                    html.Br(),
                    html.Br(),
                    html.H2('No recommendations returned.'),
                ])
            hybrid_recommendations = hybrid_recommend(
                hd2vrecommendations, bm25recommendations,
                citedbm25_recommendations)
            # magid, title, year, citations, abstract
            if upperlimit:
                all_recommendations = get_paper_details(hybrid_recommendations)
                reduced_recommendations = [
                    recomm for recomm in all_recommendations
                    if recomm[3] <= 500
                ]
                reduced_recommendations = get_topn(reduced_recommendations,
                                                   num_recs)
            else:
                reduced_recommendations = get_paper_details(
                    get_topn(hybrid_recommendations, num_recs))
            #recommended_titles = [details[1] for details in get_paper_details(reduced_recommendations)]
            return html.Div([
                    html.Br(),
                    html.Br(),
                    html.H2('Recommendations:'),
                    html.Ol([html.Li(html.A(recomm[1],
                                            href='https://academic.microsoft.com/paper/{}'.format(recomm[0]),
                                            title=' Year: {}\nAbstract:{}'\
                                                .format(recomm[2], recomm[4]))
                                    )
                        for recomm in reduced_recommendations])
                ])
        else:
            hd2vrecommendations = hd2v_wvindvout_recommend(context, hd2vmodel)
            bm25recommendations = solr_recommend(context, 'mag_en_cs_all')
            citedbm25_recommendations = solr_cited_recommend(
                context, 'mag_en_cs_cited_all')
            if not hd2vrecommendations or not bm25recommendations or not citedbm25_recommendations:
                return html.Div([
                    html.Br(),
                    html.Br(),
                    html.H2('No recommendations returned.'),
                ])
            hybrid_recommendations = hybrid_recommend(
                hd2vrecommendations, bm25recommendations,
                citedbm25_recommendations)
            # magid, title, year, citations, abstract
            if upperlimit:
                all_recommendations = get_paper_details(hybrid_recommendations)
                reduced_recommendations = [
                    recomm for recomm in all_recommendations
                    if recomm[3] <= 500
                ]
                reduced_recommendations = get_topn(reduced_recommendations,
                                                   num_recs)
            else:
                #print(hybrid_recommendations)
                reduced_recommendations = get_paper_details(
                    get_topn(hybrid_recommendations, num_recs))
            #recommended_titles = [details[1] for details in get_paper_details(reduced_recommendations)]
            return html.Div([
                    html.Br(),
                    html.Br(),
                    html.H2('Recommendations:'),
                    html.Ol([html.Li(html.A(recomm[1],
                                            href='https://academic.microsoft.com/paper/{}'.format(recomm[0]),
                                            title=' Year: {}\nAbstract:{}'\
                                                .format(recomm[2], recomm[4]))
                                    )
                        for recomm in reduced_recommendations])
            ])
示例#25
0
文件: iCook.py 项目: chris-ault/iCook
def generate_recipies(search_btn, skip_btn, clear_btn, ingredients_selected,
                      cur_recipe_idx, cached_recipes):
    """generate_recipies
    --
    Here the recipe is parsed, displayed on the screen
        other recipies are stored as a browser data element
    """
    # Stop dash from firing this callback until we are ready
    if not ingredients_selected:
        raise PreventUpdate

    recipe_buffer = 30

    # Check that search button was clicked not skip or clear
    if search_btn > clear_btn and search_btn > skip_btn:
        logging.info(
            f"search clicked, ingredients selected are: {','.join(ingredients_selected)}"
        )

        # Here we should fire the search recipe with ingredients_selected query
        # to update the recipies variable
        # https://api.spoonacular.com/recipes/findByIngredients?ingredients=apples,+flour,+sugar&number=2
        try:
            response = requests.get(
                'https://api.spoonacular.com/recipes/findByIngredients?ingredients='
                + ','.join(ingredients_selected) + '&number=' +
                str(recipe_buffer) + "&apiKey=" + API_SECRET)
            # check that requests didn't receive api related errors:
            # 401 status code
            if response.status_code == 401:
                logging.error("API Key related error")
            response.raise_for_status()
            # store json response as recipe data
            recipies = response.json()
            logging.debug(f"Response is:  {recipies}")
        except HTTPError as http_err:
            logging.error(f'HTTP error occurred: {http_err}')

    # When clearing we will hide the recipe div and blank recipe elements
    # rename the save ingredients button to clear the number value
    # return the current recipe index
    # empty the ingredients dropdown selection
    if clear_btn > search_btn and clear_btn > skip_btn:
        logging.info("clear clicked")
        return [{
            'display': 'none    '
        }, '', '', '', '', 'Save ingredients', '', cur_recipe_idx, '']
    if skip_btn > clear_btn and skip_btn > search_btn:
        logging.info("skip clicked")

        # Use the cached list and iterate to the next element
        recipies = cached_recipes

        # TODO: Return a "Last recipe message"
        # this is a quick fix that will wrap the user back
        # to the first recipe to prevent a index error on recipies
        if cur_recipe_idx < recipe_buffer - 1:
            cur_recipe_idx = cur_recipe_idx + 1
        else:
            cur_recipe_idx = 0

    # recipe title
    recipe_title = html.H4(recipies[cur_recipe_idx]['title'])

    # recipe image
    cur_recipe_image = recipies[cur_recipe_idx]['image']

    # recipe ingredients we have
    used_ingredients_images = [
        html.Img(src=n['image'])
        for n in recipies[cur_recipe_idx]['usedIngredients']
    ]

    # TODO: Make 'recipe steps' a first-class class
    # Quick fix: Append to our ingredients photo a header and list of steps
    current_id = recipies[cur_recipe_idx]['id']

    logging.info(f"Current recipe id: {current_id}")

    try:
        response = requests.get('https://api.spoonacular.com/recipes/' +
                                str(current_id) + '/analyzedInstructions' +
                                "?stepBreakdown=true&apiKey=" + API_SECRET)
        # check that requests didn't receive api related errors:
        # 401 status code
        if response.status_code == 401:
            logging.error("API Key related error")
        response.raise_for_status()
        # access JSOn content
        recipe_steps = response.json()
    except HTTPError as http_err:
        print(f'HTTP error occurred: {http_err}')

    if len(recipe_steps) > 0:
        recipe_steps = [
            html.H5("Steps:"),
            html.Ol([
                html.Li(children=recipe_steps[0]['steps'][n]['step'])
                for n in range(len(recipe_steps[0]['steps']))
            ])
        ]
        used_ingredients_images = used_ingredients_images + recipe_steps

    # recipe missing ingredients
    recipe_missing_ingredients = [{
        'name': n['name'],
        'id': n['id'],
        'aisle': n['aisle'],
        'amount': n['amount'],
        'unit': n['unit']
    } for n in recipies[cur_recipe_idx]['missedIngredients']]
    logging.debug(
        f"Writing missing ingredients as {recipe_missing_ingredients}")

    # update button title
    save_recipe_btn = "Save " + \
        str(recipies[cur_recipe_idx]['missedIngredientCount']
            ) + " Missing ingredients to cart"
    return [{
        'display': 'block',
        'border-radius': '25px',
        'border': '15px solid #73AD21',
        'padding': '20px',
    }, recipe_title, cur_recipe_image, used_ingredients_images,
            recipe_missing_ingredients, save_recipe_btn, recipies,
            cur_recipe_idx, ingredients_selected]
示例#26
0
app = dash.Dash()

app.layout = html.Div(
html.H1(children="Hello Dash!")
)

app.run_server(debug=True, use_reloader=False)
    


app.layout = html.Div([
    html.H1("Hello Dash!"),
    html.P("Let's add an ordered list"),
    html.Ol([
        html.Li("Item one"), html.Li("Item two"), html.Li("Item three")
        ])
])



app.layout = html.Div([
    html.Label('Select a country:'),
    dcc.Dropdown(
        options=[
            {'label': 'United Kingdom', 'value': 'GBR'},
            {'label': 'United States', 'value': 'USA'},
            {'label': 'France', 'value': 'FRA'}
        ],
        value='GBR'
    )
示例#27
0
        ],
                 className="collapse navbar-collapse",
                 id="myNavbar")
    ],
             className="container")
],
                   className="navbar navbar-default navbar-fixed-top")

## carousel
carousel = html.Div(
    [
        # Indicators
        html.Ol([
            html.Li(**{'data-target': '#myCarousel'},
                    **{'data-slide-to': '0'},
                    className="active"),
            html.Li(**{'data-target': '#myCarousel'}, **{'data-slide-to': '1'})
        ],
                className="carousel-indicators"),
        # Wrapper for slides
        html.Div([
            html.Div([
                html.Img(src=app.get_asset_url('cover2.png'),
                         width="100%",
                         height='70%'),
                html.Div([
                    html.H3(['Audrey Hepburn']),
                    html.P(['The Angel Failing To The Earth!'])
                ],
                         className="carousel-caption")
            ],
示例#28
0
 html.Ol([
     html.Li([
         "After the market is closed, retrieve the past 100 days (not including today)' " + \
         "data of the following 5 variables:",
         html.Ul([
             html.Li("IVV signal: retrieve the past 99 days and today's IVV return(close / last day's close - 1). "
                 "If the IVV return is >= 0, we denote it as +1, else -1. And we call it IVV signal."),
             html.Li("ROE: daily IVV ROE"),
             html.Li("Turnover Ratio: average turnover ratio of the 500 component stocks in S&P 500"),
             html.Li("Expected Inflation: 10Y Treasury Yield - 10Y TIPS Yield"),
             html.Li("Trend Score in past 3 days: When one day's return is (> 0, < 0, 0), "
                     "the day get (+1, -1, +1) score. For example, in the past 3 days"
                     ", if the daily return(close / last day's close) is (0.01, 0, -0.01), then "
                     "the scores are (1, 1, -1), the Trend Score = 1 + 1 - 1 = 1")
         ]),
     ]),
     html.Li([
         'Use these 100 data to train a Logistic regression model. The training data are',
         html.Ul([
             html.Li('y: IVV signal in past 99 days and today.'),
             html.Li('x: ROE, Turnover Ratio, Expected Inflation and Trend Score in past 100 days')
         ])
     ]),
     html.Li(
         "In step 2, we can get the coefficients of the Logistic regression.\n Then, we put today's "
         "ROE, Turnover Ratio, Expected Inflation and Trend Score into the model. And get next day's IVV signal"
     ),
     html.Li([
         "If the IVV signal in next day is +1:",
         html.Ul([
             html.Li("Use half of the cash to bid a limited price on today's close price"),
             html.Li("Use half of the cash to bid a market price on next day's open price")
         ]),
         "  If the IVV signal in next day is -1:",
         html.Ul([
             html.Li("Use half of the stock shares to ask a limited price on today's close price"),
             html.Li("Use half of the stock shares to ask a market price on next day's open price")
         ])]
     )
 ])
示例#29
0
                                html.P('MOST SELLS OFFICE', className='twelve columns indicator_text font-sans text-4xl font-bold'),
                                html.P(id='top-office-sells', className='indicator_value text-3xl')
                            ]
                        ),
                        html.Div(
                            className='w-4/12 indicator pretty_container text-teal-700 text-center bg-blue-100 px-4 py-10 m-2',
                            children=[
                                html.P('MOST REVENUE OFFICE', className='twelve columns indicator_text font-sans text-4xl font-bold'),
                                html.P(id='top-office-revenue', className='indicator_value text-3xl')
                            ]
                        ),
                        html.Div(
                            className='w-4/12 indicator pretty_container text-teal-700 text-center bg-blue-100 px-4 py-10 m-2',
                            children=[
                                html.P('TOP DISTRIBUTORS', className='twelve columns indicator_text font-sans text-4xl font-bold'),
                                html.Ol(id='top-distributors', className='indicator_value text-3xl')
                            ]
                        ),
                        html.Div(
                            className='w-4/12 indicator pretty_container text-teal-700 text-center bg-blue-100 px-4 py-10 m-2',
                            children=[
                                html.P('TOP PRODUCTS', className='twelve columns indicator_text font-sans text-4xl font-bold'),
                                html.Ol(id='top-products', className='indicator_value text-3xl')
                            ]
                        )
                    ],
                ),
            ]),
    ])
]
示例#30
0
    def get_page_content(self):
        '''
        Generates the dashboard page content
        '''

        return [
            html.Section(
                className='content-header',
                children=[
                    html.H1(children='Maneuver Detection'),
                    html.Ol(
                        className='breadcrumb',
                        children=[
                            html.Li(children=[
                                html.I(className='fa fa-dashboard'), ' Home'
                            ]),
                            html.Li(className='active',
                                    children='Maneuver Detection'),
                        ])
                ]),
            html.Section(
                className='content',
                children=[
                    html.Div(
                        className='row',
                        children=[
                            html.Div(
                                className='col-md-12',
                                children=[
                                    html.Div(
                                        className='box',
                                        children=[
                                            html.Div(
                                                className=
                                                'box-header with-border',
                                                children=[
                                                    html.H3(
                                                        className='box-title',
                                                        children=
                                                        'Maneuver Detection')
                                                ]),
                                            html.Div(
                                                className='box-body',
                                                children=[
                                                    html.
                                                    P("A few noval approaches were attempted to detect satellite maneuvers as demonistrated in the following images."
                                                      ),
                                                    dcc.Tabs(
                                                        id="maneuver-tabs",
                                                        value='maneuver-aqua',
                                                        children=[
                                                            dcc.Tab(
                                                                label='AQUA',
                                                                value=
                                                                'maneuver-aqua'
                                                            ),
                                                            dcc.Tab(
                                                                label=
                                                                'COSMOS 2251',
                                                                value=
                                                                'maneuver-cosmos'
                                                            ),
                                                            dcc.Tab(
                                                                label='GCOM W1',
                                                                value=
                                                                'maneuver-gcom'
                                                            ),
                                                            dcc.Tab(
                                                                label='GLAST',
                                                                value=
                                                                'maneuver-glast'
                                                            ),
                                                            dcc.Tab(
                                                                label=
                                                                'ISS (ZARYA)',
                                                                value=
                                                                'maneuver-iss'
                                                            ),
                                                            dcc.Tab(
                                                                label='OCO 2',
                                                                value=
                                                                'maneuver-oco'
                                                            ),
                                                            dcc.Tab(
                                                                label=
                                                                'PAYLOAD C',
                                                                value=
                                                                'maneuver-payloadc'
                                                            ),
                                                            dcc.Tab(
                                                                label=
                                                                'STARLINK-1007',
                                                                value=
                                                                'maneuver-starlink'
                                                            ),
                                                        ]),
                                                    html.P(" "),
                                                    html.Div(id='tab-content')
                                                ])
                                        ])
                                ])
                        ])
                ])
        ]