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)
def get_update_widget(self): """Get the list of datalayers that are updated through the upload""" if len(self.update_datalayer_list) > 0: update_title = widgets.HTML( value= '<h4><center><b>Below datalayers will be updated:</b></center></h4>' ) update_html_list = self.get_update_html_list() return widgets.VBox([update_title, update_html_list]) return widgets.VBox([])
def reveal_figure(b): global controls record_action('predict', b.description) controls.close() descr = describe_and_show_figure(current_figure) descr += '<br/><br/>Actual chart form:' controls = widgets.VBox( [widgets.HTML(descr), widgets.HBox(confirm_buttons)]) display(controls)
def render(self, change=None): header = widgets.HTML( header_template.render( name=self.exp.task, status=self.status, app_id=self.exp.app_id, ), ) tabs = widgets.Tab(children=[self.config_tab]) tabs.set_title(0, 'Configuration') self.children = [header, tabs]
def get_open_screen(self, *args): """Displays the opening screen where player enters their name.""" header = widgets.HTML( f"<h1><font color='black'>Welcome To Hangman!</h1>", layout=widgets.Layout(height='auto')) self.get_name_field() center = self.name_box self.name_field.on_submit(self.get_app) self.start_button.on_click(self.get_app) app = widgets.AppLayout(header=header, center=center) clear_output() display(app)
def __setUpStage(self): style = '''<style>.output_wrapper, .output { height:auto !important; max-height:1000px; /* your desired max-height here */ } .output_scroll { box-shadow:none !important; webkit-box-shadow:none !important; } </style>''' display(widgets.HTML(style)) pass
def select_bin_parameter(self): _width = self.image_dimension['width'] _height = self.image_dimension['height'] left_widgets = widgets.VBox([ widgets.HTML(value="<b>Current Image Size:</b>", layout=widgets.Layout(width='250px')), widgets.Label("Width: {} pixels".format(_width), layout=widgets.Layout(width='100%')), widgets.Label("Height: {} pixels".format(_height), layout=widgets.Layout(width='100%')) ]) options_list = [str(_) for _ in np.arange(2, 21)] self.bin_para = widgets.Dropdown(options=options_list, value='2', continuous_update=False, layout=widgets.Layout(width='50%')) self.bin_para.observe(self.__bin_parameter_changed) center_widgets = widgets.VBox([ widgets.HTML("<b>Bin Parameter:</b>", layout=widgets.Layout(width='250px')), self.bin_para ]) self.right_widgets = widgets.VBox([ widgets.HTML("<b>New Image Size:</b>", layout=widgets.Layout(width='250px')), widgets.Label("Width: {} pixels".format(250), layout=widgets.Layout(width='100%')), widgets.Label("Height: {} pixels".format(250), layout=widgets.Layout(width='100%')) ]) self.__bin_parameter_changed(None) full_widget = widgets.HBox( [left_widgets, center_widgets, self.right_widgets]) display(full_widget)
def show_lfp(node, **kwargs): lfp = node.electrical_series['lfp'] ntabs = 3 children = [widgets.HTML('Rendering...') for _ in range(ntabs)] def on_selected_index(change): if change.new == 1 and isinstance(change.owner.children[1], widgets.HTML): slider = widgets.IntSlider(value=0, min=0, max=lfp.data.shape[1] - 1, description='Channel', orientation='horizontal') def create_spectrogram(channel=0): f, t, Zxx = stft(lfp.data[:, channel], lfp.rate, nperseg=128) spect = np.log(np.abs(Zxx)) image = itk.GetImageFromArray(spect) image.SetSpacing([(f[1] - f[0]), (t[1] - t[0]) * 1e-1]) direction = image.GetDirection() vnl_matrix = direction.GetVnlMatrix() vnl_matrix.set(0, 0, 0.0) vnl_matrix.set(0, 1, -1.0) vnl_matrix.set(1, 0, 1.0) vnl_matrix.set(1, 1, 0.0) return image spectrogram = create_spectrogram(0) viewer = itkwidgets.view(spectrogram, ui_collapsed=True, select_roi=True, annotations=False) spect_vbox = widgets.VBox([slider, viewer]) children[1] = spect_vbox change.owner.children = children channel_to_spectrogram = {0: spectrogram} def on_change_channel(change): channel = change.new if channel not in channel_to_spectrogram: channel_to_spectrogram[channel] = create_spectrogram(channel) viewer.image = channel_to_spectrogram[channel] slider.observe(on_change_channel, names='value') vbox = [] for key, value in lfp.fields.items(): vbox.append(widgets.Text(value=repr(value), description=key, disabled=True)) children[0] = widgets.VBox(vbox) tab_nest = widgets.Tab() # Use Rendering... as a placeholder tab_nest.children = children tab_nest.set_title(0, 'Fields') tab_nest.set_title(1, 'Spectrogram') tab_nest.set_title(2, 'test') tab_nest.observe(on_selected_index, names='selected_index') return tab_nest
def make_email_draft(**kwargs): letter_date = datetime.date.isoformat(datetime.date.today()) # doc_urls = make_html_url_list(TakedownStore.data_store.infringing_docs) doc_urls = make_infringing_lists( TakedownStore.data_store.infringing_doc_tuples) with open('{}/takedown_request.html'.format(env.TEMPLATE_FOLDER), 'r') as o: template = o.read() formatted = template.format(letter_date=letter_date, doc_urls=doc_urls, **kwargs) return display(widgets.HTML(value=formatted))
def _simple_columnwise_widget(ls, plot_function, columns): """Basic column-wise plot widget""" dropdown = widgets.Dropdown(options=columns, description='Column:') plot_area = widgets.HTML() update_plot(plot_function, [ls, columns[0]], plot_area, height=500) dropdown.observe(lambda x: update_plot( plot_function, [ls, x['new']], plot_area, height=500), names='value', type='change') return widgets.VBox([dropdown, plot_area], padding=PADDING)
def get_update_html_list(self): """Create HTML List with to be updated datalayers""" update_html_list = [] for datalayer in self.update_datalayer_list: new_data = datalayer['new'] old_data = datalayer['old'] datalayer_id = datalayer['datalayer_id'] diff_title = widgets.VBox([ widgets.HTML( f'<b>> {datalayer_id}</b>') ]) html_diff = widgets.VBox( [widgets.HTML(diff_json(old_data, new_data))], layout=LAYOUT_UPLOAD_UPDATE_DIFF) update_html_list.append( widgets.HBox([diff_title, html_diff], layout=LAYOUT_UPLOAD_UPDATE_BOX)) return widgets.VBox(update_html_list, layout=LAYOUT_UPDATE_FILES_LIST)
def __init__(self, path=tumblrsPath): self.path = path self.AC = AccountCollection(path) self.A = self.AC[random.randint(0, len(self.AC))] self.accountSelector = widgets.Dropdown( options=self.AC.names, value=self.A.name, description='Account:', ) self.tagsSelector = widgets.Dropdown( options=[f'{len(self.A)} None'] + self.A.sortedTags(count=True), value=f'{len(self.A)} None', description='tags:', ) self.typesSelector = widgets.RadioButtons( options=self.A.postTypes, value=self.A.currentType, description='Post type:', ) self.postSlider = widgets.IntSlider(min=0, max=len(self.A) - 1, value=0, description=str(len(self.A)) + ' posts') self.mainCaption = widgets.HTML(value=self.A(0)) self.nextButton = widgets.Button(description="Next") self.previousButton = widgets.Button(description="Previous") self.tagSearchEnable = widgets.Button(description="Enable tag search") self.globalTagSelector = widgets.RadioButtons( options=['None'], value='None', description='Global tag filter:', disabled=True, display=False, ) self.controls = HBox([ VBox([ HBox([self.accountSelector, self.tagsSelector]), HBox([self.postSlider, self.previousButton, self.nextButton]) ]), self.typesSelector ])
def create_view_all_comments_widget(ws_names2id: Dict[str, str], ws_paths: Dict[str, WorkspacePaths], output): """Create an ipywidget UI to display the contents of all comment files within a particular workspace.""" workspace_chooser = widgets.Dropdown( options=ws_names2id, value=None, description='<b>Choose a workspace to view:</b>', style={'description_width': 'initial'}, layout=widgets.Layout(width='900px') ) def on_choose_workspace(changed): with output: output.clear_output() workspace_paths = ws_paths[changed['new']] comment_files = get_ipython().getoutput(f'gsutil ls {workspace_paths.get_comment_file_glob()}') if not comment_files[0].startswith('gs://'): display(HTML('''<div class="alert alert-block alert-warning"> No comment files found for HTML snapshots in this workspace.</div>''')) return progress = widgets.IntProgress( value=0, min=0, max=len(comment_files), step=1, description=f'Retrieving {len(comment_files)} comments:', bar_style='success', orientation='horizontal', layout=widgets.Layout(width='450px'), style={'description_width': 'initial'} ) display(progress) comment_num = 0 comment_file_contents = [] for file in comment_files: comment = get_ipython().getoutput(f"gsutil cat '{file}'") version = file.replace(workspace_paths.get_subfolder(), '') comment_file_contents.append({'version': version, 'comment': comment}) comment_num += 1 progress.value = comment_num comments = pd.DataFrame(comment_file_contents) display(comments) workspace_chooser.observe(on_choose_workspace, names='value') return widgets.VBox( [widgets.HTML(''' <h3>View all comments for a workspace</h3> <p>Use the dropdown to choose a workspace. Then this will display the contents of all comment files for the selected workspace. <br>The user, date, time, and notebook name are shown in the left column. The comment is shown in the right column. </p><hr>'''), workspace_chooser], layout=widgets.Layout(width='auto', border='solid 1px grey'))
def get_footer(self): """ Builds the footer section of the app. Contains: Letter Buttons Guess Word Field """ footer_text = widgets.HTML( "<h3>Click on a letter to guess it or try to guess the full word.</h3>", layout=widgets.Layout(margin="0px 0px 0px 70px")) self.footer = widgets.VBox( [footer_text, self.letter_button_box, self.guess_word]) self.footer.layout.margin = "-60px 0px 0px 0px"
def __init__(self, units: Units, trials: pynwb.epoch.TimeIntervals = None, unit_index=0): super().__init__() self.units = units if trials is None: self.trials = self.get_trials() if self.trials is None: self.children = [widgets.HTML('No trials present')] return else: self.trials = trials groups = self.get_groups() rows_controller = widgets.Dropdown(options=[None] + list(groups), description='rows') cols_controller = widgets.Dropdown(options=[None] + list(groups), description='cols') trial_event_controller = make_trial_event_controller(self.trials) unit_controller = widgets.Dropdown(options=range(len(units['spike_times'].data)), value=unit_index, description='unit') before_slider = widgets.FloatSlider(.1, min=0, max=5., description='before (s)', continuous_update=False) after_slider = widgets.FloatSlider(1., min=0, max=5., description='after (s)', continuous_update=False) self.controls = { 'units': fixed(units), 'time_intervals': fixed(self.trials), 'index': unit_controller, 'after': after_slider, 'before': before_slider, 'align_by': trial_event_controller, 'rows_label': rows_controller, 'cols_label': cols_controller } self.children = [ unit_controller, rows_controller, cols_controller, trial_event_controller, before_slider, after_slider, ] self.select_trials() out_fig = interactive_output(raster_grid, self.controls, self.process_controls) self.children = list(self.children) + [out_fig]
def new_question(b=None): global controls, current_figure if b != None: record_action('confirm', b.description) controls.close() current_figure = select_random_figure(keywords) descr = describe_figure(current_figure) descr += '<br/><br/>Predicted chart form:' controls = widgets.VBox( [widgets.HTML(descr), widgets.HBox(expect_buttons)]) display(controls)
def make_text_display(student_id, text, student_name=''): """Handles the formatting of the student's text""" entry = """ <div id='%s'> <h3>%s</h3> <p> %s </p> </div>""" student_name = "{} | ".format( student_name) if len(student_name) > 1 else student_name header = "{}{}".format(student_name, student_id) e = entry % (student_id, header, text) return widgets.HTML(e)
def start(self): """In running time, start to display a sample in the notebook output cell""" logMsg(('start step id/total steps', self.pos_id, len(self.workflow.steps))) if len(self.master.js) > 0: display(widgets.HTML(self.master.js)) self.toggle.button_style = 'success' self.progress.value = self.pos_id + 1 self.progress.description = 'Progress: ' + str( self.progress.value) + '/' + str(self.progress.max) clear_output(True) display(self.box) self.initNextDoc() pass
def __init__(self, fontawesome_icon: str): """Clickable icon Parameters ---------- fontawesome_icon: str icon string from the fontawesome https://fontawesome.com. For example, "fab fa-500px" """ self.el_icon = widgets.HTML( value=f'<i class="{fontawesome_icon}"></i>') self.on_click_callback = lambda: 1 self.event_listener = Event(source=self.el_icon, watched_events=['click']) self.event_listener.on_dom_event(self.fire_on_click_event)
def requestUMLSAPIKey(self, rows): api_key = ConfigReader.getValue("api_key") if api_key is None or len(api_key) == 0: rows.append( widgets.HTML( value= '<h4>Set up your Glove model</h4><p>In order to use word embedding, you need ' 'to tell where the glove model locates:</p>')) self.api_key_input = widgets.Text(value='', placeholder='', description='', disabled=False) rows.append(self.api_key_input) rows += self.addSeparator()
def recursive_build(t): frames = [] frames.append(widgets.HTML(get_type_html(t))) if isinstance(t, hl.tstruct): append_struct_frames(t, frames) elif isinstance(t, hl.ttuple): if len(t) == 0: frames.append(widgets.HTML('<big>No fields.</big>')) else: frames.append(widgets.HTML('<big>Fields:</big>')) acc = widgets.Accordion([recursive_build(x) for x in t.types]) for i, fd in enumerate(t.types): acc.set_title(i, f'[{i}] ({format_type(fd)})') acc.selected_index = None frames.append(acc) elif isinstance(t, (hl.tarray, hl.tset)): acc = widgets.Accordion([recursive_build(t.element_type)]) acc.set_title(0, f'<element> ({format_type(t.element_type)})') acc.selected_index = None frames.append(acc) elif isinstance(t, hl.tdict): acc = widgets.Accordion( [recursive_build(t.key_type), recursive_build(t.value_type)]) acc.set_title(0, f'<key> ({format_type(t.key_type)})') acc.set_title(1, f'<value> ({format_type(t.element_type)})') acc.selected_index = None frames.append(acc) elif isinstance(t, (hl.tinterval)): acc = widgets.Accordion([recursive_build(t.point_type)]) acc.set_title(0, f'<point> ({format_type(t.point_type)})') acc.selected_index = None frames.append(acc) return widgets.VBox(frames)
def __init__(self, text, solution, *other_correct_choices, is_correct_fun=None, inst=None): self.correct_choices = list(other_correct_choices) self.correct_choices.append(solution) self.is_correct_fun = is_correct_fun textbox = widgets.HTML( value='<h4 style="font-size:14px;">{}</h4>'.format(text)) instbox = widgets.HTML(value='<i>{}</i>'.format(inst)) answer_input = widgets.Text() submit_button = widgets.Button(description="OK") give_up_button = widgets.Button(description="Lösung zeigen") button_box = widgets.HBox(children=[submit_button, give_up_button]) super().__init__(children=[textbox, instbox, answer_input, button_box]) self.answered = False def on_ok_button_clicked(b): if self.answered: return given_answer = answer_input.value answer_input.layout.border = '2px solid lightgreen' if self.is_correct( given_answer) else '2px solid red' submit_button.on_click(on_ok_button_clicked) def on_show_solution_button_clicked(b): answer_input.value = solution answer_input.layout.border = '2px solid lightgreen' answer_input.disabled = True give_up_button.on_click(on_show_solution_button_clicked)
def get_batch_grid(items: List[Renderable], batch_size: int, titles: bool, subtitles: bool) -> widgets.GridBox: layout = widgets.Layout( width="100%", grid_template_columns=" ".join([f"{int(100 / batch_size)}%"] * batch_size), ) out = [] for item in items: if subtitles: out.append( widgets.VBox([ widgets.HTML(f"<h5><em>{ item.name }</em></h5>"), item.render() ])) elif titles: out.append( widgets.VBox( [widgets.HTML(f"<h4>{ item.name }</h4>"), item.render()])) else: out.append(item.render()) return widgets.GridBox(out, layout=layout)
def requestUMLSAPIKey(self, rows): api_key = ConfigReader.getValue("api_key") if api_key is None or len(api_key) == 0: rows.append( widgets.HTML( value='<h4>Set your API Key</h4><p>In order to use the UMLS synonym checking module, you need to set' ' up your API key: (<a href="https://www.nlm.nih.gov/research/umls/user_education/quick_tours/' 'UTS-API/UTS_REST_API_Authentication.html" target="_blank">How to get your API Key_at 01:12 from' ' beginning. </a>)</p><p>If you do not set the api key, the UMLS synonym extender will be ' '<b>skipped</b>.</p>')) self.api_key_input = widgets.Text(value='', placeholder='', description='', disabled=False) rows.append(self.api_key_input) rows += self.addSeparator()
def __init__(self, btn: Tag, metadata: dict = None): self.btn_id = "btn-" + str(uuid4()) self.btn_cls = btn.get_attr("class", "") btn.attr( htmlClass=self.btn_cls + f" {self.btn_id}", onclick= f"window.IPyCallback.get('{LabExt.tunnel.tunnel_id}').send_msg(JSON.stringify({{ receiver: '{self.btn_id}', content: {{ type: 'click' }} }}));" ) self.btn = btn self.el_btn = widgets.HTML(btn.value()) self.metadata = metadata or {} self.on_click_callback = None LabExt.add_listener(self.btn_id, self.on_js_event)
def display(self): #interactive(self.read_selected,generations=self.widget_selectGenerations) self.widget_plot.on_click(self.plot_function) instructions = widgets.HTML( "<p>Press <i>ctrl</i>, <i>cmd</i>, or <i>shift</i> for multi-select</p>" ) self.widget = widgets.VBox([ instructions, widgets.HBox( [self.widget_selectGenerations, self.widget_selectText]), self.widget_plot ]) #to_display = widgets.VBox([self.widget_plot]) display(self.widget)
def show_neurodata_base(node: NWBDataInterface, neurodata_vis_spec: dict) -> widgets.Widget: """ Gets a pynwb object and returns a Vertical Box containing textual info and an expandable Accordion with it's children. """ field_lay = widgets.Layout(max_height='40px', max_width='500px', min_height='30px', min_width='180px') info = [] # string data type, exposed as a Text widget neuro_data = [] # more complex data types, also with children labels = [] for key, value in node.fields.items(): if isinstance(value, (str, datetime)): lbl_key = widgets.Label(key + ':', layout=field_lay) lbl_val = widgets.Label(str(value), layout=field_lay) info.append(widgets.HBox(children=[lbl_key, lbl_val])) elif key == 'related_publications': pub_list = [] for pub in value: pub_list.append( widgets.HTML(value="<a href=http://dx.doi.org/" + pub[4:] + ">" + pub + "</a>")) lbl_key = widgets.Label(key + ':', layout=field_lay) pub_list.insert(0, lbl_key) info.append(widgets.HBox(children=pub_list)) elif key == 'experimenter': lbl_experimenter = widgets.Label('Experimenter:', layout=field_lay) if isinstance(value, (list, tuple)): lbl_names = widgets.Label(', '.join(value), layout=field_lay) else: lbl_names = widgets.Label(value, layout=field_lay) hbox_exp = widgets.HBox(children=[lbl_experimenter, lbl_names]) info.append(hbox_exp) elif (isinstance(value, Iterable) and len(value)) or value: neuro_data.append( view.nwb2widget(value, neurodata_vis_spec=neurodata_vis_spec)) labels.append(key) accordion = widgets.Accordion(children=neuro_data, selected_index=None) for i, label in enumerate(labels): if hasattr(node.fields[label], 'description') and node.fields[label].description: accordion.set_title(i, label + ': ' + node.fields[label].description) else: accordion.set_title(i, label) return widgets.VBox(info + [accordion])
def __init__(self, description='', name=str(Step.global_id + 1), sampler_cls: type = KeywordStratefiedSampler): super().__init__(name=name) self.toggle = widgets.ToggleButtons( options=sample_options, value=sample_options[-1], description='What to do with previously sampled data? ', style=dict(description_width='initial'), button_style='info') self.toggle.observe(self.onPreviousSampleHandleChange) self.sample_size_input = widgets.BoundedIntText( value=0, min=0, max=0, step=1, description='Total documents you want to sample:', style=dict(description_width='initial')) self.sample_size_input.observe(self.onSampleConfigChange) self.sampler_cls = sampler_cls self.sampled_summary = widgets.HTML(value='') self.percent_slider = widgets.IntSlider(value=70, min=0, max=100, step=5, description='', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d') self.percent_slider.observe(self.onSampleConfigChange) # save DOC_IDs that contain or not contain keywords filters (used in sampling strategy) self.samples = {"contain": [], "notcontain": []} self.box = None self.data = {'docs': [], 'annos': OrderedDict()} self.ready = False # reset, continue, addmore, self.move_next_option = '' self.total = None self.total_contains = None self.un_reviewed = 0 self.sampler = None self.samples = dict() self.current_stats = dict() self.max_threshold = ConfigReader.getValue("review/rb_model_threshold") self.sample_sizes = dict()
def add_description(text, annotated_widget, width=50): """ Add a description (as an HTML widget) to the left of `annotated_widget` Parameters ---------- text: string The text to be added annotated_widget: an ipywidgets widget The widget to which the description will be added width: int The width of the description """ html_widget = widgets.HTML(text) set_widget_dimensions(html_widget, width=width) return (widgets.HBox(children=[html_widget, annotated_widget]))
def _init_ui(self) -> VBox: "Initialize the widget UI and return the UI." self._search_input = Text(placeholder="What images to search for?") self._count_input = BoundedIntText(placeholder="How many pics?", value=10, min=1, max=5000, step=1, layout=Layout(width='60px')) self._size_input = Dropdown(options= _img_sizes.keys(), value='>400*300', layout=Layout(width='120px')) self._download_button = Button(description="Search & Download", icon="download", layout=Layout(width='200px')) self._download_button.on_click(self.on_download_button_click) self._output = Output() self._controls_pane = HBox([self._search_input, self._count_input, self._size_input, self._download_button], layout=Layout(width='auto', height='40px')) self._heading = "" self._download_complete_heading = "<h3>Download complete. Here are a few images</h3>" self._preview_header = widgets.HTML(self._heading, layout=Layout(height='60px')) self._img_pane = Box(layout=Layout(display='inline')) return VBox([self._controls_pane, self._preview_header, self._img_pane])