Esempio n. 1
0
    def _populate_tab(index: int, df: pd.DataFrame):
        df_widget, visible_df = searchable_dataframe(df)

        my_graph_output = widgets.Output(layout=widgets.Layout(
            min_width="40%"))
        render_points_button = widgets.Button(description="Render points")
        with my_graph_output:
            display(starter_cluster_fig)

        def _plot_dataframe_points(mysom: sompy.sompy.SOM, df: pd.DataFrame):
            my_graph_output.clear_output()
            with my_graph_output:
                fig, ax = make_cluster_graph(mysom, cl_labels)
                coords = dataframe_to_coords(mysom, df)
                render_points_to_axes(ax, coords)
                display(fig)

        render_points_button.on_click(
            lambda *args: _plot_dataframe_points(mysom, visible_df.df))

        return widgets.HBox([
            widgets.VBox([
                widgets.HBox([
                    widgets.Label(value=f"Cluster #{index}"),
                    widgets.HTML(
                        layout={
                            'min_width': '20px',
                            'min_height': '20px'
                        },
                        value=
                        f"<div style='min_width: 20px; min_height: 20px; border: 1px solid black; background-color: {tuple_to_css_rgba(get_tab20_color(index))}; color: {tuple_to_css_rgba(get_tab20_color(index))};'>_</div>"
                    ),
                ]), render_points_button, df_widget
            ]),
            # By including the same "graph_output" instance across all tabs,
            # we can render the graph once and have it show up in every tab
            my_graph_output
        ])
Esempio n. 2
0
    def __init__(self, paramlist, paramdefs, title=None):
        super(Configurator,
              self).__init__(layout=ipy.Layout(display='flex',
                                               flex_flow='column',
                                               align_self='flex-start',
                                               align_items='stretch',
                                               max_width='100%'))
        self.paramlist = paramlist
        self.paramdefs = paramdefs

        self.apply_button = ipy.Button(description='Apply')
        self.apply_button.on_click(self.apply_values)

        self.reset_button = ipy.Button(description='Reset')
        self.reset_button.on_click(self.reset_values)
        self.buttons = ipy.Box([self.reset_button, self.apply_button],
                               layout=ipy.Layout(align_self='center'))

        self.selectors = collections.OrderedDict([(p.name, ParamSelector(p))
                                                  for p in paramdefs])
        self.reset_values()

        title = utils.if_not_none(title, 'Configuration')
        self.title = ipy.HTML('<center><h4>%s</h4></center><hr>' % title,
                              align_self='center')

        self.currentconfig = ipy.Textarea(description='<i>Current params</i>',
                                          disabled=True,
                                          value=self._pretty_print_config(),
                                          layout=ipy.Layout(
                                              width='350px',
                                              min_height='300px',
                                              max_height='500px',
                                              display='flex',
                                              flex_flow='column'))
        self.middle = ipy.HBox(
            [ipy.VBox(self.selectors.values()), self.currentconfig])
        self.children = [self.title, self.middle, self.buttons]
Esempio n. 3
0
    def __init__(self,
                 description='Select computer:',
                 path_to_root='../',
                 **kwargs):
        """Dropdown for configured AiiDA Computers.

        description (str): Text to display before dropdown.

        path_to_root (str): Path to the app's root folder.
        """

        self.output = ipw.Output()

        self._dropdown = ipw.Dropdown(options={},
                                      value=None,
                                      description=description,
                                      style={'description_width': 'initial'},
                                      disabled=True)
        link((self, 'computers'), (self._dropdown, 'options'))
        link((self._dropdown, 'value'), (self, 'selected_computer'))

        btn_refresh = ipw.Button(description="Refresh",
                                 layout=ipw.Layout(width="70px"))
        btn_refresh.on_click(self.refresh)

        self.observe(self.refresh, names='allow_select_disabled')

        self._setup_another = ipw.HTML(
            value=
            """<a href={path_to_root}aiidalab-widgets-base/setup_computer.ipynb target="_blank">
            Setup new computer</a>""".format(path_to_root=path_to_root))

        children = [
            ipw.HBox([self._dropdown, btn_refresh, self._setup_another]),
            self.output
        ]
        self.refresh()
        super().__init__(children=children, **kwargs)
Esempio n. 4
0
    def __init__(self):

        self._layout = wg.Layout(width='300px', height='60px')
        self._mkdir = wg.Button(value=False,
                                description='Package creation',
                                disabled=False,
                                layout=self._layout)
        self._create = wg.Button(value=False,
                                 description='Model creation',
                                 disabled=False,
                                 layout=self._layout)
        self._edit = wg.Button(value=False,
                               description='Model edition',
                               disabled=False,
                               layout=self._layout)
        self._transformation = wg.Button(value=False,
                                         description='Model transformation',
                                         disabled=False,
                                         layout=self._layout)
        self._display = wg.Button(value=False,
                                  description='Model display',
                                  disabled=False,
                                  layout=self._layout)
        self._about = wg.Button(value=False,
                                description='About',
                                disabled=False,
                                layout=self._layout)

        self._displayer = wg.VBox([
            wg.HTML(
                value='<font size="5"><b>Model manager for Pycrop2ml</b></font>'
            ), self._mkdir, self._create, self._edit, self._transformation,
            self._display, self._about
        ],
                                  layout=wg.Layout(align_items='center'))

        self._out = wg.Output()
        self._out2 = wg.Output()
Esempio n. 5
0
    def __init__(self, flows, **kwargs):
        super().__init__(1, 3, grid_gap="10px", **kwargs)

        self._selector = ipywidgets.Select(
            layout=ipywidgets.Layout(height="100%", width="initial"))
        self._flow_widget = WorkflowWidget(layout=ipywidgets.Layout(
            flex="1 0 auto"))
        self._vg_widget = VersionGraftWidget(layout=ipywidgets.Layout(
            flex="1 0 auto"))

        self.flows = flows

        ipywidgets.link((self._selector, "value"), (self, "selected_id"))
        ipywidgets.link((self._flow_widget, "version"),
                        (self, "selected_version"))
        traitlets.dlink(
            (self._selector, "value"),
            (self._flow_widget, "flow"),
            transform=lambda flow_id: self._flows_lookup.get(flow_id, None),
        )
        traitlets.dlink((self._flow_widget, "current_vg"),
                        (self._vg_widget, "vg"))

        self._flow_widget.observe(
            lambda change: self.set_trait("current_flow", change["new"]),
            names="flow")
        self._flow_widget.observe(
            lambda change: self.set_trait("current_vg", change["new"]),
            names="current_vg",
        )

        self[0, 0] = ipywidgets.VBox(
            children=[ipywidgets.HTML("<h2>Workflows</h2>"), self._selector],
            layout=ipywidgets.Layout(flex="1 0 auto"),
        )

        self[0, 1] = self._flow_widget
        self[0, 2] = self._vg_widget
Esempio n. 6
0
def get_start_widget(appbase, jupbase):
    #http://fontawesome.io/icons/
    template = """
    <table>
    <tr>
        <th style="text-align:center">Tutorials</th>
        <th style="width:70px" rowspan=2></th>
        <th style="text-align:center">Corelevel Spectra</th>
        <th style="width:70px" rowspan=2></th>
        <th style="text-align:center">Utility</th>
        <th style="width:70px" rowspan=2></th>
        <th style="text-align:center">Workflow check</th>
        
    <tr>
    <td valign="top"><ul>
    <li><a href="{appbase}/fleur_tutorial/getting_started.ipynb" target="_blank">Fleur tutorial</a>
    </ul></td>
    
    <td valign="top"><ul>
    <li><a href="{appbase}/corelevel_spectra/Plotting_corelevel_spectra_app.ipynb" target="_blank">all in one</a>
    <li><a href="{appbase}/corelevel_spectra/display.ipynb" target="_blank">display</a>
    <li><a href="{appbase}/corelevel_spectra/compare.ipynb" target="_blank">compare</a>
    <li><a href="{appbase}/corelevel_spectra/search.ipynb" target="_blank">search</a>
    </ul></td>
    
    <td valign="top"><ul>
    <li><a href="{appbase}/slab/build.ipynb" target="_blank">Construct slab</a>
    </ul></td>

    <td valign="top"><ul>
    <li><a href="{appbase}/slab/build.ipynb" target="_blank">fleur_scf</a>
    <li><a href="{appbase}/slab/build.ipynb" target="_blank">fleur_eos</a>    
    </ul></td>
    </tr></table>
"""

    html = template.format(appbase=appbase, jupbase=jupbase)
    return ipw.HTML(html)
Esempio n. 7
0
    def __init__(
            self,
            question,
            labels,
            question_template=None,  # type: Optional[Dict[str, str]]
            width="150px",
            buttons_per_row=1):
        # type: (...) -> None
        self.question_box = ipw.HTML(value='')
        self.labels = labels
        self.width = width
        self.buttons_per_row = buttons_per_row
        self._make_buttons(labels)
        if question_template is not None:
            self.question_template = question_template
        else:
            self.question_template = {}
        self.set_question(question)

        self.submit_func = None
        super().__init__(
            ipw.VBox([self.question_box] + self.button_rows,
                     layout=ipw.Layout(width="250px")))
Esempio n. 8
0
    def show_plots(val):
        plot_area.clear_output()
        show = show_groups_toggle.value
        exclusive = exclusive_groups_toggle.value == 'Exclusive'
        with plot_area:
            if raw_data_toggle.value == 'Raw':
                if show and exclusive:
                    display(iw.VBox(rows_groups_exclusive_raw))
                elif show and not exclusive:
                    display(iw.VBox(rows_groups_nonexclusive_raw))
                elif not show:
                    display(iw.VBox(rows_raw))
            elif raw_data_toggle.value == 'Filtered':
                if show and exclusive:
                    display(iw.VBox(rows_groups_exclusive))
                if show and not exclusive:
                    display(iw.VBox(rows_groups_nonexclusive))
                elif not show:
                    display(iw.VBox(rows))

        status_indicator.clear_output()
        with status_indicator:
            display(iw.HTML('<h3 style="color:green">Ready</h3>'))
Esempio n. 9
0
def save_source(sender):
    UI.source_column = sender["new"]
    val = "Source Column set to"
    if sender["old"] == None:

        new1 = Widget = widgets.HTML(
            value="<b><font color='%s'>%s: </font> </b>%s<br><br>" %
            (UI.hl_color1, val, sender["new"]))

        new2 = widgets.Select(options=UI.main_df.columns,
                              value=None,
                              description='Destination Column',
                              style=UI.descr_style)
        new2.observe(save_dest, names="value")
        UI.reload_data("Data", new1, new2)
    else:
        for i in UI.content["Data"]:
            if "HTML" in str(type(i)):
                if val in i.value:
                    text = sender["new"]
                    i.value = "<b><font color='%s'>%s: </font></b>%s<br><br>" % (
                        UI.hl_color1, val, sender["new"])
        UI.reload_data("Data")
Esempio n. 10
0
 def __init__(self,
              value=60,
              min=0,
              max=100,
              step=10,
              description='Choose the percentage below:',
              name=str(Step.global_id + 1),
              show_previous=True,
              show_next=True):
     self.title = widgets.HTML(description)
     self.slider = widgets.IntSlider(value=value,
                                     min=min,
                                     max=max,
                                     step=step,
                                     description='',
                                     disabled=False,
                                     continuous_update=False,
                                     orientation='horizontal',
                                     readout=True,
                                     readout_format='d')
     super().__init__(name, show_previous, show_next)
     self.resetParameters()
     pass
Esempio n. 11
0
    def __init__(self, label_name):
        self.clix = 0  # current landmark index
        self.length = len(db)
        self.n_panels = 5
        self.panels = [ImageAndLabel() for _ in range(self.n_panels)]
        self.label_name = label_name
        self.landmarks = Landmarks({k: None for k in db.keys()})

        self.c = widgets.HTML('Click or type on me!')
        button = widgets.Button(description="Save",
                                layout=widgets.Layout(width='auto'))
        button.on_click(self.save)
        w = widgets.HBox([*self.panels])
        w = widgets.VBox([w, self.c, button])
        self.widget = w

        self.d = Event(source=self.widget, watched_events=['keydown'])
        self.d.on_dom_event(self.handle_event)

        self.target_label = 'q'

        self.render()
        display(self.widget)
Esempio n. 12
0
    def __init__(self, ip, name):
        # Here we call ipython ip to avoid conflict with the ipython file
        self.ip = ip
        self.name = name
        if self.name in self.ip.shell.user_ns:
            aut = self.ip.shell.user_ns[self.name].strip()
            states, transitions, _ = self._d3_of_aut(aut)
            self.context = aut.context()
        # Here Add the conversion from vcsn to d3 datas
        else:
            states = [{'id': 0}]
            transitions = [{'source': '0', 'label': ''},
                           {'target': '0', 'label': ''}]
            self.context = vcsn.context('lal(a-z), b')

        aut = AutomatonD3Widget(states=states, transitions=transitions)#, context=self.context)
        self.error = widgets.HTML(value='')

        self._widget_ctx = vcsn.ipython.ContextText(self, self.context)
        self._widget_ctx.text.observe(self._on_change, 'value')

        self._widget = aut
        self._widget.observe(self._on_change, ['states','transitions'])
def quiz_word2vec_subsampling():
    # lesson 4, quiz 4

    import ipywidgets as widgets
    from IPython.display import display

    description = widgets.Output()
    with description:
        display(
            widgets.HTML("""
            In the implementation above, which words are subsampled (i.e. too frequent words are thrown away with some probability)?
        """))

    return Quiz(
        description,
        [
            "Central words",
            "Context words",
            "Negative samples",
            "All of them",
        ],
        "Central words",
    )
    def __init__(self, title="Progress Bar", **kwargs):
        """Initialize ProgressBarWidget."""

        self.title = title
        self.correspondance = {
            "created": 0,
            "running": 1,
            "waiting": 1,
            "killed": 2,
            "excepted": 2,
            "finished": 2,
        }
        self.progress_bar = ipw.IntProgress(
            value=0,
            min=0,
            max=2,
            step=1,
            description='Progress:',
            bar_style='warning',  # 'success', 'info', 'warning', 'danger' or ''
            orientation='horizontal',
            layout={'width': '800px'})
        self.state = ipw.HTML(description="Calculation state:", value='Created', style={'description_width': 'initial'})
        super().__init__(children=[self.progress_bar, self.state], **kwargs)
def quiz_word2vec_negative_sampling():
    # lecture 4, quiz 5

    import ipywidgets as widgets
    from IPython.display import display

    description = widgets.Output()
    with description:
        display(
            widgets.HTML("""
            How is negative sampling performed? Why?
        """))

    return Quiz(
        description,
        [
            "without replacement; negative samples are i.i.d.",
            "with replacement; negative samples are i.i.d.",
            "without replacement; it is efficient",
            "with replacement; it is efficient",
        ],
        "with replacement; negative samples are i.i.d.",
    )
Esempio n. 16
0
    def _widget_upload_data_type1(self):
        """upload EM file and parse metadata
        """
        title = widgets.HTML('''<h5>Upload data type 1 <h5/>
        <hr style="height:1px;border-width:0;color:black;background-color:gray">
        ''')

        self.data1 = FileChooser(use_dir_icons=True)
        self.data1.title = '<b>data type 1</b>'

        vbox = widgets.VBox([title, self.data1])

        def on_upload_change(change):
            #for name, file_info in self.EM_upload.value.items():
            name = self.data0.selected
            self._add_to_dir(name, target_dir='data', level_dir='type1')
            self._add_to_Exdir(name, target_dir='data', level_dir='type1')
            #self._add_file_to_Expipe(name, target_dir='data', level_dir='type1')
            #self._add_to_Zip(name, target_dir='data', level_dir='type1')

        self.data0.register_callback(on_upload_change)

        return vbox
def quiz_word2vec_word_vector():
    # lesson 4, quiz 3
    import ipywidgets as widgets
    from IPython.display import display

    description = widgets.Output()
    with description:
        display(
            widgets.HTML("""
            word2vec algorithm learns two matrices: the matrix of central vectors and the matrix of context vectors.
            In the implementation above, how is the word vector computed for a given word?
        """))

    return Quiz(
        description,
        [
            "Taken from the matrix of context vectors",
            "Taken from the matrix of central vectors",
            "It is the average of central and context vectors",
            "None of the above",
        ],
        "Taken from the matrix of central vectors",
    )
Esempio n. 18
0
def circuit_data_table(qc):

    ops = qc.count_ops()

    num_cx = None
    if 'cx' in ops.keys():
        num_cx = ops['cx']

    html = "<table {}>".format(TABLE_STYLE)
    html += "<tr><th style={}>{}</th><th></tr>".format(TD_STYLE, qc.name)

    html += "<tr><td style={}>Width</td><td>{}</td></tr>".format(
        TD_STYLE, qc.width())
    html += "<tr><td style={}>Depth</td><td>{}</td></tr>".format(
        TD_STYLE, qc.depth())
    html += "<tr><td style={}>Gate Count</td><td>{}</td></tr>".format(
        TD_STYLE, sum(ops.values()))
    html += "<tr><td style={}>CX Count</td><td>{}</td></tr>".format(
        TD_STYLE, num_cx)
    html += "</table>"

    out_wid = wid.HTML(html, layout=wid.Layout(width='45%'))
    return out_wid
Esempio n. 19
0
    def _ipython_display_(self):
        import ipywidgets
        from IPython.display import display, Markdown
        names = dir(self)
        names.sort()

        def change_field(_ftype, _box, _var_window):
            def _change_field(event):
                fobj = getattr(_ftype, event['new'])
                _box.clear_output()
                with _box:
                    display(
                        Markdown(data="```python\n" +
                                 textwrap.dedent(fobj.get_source()) + "\n```"))
                values = inspect.getclosurevars(fobj._function).nonlocals
                _var_window.value = _fill_values(values)

            return _change_field

        flist = ipywidgets.Select(options=names,
                                  layout=ipywidgets.Layout(height='95%'))
        source = ipywidgets.Output(
            layout=ipywidgets.Layout(width='100%', height='9em'))
        var_window = ipywidgets.HTML(value='Empty')
        var_box = ipywidgets.Box(layout=ipywidgets.Layout(
            width='100%', height='100%', overflow_y='scroll'))
        var_box.children = [var_window]
        ftype_tabs = ipywidgets.Tab(children=[source, var_box],
                                    layout=ipywidgets.Layout(flex='2 1 auto',
                                                             width='auto',
                                                             height='95%'))
        ftype_tabs.set_title(0, "Source")
        ftype_tabs.set_title(1, "Variables")
        flist.observe(change_field(self, source, var_window), "value")
        display(
            ipywidgets.HBox([flist, ftype_tabs],
                            layout=ipywidgets.Layout(height='14em')))
Esempio n. 20
0
    def _get_param_iterator(self):
        """Return ParameterGrid instance for the given param_grid"""

        iterator = super()._get_param_iterator()
        iterator = list(iterator)
        n_candidates = len(iterator)

        cv = model_selection._split.check_cv(self.cv, None)
        n_splits = getattr(cv, "n_splits", 3)
        max_value = n_candidates * n_splits  # count the amount of iterations total

        progress_label = ipywidgets.HTML()
        progress_bar = ipywidgets.FloatProgress(
            min=0, max=max_value, description="GridSearchCV:"
        )
        progress_box = ipywidgets.HBox(
            children=[progress_bar, progress_label]
        )  # setup a progress label + bar

        display(progress_box)
        original_fit = self.estimator.__class__.fit

        def fit(*args, **kwargs):
            progress_bar.value += (
                1
            )  # every time fit is called, increase progress bar by 1
            if (
                progress_bar.value == max_value
            ):  # if max value is reached, display finished and turn green
                progress_label.value = "finished"
                progress_bar.bar_style = "success"

            original_fit(*args, **kwargs)

        self.estimator.__class__.fit = fit

        return iterator
Esempio n. 21
0
    def _build(self):
        desc = self.desc
        if self.units is not None:
            desc += "\n\nValues with no units will be assumed to be %s [%s]." % (
                self.units, '{:~}'.format(self.units))

        if self.min is not None or self.max is not None:
            desc += "\n\n"
            if self.min is not None:
                desc += "Min: %s\n" % self.min
            if self.max is not None:
                desc += "Max: %s\n" % self.max
            desc += "\n"

        if self.units:
            desc += "You can type expressions using other units and they will be converted if possible."

        if self.min is not None:
            desc += "\n\n"
            if self.min is not None:
                desc += "Min: %s\n" % self.min
            if self.max is not None:
                desc += "Max: %s\n" % self.max
            desc += "\n"

        label = widgets.HTML(
            value='<p data-toggle="popover" title="%s">%s</p>' %
            (desc, self.name),
            layout=widgets.Layout(flex='2 1 auto'))
        form_item_layout = widgets.Layout(display='flex',
                                          flex_flow='row',
                                          border='solid 1px lightgray',
                                          justify_content='space-between',
                                          padding='5px',
                                          width=self._width)
        self.w = widgets.Box([label, self.dd, self.valid],
                             layout=form_item_layout)
Esempio n. 22
0
    def __call__(self, filename):
        
        cmd = (self.cmd + ' ' + filename).split(' ')
        zero = time.monotonic_ns()

        p = subprocess.Popen(cmd,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)


        #
        status = widgets.HTML()
        progress = widgets.FloatProgress(value=0.0, min=0.0, max=1.0)

        display(widgets.VBox([status,progress]))


        out = widgets.Output()
        a = widgets.HBox([out], layout=widgets.Layout(height='100px', overflow_y='auto'))
        display(a)

        with out:
            total = 0
            for line in iter(p.stdout.readline, b''):
                tmp = re.search(r'([0-9]*) it',line.decode('utf-8'))
                print(">>> " + line.decode('utf-8').rstrip())
                if tmp:
                    cur = int(tmp.groups()[0])
                    if total > 0 and cur > 0: 
                        progress.value = float(cur) / total
                        ellapsed = int((time.monotonic_ns() - zero)*1e-9)
                        speed = cur / ellapsed
                        status.value = f'{cur} / {total} Iters. <br/> {ellapsed} seconds. </br> {(total - cur) / speed} seconds to finish'
                    #print(">>> " + str(cur) + ' / ' + str(total))
                tmp = re.search(r'Setting action Solve at ([0-9\.]*) iterations',line.decode('utf-8')) 
                if tmp:
                    total = int(float(tmp.groups()[0]))
Esempio n. 23
0
    def __init__(
        self,
        embedded: bool = True,
        title: str = None,
        **kwargs,
    ) -> None:
        providers_header = ipw.HTML("<h4>Select a provider</h4>")
        providers = OptimadeQueryProviderWidget(
            embedded=embedded,
            width_ratio=kwargs.pop("width_ratio", None),
            width_space=kwargs.pop("width_space", None),
            database_limit=kwargs.pop("database_limit", None),
            disable_providers=kwargs.pop("disable_providers",
                                         self._disable_providers),
            skip_databases=kwargs.pop("skip_databases", self._skip_databases),
            provider_database_groupings=kwargs.pop(
                "provider_database_groupings", self._database_grouping),
        )
        filters = OptimadeQueryFilterWidget(
            embedded=embedded,
            button_style=kwargs.pop("button_style", None),
            result_limit=kwargs.pop("results_limit", None),
            subparts_order=kwargs.pop("subparts_order", None),
        )

        ipw.dlink((providers, "database"), (filters, "database"))

        filters.observe(self._update_structure, names="structure")

        self.title = title or "OPTIMADE"
        layout = kwargs.pop("layout", {"width": "auto", "height": "auto"})

        super().__init__(
            children=(providers_header, providers, filters),
            layout=layout,
            **kwargs,
        )
Esempio n. 24
0
def nbquiz(question: str, options: List[str], correct_answer: int, 
    globals: Optional[Dict[str, Any]], 
    title: str = 'Quiz', debug: bool = False) -> object:
    import ipywidgets as widgets

    if isinstance(correct_answer, str):
        correct_answer = int(eval(correct_answer, globals))
  
    radio_options = [(quiztext(words), i) for i, words in enumerate(options)]
    alternatives = widgets.RadioButtons(
        options = radio_options,
        description = '',
        disabled = False
    )

    title_out =  widgets.HTML(value=f'<h4>{quiztext(title)}</h4><strong>{quiztext(question)}</strong>')

    check = widgets.Button()
    
    def clear_selection(change: Any) -> None:
        check.description = 'Submit'
        
    clear_selection(None)

    def check_selection(change: Any) -> None:
        answer = int(alternatives.value) + 1

        if answer == correct_answer:
            check.description = 'Correct!'
        else:
            check.description = 'Incorrect!'
        return
    
    check.on_click(check_selection)
    alternatives.observe(clear_selection, names='value')
    
    return widgets.VBox([title_out, alternatives, check])
    def __init__(self):
        super(ChangeLog, self).__init__(orientation='vertical')
        try:
            current = version.parse(mdt.__version__)
            latest = self.version_check()
            if current >= latest:
                versiontext = 'Up to date. Latest release: %s' % latest
            else:
                versiontext = (
                    'New release available! '
                    '(Current: %s, latest: %s <br>' % (current, latest) +
                    '<b>Install it:</b> '
                    '<span style="font-family:monospace">pip install -U moldesign'
                    '</span>')
        except Exception as e:
            versiontext = '<b>Failed update check</b>: %s' % e

        self.version = ipy.HTML(versiontext)
        self.textarea = ipy.Textarea(width='700px', height='300px')

        p1 = os.path.join(mdt.PACKAGEPATH, "HISTORY.rst")
        p2 = os.path.join(mdt.PACKAGEPATH, "..", "HISTORY.rst")
        if os.path.exists(p1):
            path = p1
        elif os.path.exists(p2):
            path = p2
        else:
            path = None

        if path is not None:
            with open(path, 'r') as infile:
                self.textarea.value = infile.read()
        else:
            self.textarea.value = 'HISTORY.rst not found'

        self.textarea.disabled = True
        self.children = (self.version, self.textarea)
Esempio n. 26
0
    def __init__(
        self,
        description: str,
        input_widget: Callable = None,
        hint: str = None,
        description_width: str = None,
        **kwargs,
    ):
        _description_width = (description_width
                              if description_width is not None else "170px")
        description = ipw.HTML(description,
                               layout={"width": _description_width})

        _layout = {"width": "100%"}
        self.input_widget = (input_widget(layout=_layout, **kwargs)
                             if input_widget is not None else ipw.Text(
                                 layout=_layout))

        if hint and isinstance(self.input_widget,
                               ipw.widgets.widget_string._String):
            self.input_widget.placeholder = hint

        super().__init__(children=[description, self.input_widget],
                         layout=ipw.Layout(width="auto"))
Esempio n. 27
0
    def __init__(self, name, **kwargs):
        self.name = name
        width = kwargs.get('width', 'auto')
        self._ncb = kwargs.get('cb')

        # accept either 'description' or 'desc'
        desc = kwargs.get('desc', kwargs.get('description', ''))

        form_item_layout = widgets.Layout(display='flex',
                                          flex_flow='row',
                                          border='solid 1px lightgray',
                                          justify_content='space-between',
                                          padding='3px',
                                          width=width)

        self.dd.layout = {'width': 'initial'}
        self.dd.disabled = kwargs.get('disabled', False)
        self.dd.observe(self._cb, names='value')

        popup = '<div data-toggle="popover" title="%s" data-container="body">%s</div>' % (
            desc, name)
        label = widgets.HTML(value=popup,
                             layout=widgets.Layout(flex='2 1 auto'))
        widgets.HBox.__init__(self, [label, self.dd], layout=form_item_layout)
Esempio n. 28
0
    def __init__(self, title='Output:', num_lines_shown=3, **kwargs):
        self.description = ipw.Label(value=title)
        self.last_lines = ipw.HTML()

        self.lines = []
        self.lines_shown = deque([''] * num_lines_shown,
                                 maxlen=num_lines_shown)

        self.raw_log = ipw.Textarea(layout=ipw.Layout(
            width='auto',
            height='auto',
            display='flex',
            flex='1 1 auto',
        ),
                                    disabled=True)

        self.accordion = ipw.Accordion(children=[self.raw_log])
        self.accordion.set_title(0, 'Raw log')
        self.accordion.selected_index = None

        self._update()
        super().__init__(
            children=[self.description, self.last_lines, self.accordion],
            **kwargs)
Esempio n. 29
0
    def __init__(self, f, log=logger):
        self.f = f
        self.log = log
        self.grid_widget = qgrid.show_grid(f(),
                                           show_toolbar=False,
                                           grid_options={
                                               'editable': False,
                                               'minVisibleRows': 10,
                                               'maxVisibleRows': 8
                                           })

        refresh_btn = ipywidgets.ToggleButton(
            value=False,
            description='Refresh',
            disabled=False,
            button_style='',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip='Auto refresh',
            icon='refresh')
        refresh_btn.observe(self.refresh_btn_handler)
        self.refresh_btn = refresh_btn

        self.updated_at = ipywidgets.HTML(value='<i>%s</i>' %
                                          datetime.datetime.now(),
                                          description='Updated at')
Esempio n. 30
0
 def __init__(self, **kwargs):
     self.correspondance = {
         None: (0, 'warning'),
         "created": (0, 'info'),
         "running": (1, 'info'),
         "waiting": (1, 'info'),
         "killed": (2, 'danger'),
         "excepted": (2, 'danger'),
         "finished": (2, 'success'),
     }
     self.bar = ipw.IntProgress(  # pylint: disable=blacklisted-name
         value=0,
         min=0,
         max=2,
         step=1,
         bar_style='warning',  # 'success', 'info', 'warning', 'danger' or ''
         orientation='horizontal',
         layout=ipw.Layout(width="auto"))
     self.state = ipw.HTML(
         description="Calculation state:",
         value='',
         style={'description_width': '100px'},
     )
     super().__init__(children=[self.state, self.bar], **kwargs)