Ejemplo n.º 1
0
    def __init__(self):
        self.ipython = check_ipython()

        if self.ipython:
            from ipywidgets import HTML
            from IPython.display import display

            self.display = display

            self.html_box = HTML()
        else:
            pass
Ejemplo n.º 2
0
def traffic_map_leaflet(
    traffic: "Traffic",
    *,
    zoom: int = 7,
    highlight: Optional[Dict[str, Union[str, Flight,
                                        Callable[[Flight],
                                                 Optional[Flight]]]]] = None,
    airport: Union[None, str, Airport] = None,
    **kwargs: Any,
) -> Optional[Map]:

    from traffic.data import airports

    _airport = airports[airport] if isinstance(airport, str) else airport

    if "center" not in kwargs:
        if _airport is not None:
            kwargs["center"] = _airport.latlon
        else:
            kwargs["center"] = (
                traffic.data.latitude.mean(),
                traffic.data.longitude.mean(),
            )

    m = Map(zoom=zoom, **kwargs)

    if _airport is not None:
        m.add_layer(_airport)

    for flight in traffic:
        if flight.query("latitude == latitude"):
            elt = m.add_layer(flight)
            elt.popup = HTML()
            elt.popup.value = flight._info_html()

        if highlight is None:
            highlight = dict()

        for color, value in highlight.items():
            if isinstance(value, str):
                value = getattr(Flight, value, None)
                if value is None:
                    continue
            assert not isinstance(value, str)
            f: Optional[Flight]
            if isinstance(value, Flight):
                f = value
            else:
                f = value(flight)
            if f is not None:
                m.add_layer(f, color=color)

    return m
Ejemplo n.º 3
0
def get_zoom_widgets(image_path):
    img_zoom_html_str = """
        <style> 
            .img-container { width: 500px; height: 500px; float: left;}
            .img-zoom-lens { width: 200px; height: 200px; position: absolute; border: 1px solid #d4d4d4;}
            .img-zoom-result {margin-left: 520px; width: 500px; height: 500px; }
        </style> """+f"""
        <section class="container-annotator">
            <img class ="img-container" id="image"  src="{image_path}" >
            <div id="zoom_area" class="img-zoom-result"></div> 
        </section>"""
    return [HTML(value=img_zoom_html_str), Javascript(image_zoom_js)]
Ejemplo n.º 4
0
    def __init__(self, text, correct, wrong, sonst=False, inst=multiple):
        self.chosenList = []
        if sonst == True:
            allAnsw = ["Keine der Alternativen"] + correct + wrong
        else:
            allAnsw = correct + wrong
        allAnsw.sort()
        self.myCor = correct
        self.myCor.sort()

        aufgabenstellung = HTML(
            value='<h4 style="font-size:14px;">{}</h4>'.format(text))
        instbox = widgets.HTML(value='<i>{}</i>'.format(inst),
                               layout=widgets.Layout(justify_content="center"))

        button = Button(description="Korrekt?",
                        layout=widgets.Layout(width="250px"))

        def on_change_check(change):
            if change['type'] == 'change' and change['name'] == 'value':
                if change['new'] == True:
                    box = change['owner']
                    d = box.description
                    self.chosenList.append(d)
                else:
                    box = change['owner']
                    if box.description in self.chosenList:
                        self.chosenList.remove(box.description)
            button.style.button_color = None

        cb = []
        style = {'description_width': 'initial'}
        for answer in allAnsw:
            cb.append(
                Checkbox(value=False,
                         description=answer,
                         disabled=False,
                         style=style,
                         layout=Layout(width="600px")))
            cb[-1].observe(on_change_check)

        box = widgets.VBox(children=cb)

        super().__init__(children=[aufgabenstellung, instbox, box, button])

        def on_button_clicked(button):
            self.chosenList.sort()
            if self.chosenList == self.myCor:
                button.style.button_color = 'lightgreen'
            else:
                button.style.button_color = 'red'

        button.on_click(on_button_clicked)
Ejemplo n.º 5
0
        def iterate(self, param=""):
            self.progr += 1
            display(
                Javascript("$('div#%s0').width('%i%%');" %
                           (self.divid, 100 * self.progr / self.max_it)))
            outp = "<table style='width:100%%;border:none'><tr style='border:none'><td style='border:none'>%s (%i/%i) </td><td style='border:none'>&#9992; %s    </td><td style='border:none'>&#128336;  %s   (estimated)</td><td style='border:none'>&#10010;  %s (elapsed) </td><td style='border:none'>&#9866;  %s (remaining)</td></tr></table>" % (
                param,  #"%s (%i/%i) &#10148;  ETA: %s &#10148; Time elapsed: %s" %(param,
                self.progr,
                self.max_it,
                time.strftime(
                    '%Y-%m-%d (%a) %H:%M:%S',
                    time.localtime(time.time() +
                                   float(time.time() - self.start_eta_time) /
                                   (self.progr -
                                    (0 if self.progr == 1 else 1)) *
                                   (self.max_it - self.progr))),  #ETA
                hourformat(self.start_eta_time - self.starttime +
                           float(time.time() - self.start_eta_time) /
                           (self.progr - (0 if self.progr == 1 else 1)) *
                           (self.max_it)),  #estimated
                hourformat(time.time() - self.starttime),  #elapsed
                hourformat(
                    float(time.time() - self.start_eta_time) /
                    (self.progr - (0 if self.progr == 1 else 1)) *
                    (self.max_it - self.progr)))  #remaining
            if self.progr == 1:
                "this is a little academic, but the time between the first and the second iteration has usually a time lag."
                self.start_eta_time = time.time()
            #outp = "%s (%i/%i) &#10148;  ETA: %s &#10148; Time elapsed: %s"%(param,self.progr,self.max_it,time.ctime(time.time() + float(time.time()-self.starttime)/self.progr * (self.max_it - self.progr)),time.strftime('%H:%M:%S',time.gmtime(time.time()-self.starttime)))
            display(
                Javascript(
                    "document.getElementById('%s_text').innerHTML = \"%s\";" %
                    (self.divid, outp)))

            if self.progr == self.max_it:  #end of progress bar
                #Turn the status bar into green
                #Delete all <div> containers
                outp = "%s (%i/%i) &#9992; %s    &#10010;  %s  " % (
                    param,  #"%s (%i/%i) &#10148;  ETA: %s &#10148; Time elapsed: %s" %(param,
                    self.progr,
                    self.max_it,
                    time.strftime('%Y-%m-%d (%a) %H:%M:%S'),
                    hourformat(time.time() - self.starttime))
                display(
                    Javascript(
                        "document.getElementById('%s_title').parentNode.remove();"
                        % self.divid))  #title
                self.pb = HTML("""
                <div id="%st"> %s</div>
                <div id="%s" style="border: 1px solid black; width:900px;text-align: center; color:white; background-color:green;">%s
                </div>
                """ % (self.name, self.name, self.name, outp))
                display(self.pb)
Ejemplo n.º 6
0
 def __init__(self, model):
     self.dic_figures = {}
     self.labels = {}
     for key in model.params.keys():
         if key not in ['S', 'V', 'C']:
             self.dic_figures[key] = Fig(model, key)
             self.labels[key] = HTML(layout=Layout(
                 width='200px', height='200px', padding='20px'))
     super().__init__([
         HBox([self.dic_figures[figure], self.labels[figure]])
         for figure in self.dic_figures
     ])
Ejemplo n.º 7
0
    def __init__(self, training_length=None, update_interval=100,
                 bar_length=50, out=sys.stdout):
        self._training_length = training_length
        if training_length is not None:
            self._init_status_template()
        self._update_interval = update_interval
        self._recent_timing = []

        self._total_bar = FloatProgress(description='total',
                                        min=0, max=1, value=0,
                                        bar_style='info')
        self._total_html = HTML()
        self._epoch_bar = FloatProgress(description='this epoch',
                                        min=0, max=1, value=0,
                                        bar_style='info')
        self._epoch_html = HTML()
        self._status_html = HTML()

        self._widget = VBox([HBox([self._total_bar, self._total_html]),
                             HBox([self._epoch_bar, self._epoch_html]),
                             self._status_html])
Ejemplo n.º 8
0
    def setup_notebook_container(self):
        """Display the display widgets if the Swarm is running in an IPython kernel."""
        if running_in_ipython() and self._use_notebook_widget:
            from ipywidgets import HTML
            from IPython.core.display import display, HTML as cell_html

            # Set font weight of tqdm progressbar
            display(
                cell_html(
                    "<style> .widget-label {font-weight: bold !important;} </style>"
                ))
            self._notebook_container = HTML()
    def __init__(self, goal):
        self.bar = IntProgress(min=0, max=goal, value=0)
        self.label = HTML()
        box = HBox(children=[self.bar, self.label])

        self.goal = goal
        self.value = 0
        self.template = '{{0}} / {goal}'.format(goal=goal)

        self.set_value(0)

        display(box)
Ejemplo n.º 10
0
 def displayCP(self):
   
   self.rowSW = Dropdown(options=[1,2,3,4],value=1,description='Rows:',
                         disabled=False,layout={'width':'150px'}
                        )
   self.colSW = Dropdown(options=[1,2,3,4],value=1,description='Columns:',
                           disabled=False,layout={'width':'150px'}
                         )
   self.row  = Dropdown(options=[1,2,3,4],value=1,
                        description='# of row:',disabled=True)
   self.col  = Dropdown(options=[1,2,3,4],value=1,
                        description='# of col:',disabled=True)
   self.obj  = Dropdown(options=[],value=None,
                        description='Object:',disabled=True)
   self.conDB = Button(description='Configure Dashboard',disabled=False,
                         layout={'width':'150px','border':'3px outset'}
                        )
   self.topLabel = HTML(disabled=False,layout={'width': 'auto'})
     
   self.topLabel.value = ( '<div style="background-color: #C0C0C0 ;'+ 
                           'padding: 1em 0em 0em 0em;border-bottom-style:groove;border-width:4px">'+
                          '<b><font size="4"><center><h2>'+self.title+'</h2></center></font></b></div>')
   self.rule = HTML(disabled=True,layout=Layout(width='auto',padding='0px'))
     
   self.rule.value = ( '<div >'+'<hr></div>')
   self.cpMain   = VBox([ 
                         HBox([self.topLabel],layout={'justify_content':'center','flex_flow':'column'}),
                         HBox([
                               HBox([self.rowSW],layout={'justify_content':'flex-start'}),
                               HBox([self.colSW],layout={'justify_content':'flex-end'})
                              ],layout={'padding':'15px'}
                             ),
                         HBox([self.conDB],layout={'justify_content':'center','padding':'15px'})
                              ],layout={'border':'3px groove','width': '400px'}
                       )
   self.rowSW.observe(self.rowSWCB,names='value')
   self.colSW.observe(self.colSWCB,names='value')
   self.conDB.on_click(self.configDBCB)
   with self.out_cp:
     display(self.cpMain)
def log_progress(sequence, every=None, size=None, name='Items'):
    """
    taken from https://github.com/alexanderkuk/log-progress

    """
    from ipywidgets import IntProgress, HTML, VBox
    from IPython.display import display

    is_iterator = False
    if size is None:
        try:
            size = len(sequence)
        except TypeError:
            is_iterator = True
    if size is not None:
        if every is None:
            if size <= 200:
                every = 1
            else:
                every = int(size / 200)  # every 0.5%
    else:
        assert every is not None, 'sequence is iterator, set every'

    if is_iterator:
        progress = IntProgress(min=0, max=1, value=1)
        progress.bar_style = 'info'
    else:
        progress = IntProgress(min=0, max=size, value=0)
    label = HTML()
    box = VBox(children=[label, progress])
    display(box)

    index = 0
    try:
        for index, record in enumerate(sequence, 1):
            if index == 1 or index % every == 0:
                if is_iterator:
                    label.value = '{name}: {index} / ?'.format(name=name,
                                                               index=index)
                else:
                    progress.value = index
                    label.value = u'{name}: {index} / {size}'.format(
                        name=name, index=index, size=size)
            yield record
    except:  # noqa: E722
        progress.bar_style = 'danger'
        raise
    else:
        progress.bar_style = 'success'
        progress.value = index
        label.value = "{name}: {index}".format(name=name,
                                               index=str(index or '?'))
Ejemplo n.º 12
0
 def display_research(player: S) -> Widget:
     player_query = urllib.parse.quote(f'{player["Long Name"]} FPL')
     team_query = urllib.parse.quote(f'{player["Team Name"]}')
     return HTML(
         layout=Layout(padding='0 0 0 50px'),
         value=
         ('<style>div.player a {text-decoration-line: underline; margin-right: 20px}</style>'
          '<div class="player">'
          f'<h3>Further Research</h3>'
          f'<a href="https://www.google.co.uk/search?q={player_query}&ie=UTF-8&tbm=nws" target="_blank">Search Google News for {player["Name"]}<br></a>'
          f'<a href="https://www.google.co.uk/search?q={player_query}&ie=UTF-8" target="_blank">Search Google for {player["Name"]}<br></a>'
          f'<a href="https://www.google.co.uk/search?q={team_query}&ie=UTF-8" target="_blank">Search Google for {player["Team Name"]}</a>'
          '</div>'))
Ejemplo n.º 13
0
    def setup_jupyter(self):
        """
        Sets up elements on the page for use with a Jupyter notebook.
        """
        self._label = Label('Move the cursor over the cell and use the left and right arrow keys to navigate')
        self._hbox = HBox()
        self._html = HTML('<h3>Label position?</h3>')

        self._inner = VBox()
        self._vbox = VBox([self._html, self._inner, self._label])
        self._event = Event(source=self._vbox, watched_events=['keydown'])
        self._event.on_dom_event(self.handle_event)
        return self
Ejemplo n.º 14
0
 def search(KeyWord="", ):
     for col in columns:
         result = df[col].fillna("NaN Value").str.contains(KeyWord)
         if sum(result) > 0:
             with PandasDisplay(max_colwidth=0, max_rows=max_rows):
                 display(
                     HTML(
                         f"<h3>\"{KeyWord}\" matched on column:[{col}]</h3>"
                     ))
                 callback(df[result].head(max_rows))
                 return
     print(f"Nothing found on any column on keyword:{KeyWord}")
     return
Ejemplo n.º 15
0
    def make_widget(self, all):
        from ipywidgets import FloatProgress, HBox, VBox, HTML
        import cgi
        self.elapsed_time = HTML('')
        self.bars = {key: FloatProgress(min=0, max=1, description='',
                                        height='10px')
                        for key in all}
        self.bar_texts = {key: HTML('', width = "140px") for key in all}
        self.bar_labels = {key: HTML('<div style=\"padding: 0px 10px 0px 10px; text-align:left; word-wrap: break-word;\">' + cgi.escape(key.decode() if isinstance(key, bytes) else key) + '</div>')
                            for key in all}

        def key(kv):
            """ Order keys by most numerous, then by string name """
            return kv[::-1]

        key_order = [k for k, v in sorted(all.items(), key=key, reverse=True)]

        self.bar_widgets = VBox([ HBox([ self.bar_texts[key],
                                         self.bars[key],
                                         self.bar_labels[key] ])
                                for key in key_order ])
        self.widget.children = (self.elapsed_time, self.bar_widgets)
Ejemplo n.º 16
0
 def ipywidget(self):
     if self._ipywidget is None:
         logs = self.log_ipywidget()
         logs_toolbar = LogToolBar(logs)
         status = self.status_ipywidget
         space = HTML(layout=Layout(height='7px'))
         self._ipywidget = VBox([HBox([status, logs_toolbar],
                                      layout=Layout(justify_content='space-between', align_items='flex-end')),
                                 space, logs])
         self._ipywidget.logs = logs
         self._ipywidget.logs_toolbar = logs_toolbar
         self._ipywidget.status = status
     return self._ipywidget
Ejemplo n.º 17
0
def make_link(fig, filename=None):
    outdir = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                          'output')
    if filename is None:
        _, tempfile_path = tempfile.mkstemp(dir=outdir, suffix='.pdf')
    else:
        tempfile_path = os.path.join(outdir, filename)
    fig.savefig(tempfile_path, type='pdf')
    link = HTML()
    filename = str(
        os.path.join('../utils/output', os.path.basename(tempfile_path)))
    link.value = FileLink(filename)._format_path()
    return link
Ejemplo n.º 18
0
 def _build_resources_widgets(resources: Dict[str, str]) -> VBox:
     """
     Build tab with resources (description: html links) to be displayed under 'Resources' tab
     :param resources: Dictionary description: html link from which the values are put into HTML and presented as
     description and link
     :return: VBox with resources to display
     """
     widget_list = []
     for key, val in resources.items():
         widget_list.append(
             HTML(value=f"{key}: <a href='{val}' target='_blank'>{val}</a>",
                  ))
     return VBox(widget_list)
Ejemplo n.º 19
0
 def render(self,
            same_tab: bool = True,
            new_window: bool = False,
            shadow_dom: Optional[bool] = None):
     assert same_tab is True and new_window is False
     display(HTML(f'<div id="{self.app_id}"></div>'), self.output)
     display(
         Javascript(f"""
     if (window.IPyApps === undefined) {{
         window.IPyApps = new Map();
     }}
     window.IPyApps.set('{self.app_id}', window);
     """))
Ejemplo n.º 20
0
    def __init__(self, omx, shapefile):

        if OMX is None:
            raise ModuleNotFoundError('larch.omx')
        if isinstance(omx, str):
            omx = OMX(omx, mode='r')
        self.omx = omx

        self.omx_taz_ids_rows = pd.RangeIndex(1, self.omx.shape[0]+1)
        self.omx_taz_ids_cols = pd.RangeIndex(1, self.omx.shape[1]+1)

        self.shapefile = shapefile

        self.fig = shapefile.plotly_choropleth(show_colorbar=True)

        self.matrix_dropdown = Dropdown(
            # label='Matrix Table',
            options=list(self.omx.data._v_children),
        )

        self.otaz_dropdown = Dropdown(
            options=list(self.omx_taz_ids_rows),
        )

        self.panel = VBox([
            Label(f"File: {self.omx.filename}"),
            HTML(
                value="<hr>",
            ),
            Label("Matrix Table"),
            self.matrix_dropdown,
            Label("Origin TAZ"),
            self.otaz_dropdown,
        ])

        self.matrix_dropdown.observe(self._change_matrix, names='value')
        self.otaz_dropdown.observe(self._change_otaz, names='value')
        self.fig.data[0].on_click(self._set_otaz_by_click)

        self.matrix_name = None
        self.otaz = None

        self.change_view(
            matrix_name=self.matrix_dropdown.value,
            otaz=self.otaz_dropdown.value,
        )

        super().__init__(children=(
            self.fig,
            self.panel,
        ))
Ejemplo n.º 21
0
def log_progress(sequence,
                 every=None,
                 size=None,
                 user_label=None,
                 refresh=False):
    from ipywidgets import IntProgress, HTML, VBox
    from IPython.display import display

    is_iterator = False
    if size is None:
        try:
            size = len(sequence)
        except TypeError:
            is_iterator = True
    if size is not None:
        if every is None:
            if size <= 200:
                every = 1
            else:
                every = int(size / 200)  # every 0.5%
    else:
        assert every is not None, 'sequence is iterator, set every'

    if is_iterator:
        progress = IntProgress(min=0, max=1, value=1)
        progress.bar_style = 'info'
    else:
        progress = IntProgress(min=0, max=size, value=0)
    label = HTML()
    box = VBox(children=[label, progress])
    display(box)

    index = 0
    try:
        for index, record in enumerate(sequence, 1):
            if index == 1 or index % every == 0:
                if is_iterator:
                    label.value = '{index} / ?'.format(index=index)
                else:
                    progress.value = index
                    label.value = u'{index} / {size} - {user_label}'.format(
                        index=index, size=size, user_label=user_label)
            yield record
        if refresh: box.close()
    except:
        progress.bar_style = 'danger'
        raise
    else:
        progress.bar_style = 'success'
        progress.value = index
        label.value = str(index or '?')
Ejemplo n.º 22
0
def fit_component_ipy(obj, **kwargs):
    wdict = {}
    only_current = Checkbox()
    iterpath = enum2dropdown(obj.traits()["iterpath"])

    def disable_iterpath(change):
        iterpath.disabled = change.new

    only_current.observe(disable_iterpath, "value")

    wdict["only_current"] = only_current
    wdict["iterpath"] = iterpath
    help_text = HTML(
        "Click on the signal figure and drag to the right to select a"
        "range. Press `Fit` to fit the component in that range. If only "
        "current is unchecked the fit is performed in the whole dataset.",
        layout=ipywidgets.Layout(width="auto"))
    wdict["help_text"] = help_text

    help = Accordion(children=[help_text], selected_index=None)
    set_title_container(help, ["Help"])

    link((obj, "only_current"), (only_current, "value"))
    link((obj, "iterpath"), (iterpath, "value"))
    fit = Button(description="Fit", tooltip="Fit in the selected signal range")
    close = Button(
        description="Close",
        tooltip="Close widget and remove span selector from the signal figure."
    )
    wdict["close_button"] = close
    wdict["fit_button"] = fit

    def on_fit_clicked(b):
        obj._fit_fired()

    fit.on_click(on_fit_clicked)
    box = VBox([
        labelme("Only current", only_current),
        labelme("Iterpath", wdict["iterpath"]), help,
        HBox((fit, close))
    ])

    def on_close_clicked(b):
        obj.span_selector_switch(False)
        box.close()

    close.on_click(on_close_clicked)
    return {
        "widget": box,
        "wdict": wdict,
    }
Ejemplo n.º 23
0
    def addTab(self, name, handler, widget=None):
        """ Add a Tab to the Panel. The handler is for the Map

        :param name: name for the new tab
        :type name: str
        :param handler: handle function for the new tab. Arguments of the
            function are:

            :type: the type of the event (click, mouseover, etc..)
            :coordinates: coordinates where the event occured [lon, lat]
            :widget: the widget inside the Tab
            :map: the Map instance

        :param widget: widget inside the Tab. Defaults to HTML('')
        :type widget: ipywidgets.Widget
        """
        # Widget
        wid = widget if widget else HTML('')
        # Get tab's children as a list
        tab_children = list(self.tabs.children)
        # Get a list of tab's titles
        titles = [
            self.tabs.get_title(i) for i, child in enumerate(tab_children)
        ]
        # Check if tab already exists
        if name not in titles:
            ntabs = len(tab_children)
            # Add widget as a new children
            self.childrenDict[name] = wid
            tab_children.append(wid)
            # Overwrite tab's children
            self.tabs.children = tab_children
            # Set name of the new tab
            self.tabs.set_title(ntabs, name)

            # Set the handler for the new tab
            def proxy_handler(f):
                def wrap(**kwargs):
                    # Add widget to handler arguments
                    kwargs['widget'] = self.childrenDict[name]
                    coords = kwargs['coordinates']
                    kwargs['coordinates'] = inverse_coordinates(coords)
                    kwargs['map'] = self
                    return f(**kwargs)

                return wrap

            self.handlers[name] = proxy_handler(handler)
        else:
            print('Tab {} already exists, please choose another name'.format(
                name))
 def __init__(self):
     self.dx, self.dy = 0.005, 0.005
     self.w_title = HTML("<h3>Область с заданной неравномерностью </h3>")
     self.w_out5 = Output()  
     self.w_label_var = Label("Допустимая неравномерность:")
     self.w_var = FloatSlider(1.1, min=1., max=1.5, step=0.005, continuous_update=False,  readout_format='.3f')
     self.w_label_xarea = Label('Границы допустимой области по горизонтали: ')
     self.w_xarea = FloatRangeSlider(value=[0.2,0.7],
         min=0,
         max=1.0,
         step=0.005,    
         disabled=False,
         continuous_update=False,
         orientation='horizontal',
         readout=True,
         readout_format='.3f')
     self.w_label_yarea = Label('Границы допустимой области по вертикали: ')
     self.w_yarea = FloatRangeSlider(value=[0.45,0.55],
         min=0,
         max=1.0,
         step=0.005,    
         disabled=False,
         continuous_update=False,
         orientation='horizontal',
         readout=True,
         readout_format='.3f')
     self.w_varn = Label()
     self.btn_var = Button(description ='Пересчитать', button_style='primary', disabled = True) # доработать
     self.btn_break = Button(description ='Прервать',  disabled = True)
     self.w_message = HTML("")
     self.w_result = HTML("")
     self.layout = VBox([self.w_title, self.w_label_var, self.w_var, 
     self.w_label_xarea,  self.w_xarea,
     self.w_label_yarea,  self.w_yarea,
     self.w_varn,
     self.btn_var,  self.w_message, self.w_result,
     self.w_out5])
     self.btn_var.on_click(self.button_var_onclick)
Ejemplo n.º 25
0
    def set_check_radio_boxes_layout(self, labels):
        output_layout = []
        self.check_radio_boxes_layout = {}
        for rb_k, rb_v in self.radiobuttons.items():
            rb_v.layout.width = '180px'
            rb_v.observe(self.checkbox_changed)
            rb_v.add_class(rb_k)
            html_title = HTML(value="<b>" + labels[rb_k] + "</b>")
            self.check_radio_boxes_layout[rb_k] = VBox([rb_v])
            output_layout.append(VBox([html_title, self.check_radio_boxes_layout[rb_k]]))

        for cb_k, cb_i in self.checkboxes.items():
            for cb in cb_i:
                cb.layout.width = '180px'
                cb.observe(self.checkbox_changed)
                cb.add_class(cb_k)
            html_title = HTML(value="<b>" + labels[cb_k] + "</b>")
            self.check_radio_boxes_layout[cb_k] = VBox(children=[cb for cb in cb_i])
            output_layout.append(VBox([html_title, self.check_radio_boxes_layout[cb_k]]))

        for bf_k, bf in self.bounded_text.items():
            bf.layout.width = '80px'
            bf.layout.height = '35px'
            bf.observe(self.checkbox_changed)
            bf.add_class(bf_k)
            html_title = HTML(value="<b>" + labels[bf_k] + "</b>")
            self.check_radio_boxes_layout[bf_k] = VBox([bf])
            output_layout.append(VBox([html_title, self.check_radio_boxes_layout[bf_k]]))

        for tb_k, tb_i in self.box_text.items():
            tb_i.layout.width = '500px'
            tb_i.observe(self.checkbox_changed)
            tb_i.add_class(tb_k)
            html_title = HTML(value="<b>" + labels[tb_k] + "</b>")
            self.check_radio_boxes_layout[tb_k] = VBox([tb_i])
            output_layout.append(VBox([html_title, self.check_radio_boxes_layout[tb_k]]))

        return output_layout
Ejemplo n.º 26
0
    def _create_vbox(self):

        from ipywidgets import VBox, Layout, HTML
        return VBox([
            HTML('<b>' + self.array_name.upper() + '</b>'),
            self.scalar,
            self.velocity_vectors,
            self.vector_size,
            self.scalar_size,
            self.scalar_cmap,
        ],
                    layout=Layout(border='1px solid',
                                  margin='3px',
                                  min_width='320px'))
Ejemplo n.º 27
0
    def addTab(self, name, handler=None, widget=None):
        """ Add a Tab to the Panel. The handler is for the Map

        :param name: name for the new tab
        :type name: str
        :param handler: handle function for the new tab. Arguments of the
        function are:

          - type: the type of the event (click, mouseover, etc..)
          - coordinates: coordinates where the event occurred [lon, lat]
          - widget: the widget inside the Tab
          - map: the Map instance

        :param widget: widget inside the Tab. Defaults to HTML('')
        :type widget: ipywidgets.Widget
        """
        # Widget
        wid = widget if widget else HTML('')
        # Get tab's children as a list
        # tab_children = list(self.tab_widget.children)
        tab_children = self.tab_children_dict.values()
        # Get a list of tab's titles
        # titles = [self.tab_widget.get_title(i) for i, child in enumerate(tab_children)]
        titles = self.tab_children_dict.keys()
        # Check if tab already exists
        if name not in titles:
            ntabs = len(tab_children)

            # UPDATE DICTS
            # Add widget as a new children
            self.tab_children_dict[name] = wid
            # Set the handler for the new tab
            if handler:
                def proxy_handler(f):
                    def wrap(**kwargs):
                        # Add widget to handler arguments
                        kwargs['widget'] = self.tab_children_dict[name]
                        coords = kwargs['coordinates']
                        kwargs['coordinates'] = inverseCoordinates(coords)
                        kwargs['map'] = self
                        return f(**kwargs)
                    return wrap
                self.handlers[name] = proxy_handler(handler)
            else:
                self.handlers[name] = handler

            # Update tab children
            self._update_tab_children()
        else:
            print('Tab {} already exists, please choose another name'.format(name))
Ejemplo n.º 28
0
    def __init__(self, *args, **kargs):

        # Ipython gives warnings when using widgets about the API potentially changing
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            try:
                from ipywidgets import IntProgress, HTML, HBox
            except ImportError:  # Support IPython < 4.0
                from IPython.html.widgets import IntProgress, HTML, HBox

        super(ProgressIPy, self).__init__(*args, **kargs)
        self.prog = IntProgress(max=self.length)
        self._label = HTML()
        self._box = HBox((self.prog, self._label))
Ejemplo n.º 29
0
 def __init__(self, desc, interval=.01):
     from IPython.display import display
     from ipywidgets import HBox, IntProgress, HTML
     self._total = 0
     self.value = 0
     self._last_update = 0
     self.interval = interval
     prog = self.progress = IntProgress(description=desc, value=0, max=0)
     text = HTML()
     def _update_text(change):
         text.value = f"{prog.value}/{prog.max}"
     _update_text(None)
     prog.observe(_update_text, names=['value', 'max'])
     display(HBox([prog, text]))
Ejemplo n.º 30
0
    def _generateMarkers(self):
        popupTemplate = """
        <head>
        <style>
        table {
            border: 1px solid black;
            border-radius: 25px;
        }
        </style>
        </head>
        <body>
        <table style="width:100%">
              <tr>
                <th>Key</th>
                <th>Value</th>
              </tr>
              ROWS
            </table>

        </body>
        """
        # tableTemplate = """<table style="width:100%"><tr><th>key</th><th>value</th></tr>ROWS</table>"""
        rowTemplate = """<tr><td>KEY</td><td>VALUE</td></tr>"""
        markers = []
        for _, row in self.df.iterrows():
            if isinstance(row[self.lon], numbers.Number) and isinstance(
                    row[self.lat], numbers.Number):
                markerTemp = ipyleaflet.Marker(
                    location=[row[self.lat], row[self.lon]], draggable=False)
                # popup information
                message = HTML()
                rowList = []
                for x, y in row.iteritems():
                    if x in self.properties:
                        str_x = re.escape(str(x))
                        str_y = re.escape(str(y))
                        rowTemp = re.sub('VALUE', str_y,
                                         re.sub('KEY', str_x, rowTemplate))
                        rowTemp = re.sub(r'\\(.)', r'\1', rowTemp)
                        rowList.append(rowTemp)
                message.value = re.sub(
                    r'\\(.)', r'\1',
                    re.sub('ROWS', ''.join(rowList), popupTemplate))
                message.placeholder = ''
                message.description = ''
                markerTemp.popup = message
                # style of marker
                markerTemp.layout = {'padding': '1px'}
                markers.append(markerTemp)
        return markers