Python ipywidgets.Layout() Examples

The following are 30 code examples for showing how to use ipywidgets.Layout(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module ipywidgets , or try the search function .

Example 1
Project: ipygee   Author: fitoprincipe   File: map.py    License: MIT License 6 votes vote down vote up
def setDimensions(self, width=None, height=None):
        """ Set the dimensions for the map """
        def check(value, t):
            if value is None: return value
            if isinstance(value, (int, float)):
                return '{}px'.format(value)
            elif isinstance(value, (str,)):
                search = re.search('(\d+)', value).groups()
                intvalue = search[0]
                splitted = value.split(intvalue)
                units = splitted[1]
                if units == '%':
                    if t == 'width': return '{}%'.format(intvalue)
                    else: return None
                else:
                    return '{}px'.format(intvalue)
            else:
                msg = 'parameter {} of setDimensions must be int or str'
                raise ValueError(msg.format(t))
        self.layout = Layout(width=check(width, 'width'),
                             height=check(height, 'height')) 
Example 2
Project: qiskit-terra   Author: Qiskit   File: job_widgets.py    License: Apache License 2.0 6 votes vote down vote up
def make_labels():
    """Makes the labels widget.

    Returns:
        widget: The labels widget.
    """
    labels0 = widgets.HTML(value="<h5>Job ID</h5>",
                           layout=widgets.Layout(width='190px'))
    labels1 = widgets.HTML(value='<h5>Backend</h5>',
                           layout=widgets.Layout(width='145px'))
    labels2 = widgets.HTML(value='<h5>Status</h5>',
                           layout=widgets.Layout(width='95px'))
    labels3 = widgets.HTML(value='<h5>Queue</h5>',
                           layout=widgets.Layout(width='70px'))
    labels4 = widgets.HTML(value='<h5>Message</h5>')

    labels = widgets.HBox(children=[labels0, labels1, labels2, labels3, labels4],
                          layout=widgets.Layout(width='600px',
                                                margin='0px 0px 0px 37px'))
    return labels 
Example 3
Project: qiskit-terra   Author: Qiskit   File: library.py    License: Apache License 2.0 6 votes vote down vote up
def circuit_diagram_widget() -> wid.Box:
    """Create a circuit diagram widget.

    Returns:
        Output widget.
    """
    # The max circuit height corresponds to a 20Q circuit with flat
    # classical register.
    top_out = wid.Output(layout=wid.Layout(width='100%',
                                           height='auto',
                                           max_height='1000px',
                                           overflow='hidden scroll',))

    top = wid.Box(children=[top_out], layout=wid.Layout(width='100%', height='auto'))

    return top 
Example 4
Project: qkit   Author: qkitgroup   File: VirtualAWG.py    License: GNU General Public License v2.0 6 votes vote down vote up
def plot(self, show_quadrature = "", x_unit = "ns"): 
        """
        Plots the sequences stored in channel.
        A slider provides the option to sweep through different time values.
        Readout pulse is fixed at t = 0, where is t>0 before the readout tone.

        Args:
            x_unit: unit of the x-axis in the plot. Options are "s", "ms", "us", "ns".
        """
        show_iq = False
        if show_quadrature in ["I", "Q"]:
            show_iq = True
        sequences, readout_indices = self._get_sequences(IQ_mixing=show_iq)
        seq_max = len(readout_indices) - 1
        if show_quadrature is "I":
            sequences = [np.real(seq) for seq in sequences]
        elif show_quadrature is "Q":
            sequences = [np.imag(seq) for seq in sequences]
        
        bounds = self._get_boundaries(sequences, readout_indices, x_unit)
        
        interact(lambda sequence: self._plot_sequence(sequences[sequence], readout_indices[sequence], x_unit, bounds), 
                sequence = widgets.IntSlider(value = 0, min = 0, max = seq_max, layout = Layout(width = "98%", height = "50px")))
        return True 
Example 5
Project: scikit-dsp-comm   Author: mwickert   File: rtlsdr_helper.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _interact_frequency(self,freq_val,min_freq=87.5,max_freq=108,freq_step=0.2):
        '''
        Sets up tuning frequency slider widget for Mono FM Example
        '''
        self.slider = FloatSlider(
            value=freq_val,
            min=min_freq,
            max=max_freq,
            step=freq_step,
            description=r'$f_c\;$',
            continuous_update=False,
            orientation='horizontal',
            readout_format='0.1f',
            layout=Layout(
                width='90%',
            ) 
        )
        self.slider.style.handle_color = 'lightblue'

        self.center_freq_widget = interactive(self.set_fc_mhz, fc = self.slider)
        display(self.center_freq_widget) 
Example 6
Project: scikit-dsp-comm   Author: mwickert   File: rtlsdr_helper.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _interact_audio_gain(self,gain_val=0,min_gain=-60,max_gain=6,gain_step=0.1):
        '''
        Sets up audio gain slider widget for Mono FM Example
        '''
        self.gain_slider = FloatSlider(
            value=gain_val,
            min=min_gain,
            max=max_gain,
            step=gain_step,
            description='Gain (dB)',
            continuous_update=True,
            orientation='horizontal',
            readout_format='0.1f',
            layout=Layout(
                width='90%',
            )
        )
        self.gain_slider.style.handle_color = 'lightgreen'

        self.audio_gain_widget = interactive(self.set_audio_gain_db,gain=self.gain_slider)
        display(self.audio_gain_widget) 
Example 7
Project: qiskit-ibmq-provider   Author: Qiskit   File: job_widgets.py    License: Apache License 2.0 6 votes vote down vote up
def make_labels() -> widgets.HBox:
    """Makes the labels widget.

    Returns:
        The labels widget.
    """
    labels0 = widgets.HTML(value="<h5>Job ID</h5>",
                           layout=widgets.Layout(width='190px'))
    labels1 = widgets.HTML(value='<h5>Backend</h5>',
                           layout=widgets.Layout(width='165px'))
    labels2 = widgets.HTML(value='<h5>Status</h5>',
                           layout=widgets.Layout(width='125px'))
    labels3 = widgets.HTML(value='<h5>Est. Start Time</h5>',
                           layout=widgets.Layout(width='100px'))

    labels = widgets.HBox(children=[labels0, labels1, labels2, labels3],
                          layout=widgets.Layout(width='700px',
                                                margin='0px 0px 0px 35px'))
    return labels 
Example 8
Project: dask-gateway   Author: dask   File: options.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _widget(self):
        if not hasattr(self, "_cached_widget"):
            try:
                import ipywidgets

                children = [ipywidgets.HTML("<h2>Cluster Options</h2>")]
                children.extend([f.widget() for f in self._fields.values()])
                column = ipywidgets.Box(
                    children=children,
                    layout=ipywidgets.Layout(
                        display="flex", flex_flow="column", align_items="stretch"
                    ),
                )
                widget = ipywidgets.Box(children=[column])
            except ImportError:
                widget = None
            object.__setattr__(self, "_cached_widget", widget)
        return self._cached_widget 
Example 9
Project: dask-gateway   Author: dask   File: options.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def widget(self):
        import ipywidgets

        def handler(change):
            self.set(change.new)

        input = self._widget()
        input.observe(handler, "value")
        self._widgets.add(input)

        label = ipywidgets.HTML(
            "<p style='font-weight: bold; margin-right: 8px'>%s:</p>" % self.label
        )

        row = ipywidgets.Box(
            children=[label, input],
            layout=ipywidgets.Layout(
                display="flex", flex_flow="row wrap", justify_content="space-between"
            ),
        )

        return row 
Example 10
Project: notebook-molecular-visualization   Author: Autodesk   File: visualization.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, pyname, getversion=False):
        self.displays = {}
        self.pyname = pyname
        self.getversion = getversion

        self.nbv_display = VBox()
        self.widgets_display = VBox()
        self.warning = ipywidgets.HTML()

        super().__init__()
        children = [ipywidgets.HTML("<h4><center>%s</center></h4>" % self.pyname,
                                    layout=ipywidgets.Layout(align_self='center')),
                    ipywidgets.HTML(self.HEADER)]

        for location in install.nbextension_ordered_paths():
            self.state = install.get_installed_versions(self.pyname, self.getversion)
            props = self._get_props(location)
            self.displays[location] = ExtensionInstallLocation(self, props)
            children.append(self.displays[location])

        children.append(self.warning)

        self.children = children
        self._highlight_active() 
Example 11
Project: notebook-molecular-visualization   Author: Autodesk   File: images.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, image, client):
        self._err = False
        self._client = client
        self.image = image
        self.status = ipy.HTML(layout=ipy.Layout(width="20px"))
        self.html = ipy.HTML(value=image, layout=ipy.Layout(width="400px"))
        self.html.add_class('nbv-monospace')
        self.msg = ipy.HTML(layout=ipy.Layout(width='300px'))
        self.button = ipy.Button(layout=ipy.Layout(width='100px'))
        if mdt.compute.config.devmode:
            self.button.on_click(self.rebuild)
        else:
            self.button.on_click(self.pull)
        self._reactivate_button()
        self._set_status_value()
        super().__init__(children=[self.status, self.html, self.button, self.msg]) 
Example 12
Project: notebook-molecular-visualization   Author: Autodesk   File: selection.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, mol):
        super().__init__(mol)

        self._atomset = collections.OrderedDict()

        self.atom_listname = ipy.Label('Selected atoms:', layout=ipy.Layout(width='100%'))
        self.atom_list = ipy.SelectMultiple(options=list(self.viewer.selected_atom_indices),
                                            layout=ipy.Layout(height='150px'))
        traitlets.directional_link(
            (self.viewer, 'selected_atom_indices'),
            (self.atom_list, 'options'),
            self._atom_indices_to_atoms
        )

        self.select_all_atoms_button = ipy.Button(description='Select all atoms')
        self.select_all_atoms_button.on_click(self.select_all_atoms)

        self.select_none = ipy.Button(description='Clear all selections')
        self.select_none.on_click(self.clear_selections)

        self.representation_buttons = ipy.ToggleButtons(options=['stick','ribbon', 'auto', 'vdw'],
                                                        value='auto')
        self.representation_buttons.observe(self._change_representation, 'value') 
Example 13
Project: notebook-molecular-visualization   Author: Autodesk   File: selection.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, mol):
        super().__init__(mol)

        self._bondset = collections.OrderedDict()
        self._drawn_bond_state = set()

        self.bond_listname = ipy.Label('Selected bonds:', layout=ipy.Layout(width='100%'))
        self.bond_list = ipy.SelectMultiple(options=list(),
                                            layout=ipy.Layout(height='150px'))
        self.viewer.observe(self._update_bondlist, 'selected_atom_indices')

        self.atom_list.observe(self.remove_bondlist_highlight, 'value')

        self.subtools.children = [HBox([self.select_all_atoms_button,
                                        self.select_none])]
        self.toolpane.children = (self.atom_listname,
                                  self.atom_list,
                                  self.bond_listname,
                                  self.bond_list) 
Example 14
Project: notebook-molecular-visualization   Author: Autodesk   File: selection.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, mol):
        super().__init__(mol)

        self.selection_type = ipy.Dropdown(description='Clicks select:',
                                           value=self.viewer.selection_type,
                                           options=('Atom', 'Residue', 'Chain'))

        traitlets.link((self.selection_type, 'value'), (self.viewer, 'selection_type'))

        self.residue_listname = ipy.Label('Selected residues:', layout=ipy.Layout(width='100%'))
        self.residue_list = ipy.SelectMultiple(options=list(), height='150px')
        self.viewer.observe(self._update_reslist, 'selected_atom_indices')

        self.residue_list.observe(self.remove_atomlist_highlight, 'value')
        self.atom_list.observe(self.remove_reslist_highlight, 'value')

        self.subtools.children = [self.representation_buttons]
        self.subtools.layout.flex_flow = 'column'
        self.toolpane.children = [self.selection_type,
                                  HBox([self.select_all_atoms_button, self.select_none]),
                                  self.atom_listname,
                                  self.atom_list,
                                  self.residue_listname,
                                  self.residue_list] 
Example 15
Project: notebook-molecular-visualization   Author: Autodesk   File: components.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, format=None, *args, **kwargs):
        description = kwargs.pop('description', 'FloatSlider')
        min = kwargs.setdefault('min', 0.0)
        max = kwargs.setdefault('max', 10.0)
        self.formatstring = format
        self.header = ipy.HTML()
        self.readout = ipy.Text(layout=ipy.Layout(width='100px'))
        self.readout.on_submit(self.parse_value)

        kwargs.setdefault('readout', False)
        self.slider = ipy.FloatSlider(*args, **process_widget_kwargs(kwargs))
        self.minlabel = ipy.HTML(u'<font size=1.5>{}</font>'.format(self.formatstring.format(min)))
        self.maxlabel = ipy.HTML(u'<font size=1.5>{}</font>'.format(self.formatstring.format(max)))
        self.sliderbox = HBox([self.minlabel, self.slider, self.maxlabel])
        traitlets.link((self, 'description'), (self.header, 'value'))
        traitlets.link((self, 'value'), (self.slider, 'value'))
        self.description = description
        self.update_readout()
        super().__init__([self.header,
                                                  self.readout,
                                                  self.sliderbox]) 
Example 16
Project: notebook-molecular-visualization   Author: Autodesk   File: components.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, value=None, units=None, **kwargs):
        kwargs.setdefault('display', 'flex')
        kwargs.setdefault('flex_flow','row wrap')
        super().__init__(layout=ipy.Layout(display='flex', flex_flow='row wrap'),
                                       **process_widget_kwargs(kwargs))
        self.textbox = ipy.Text()
        self.textbox.observe(self._validate, 'value')
        self._error_msg = None

        if units is not None:
            self.dimensionality = u.get_units(units).dimensionality
        else:
            self.dimensionality = None

        self._validated_value = None
        self.validated = ipy.HTML(self.INVALID)
        self.children = [self.textbox, self.validated]
        self._is_valid = False
        if value is not None:
            self.value = value 
Example 17
Project: abu   Author: bbfamily   File: ABuWGPosBase.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, wg_manager):
        super(WidgetPositionBase, self).__init__(wg_manager)
        self.add = widgets.Button(description=u'选定为全局资金管理策略', layout=widgets.Layout(width='98%'),
                                  button_style='info')
        # 选定全局资金管理略指令按钮
        self.add.on_click(self.add_position)
        # 运行混入的BFSubscriberMixin中ui初始化
        self.subscriber_ui([u'点击\'已添加的买入策略\'框中的买入策略', u'资金管理做为买入策略的资金管理策略'])
        # 买入策略框点击行为:将本卖出策略加到对应的买入策略做为附属
        self.buy_factors.observe(self.add_position_to_buy_factor, names='value')
        self.accordion.set_title(0, u'添加为指定买入因子的资金管理策略')
        accordion_shut(self.accordion)
        self.add_box = widgets.VBox([self.add, self.accordion])

        # 具体子策略构建
        self._init_widget() 
Example 18
Project: abu   Author: bbfamily   File: ABuWGUmp.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _init_feature_ui(self):
        """裁判特征采集界面初始化"""
        ml_feature_description = widgets.Textarea(
            value=u'裁判特征采集\n'
                  u'裁判是建立在机器学习技术基础上的,所以必然会涉及到特征,abu量化系统支持在回测过程中生成特征数据,切分训练测试集,'
                  u'甚至成交买单快照图片,通过打开下面的开关即可在生成最终的输出结果数据订单信息上加上买入时刻的很多信息,'
                  u'比如价格位置、趋势走向、波动情况等等特征, 注意需要生成特征后回测速度效率会降低\n'
                  u'如在下拉选择中选中\'回测过程生成交易特征\'在回测完成后将保存回测结果,通过在\'裁判特征训练\'可进行查看并进行'
                  u'裁判训练',
            disabled=False,
            layout=widgets.Layout(height='150px')
        )

        self.enable_ml_feature = widgets.Dropdown(
            options={u'回测过程不生成交易特征': 0,
                     u'回测过程生成交易特征': 1},
            value=0,
            description=u'特征生成:',
        )
        return widgets.VBox([ml_feature_description, self.enable_ml_feature]) 
Example 19
Project: pywr   Author: pywr   File: progress.py    License: GNU General Public License v3.0 5 votes vote down vote up
def reset(self):
        from ipywidgets import FloatProgress, HBox, Label, Layout
        from IPython.display import display
        super(JupyterProgressRecorder, self).reset()
        self.progress_bar = FloatProgress(min=0, max=100, description='Running:')
        self.label = Label("", layout=Layout(width='100%'))
        self.box = HBox([self.progress_bar, self.label])
        display(self.box) 
Example 20
Project: python-esppy   Author: sassoftware   File: visuals.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self,visuals,datasource,**kwargs):
        Options.__init__(self,**kwargs)
        widgets.VBox.__init__(self,layout=widgets.Layout(width=self.getOpt("width","95%"),height=self.getOpt("height","95%"),border=visuals.getOpt("border","0"),padding=visuals.getOpt("padding","10px"),margin=visuals.getOpt("margin","10px")))
        self._visuals = visuals
        self._datasource = datasource
        self._figure = None
        self._data = None
        self._layout = None
        self._controls = None
        self._title = widgets.HTML(layout=widgets.Layout(overflow="hidden"))
        self._banner = widgets.VBox([self._title]) 
Example 21
Project: python-esppy   Author: sassoftware   File: visuals.py    License: Apache License 2.0 5 votes vote down vote up
def create(self):
        self.createContent()

        if self._data != None:
            self._layout = go.Layout()

            margin = 20
            self._layout["margin"] = dict(l=margin,r=margin,b=margin,t=margin)

            xRange = self.getOpt("xrange")
            if xRange != None:
                self._layout["xaxis"]["range"] = xRange
            yRange = self.getOpt("yrange")
            if yRange != None:
                self._layout["yaxis"]["range"] = yRange

            self._layout["xaxis"]["showticklabels"] = self.getOpt("showticks",True)
            self._layout["xaxis"]["showline"] = False

            self._figure = go.FigureWidget(data=self._data,layout=self._layout)

            children = [self._banner,self._figure]

            if self.getOpt("show_controls",False):
                if self._controls == None:
                    self._controls = ControlPanel(self._datasource) 
                children.append(self._controls)

            self.children = children

        self.draw(None,True) 
Example 22
Project: python-esppy   Author: sassoftware   File: visuals.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self,visuals,datasource,**kwargs):
        Chart.__init__(self,visuals,datasource,**kwargs)
        self._header = widgets.HTML(layout=widgets.Layout(overflow="hidden",margin="0",padding="0"))
        self._table = widgets.HTML(layout=widgets.Layout(overflow="auto",height="90%",margin="0",padding="0"))
        self.children = [self._banner,self._header,self._table] 
Example 23
Project: python-esppy   Author: sassoftware   File: visuals.py    License: Apache License 2.0 5 votes vote down vote up
def draw(self,data = None,clear = False):
        if data != None and len(data) > 0:

            if self._detection == None:
                if self._datasource.schema.hasFields():
                    self._detection = (self._datasource.schema.getField("_nObjects_") != None)

            self._data = data[len(data) - 1]
            field = self.getOpt("image");

            html = None

            if field in self._data:
                imagedata = b64encode(self._data[field]).decode("utf-8")
                html = ""
                html += "<div style='width:" + str(self.getOpt("image_width",400)) + "px;height:" + str(self.getOpt("image_height",400)) + "px;position:relative;margin:auto;border:" + self.getOpt("image_border","1px solid #000000") + "'>"
                html += "<img style='width:100%;height:100%' src='data:image/jpeg;base64," + imagedata + "'/>"

                if self._detection:
                    if "_nObjects_" in self._data:
                        value = str(self._data["_nObjects_"])
                        numObjects = int(float(value))
                        for i in range(0,numObjects):
                            s = "_Object" + str(i) + "_"
                            text = self._data[s].strip()
                            s = "_Object" + str(i) + "_x"
                            x = int(float(self._data[s]) * 100)
                            s = "_Object" + str(i) + "_y"
                            y = int(float(self._data[s]) * 100)
                            html += "<div style='position:absolute;zindex:1000;font-weight:normal;color:" + self.getOpt("label_color","white") + ";left:" + str(x) + "%;top:" + str(y) + "%;'>" + text + "</div>"

                html += "</div>";

            if html != None:
                content = widgets.HTML(value=html,layout=widgets.Layout(border=self._visuals.getOpt("border","1px solid #d8d8d8"),width="100%",height="100%",overflow="auto"))
                self.children = [self._banner,content]

        self.setTitle() 
Example 24
Project: python-esppy   Author: sassoftware   File: visuals.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self,compass,**kwargs):
        Options.__init__(self,**kwargs)
        widgets.VBox.__init__(self,layout=widgets.Layout(border=compass.getOpt("border","1px solid #d8d8d8"),padding=compass.getOpt("padding","10px"),margin=compass.getOpt("margin","10px")))
        self._compass = compass
        self._figure = None
        self._layout = None
        self._heading = 0
        self._title = widgets.HTML()
        self._innerCircle = None 
Example 25
Project: python-esppy   Author: sassoftware   File: viewers.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self,visuals,connection,**kwargs):
        widgets.VBox.__init__(self,layout=widgets.Layout(border=visuals.getOpt("border","0"),padding=visuals.getOpt("padding","10px"),margin=visuals.getOpt("margin","10px")))
        Options.__init__(self,**kwargs)
        self._visuals = visuals
        self._connection = connection 
Example 26
Project: python-esppy   Author: sassoftware   File: viewers.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self,visuals,connection,**kwargs):
        ViewerBase.__init__(self,visuals,connection,**kwargs)

        width = self.getOpt("width","98%")
        height = self.getOpt("height","200px")

        self._max = self.getOpt("max",50);

        self._bg = self.getOpt("bg","#f8f8f8")
        self._border = self.getOpt("border","1px solid #d8d8d8")

        components = []
        self._log = widgets.HTML(value="",layout=widgets.Layout(width=width,height=height,border=self._border,overflow="auto"))
        components.append(self._log)

        self._filter = self.getOpt("filter")
        self._regex = None

        if self._filter != None:
            self._filterText = widgets.Text(description="Filter",value=self._filter,layout=widgets.Layout(width="70%"))
            if len(self._filter) > 0:
                self._regex = re.compile(self._filter,re.I)
            setButton = widgets.Button(description="Set")
            clearButton = widgets.Button(description="Clear")
            setButton.on_click(self.filter)
            clearButton.on_click(self.clearFilter)
            components.append(widgets.HBox([self._filterText,setButton,clearButton]))

        self._box = widgets.VBox(components,layout=widgets.Layout(width="100%"))

        s = ""
        s += "<div style='width:100%;height:100%;background:" + self._bg + "'>"
        s += "</div>"
        self._log.value = s

        self._messages = []

        self._connection.getLog().addDelegate(self)
        
        self.children = [self._box] 
Example 27
Project: msticpy   Author: microsoft   File: nbinit.py    License: MIT License 5 votes vote down vote up
def _set_nb_options(namespace):
    namespace["WIDGET_DEFAULTS"] = {
        "layout": widgets.Layout(width="95%"),
        "style": {"description_width": "initial"},
    }

    # Some of our dependencies (networkx) still use deprecated Matplotlib
    # APIs - we can't do anything about it, so suppress them from view
    warnings.simplefilter("ignore", category=MatplotlibDeprecationWarning)
    warnings.filterwarnings("ignore", category=DeprecationWarning)
    sns.set()
    pd.set_option("display.max_rows", 100)
    pd.set_option("display.max_columns", 50)
    pd.set_option("display.max_colwidth", 100)
    os.environ["KQLMAGIC_LOAD_MODE"] = "silent" 
Example 28
Project: scqubits   Author: scqubits   File: qubit_widget.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_widget(callback_func, init_params, image_filename=None):
    """
    Displays ipywidgets for initialization of a QuantumSystem object.

    Parameters
    ----------
    callback_func: function
        callback_function depends on all the parameters provided as keys (str) in the parameter_dict, and is called upon
        changes of values inside the widgets
    init_params: {str: value, str: value, ...}
        names and values of initialization parameters
    image_filename: str, optional
        file name for circuit image to be displayed alongside the qubit
    Returns
    -------

    """
    widgets = {}
    box_list = []
    for name, value in init_params.items():
        label = ipywidgets.Label(value=name)
        if isinstance(value, float):
            enter_widget = ipywidgets.FloatText
        else:
            enter_widget = ipywidgets.IntText

        widgets[name] = enter_widget(value=value, description='', disabled=False)
        box_list.append(ipywidgets.HBox([label, widgets[name]], layout=ipywidgets.Layout(justify_content='flex-end')))

    if image_filename:
        file = open(image_filename, "rb")
        image = file.read()
        image_widget = ipywidgets.Image(value=image, format='png', layout=ipywidgets.Layout(width='400px'))
        ui_widget = ipywidgets.HBox([ipywidgets.VBox(box_list), ipywidgets.VBox([image_widget])])
    else:
        ui_widget = ipywidgets.VBox(box_list)

    out = ipywidgets.interactive_output(callback_func, widgets)
    display(ui_widget, out) 
Example 29
Project: qiskit-terra   Author: Qiskit   File: job_widgets.py    License: Apache License 2.0 5 votes vote down vote up
def make_clear_button(watcher):
    """Makes the clear button

    Args:
        watcher (widget): The watcher widget instance.

    Returns:
        widget: The clear button widget.
    """
    clear = widgets.Button(
        description='Clear',
        button_style='primary',
        layout=widgets.Layout(width='70px',
                              grid_area='right',
                              padding="0px 0px 0px 0px"))

    def on_clear_button_clicked(_):
        watcher.clear_done()

    clear.on_click(on_clear_button_clicked)

    clear_button = widgets.GridBox(children=[clear],
                                   layout=widgets.Layout(
                                       width='100%',
                                       grid_template_columns='20% 20% 20% 20% 20%',
                                       grid_template_areas='''
                                       ". . . . right "
                                        '''))
    return clear_button 
Example 30
Project: qiskit-terra   Author: Qiskit   File: job_widgets.py    License: Apache License 2.0 5 votes vote down vote up
def build_job_viewer():
    """Builds the job viewer widget

    Returns:
        widget: Job viewer.
    """
    acc = widgets.Accordion(children=[widgets.VBox(layout=widgets.Layout(max_width='710px',
                                                                         min_width='710px'))],
                            layout=widgets.Layout(width='auto',
                                                  max_width='750px',
                                                  max_height='500px',
                                                  overflow_y='scroll',
                                                  overflow_x='hidden'))
    acc.set_title(0, 'IBMQ Jobs')
    acc.selected_index = None
    acc.layout.visibility = 'hidden'
    display(acc)
    acc._dom_classes = ['job_widget']
    display(Javascript("""$('div.job_widget')
        .detach()
        .appendTo($('#header'))
        .css({
            'z-index': 999,
             'position': 'fixed',
            'box-shadow': '5px 5px 5px -3px black',
            'opacity': 0.95,
            'float': 'left,'
        })
        """))
    acc.layout.visibility = 'visible'
    return acc