def create_mulligan(team1, team2): check1 = create_checkbox(team1) check2 = create_checkbox(team2) accord = Accordion(children=[check1, check2]) accord.set_title(0, 'Team 1') accord.set_title(1, 'Team 2') return accord, check1, check2
def update_ipywidget(self): w = [] root_accordion = self._ipywidget.accordion toolbar = self._ipywidget.toolbar for n in self._process_tree.walk(): address = n.address if len(address) > 1: parent_accordion = self.accordion_by_id(address[:-1]) else: parent_accordion = root_accordion child = list(parent_accordion.children) if len(child) <= address[-1] or child[address[-1]].children[2].source is not n.data: node_w = n.data.log_ipywidget(toolbar=False) acc = Accordion(layout=Layout(width='100%', max_height='500px')) #acc.selected_index = -1 new_item = VBox([acc, VSpace(), node_w], layout=Layout(overflow_y='auto')) if len(child) <= address[-1]: child.append(new_item) else: child[address[-1]] = new_item name = n.data.name if isinstance(n.data, Process) and n.data.state in ('success', 'failed'): name += ' (ended in %s)' % second_to_str(n.data.elapsed_time()) parent_accordion.set_title(address[-1], name) parent_accordion.children = tuple(child) else: node_w = parent_accordion.children[address[-1]].children[2] w.append(node_w) toolbar.logviews = w
def aristeia_dice_widget(): a = create_die_widgets() d = create_die_widgets() accordion = Accordion(children=[display_widgets(a), display_widgets(d)]) accordion.set_title(0, 'Attacker') accordion.set_title(1, 'Defender') return accordion
def _widget(self): from ipywidgets import Accordion accordion = Accordion( children=[log._widget() for log in self.values()]) [accordion.set_title(i, title) for i, title in enumerate(self.keys())] return accordion
def info2map(map): """ Add an information Tab to a map displayed with `geetools.ipymap` module :param map: the Map where the tab will be added :type map: geetools.ipymap.Map :return: """ map.addTab('BAP Inspector', info_handler, Accordion())
def image(image, region=None, visualization=None, name=None, dimensions=(500, 500), do_async=None): """ Preview an Earth Engine Image """ if do_async is None: do_async = CONFIG.get('do_async') start = time() if name: label = '{} (Image)'.format(name) loading = 'Loading {} preview...'.format(name) else: label = 'Image Preview' loading = 'Loading preview...' formatdimension = "x".join([str(d) for d in dimensions]) wid = Accordion([Label(loading)]) wid.set_title(0, loading) def compute(image, region, visualization): if not region: region = tools.geometry.getRegion(image) else: region = tools.geometry.getRegion(region) params = dict(dimensions=formatdimension, region=region) if visualization: params.update(visualization) url = image.getThumbURL(params) req = requests.get(url) content = req.content rtype = req.headers['Content-type'] if rtype in ['image/jpeg', 'image/png']: img64 = base64.b64encode(content).decode('utf-8') src = '<img src="data:image/png;base64,{}"></img>'.format(img64) result = HTML(src) else: result = Label(content.decode('utf-8')) return result def setAccordion(acc): widget = compute(image, region, visualization) end = time() elapsed = end-start acc.children = [widget] elapsed = utils.format_elapsed(elapsed) acc.set_title(0, '{} [{}]'.format(label, elapsed)) if do_async: thread = threading.Thread(target=setAccordion, args=(wid,)) thread.start() else: setAccordion(wid) return wid
def collapsible(fn, *args, **kwargs): from ipywidgets import Output, Accordion out = Output() with out: fn(*args, **kwargs) acc = Accordion(children=[out]) acc.set_title(0, "View output") acc.selected_index = None return acc
def _on_child(self, change): new = change['new'] # list of any widget newwidgets = [] for widget in new: # constract the widget acc = Accordion(children=(widget, )) acc.selected_index = None # this will unselect all # create a CheckRow checkrow = CheckRow(acc) newwidgets.append(checkrow) newchildren = tuple(newwidgets) self.children = newchildren
def __init__(self, **kwargs): self._stats_view = StatsView() self._tools = Tools() self._side_bar = Accordion(children=[self._stats_view, self._tools]) self._side_bar.set_title(0, 'Statistics') self._side_bar.set_title(1, 'Tools') super().__init__(children=[self._side_bar], **kwargs) self.setup_connections()
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, }
def __init__(self, **kwargs): # Change defaults kwargs.setdefault('center', [0, 0]) kwargs.setdefault('zoom', 2) super(Map, self).__init__(**kwargs) # self.added_geometries = {} # self.added_images = {} self.is_shown = False self.EELayers = {} # CREATE TABS self.tabs = Tab() tab_names = ['Inspector', 'Assets', 'Tasks'] ## widgets self.inspectorWid = Accordion() # Inspector Widget self.assetsWid = Accordion() # Assets Widget self.tasksWid = HTML() # Tasks Widget childrenName = ['Inspector', 'Assets', 'Tasks'] childrenWid = [self.inspectorWid, self.assetsWid, self.tasksWid] # Dictonary to hold tab's widgets # (tab's name:widget) self.childrenDict = OrderedDict(zip(childrenName, childrenWid)) # Set tabs children self.tabs.children = self.childrenDict.values() # Set tabs names for i, name in enumerate(tab_names): self.tabs.set_title(i, name) # Handlers self.tabs.observe(self.handle_change_tab) self.handlers = {'Inspector': self.handle_inspector} # First handler: Inspector self.on_interaction(self.handlers['Inspector'])
def ipywidget(self): if self._ipywidget is None: accordion = Accordion() #accordion.selected_index = -1 toolbar = LogToolBar() header = HBox([HSpace(400), toolbar], layout=Layout(justify_content='space-between', align_items='flex-end')) self._ipywidget = VBox([header, accordion]) self._ipywidget.header = self._ipywidget.children[0] self._ipywidget.accordion = accordion self._ipywidget.toolbar = toolbar self.update_ipywidget() return self._ipywidget
def constructAccordion(param, itemList): param.element = {} for item, good in itemList.items(): param.element[item] = renderParam(param, param.setVar(item), item.title(), param.get(item), circle=good.color) accordion = Accordion( children=[HBox(list(param.element.values()))]) accordion.set_title(0, param.title) accordion.add_class('helipad_param_peritem') return accordion
def get_model_widget(obj, **kwargs): """Creates interactive notebook widgets for all components and parameters, if available. """ children = [] wdict = {} for component in obj: idict = component.gui(display=False, toolkit="ipywidgets")["ipywidgets"] children.append(idict["widget"]) wdict["component_{}".format(component.name)] = idict["wdict"] accordion = Accordion(children=children) set_title_container(accordion, [comp.name for comp in obj]) return {"widget": accordion, "wdict": wdict}
def info2map(map): """ Add an information Tab to a map displayed with `geetools.ipymap` module :param map: the Map where the tab will be added :type map: geetools.ipymap.Map :return: """ try: from ipywidgets import Accordion except: print('Cannot use ipytools without ipywidgets installed\n' 'ipywidgets.readthedocs.io') map.addTab('BAP Inspector', info_handler, Accordion())
def _dock_add_group_box(self, name, *, collapse=None, layout=None): layout = self._dock_layout if layout is None else layout if collapse is None: hlayout = VBox([HTML("<strong>" + name + "</strong>")]) else: assert isinstance(collapse, bool) vbox = VBox() hlayout = Accordion([vbox]) hlayout.set_title(0, name) if collapse: hlayout.selected_index = None else: hlayout.selected_index = 0 self._layout_add_widget(layout, hlayout) return hlayout
def __init__(self, obj=None): """ TESTS:: sage: from sage_explorer.sage_explorer import SageExplorer sage: S = StandardTableaux(15) sage: t = S.random_element() sage: widget = SageExplorer(t) """ super(SageExplorer, self).__init__() self.title = Title() self.propsbox = VBox( ) # Will be a VBox full of HBoxes, one for each property self.titlebox = VBox() self.titlebox.add_class('titlebox') self.titlebox.children = [self.title, self.propsbox] self.visualbox = Box() self.visualtext = Textarea('', rows=8) self.visualwidget = None self.visualbox.add_class('visualbox') self.visualbox.children = [self.visualtext] self.top = HBox([self.titlebox, self.visualbox], layout=justified_h_layout) self.menus = Accordion(selected_index=None) self.menusbox = VBox([Title("Menus", 2), self.menus]) self.inputs = HBox() self.gobutton = Button( description='Run!', tooltip='Run the function or method, with specified arguments') self.output = HTML() self.worktab = VBox((self.inputs, self.gobutton, self.output)) self.doc = HTML() self.doctab = HTML() # For the method docstring self.tabs = Tab( (self.worktab, self.doctab)) # Will be used when a method is selected self.tabs.add_class('tabs') self.tabs.set_title(0, 'Call') self.tabs.set_title(1, 'Help') self.main = Box((self.doc, self.tabs)) self.tabs.add_class('invisible') # Hide tabs at first display self.bottom = HBox((self.menusbox, self.main), layout=main_h_layout) self.menusbox.add_class('lightborder') self.main.add_class('lightborder') self.titlebox.add_class('lightborder') self.children = (self.top, self.bottom) self.history = [] self.set_value(obj)
def update_instrument_params(b): insdict = ric.get_all_instrument_params() for ins in sorted(insdict): if not ins in b.accordions: b.accordions[ins] = Accordion() table = "<table style='line-height:180%'>" # <tr style='font-weight:bold'><td> Parameter </td><td>Value</td></tr> for p in sorted(insdict[ins]): table += "<tr><td style='text-align:right;padding-right:10px'>" + str( p) + "</td><td>" + fmt( insdict[ins][p][0]) + insdict[ins][p][1] + "</td></tr>" table += """</table>""" b.accordions[ins].children = [HTML(table)] b.accordions[ins].set_title(0, ins) for child in b.accordions.keys(): if child not in insdict: del b.accordions[child] b.hbox.children = b.accordions.values()
def wrap(button): self.selected_tab().children = (HTML('Loading...'), ) try: tasklist = ee.data.getTaskList() # empty lists running_list = [] completed_list = [] failed_list = [] canceled_list = [] unknown_list = [] all_list = { 'RUNNING': running_list, 'COMPLETED': completed_list, 'FAILED': failed_list, 'CANCELED': canceled_list, 'UNKNOWN': unknown_list } for task in tasklist: state = task['state'] accordion = create_accordion(task) if task['state'] == 'COMPLETED': start = int(task['start_timestamp_ms']) end = int(task['creation_timestamp_ms']) seconds = float((start - end)) / 1000 name = '{} ({} sec)'.format( task['output_url'][0].split('/')[-1], seconds) else: name = '{}'.format(task['description']) # Accordion for CheckRow widget mainacc = Accordion(children=(accordion, )) mainacc.set_title(0, name) mainacc.selected_index = None # CheckRow wid = CheckRow(mainacc) # Append widget to the CORRECT list all_list[state].append(wid) # Assign Children self.runningVBox.children = tuple(running_list) self.completedVBox.children = tuple(completed_list) self.failedVBox.children = tuple(failed_list) self.canceledVBox.children = tuple(canceled_list) self.unknownVBox.children = tuple(unknown_list) except Exception as e: self.selected_tab().children = (HTML(str(e)), )
def box(self): layout = Accordion(children=[ VBox([ self.ui_th_std0, self.ui_qv0, self.ui_p0, self.ui_kappa, self.ui_w_max ]), VBox([*self.ui_processes]), VBox([ self.ui_nx, self.ui_nz, self.ui_sdpg, self.ui_dt, self.ui_n_steps, self.ui_condensation_rtol_lnv, self.ui_condensation_rtol_thd, *self.ui_mpdata_options ]), VBox([]) ]) layout.set_title(0, 'parameters') layout.set_title(1, 'processes') layout.set_title(2, 'discretisation') layout.set_title(3, 'parallelisation') return layout
def create_object_output(object): ''' Create a output Widget for Images, Geometries and Features ''' ty = object.__class__.__name__ if ty == 'Image': info = object.getInfo() image_id = info['id'] if 'id' in info else 'No Image ID' prop = info['properties'] bands = info['bands'] bands_names = [band['id'] for band in bands] bands_types = [band['data_type']['precision'] for band in bands] bands_crs = [band['crs'] for band in bands] new_band_names = [ '<li>{} - {} - {}</li>'.format(name, ty, epsg) for name, ty, epsg in zip(bands_names, bands_types, bands_crs) ] new_properties = [ '<li><b>{}</b>: {}</li>'.format(key, val) for key, val in prop.items() ] header = HTML('<b>Image id:</b> {id} </br>'.format(id=image_id)) bands_wid = HTML('<ul>' + ''.join(new_band_names) + '</ul>') prop_wid = HTML('<ul>' + ''.join(new_properties) + '</ul>') acc = Accordion([bands_wid, prop_wid]) acc.set_title(0, 'Bands') acc.set_title(1, 'Properties') acc.selected_index = None # this will unselect all return VBox([header, acc]) elif ty == 'FeatureCollection': try: info = object.getInfo() except: print('FeatureCollection limited to 4000 features') info = object.limit(4000) return create_accordion(info) else: info = object.getInfo() return create_accordion(info)
def get_parameter_widget(obj, **kwargs): """Creates interactive notebook widgets for the parameter, if available. """ if obj._number_of_elements == 1: return _get_value_widget(obj) else: wdict = {} par_widgets = [] for i in range(obj._number_of_elements): thiswd = _get_value_widget(obj=obj, index=i) par_widgets.append(thiswd["widget"]) wdict["element{}".format(i)] = thiswd["wdict"] update = Button( description="Update", tooltip="Unlike most other widgets, the multivalue parameter " "widgets do not update automatically when the value of the " "changes by other means. Use this button to update the values" "manually") def on_update_clicked(b): for value, container in zip(obj.value, par_widgets): minwidget = container.children[0] vwidget = container.children[1] maxwidget = container.children[2] if value < vwidget.min: minwidget.value = value elif value > vwidget.max: maxwidget.value = value vwidget.value = value update.on_click(on_update_clicked) wdict["update_button"] = update container = Accordion([VBox([update] + par_widgets)], descrition=obj.name) container.set_title(0, obj.name) return { "widget": container, "wdict": wdict, }
def _build_highlights_accordion(self) -> DOMWidget: """ Creates a widget that displays highlights for this `Tier` in an `ipywidgets.Accordion` - which is nice! """ highlights = self.tier.get_highlights() if not highlights: return None widget = Accordion() for i, (name, highlight) in enumerate(highlights.items()): out = Output() widget.children = (*widget.children, out) with out: for item in highlight: publish_display_data(**item) widget.set_title(i, name) widget.selected_index = None return widget
def create(self): """Create the sidecar view""" self.sc = Sidecar( title="Databases-%s" % os.environ["DBJL_CLUSTER"].split("-")[-1], layout=Layout(width="300px"), ) self.refresh = Button(description="refresh") self.refresh.on_click(self.on_refresh) self.output = Output( layout=Layout( height="600px", width="320px", overflow_x="scroll", overflow_y="scroll" ) ) self.output.add_class("db-detail") self.selects = [] self.accordion = Accordion(children=[]) with self.sc: display(VBox([self.refresh, self.accordion, self.output])) self.update() self.set_css()
def create_accordion(dictionary): """ Create an Accordion output from a dict object """ widlist = [] ini = 0 widget = Accordion() widget.selected_index = None # this will unselect all for key, val in dictionary.items(): if isinstance(val, dict): newwidget = create_accordion(val) widlist.append(newwidget) elif isinstance(val, list): # tranform list to a dictionary dictval = {k: v for k, v in enumerate(val)} newwidget = create_accordion(dictval) widlist.append(newwidget) else: value = HTML(str(val)) widlist.append(value) widget.set_title(ini, key) ini += 1 widget.children = widlist return widget
def fit_component_ipy(obj, **kwargs): wdict = {} only_current = Checkbox() wdict["only_current"] = only_current help = 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"] = only_current help = Accordion(children=[help]) help.set_title(0, "Help") link((obj, "only_current"), (only_current, "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), 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, }
def box(self): layout = Accordion(children=[ VBox([ self.ui_th_std0, self.ui_qv0, self.ui_p0, self.ui_kappa, self.ui_amplitude ]), VBox([ *self.ui_processes # , self.ui_ept # TODO ]), VBox([ self.ui_nx, self.ui_nz, self.ui_sdpg, self.ui_dt, self.ui_n_steps, self.ui_condensation_rtol_x, self.ui_condensation_rtol_thd, self.ui_adaptive, self.ui_condensation_coord, *self.ui_mpdata_options ]), # VBox([]) # TODO ]) layout.set_title(0, 'environment parameters') layout.set_title(1, 'processes') layout.set_title(2, 'discretisation') # layout.set_title(3, 'parallelisation') # TODO return layout
def collapsible(function, *args, **kwargs): """ An IPython widget that can collapse its contents. Parameters ---------- function : callable A function that generates some kind of output (print, plots, etc). Args and kwargs will be forwarded here. Returns ------- ipywidgets.Accordion """ from ipywidgets import Output, Accordion out = Output() with out: function(*args, **kwargs) acc = Accordion(children=[out]) acc.set_title(0, "View output") acc.selected_index = None return acc
def __init__(self, **kwargs): desc = 'Select one or more layers' super(CustomInspector, self).__init__(description=desc, **kwargs) self.selector = SelectMultiple() self.main = Accordion() self.children = [self.selector, self.main]
def _widget(self): """ Create IPython widget for display within a notebook """ try: return self._cached_widget except AttributeError: pass from ipywidgets import Layout, VBox, HBox, IntText, Button, HTML, Accordion layout = Layout(width='150px') if 'bokeh' in self.scheduler.services: template = config.get('diagnostics-link', 'http://{host}:{port}/status') host = self.scheduler.address.split('://')[1].split(':')[0] port = self.scheduler.services['bokeh'].port link = template.format(host=host, port=port, **os.environ) link = '<p><b>Dashboard: </b><a href="%s" target="_blank">%s</a></p>\n' % (link, link) else: link = '' title = '<h2>%s</h2>' % type(self).__name__ title = HTML(title) dashboard = HTML(link) status = HTML(self._widget_status(), layout=Layout(min_width='150px')) request = IntText(0, description='Workers', layout=layout) scale = Button(description='Scale', layout=layout) minimum = IntText(0, description='Minimum', layout=layout) maximum = IntText(0, description='Maximum', layout=layout) adapt = Button(description='Adapt', layout=layout) accordion = Accordion([HBox([request, scale]), HBox([minimum, maximum, adapt])], layout=Layout(min_width='500px')) accordion.selected_index = None accordion.set_title(0, 'Manual Scaling') accordion.set_title(1, 'Adaptive Scaling') box = VBox([title, HBox([status, accordion]), dashboard]) self._cached_widget = box def adapt_cb(b): self.adapt(minimum=minimum.value, maximum=maximum.value) adapt.on_click(adapt_cb) def scale_cb(b): with log_errors(): n = request.value with ignoring(AttributeError): self._adaptive.stop() self.scale(n) scale.on_click(scale_cb) scheduler_ref = ref(self.scheduler) def update(): status.value = self._widget_status() pc = PeriodicCallback(update, 500, io_loop=self.scheduler.loop) self.scheduler.periodic_callbacks['cluster-repr'] = pc pc.start() return box