Beispiel #1
0
 def on_button_yes_clicked(b):
     disable_buttons()
     response = trigger_subscription(entity_id, entity_type, credentials)
     if response:
         display(HTML(responses.get('ok')))
     else:
         display(HTML(responses.get('error')))
Beispiel #2
0
def column_output_widget(df, colname, **kwargs):
    logger.debug("inside column_output_widget")
    output = Output()
    with output:
        vis_output = Output()
        preds_output = Output()

        with vis_output:
            if df[colname].dtype.name in ['int64', 'float64']:
                logger.debug("invoking histogram_widget for %s" % (colname))
                hplot = histogram_widget(df, colname)
                logger.debug("histogram widget created for %s" % (colname))
                hist_html = HTML("<h2>Histogram Plot of %s</h2>" % (colname))
                display(hist_html)
                display(hplot)
            else:
                logger.debug("invoking histogram_widget for %s" % (colname))
                hplot = histogram_widget(df, colname)
                logger.debug("histogram widget created for %s" % (colname))
                logger.debug("invoking pie_chart_widget for %s" % (colname))
                pie_widg = pie_chart_widget(df, colname)
                logger.debug("pie widget created for %s" % (colname))
                pie_html = HTML("<h2>Pie Plot of %s</h2>" % (colname))
                hist_html = HTML("<h2>Histogram Plot of %s</h2>" % (colname))
                display(hist_html)
                # histogram plot
                display(hplot)
                # plot pie chart
                display(pie_html)
                display(pie_widg)

        with preds_output:
            # get preds and scores
            logger.debug("invoking predictors of %s" % colname)
            preds = predictors(df, df[colname])
            logger.debug("got predictors of %s" % colname)
            logger.debug("creating predictors_widget for %s" % colname)
            pw = predictors_widget(preds, colname)
            logger.debug("done creating predictors_widget for %s" % colname)
            display(pw)

        tab = Tab([vis_output, preds_output])
        tab.set_title(0, "Visualize")
        tab.set_title(1, "Predictors")
        # display tab
        display(tab)
    logger.debug("returning from column_output_widget")

    return output
Beispiel #3
0
def _display_existing_subscription_message_notebook(entity_id, entity_type):
    check_package('ipywidgets')

    from ipywidgets.widgets import HTML

    message = '''
        <h3>Subscription already purchased</h3>
        The {0} <b>{1}</b> has already been purchased.
        '''.format(entity_type, entity_id)
    display(HTML(message))
Beispiel #4
0
 def displayResponse(self):
     '''
     查看结果
     :return: 
     '''
     if not self.cf.isReady():
         print(Fore.RED + '配置项尚未初始化!')
     else:
         self.htmResult = HTML(value = '')
         self.gdResult = qgrid.show_grid(pd.DataFrame([]))
         boxResult = VBox([self.htmResult, self.gdResult])
         display(boxResult)
    def display_beautifully(self):
        content_items = []
        for i in range(len(self.data_results)):
            news, titles, texts, urls, scores = self.data_results[i]
            #content_items.append(self.rsspedia_search.display_beautifully(titles, texts, urls, scores))
            content_items.append(
                HTML(value="{}".format(
                    self.rsspedia_search.display_beautifully(
                        titles, texts, urls, scores))))
        accordion = Accordion(children=(content_items), )

        for i in range(len(self.data_titles)):
            accordion.set_title(i, "{}. {}".format(i + 1, self.data_titles[i]))

        display(accordion)
Beispiel #6
0
    def displayExecute(self):
        '''
        执行请求
        :return: 
        '''
        if not self.cf.isReady():
            print(Fore.RED + '配置项尚未初始化!')
        elif self.env.tester is not None:
            self.btnExecute = Button(description = '执行请求', button_style = 'primary')
            btnCopy = Button(description = '复制请求链接')

            self.btnExecute.on_click(self.on_execute_clicked)
            btnCopy.on_click(self.on_copy_clicked)

            self.htmExecute = HTML(value = '')
            # boxExecute = VBox([Box([self.btnExecute, btnCopy]), self.htmExecute])
            boxExecute = VBox([self.btnExecute, self.htmExecute])

            display(boxExecute)
Beispiel #7
0
    def run(self):
        display(self.keyword)
        display(self.search_button)
        display(self.setting)
        display(self.save_button)
        display(self.out)

        style = """
            <style>
            .jupyter-widgets-output-area .output_scroll {
                height: unset !important;
                border-radius: unset !important;
                -webkit-box-shadow: unset !important;
                box-shadow: unset !important;
            }
            .jupyter-widgets-output-area  {
                  height: auto !important;
            }
         </style>
        """
        display(HTML(style))
Beispiel #8
0
    def build_dashboard(self, df):
        # build tab children
        logger.info("building glimpse output widget...")
        glimpse = glimpse_output_widget(df)
        logger.info("finished building glimpse output widget")
        logger.info("building column output widget...")
        column = columns_output_widget(df)
        logger.info("finished building columns output widget")
        logger.info("building pairwise output widget..")
        pairwise = HTML("Dummy")
        logger.info("finished building pairwise output widget")
        logger.info("building cross filter widget...")
        cross_filter = cf_output_widget(df)
        logger.info("finished building cross filter widget")

        tab_children = [glimpse, column, cross_filter, pairwise]
        # set tab children
        self.set_tab_children(tab_children)
        # set dashboard children
        self.set_dash_children([self.tab])

        return self.dashboard
Beispiel #9
0
def _create_notebook_form(entity_id, entity_type, message, responses,
                          credentials):
    check_package('ipywidgets')

    from ipywidgets.widgets import HTML, Layout, Button, GridspecLayout

    text = HTML(message)

    button_yes = Button(description='Yes',
                        button_style='info',
                        layout=Layout(height='32px', width='176px'))
    button_no = Button(description='No',
                       button_style='',
                       layout=Layout(height='32px', width='176px'))

    buttons = GridspecLayout(1, 5)
    buttons[0, 0] = button_yes
    buttons[0, 1] = button_no

    def disable_buttons():
        button_yes.disabled = True
        button_no.disabled = True

    def on_button_yes_clicked(b):
        disable_buttons()
        response = trigger_subscription(entity_id, entity_type, credentials)
        if response:
            display(HTML(responses.get('ok')))
        else:
            display(HTML(responses.get('error')))

    def on_button_no_clicked(b):
        disable_buttons()
        display(HTML(responses.get('cancel')))

    button_yes.on_click(on_button_yes_clicked)
    button_no.on_click(on_button_no_clicked)

    return (text, buttons)
Beispiel #10
0
    def displayEnv(self):
        '''
        显示环境组件
        :return: 
        '''
        if not self.cf.isReady():
            print(Fore.RED + '配置项尚未初始化!')
        else:
            self.envcode = self.cf.readConf(self.default['interface'], 'env') # 环境代码
            self.testercode = self.cf.readConf(self.default['interface'], 'tester') # 测试员代码
            self.catagoryname = self.cf.readConf(self.default['interface'], 'catagoryname') # 接口类别名称
            self.server = servers[self.envcode] if self.envcode is not None else None # 服务器地址
            self.tester = testers[self.testercode] if self.envcode is not None else None # 测试信息
            # 组件初始化
            self.dpEnv = Dropdown(
                options = [key for key, value in servers.items()],
                value = self.envcode if self.envcode is not None else None,
                description = '环境:'
            )
            self.dpTester = Dropdown(
                options = [key for key, value in testers.items() if value['envcode'] == self.dpEnv.value],
                value = self.testercode if self.testercode is not None else None,
                description = '账号:'
            )

            self.dpEnv.observe(self.on_env_change)
            self.dpTester.observe(self.on_tester_change)

            self.htmEnv = HTML(value = self.choiceResult())

            debug.out('display from env object=%s' % self)
            display(self.dpEnv)
            display(self.dpTester)

            acRef = Accordion(children = [self.htmEnv])
            acRef.set_title(0, '环境参考')
            toggleRefDisplay(acRef)
            display(acRef)
            ref.append(acRef)
Beispiel #11
0
def predictors_widget(preds, target):
    # plen = len(preds)
    logger.debug("inside predictors_widget")
    preds_btn = []
    for key, val in preds:
        btn = Button(description='%s : %s' % (key, val),
                     disabled=False,
                     button_style='',
                     tooltip=str(val),
                     layout=predbtn_layout,
                     display='flex',
                     flex_flow='column',
                     align_items='stretch')  # , icon='check')
        # set btn color
        btn.style.button_color = 'lightgreen'
        preds_btn.append(btn)

    logger.info("Done creating predictor buttons")

    head_out = HTML(
        "<h3> Predictors of `%s` with their predictive power </h3>" % (target))
    preds_btn.insert(0, head_out)
    children = preds_btn
    preds_widget = VBox(children, layout=pred_wiget_layout)
    bar_w = pp_barplot_widget(preds)
    # set width of bar plot
    bar_w.layout.width = 450

    rightside_vis = HBox([bar_w], display='flex', align_items="stretch")
    #rightside_vis.layout.align_items = 'center'
    rightside_vis.layout.flex = "1.5 1 auto"
    rightside_vis.layout.width = "60%"
    rightside_vis.layout.border = '1px solid black'
    preds_widget.layout.flex = "1 1 auto"
    preds_widget = HBox([preds_widget, rightside_vis],
                        layout=layout,
                        display='flex')
    return preds_widget
Beispiel #12
0
def mk_map_region_selector(height='600px', **kwargs):
    from ipyleaflet import Map, WidgetControl, FullScreenControl, DrawControl
    from ipywidgets.widgets import Layout, Button, HTML
    from types import SimpleNamespace

    state = SimpleNamespace(selection=None, bounds=None, done=False)

    btn_done = Button(description='done', layout=Layout(width='5em'))
    btn_done.style.button_color = 'green'
    btn_done.disabled = True

    html_info = HTML(
        layout=Layout(flex='1 0 20em', width='20em', height='3em'))

    def update_info(txt):
        html_info.value = '<pre style="color:grey">' + txt + '</pre>'

    m = Map(**kwargs) if len(kwargs) else Map(zoom=2)
    m.scroll_wheel_zoom = True
    m.layout.height = height

    widgets = [
        WidgetControl(widget=btn_done, position='topright'),
        WidgetControl(widget=html_info, position='bottomleft'),
    ]
    for w in widgets:
        m.add_control(w)

    draw = DrawControl()

    draw.circle = {}
    draw.polyline = {}
    draw.circlemarker = {}

    shape_opts = {
        "fillColor": "#fca45d",
        "color": "#000000",
        "fillOpacity": 0.1
    }
    draw.rectangle = {"shapeOptions": shape_opts}
    poly_opts = {"shapeOptions": dict(**shape_opts)}
    poly_opts["shapeOptions"]["original"] = dict(**shape_opts)
    poly_opts["shapeOptions"]["editing"] = dict(**shape_opts)

    draw.polygon = poly_opts
    draw.edit = True
    draw.remove = True
    m.add_control(draw)
    m.add_control(FullScreenControl())

    def on_done(btn):
        state.done = True
        btn_done.disabled = True
        m.remove_control(draw)
        for w in widgets:
            m.remove_control(w)

    def bounds_handler(event):
        (lat1, lon1), (lat2, lon2) = event['new']
        txt = 'lat: [{:.{n}f}, {:.{n}f}]\nlon: [{:.{n}f}, {:.{n}f}]'.format(
            lat1, lat2, lon1, lon2, n=4)
        update_info(txt)
        state.bounds = dict(lat=(lat1, lat2), lon=(lon1, lon2))

    def on_draw(event):
        v = event['new']
        action = event['name']
        if action == 'last_draw':
            state.selection = v['geometry']
        elif action == 'last_action' and v == 'deleted':
            state.selection = None

        btn_done.disabled = state.selection is None

    draw.observe(on_draw)
    m.observe(bounds_handler, ('bounds', ))
    btn_done.on_click(on_done)

    return m, state
Beispiel #13
0
    def __init__(self, logviews=None):
        if logviews is None:
            logviews = []

        line = Text(value='',
                    placeholder='log filters',
                    layout=Layout(width='200px'),
                    disabled=False)

        icon_info = ToolButton(value=True,
                               toggleable=True,
                               button_color='#bdbdbd',
                               pressed_color='#eee',
                               icon='info-circle',
                               color='#2176ff')

        def info_color(value):
            icon_info.color = '#2176ff' if value else '#333'

        icon_info.on_value_changed(info_color)

        icon_warn = ToolButton(value=True,
                               toggleable=True,
                               button_color='#bdbdbd',
                               pressed_color='#eee',
                               icon='exclamation-triangle',
                               color='#eba427')

        def warn_color(value):
            icon_warn.color = '#eba427' if value else '#333'

        icon_warn.on_value_changed(warn_color)

        icon_error = ToolButton(value=True,
                                toggleable=True,
                                button_color='#bdbdbd',
                                pressed_color='#eee',
                                icon='exclamation-circle',
                                color='#c71e1e')

        def error_color(value):
            icon_error.color = '#c71e1e' if value else '#333'

        icon_error.on_value_changed(error_color)

        icon_debug = ToolButton(value=True,
                                toggleable=True,
                                button_color='#bdbdbd',
                                pressed_color='#eee',
                                icon='code',
                                color='#111')

        def debug_color(value):
            icon_debug.color = '#111' if value else '#333'

        icon_debug.on_value_changed(debug_color)

        space = HTML(layout=Layout(width='25px'))
        case_sensitive = HTMLButton(value=True,
                                    html='Aa',
                                    size=40,
                                    button_color='#bdbdbd',
                                    pressed_color='#eee',
                                    toggleable=True)

        super(LogToolBar, self).__init__([
            icon_info, icon_warn, icon_error, icon_debug, space, line,
            case_sensitive
        ])
        self.info = icon_info
        self.warn = icon_warn
        self.error = icon_error
        self.debug = icon_debug
        self.filter = line
        self.case = case_sensitive
        if not isinstance(logviews, list):
            logviews = [logviews]

        self._logviews = []
        for logview in logviews:
            self.link_to(logview)
Beispiel #14
0
 def on_button_no_clicked(b):
     disable_buttons()
     display(HTML(responses.get('cancel')))
Beispiel #15
0
def mk_map_region_selector(map=None, height="600px", **kwargs):
    from ipyleaflet import Map, WidgetControl, FullScreenControl, DrawControl
    from ipywidgets.widgets import Layout, Button, HTML
    from types import SimpleNamespace

    state = SimpleNamespace(selection=None, bounds=None, done=False)

    btn_done = Button(description="done", layout=Layout(width="5em"))
    btn_done.style.button_color = "green"
    btn_done.disabled = True

    html_info = HTML(layout=Layout(flex="1 0 20em", width="20em", height="3em"))

    def update_info(txt):
        html_info.value = '<pre style="color:grey">' + txt + "</pre>"

    def render_bounds(bounds):
        (lat1, lon1), (lat2, lon2) = bounds
        txt = "lat: [{:.{n}f}, {:.{n}f}]\nlon: [{:.{n}f}, {:.{n}f}]".format(
            lat1, lat2, lon1, lon2, n=4
        )
        update_info(txt)

    if map is None:
        m = Map(**kwargs) if len(kwargs) else Map(zoom=2)
        m.scroll_wheel_zoom = True
        m.layout.height = height
    else:
        m = map
        render_bounds(m.bounds)

    widgets = [
        WidgetControl(widget=btn_done, position="topright"),
        WidgetControl(widget=html_info, position="bottomleft"),
    ]
    for w in widgets:
        m.add_control(w)

    draw = DrawControl()

    draw.circle = {}
    draw.polyline = {}
    draw.circlemarker = {}

    shape_opts = {"fillColor": "#fca45d", "color": "#000000", "fillOpacity": 0.1}
    draw.rectangle = {"shapeOptions": shape_opts, "metric": ["km", "m"]}
    poly_opts = {"shapeOptions": dict(**shape_opts)}
    poly_opts["shapeOptions"]["original"] = dict(**shape_opts)
    poly_opts["shapeOptions"]["editing"] = dict(**shape_opts)

    draw.polygon = poly_opts
    draw.edit = True
    draw.remove = True
    m.add_control(draw)
    m.add_control(FullScreenControl())

    def on_done(btn):
        state.done = True
        btn_done.disabled = True
        m.remove_control(draw)
        for w in widgets:
            m.remove_control(w)

    def bounds_handler(event):
        bounds = event["new"]
        render_bounds(bounds)
        (lat1, lon1), (lat2, lon2) = bounds
        state.bounds = dict(lat=(lat1, lat2), lon=(lon1, lon2))

    def on_draw(event):
        v = event["new"]
        action = event["name"]
        if action == "last_draw":
            state.selection = v["geometry"]
        elif action == "last_action" and v == "deleted":
            state.selection = None

        btn_done.disabled = state.selection is None

    draw.observe(on_draw)
    m.observe(bounds_handler, ("bounds",))
    btn_done.on_click(on_done)

    return m, state
Beispiel #16
0
def table_info_widget(df):
    return HTML(
        "<b><span style='color:blue;font-weight:bold'>%s</span> Rows and <span style='color:blue;font-weight:bold'>%s</span> Columns</b>"
        % df.shape)
Beispiel #17
0
 def setUp(self):
     self.children = [HTML('0'), HTML('1')]
Beispiel #18
0
    def displayInterface(self):
        '''
        显示组件
        :return: 
        '''
        if not self.cf.isReady():
            print(Fore.RED + '配置项尚未初始化!')
            self.btnInit = Button(description = '立即初始化', button_style = 'danger')
            self.btnInit.on_click(self.on_init_clicked)
            display(self.btnInit)
        else:
            self.catagoryname = self.cf.readConf(self.default['interface'], 'catagoryname') # 类别名称
            self.catagoryname = self.default[
                'catagory'] if self.catagoryname is None else self.catagoryname # 未设置时使用默认配置
            self.interfacename = self.cf.readConf(self.default['interface'], 'interfacename') # 接口名称
            self.interfacename = self.default[
                'interface'] if self.interfacename is None else self.interfacename # 未设置时使用默认配置
            self.catagory = interfaces.get(self.catagoryname, None) if self.catagoryname is not None else None # 类别信息
            self.interfaces = self.catagory.get('interface', None) if self.catagory is not None else None # 类别下所有接口信息
            self.interface = self.interfaces.get(self.interfacename,
                                                 None) if self.interfaces is not None and self.interfacename is not None else None # 接口信息
            # 组件初始化
            self.dpCatagory = Dropdown(
                options = [key for key in interfaces.keys()],
                value = self.catagoryname if self.catagoryname is not None else None,
                description = '类别:'
            )
            debug.out('interfacename = %s' % self.interfacename)
            tmpOptions = [key for key in
                          interfaces[self.dpCatagory.value]['interface']] if self.catagory is not None else []
            self.dpInterface = Dropdown(
                options = tmpOptions,
                value = self.interfacename if self.interfacename in tmpOptions else None,
                description = '接口:'
            )

            self.dpCatagory.observe(self.on_catagory_change)
            self.dpInterface.observe(self.on_interface_change)

            self.htmInterface = HTML(value = self.choiceResult())
            self.gdParam = qgrid.show_grid(pd.DataFrame(None))
            self.gdBody = qgrid.show_grid(pd.DataFrame(None))

            if self.interface is not None:
                self.dfParams = pd.DataFrame(self.interface.get('params', ['无']), index = [0]).T
                self.dfParams.columns = ['请求参数类型']
                self.gdParam = qgrid.show_grid(self.dfParams,
                                               grid_options = {'filterable': False, 'editable': False})
                self.gdParam.layout = Layout(width = '90%')

                self.dfBody = pd.DataFrame(self.interface.get('body', ['无']))
                self.dfBody.columns = ['请求体参数名称']
                self.gdBody = qgrid.show_grid(self.dfBody, grid_options = {'filterable': False, 'editable': False})
                self.gdBody.layout = Layout(width = '90%')

            debug.out('display from interface object=%s' % self)
            display(self.dpCatagory)
            display(self.dpInterface)

            boxRequest = Box([VBox([Label(value = '请求参数:'), self.gdParam],
                                   layout = Layout(flex = '1 1 0%', width = 'auto')),
                              VBox([Label(value = '请求体参数:'), self.gdBody],
                                   layout = Layout(flex = '1 1 0%', width = 'auto'))],
                             layout = Layout(flex_flow = 'row', display = 'flex'))
            boxRef = VBox([self.htmInterface, boxRequest])
            acRef = Accordion(children = [boxRef])
            acRef.set_title(0, '接口参考')
            toggleRefDisplay(acRef)
            display(acRef)
            ref.append(acRef)