def __init__(self, position: str = "bottomleft", attr_name: str = "style", kind: str = "stroke", orientation: str = "horizontal", transparent: bool = False, a_map: Map = None, layer: Layer = None, place_control: bool = True): def updated(change): """Called after each single-letter edit of the JSON in the textarea. """ if change["type"] != "change": return value = change["owner"].value if not is_valid_json(value): return else: layer.style = json.loads(value) def close(button): a_map.remove_control(wc) layout = Layout(width="28px", height="28px", padding="0px 0px 0px 4px") btn = Button(tooltip="Close", icon="close", layout=layout) btn.on_click(close) ta = Textarea(value=json.dumps(getattr(layer, attr_name), indent=2)) ta.layout.width = "200px" ta.observe(updated) header = HBox([HTML(f"<i>{attr_name} (JSON)</i>"), btn]) ui = VBox([header, ta]) wc = WidgetControl(widget=ui, position=position, transparent_bg=True) a_map.add_control(wc)
def __init__(self, mode="text"): self.mode_widget = Dropdown( options={ 'BibTeX': 'bibtex', 'Text': 'text', '[N] author name place other year': 'citation', 'Quoted': 'quoted', }, value=mode ) self.button_widget = Button( description="Set article_list variable", disabled=mode not in ("citation", "bibtex") ) self.frompdf_widget = Textarea() self.output_widget = Textarea() self.label_widget = Label() self.frompdf_widget.observe(self.write, names="value") self.mode_widget.observe(self.select, names="value") self.button_widget.on_click(self.set_variable) self.view = VBox([ HBox([self.mode_widget, self.button_widget, self.label_widget]), HBox([self.frompdf_widget, self.output_widget]) ]) self.frompdf_widget.layout.height = "500px" self.output_widget.layout.height = "500px" self.frompdf_widget.layout.width = "50%" self.output_widget.layout.width = "50%" self.backup = "" self.ipython = get_ipython()
def fig_DataWarnings(execution): datawaringFile = execution.read("Datafile_warnings", raw=True) out_data = "" with open(datawaringFile[7:], "r") as input_text: out_data = input_text.read() out_fig = Textarea(value=out_data) out_fig.layout = Layout(width="100%", height="400px") return out_fig
def render(self, resp: requests.models.Response) -> Textarea: "Return deserialized Protobuf objects as text inside a Textarea." obj = resp.content import addressbook_pb2 person = addressbook_pb2.Person() person.ParseFromString(obj) self.data = person layout = Layout(width='100%', height='100%') ta = Textarea(layout=layout) ta.value = str(person) return ta
def render(self, resp: requests.models.Response) -> Textarea: "Return a somewhat prettified JSON string." obj = resp.json() self.data = obj layout = Layout(width='100%', height='100%') ta = Textarea(layout=layout) value = json.dumps(obj, indent=2) ta.value = value num_lines = value.count('\n') ta.rows = min(10, num_lines + 1) return ta
def create_text(self, k, anno): """ create text area widget """ if "textarea" in anno: layout = Layout(width="100%", height="auto") wi = Textarea(description=k, layout=layout) else: wi = Text(description=k) if "default" in anno: wi.value = anno["default"] return wi
def render(self, resp: requests.models.Response) -> Optional[Widget]: "Return some rendered raw 'view' of the response or None." obj = resp.content self.data = obj layout = Layout(width='100%', height='100%') ta = Textarea(layout=layout) try: ta.value = str(resp.content.decode(resp.encoding)) \ if resp.encoding else str(resp.content) except UnicodeDecodeError: ta.value = str(resp.content) num_lines = ta.value.count('\n') ta.rows = min(10, num_lines + 1) return ta
def __init__( self, existing: Optional[Dict[str, Any]] = None, save_file_name: Optional[str] = "tmp.json", ) -> None: self.box_layout = Layout( overflow="scroll hidden", border="1px solid black", width="600px", height="", flex_flow="row", display="flex", ) self.textbox_layout = Layout( overflow="scroll hidden", border="1px solid black", width="10px", height="", flex_flow="row", display="flex", ) self.tab_layout = Layout( # border="1px solid black", width="600px") self.label_layout = Layout(width="600px") self.textarea_layout = Layout(width="592px") self.smalltextarea_layout = Layout(width="570px") self.item_layout = Layout(height="200px", min_width="40px") self.cg_backend = ConfigGenerator(existing) self.save_file_name = save_file_name self.config = Textarea() self.tab = Tab() self.dict_res = {} self._make_grid()
def _make_pag(self) -> VBox: self.pagtype_box = RadioButtons( options=["No Pagination", "offset", "seek", "page", "token"], layout={"width": "max-content"}, # If the items' names are long description="", style={"description_width": "initial"}, disabled=False, ) pag_label = HTML( value= ("""<h3 style="background-color:#E8E8E8; background-size: 100px; "> <span style="color: #ff0000">4.</span> Pagination</h3>"""), layout=self.label_layout, ) self.pagparams_box = Textarea( placeholder= ("Please separate pagination key and corresponding value by ':' ;" " while each key-value pair needs to be separated by ',' " "(e.g. name:abcdefg, date:2019-12-12)"), layout=self.textarea_layout, ) carousel_4 = Box(children=[self.pagparams_box], layout=self.box_layout) pag_box = VBox([pag_label, self.pagtype_box, carousel_4]) return pag_box
def _make_auth(self) -> VBox: self.authtype_box = RadioButtons( options=[ "No Authorization", "OAuth2", "QueryParam", "Bearer", "Header" ], layout={"width": "max-content"}, # If the items' names are long description="", style={"description_width": "initial"}, disabled=False, ) auth_label = HTML( value= ("""<h3 style="background-color:#E8E8E8; background-size: 100px; ">""" """<span style="color: #ff0000">3.</span> Authorization """ """<span style="font-size: 14px">""" """<i>(some APIs require authorization)</i> </span></span></h3>""" ), layout=self.label_layout, ) self.authparams_box = Textarea( placeholder= ("Please separate authtication key and corresponding value by ':' ; " "while each key-value pair needs to be separated by ',' " "(e.g. name:abcdefg, date:2019-12-12)"), layout=self.textarea_layout, ) carousel_3 = Box(children=[self.authparams_box], layout=self.box_layout) auth_box = VBox([auth_label, self.authtype_box, carousel_3]) return auth_box
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._main_data = None self._area = Textarea() self._sheet = ipysheet.sheet() self.register_to_hub(kwargs['session'].hub)
def fig_X6paircoeffs(execution): X6pairFile = execution.read("X6paircoeffs", raw=True) out_data = "" with open(X6pairFile[7:], "r") as input_text: out_data = input_text.read() out_fig = Textarea(value=out_data) out_fig.layout = Layout(width="100%", height="400px") download = ui.Download( X6pairFile[7:], style="success", tooltip="DOWNLOAD X6paircoeffs.txt", label="Download X6paircoeffs.txt", icon="arrow-circle-down", ) out_put = VBox([out_fig, download.w]) return out_put
def __init__(self): from ipywidgets import Button self.code = Textarea() self.execute = Button(description="Run") self.clear_btn = Button(description="Clear") self.output = Output() self.exec_count = Label("[ ]") self.execute.layout.width = "60px" self.execute.layout.height = "50px" self.clear_btn.layout.width = "60px" self.clear_btn.layout.height = "50px" self.code.layout.width = "550px" self.code.rows = 6 self.view = VBox([ HBox([ VBox([ self.execute, self.clear_btn, self.exec_count ]), self.code ]), self.output ]) self.execute.on_click(self.click) self.clear_btn.on_click(self.clear_click) self.ipython = get_ipython()
def create_check_radio_boxes(self): labels = dict() for k_name, v in self.properties_and_values.items(): if len(v) == 3: label = v[2] elif MetaPropertiesType.TEXT.value == v[0].value and len(v) == 2: label = v[1] else: label = k_name labels[k_name] = label if MetaPropertiesType.UNIQUE.value == v[0].value: # radiobutton self.radiobuttons[k_name] = RadioButtons(name=k_name, options=v[1], disabled=False, indent=False) elif MetaPropertiesType.COMPOUND.value == v[0].value: # checkbox self.checkboxes[k_name] = [Checkbox(False, indent=False, name=k_name, description=prop_name) for prop_name in v[1]] elif MetaPropertiesType.CONTINUE.value == v[0].value: self.bounded_text[k_name] = BoundedFloatText(value=v[1][0], min=v[1][0], max=v[1][1]) elif MetaPropertiesType.TEXT.value == v[0].value: self.box_text[k_name] = Textarea(disabled=False) return labels
def fig_LAMMPSInput(execution): inputFile = execution.read("LAMMPSinputfile", raw=True) out_data = "" with open(inputFile[7:], "r") as input_text: out_data = input_text.read() out_fig = Textarea(value=out_data) out_fig.layout = Layout(width="100%", height="400px") download = ui.Download( inputFile[7:], style="success", tooltip="DOWNLOAD LAMMPS INPUT FILE", label="Download Inputfile", icon="arrow-circle-down", ) out_put = VBox([out_fig, download.w]) return out_put
def new_child(self) -> DOMWidget: """ Widget for creating new child for this `Tier`. """ child = self.tier.child_cls options = child.get_templates() mapping = {path.name: path for path in options} selection = Select( options=mapping.keys(), description='Template') def create(name, template, description): with form.status: obj = child(*self.tier.identifiers, name) obj.setup_files(mapping[template]) obj.description = description display(widgetify_html(obj._repr_html_())) form = InputSequence(create, Text(description=f'Identifier', placeholder=f'{child.id_regex}'), selection, Textarea(description='Motivation')) return form.as_widget()
def __init__(self, data, *args, **kwargs): super().__init__(*args, **kwargs) self._main_data = data self._area = Textarea() self._sheet = ipysheet.sheet( column_headers=[x.label for x in data.main_components]) self._add_data() self.register_to_hub(kwargs['session'].hub)
def notes(path, ds=None, parcel=None): info = HTML( value="Add a note for the parcel", placeholder='Notes', ) aoi = Text(value=ds, placeholder='MS or ragion', description='AOI:', disabled=False) try: y_ = int(ds[-4:]) except: y_ = 2000 year = BoundedIntText(value=y_, min=1980, max=2100, step=1, description='Year:', disabled=False, layout=Layout(width='180px')) pid = Text(value=parcel, placeholder='12345', description='Parcel ID:', disabled=False) note = Textarea(value=None, placeholder='', description='Note:', disabled=False, layout=Layout(width='60%')) save = Button(value=False, disabled=False, button_style='info', tooltip='Save note to notes table.', icon='save', layout=Layout(width='35px')) new = HBox([aoi, year, pid]) progress = Output() def outlog(*text): with progress: print(*text) @save.on_click def save_on_click(b): progress.clear_output() df = pd.DataFrame([[aoi.value, year.value, pid.value, note.value]]) df.to_csv(f'{path}notes.csv', mode='a', header=False) outlog(f"The note is saved in {path}notes.csv") wbox = VBox([info, new, HBox([note, save]), progress]) return wbox
def _make_req_param(self) -> VBox: self.params_box = Textarea( placeholder=( "Please separate key and value by ':' ; while each key-value pair needs to be " "separated by ',' (e.g. name:abcdefg, date:2019-12-12)" ), layout={"width": "100%", "height": "100%"}, ) carousel_2 = Box(children=[self.params_box], layout=BOX_LAYOUT) param_box = VBox([_make_header(2, "Request Parameters"), carousel_2]) return param_box
def __init__(self, mode=None): options={ "BibTeX": "bibtex", "Text": "text", "[N] author name place other year": "citation", "Quoted": "quoted", } if config.PDF_EXTRACTOR: options["PDF"] = "pdf" mode = mode or "pdf" mode = mode or "text" self.mode_widget = Dropdown( options=options, value=mode ) self.button_widget = Button( description="Set article_list variable", disabled=mode not in ("citation", "bibtex") ) self.frompdf_widget = Textarea() self.output_widget = Textarea() self.label_widget = Label() self.frompdf_widget.observe(self.write, names="value") self.mode_widget.observe(self.select, names="value") self.button_widget.on_click(self.set_variable) self.view = VBox([ HBox([self.mode_widget, self.button_widget, self.label_widget]), HBox([self.frompdf_widget, self.output_widget]) ]) self.frompdf_widget.layout.height = "500px" self.output_widget.layout.height = "500px" self.frompdf_widget.layout.width = "50%" self.output_widget.layout.width = "50%" self.backup = "" self.ipython = get_ipython() self.select_mode(mode)
async def _tail_log(fname: Path, textarea: Textarea) -> None: T = -2.0 # to make sure the update always triggers while True: await asyncio.sleep(2) try: T_new = _last_editted(fname) if T_new > T: textarea.value = _read_file(fname) T = T_new except asyncio.CancelledError: return except Exception: pass
def __init__(self, wikipedia: Wikipedia): self._last_widget_state = None self._run_timer = None self._last_search = None self.wikipedia = wikipedia self.text = Textarea( value='', placeholder='Type something', description='Search:', disabled=False, layout=dict(width="90%"), ) self.show_url = Checkbox( value=True, description='Show URL', disabled=False, ) self.show_abstract = Checkbox( value=False, description='Show Abstract', disabled=False, ) self.n_results = IntSlider( value=10, step=1, description='Number of results:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', layout=dict(width="90%"), style=dict(description_width='initial'), ) self.progress_label = Label(value="") box1 = HBox((self.show_url, self.show_abstract)) self.dashboard = VBox( (self.text, box1, self.n_results, self.progress_label)) # Set observers for observer in [ self.show_url, self.show_abstract, self.text, self.n_results ]: observer.observe(self._widgets_updates) # noinspection PyTypeChecker display(self.dashboard)
def make_attr_widget(obj, map, title, attrs, labels): box = VBox() children = [] if title is not None: children.append(Label(value=title)) for i, attr in enumerate(attrs): if hasattr(obj, attr) and isinstance(getattr(obj, attr), dict): widget = Textarea(description=labels[i]) else: widget = Text(description=labels[i]) map[labels[i]] = widget children.append(widget) box.children = children return box
def hover_handler(self, qq, content): product = content.get("data", {}).get("label", -1) is_rule = content.get("data", {}).get("tooltip", None) if product != self._hovered_product: if is_rule: self._hovered_product = content.get("data", {}).get("tooltip", None) self.graph.tooltip = Textarea( content.get("data", {}).get("tooltip", None) ) self.graph.tooltip_location = "center" else: self._hovered_product = product self.setup_product_tooltip([product]) self.graph.tooltip_location = "center"
def on_click(_): text_input = Textarea( value=text, placeholder="Enter text", disabled=False, layout=Layout(height="auto", width="auto"), ) save_button = button( "", "danger", on_click=_save_button(box, ds), button_kwargs=dict(icon="save"), ) box.children = (text_input, save_button)
def on_click(_: Button) -> None: text_input = Textarea( value=body, placeholder="Enter text", disabled=True, layout=Layout(height="300px", width="auto"), ) back_button = button( "Back", "warning", on_click=_back_button(title, body, box), button_kwargs=dict(icon="undo"), ) box.children = (text_input, back_button)
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 __init__(self, row): self.row = row self.name = row.name self.button = Button(description='Archive object!') self.button.style.button_color = 'orange' self.text = Textarea(value='', placeholder='Add comment on object!', description='Comment:', disabled=False) self.destination = Dropdown( options=['classification targets', 'misc'], value='classification targets', description='Archive as:', disabled=False, ) self.check_if_archived() self.button.on_click(self.on_button_clicked)
def _make_req_param(self) -> VBox: self.params_box = Textarea( placeholder= ("Please separate key and value by ':' ; while each key-value pair needs to be " "separated by ',' (e.g. name:abcdefg, date:2019-12-12)"), layout=self.textarea_layout, ) params_label = HTML( value= ("""<h3 style="background-color:#E8E8E8; background-size: 100px; "> <span style="color: #ff0000">2.</span> Request Parameters</h3>"""), layout=self.label_layout, ) carousel_2 = Box(children=[self.params_box], layout=self.box_layout) param_box = VBox([params_label, carousel_2]) return param_box
def __call__(self, dataframe, index): """Invokes the visuzlizer. Args: dataframe (pandas.DataFrame): the dataframe that contains the data for visualization. index (int): the positional (iloc) index of the row to visualize. Returns: list: widgets that visualize the row """ result = [] row = dataframe.iloc[index] for label in self._text_columns: result.append(Label('{}:'.format(label))) result.append( Textarea(value=str(row[label]), layout=self._text_layout, disabled=True)) return tuple(result)