def test_setitem_slices(self): box = widgets.GridspecLayout(2, 3) button1 = widgets.Button() box[:2, 0] = button1 assert len(box.children) == 1 assert button1 in box.children button1_label = button1.layout.grid_area assert box.layout.grid_template_areas == '''"{b1} . ."\n"{b1} . ."'''.format( b1=button1_label) box = widgets.GridspecLayout(2, 3) button1 = widgets.Button() button2 = widgets.Button() box[:2, 1:] = button1 assert len(box.children) == 1 assert button1 in box.children button1_label = button1.layout.grid_area assert box.layout.grid_template_areas == '''". {b1} {b1}"\n". {b1} {b1}"'''.format( b1=button1_label) # replace button box[:2, 1:] = button2 assert len(box.children) == 1 assert button2 in box.children button2_label = button2.layout.grid_area assert box.layout.grid_template_areas == '''". {b1} {b1}"\n". {b1} {b1}"'''.format( b1=button2_label)
def initGrid(out): grid = widgets.GridspecLayout(20, 30, width='auto', height='13.2cm') grid[0, 0:29] = widgets.Button( disabled=False, description='Welcome to the Quality Analysis System !', button_style='info', tooltip='标题', style={'button_color': '#004080'}, layout=widgets.Layout(width='auto', height='0.65cm')) grid[0, 29] = widgets.Button(description='X', tooltip='关闭', layout=widgets.Layout(width='0.8cm', height='0.65cm')) with out: display(grid) ''' 关闭整个程序:点击右上角×时执行 ''' def closeAll(b): out.clear_output() out.layout = {} with out: display(widgets.Label(value='Thank you for using !')) grid[0, 29].on_click(closeAll) return grid
def updateParameterAndFilepathWidgets(self, ignore): cdatabases = self.dbPathWidget.value.split(' ') cdb = cdatabases[ 0] #all databases are assumed to have same parameter list dbHeader = self.readDataBaseHeader(cdb) self.parameterWidgets.clear() self.filepathWidgets.clear() for param in dbHeader: pW = ipywidgets.ToggleButton(value=param != "FILE", description=param, disabled=False) pW.observe(self.updateParameterValueWidgets, names='value') self.parameterWidgets.append(pW) fW = ipywidgets.ToggleButton(value=param == "FILE", description=param, disabled=False) fW.observe(self.updateParameterValueWidgets, names='value') self.filepathWidgets.append(fW) grid = ipywidgets.GridspecLayout(2, len(self.parameterWidgets) + 1) grid[0, 0] = ipywidgets.Label("Parameters") for j in range(0, len(self.parameterWidgets)): grid[0, j + 1] = self.parameterWidgets[j] for j in range(0, len(self.filepathWidgets)): grid[1, j + 1] = self.filepathWidgets[j] with self.parametersAndFilepathsSelectionOutput: self.parametersAndFilepathsSelectionOutput.clear_output() # display(grid) self.updateParameterValueWidgets('') return
def __init__(self): self.testcase = widgets.Text(description="Testcase") self.input_data = widgets.Text(description="Input Data Type") self.file_size = widgets.Text(description="File Size") self.data_dir = widgets.Text(description="Files Directory") self.run_count = widgets.IntSlider(description="Run Count", min=1, max=10) self.n_nodes = widgets.IntSlider(description="# nodes", min=2, max=50) self.n_leechers = widgets.IntSlider(description="# leechers", min=1, max=50) self.n_passive = widgets.IntSlider(description="# passive ", min=0, max=10) self.max_connection_rate = widgets.IntSlider(description="Max connections (%)", value=100, min=0, max=100) self.churn_rate = widgets.IntSlider(description="Churn Rate (%)", min=0, max=100) self.isDocker = widgets.Checkbox(value=False,description='Docker Env',disabled=False,indent=False) self.bandwidth_mb = widgets.IntSlider(description="Nodes Bandwidth (MB)", value=100, min=0, max=500) self.latency_ms = widgets.IntSlider(description="Nodes Latency (ms)", value=10, min=10, max=500) self.jitter_pct = widgets.IntSlider(description="Pct Jitter (%)", value=5, min=0, max=100) self.tcpEnabled = widgets.Checkbox(value=False,description='TCP enabled',disabled=False,indent=False) self.runButton = widgets.Button( description='Run Test', disabled=False, button_style='success', tooltip='Run test', icon='check' # (FontAwesome names without the `fa-` prefix) ) self.grid = widgets.GridspecLayout(8, 2, height='300px') self.testid = ""
def generateGrid(self): import matplotlib.pyplot as plt plt.close('all') NN, ncols, nrows = self.getNxM() if (nrows * ncols > 0): grid = ipyW.GridspecLayout(nrows, ncols) self._oldpanels = [] n = 0 for i in range(grid.n_rows): for j in range(grid.n_columns): if (n < NN): try: self.parameters[n] = self.panels[n]._kwargs except: pass if not self.figsize is None: self.parameters[n]['figsize'] = self.figsize self.parameters[n]['controls'] = self.controls self.parameters[n]['timestep'] = self.timestep self.parameters[n]['zoomQ'] = self.zoomQ self.parameters[n][ 'interpolation'] = self.interpolation panel = FieldPlot2D(self.simulation, **self.parameters[n]) self._oldpanels.append(panel) grid[i, j] = panel n += 1 self.panels = self._oldpanels self.plotgrid.children = [ipyW.VBox([self.button_panel, grid])] else: self.plotgrid.children = [ipyW.VBox([self.button_panel])]
def downStudent(grid, table, nrows, ncols): temp_grid = widgets.GridspecLayout(31, 6, width='auto', height='auto') temp_grid[0, 1] = widgets.Button(style={'button_color': '#FFC125'}, button_into='info', description='班级') temp_grid[0, 2] = widgets.Button(style={'button_color': '#FFC125'}, button_into='info', description='学号') temp_grid[0, 3] = widgets.Button(style={'button_color': '#FFC125'}, button_into='info', description='姓名') temp_grid[0, 4] = widgets.Button(style={'button_color': '#FFC125'}, button_into='info', description='年名') for i in range(nrows - 30, nrows): alldata = table.row_values(i) for j in range(3): temp_grid[i - nrows + 31, j + 1] = widgets.Button(description=str(alldata[j])) temp_grid[i - nrows + 31, 4] = widgets.Button( description=str(alldata[20]).split('.')[0]) grid[1:19, 0:30].children[0].children[3].children = [temp_grid] return
def __drawWidgets(self): nv = self.nv vars = self.vars steps = self.steps self.layout = ipywidgets.GridspecLayout(nv + 1, 3) for i, (pname, pstep) in enumerate(zip(vars, steps)): self.layout[i, 0] = ipywidgets.FloatText( description=pname, value=self.parameterobj.parameters.get(pname), step=pstep) self.layout[i, 0].observe(self.__parCallBack, names='value') self.layout[i, 1] = ipywidgets.ToggleButton( description="Vary " + pname, value=pname in self.getvars()) self.layout[i, 1].observe(self.__fixVaryCallBack, names='value') self.layout[nv, 0] = ipywidgets.FloatText( description='fit_tolerance', value=self.parameterobj.parameters.get("fit_tolerance"), step=0, ) self.layout[nv, 0].observe(self.__parCallBack, names='value') self.layout[nv, 1] = ipywidgets.Button(description="Run Fit (blocks)") self.layout[nv, 1].on_click(self.__fitCallBack) self.layout[0, 2] = ipywidgets.Button(description="Load parameters") self.layout[0, 2].on_click(self.__loadCallBack) self.layout[1, 2] = ipywidgets.Button(description="Save to a file") self.layout[1, 2].on_click(self.__saveCallBack)
def __init__( self, data_source: DataSource, row: int, index: int, relative_size: float, max_height: int, ): """ :param data_source: :class:`pandas_visual_analysis.data_source.DataSource` for the widget. :param row: The row the widget is in. :param index: Index of the row the widget is in. :param relative_size: The space the widget has in a row which is then converted to the width. (e.g. 0.33 => 33%) :param max_height: height in pixels the plot has to have """ super().__init__(data_source, row, index, relative_size, max_height) self.columns = ( self.data_source.numerical_columns ) # + self.data_source.time_columns if len(self.columns) < 1: raise ValueError( "The data contains too few numerical columns to display the brush summary." "Remove the widget from the layout!" ) self.metric_select = widgets.Dropdown( options=[ ("Mean", "mean"), ("Minimum", "min"), ("1st Quartile", "25%"), ("Median", "50%"), ("3rd Quartile", "75%"), ("Maximum", "max"), ], value="mean", description="Metric:", ) # grid columns: | column_name | data metric | brushed_data metric | indicator self.num_grid_columns = 4 self.num_grid_rows = len(self.columns) + 1 # + 1 for count self.grid = widgets.GridspecLayout(self.num_grid_rows, self.num_grid_columns) self.grid.layout.height = "calc(100% - 40px)" self.base_metrics = self.data_source.data[self.columns].describe(include="all") self.brushed_metrics = self._get_brushed_metrics() self.pos_change_color = "red" self.neg_change_color = "green" self._fill_empty_grid() self._update_column_names() self._update_base_metrics() self._update_brushed_metrics() self.metric_select.observe(self._observe_metric_change, names="value") self.set_observers()
def setup(self): self.var_dropdown = widgets.Dropdown( value=self.dataset._widgets.elevation_var, options=list(self.color_vars), ) self.var_dropdown.observe(lambda change: self._set_color_var(change['new']), names='value') self.colormaps_dropdown = widgets.Dropdown( options=self.colormaps, value=self.default_colormap ) da = self.dataset._widgets.color self.min_input = widgets.FloatText( value=da.min(), layout=widgets.Layout(height='auto', width='auto') ) self.max_input = widgets.FloatText( value=da.max(), layout=widgets.Layout(height='auto', width='auto') ) self.rescale_button = widgets.Button( description='Rescale', tooltip='Rescale to actual data range', layout=widgets.Layout(height='auto', width='auto'), ) self.rescale_button.on_click(lambda _: self.reset_color_limits()) self.rescale_step_button = widgets.Button( description='Rescale Step', tooltip='Rescale to actual data range (current step)', layout=widgets.Layout(height='auto', width='auto'), ) self.rescale_step_button.on_click(lambda _: self.reset_color_limits(step=True)) self.log_scale_checkbox = widgets.Checkbox( value=False, indent=False, layout=widgets.Layout(width='100px'), description='log scale' ) self.log_scale_checkbox.observe( lambda change: self._set_color_scale(log=change['new']), names='value' ) range_grid = widgets.GridspecLayout(3, 2) range_grid[0, 0] = self.min_input range_grid[0, 1] = self.max_input range_grid[1, 0] = self.rescale_button if self.dataset._widgets.time_dim is not None: range_grid[1, 1] = self.rescale_step_button range_grid[2, 0] = self.log_scale_checkbox return widgets.VBox( [ widgets.Label('Coloring:'), self.var_dropdown, widgets.Label('Colormap:'), self.colormaps_dropdown, widgets.Label('Color range / scale:'), range_grid, ] )
def test_getitem_index(self): "test retrieving widget" box = widgets.GridspecLayout(2, 3) button1 = widgets.Button() box[0, 0] = button1 assert box[0, 0] is button1
def test_init(self): with pytest.raises(traitlets.TraitError): box = widgets.GridspecLayout() with pytest.raises(traitlets.TraitError): box = widgets.GridspecLayout(n_rows=-1, n_columns=1) box = widgets.GridspecLayout(n_rows=5, n_columns=3) assert box.n_rows == 5 assert box.n_columns == 3 assert len(box._grid_template_areas) == 5 assert len(box._grid_template_areas[0]) == 3 box = widgets.GridspecLayout(1, 2) assert box.n_rows == 1 assert box.n_columns == 2 with pytest.raises(traitlets.TraitError): box = widgets.GridspecLayout(0, 0)
def test_getitem_slices(self): "test retrieving widgets with slices" box = widgets.GridspecLayout(2, 3) button1 = widgets.Button() box[:2, 0] = button1 assert box[:2, 0] is button1 box = widgets.GridspecLayout(2, 3) button1 = widgets.Button() button2 = widgets.Button() box[0, 0] = button1 box[1, 0] = button2 assert box[0, 0] is button1 assert box[1, 0] is button2 with pytest.raises(TypeError, match="The slice spans"): button = box[:2, 0]
def image_options(): copyfile('default.jpg', 'photo.jpg') grid = w.GridspecLayout(1, 3) grid[0,0] = w.Button(description='Default') grid[0,1] = w.Button(description='Camera') grid[0,2] = w.FileUpload(accept='.jpg') grid[0,0].on_click(default_photo) grid[0,1].on_click(handle_camera) grid[0,2].observe(upload_photo, 'data') return grid
def __init__(self): self.testid = widgets.Text(description="Test ID") self.runButton = widgets.Button( description='Run Test', disabled=False, button_style='success', tooltip='Run test', icon='check' # (FontAwesome names without the `fa-` prefix) ) self.grid = widgets.GridspecLayout(1, 1)
def testPage(out, grid): grid = close_FrontPage(out, grid) grid[0, 0:29].description = '巩固测试' grid[19, 9:11] = widgets.Dropdown(options=[('目 录', 0), ('知识梳理', 1), ('过程演示', 2)], layout=widgets.Layout(width='5cm'), description='跳转到: ') grid[19, 17:18] = widgets.Button(description='进入', style={'button_color': '#004080'}, button_style='info', layout=widgets.Layout(width='2.5cm')) #显示左半部分内容:测试题 leftab = widgets.Tab(layout=widgets.Layout(width='auto', height='auto')) leftab.children = [widgets.GridspecLayout(11, 5)] leftab.set_title(0, 'Little Test') grid[1:19, 0:20] = leftab #显示右半部分内容:成绩/分析/时间 rightab = widgets.Tab(layout=widgets.Layout(width='auto', height='auto')) rightab.children = [widgets.GridspecLayout(7, 6)] rightab.set_title(0, 'Contents') grid[1:19, 20:30] = rightab #调用 test.py里函数 test.test_function(leftab.children[0], rightab.children[0]) #跳转页面 def jumpToPage(b): value = grid[19, 9:11].value if value == 0: contentsPage(out, grid) elif value == 1: knowledgePage(out, grid) elif value == 2: processPage(out, grid) grid[19, 17:18].on_click(jumpToPage) return
def audio_options(): copyfile('binary_yes', 'audio_bin') grid = w.GridspecLayout(1, 4) grid[0, 0] = w.Button(description='Default YES') grid[0, 1] = w.Button(description='Default NO') grid[0, 2] = w.Button(description='Microphone') grid[0, 3] = w.FileUpload(accept='.wav') grid[0, 0].on_click(default_yes) grid[0, 1].on_click(default_no) grid[0, 2].on_click(handle_microphone) grid[0, 3].observe(upload_wav, 'data') return grid
def create_grid(matrizbadfinal,resultados): grid = widgets.GridspecLayout(matrizbadfinal.shape[0]+1, matrizbadfinal.shape[1]+1,max_width=5) for i in range(matrizbadfinal.shape[1]): grid[0,i+1] = widgets.Text(value=str(matrizbadfinal.columns[i]), disabled=True,layout=widgets.Layout(width='100px')) for j in range(matrizbadfinal.shape[0]): grid[j+1,0] = widgets.Text(value= str(matrizbadfinal.index[j]), disabled=True, layout=widgets.Layout(width='100px')) for i in range(matrizbadfinal.shape[0]): for j in range(matrizbadfinal.shape[1]): if i < resultados['index'].values[0] and j < resultados['columns'].values[0]: grid[i+1,j+1] = widgets.ToggleButton(description=str(np.round(matrizbadfinal.values[i,j]*100,1))+"%",value=True,layout=widgets.Layout(width='100px')) else: grid[i+1,j+1] = widgets.ToggleButton(description=str(np.round(matrizbadfinal.values[i,j]*100,1))+"%",value=False,layout=widgets.Layout(width='100px')) return grid
def upStudent(grid, table, nrows, ncols): temp_grid = widgets.GridspecLayout(31, 6, width='auto', height='auto') for i in range(1, 32): alldata = table.row_values(i) for j in range(3): temp_grid[i - 1, j + 1] = widgets.Button(description=str(alldata[j])) if i == 1: temp_grid[i - 1, j + 1].style = {'button_color': '#004080'} temp_grid[i - 1, j + 1].button_style = 'info' temp_grid[i - 1, 4] = widgets.Button( description=str(alldata[20]).split('.')[0]) temp_grid[0, 4].style = {'button_color': '#004080'} temp_grid[0, 4].button_style = 'info' grid[1:19, 0:30].children[0].children[2].children = [temp_grid] return
def box(imagewidget): big_box = ipw.HBox() big_box = ipw.GridspecLayout(1, 2) layout = ipw.Layout(width='20ch') hb = ipw.HBox() ap_t = ipw.IntText(description='Aperture', value=5, layout=layout) in_t = ipw.IntText(description='Inner annulus', value=10, layout=layout) out_t = ipw.IntText(description='Outer annulus', value=20, layout=layout) hb.children = [ap_t, in_t, out_t] lil_box = ipw.VBox() lil_box.children = [out, out2, out3] # big_box.children = [imagewidget, lil_box] big_box[0, 0] = imagewidget big_box[0, 1] = lil_box big_box.layout.width = '100%' # Line below puts space between the image and the plots so the plots # don't jump around as the image value changes. big_box.layout.justify_content = 'space-between' return big_box
def test_setitem_index(self): box = widgets.GridspecLayout(2, 3) button1 = widgets.Button() button2 = widgets.Button() button3 = widgets.Button() button4 = widgets.Button() box[0, 0] = button1 button1_label = button1.layout.grid_area assert button1 in box.children assert box.layout.grid_template_areas == '''"{} . ."\n". . ."'''.format(button1_label) box[-1, -1] = button2 button2_label = button2.layout.grid_area assert button1_label != button2_label assert button2 in box.children assert box.layout.grid_template_areas == '''"{} . ."\n". . {}"'''.format(button1_label, button2_label) box[1, 0] = button3 button3_label = button3.layout.grid_area assert button1_label != button3_label assert button2_label != button3_label assert button3 in box.children assert box.layout.grid_template_areas == '''"{b1} . ."\n"{b3} . {b2}"'''.format(b1=button1_label, b2=button2_label, b3=button3_label) #replace widget box[1, 0] = button4 button4_label = button4.layout.grid_area assert button1_label != button4_label assert button2_label != button4_label assert button4 in box.children assert button3 not in box.children assert box.layout.grid_template_areas == '''"{b1} . ."\n"{b4} . {b2}"'''.format(b1=button1_label, b2=button2_label, b4=button4_label)
def printMulti(*args, colSize=None, width="100%", margin="3px"): """Display multiple output data lines and columns as desired. Args: args: multiple datas. colSize: column size. width: css style width parameter. default is 100%. you can use "px" unint. margin: css style margin parameter. default is 3px. Returns: None Example: >>> showMulti("a", "b", "c", colSize=2) a b c """ # calculate column and row counts. lenArgs = len(args) if (colSize is not None) and (colSize > 0) and (lenArgs - colSize > 0): lenRow = math.ceil(lenArgs/colSize) lenCol = colSize else: lenRow = 1 lenCol = lenArgs # create Output() of ipywidgets and to display the args to it. layout = ipw.Layout(width=width, grid_gap=margin) grid = ipw.GridspecLayout(lenRow, lenCol, layout=layout) outs = [ipw.Output() for _ in range(len(args))] for idx, out in enumerate(outs): with out: display(args[idx]) # allocate Output() to grid idxOuts = 0 for row in range(lenRow): for col in range(lenCol): grid[row, col] = outs[idxOuts] if idxOuts < lenArgs else ipw.Output() idxOuts += 1 display(grid)
def Display(self, prin=True): lst0 = list(self.TtBtn.values()) lst1 = list(self.slBtn.values()) lst2 = list(self.BtnBtn.values()) l = max(len(lst0), len(lst1), len(lst2)) grid = ipywidgets.GridspecLayout(3, l) i = 0 for gr in lst0: grid[0, i] = gr i += 1 i = 0 for gr in lst1: grid[1, i] = gr i += 1 i = 0 for gr in lst2: grid[2, i] = gr i += 1 if prin: b0 = ipywidgets.Box(lst0) b1 = ipywidgets.Box(lst1) b2 = ipywidgets.Box(lst2) display(ipywidgets.VBox([b0, b1, b2]))
def __init__(self): self.testcase = widgets.Text(description="Testcase") self.input_data = widgets.Text(description="Input Data Type") self.file_size = widgets.Text(description="File Size") self.files_directory = widgets.Text(description="Files Directory") self.run_count = widgets.IntSlider(description="Run Count", min=1, max=300) self.n_nodes = widgets.IntSlider(description="# nodes", min=2, max=300) self.n_leechers = widgets.IntSlider(description="# leechers", min=1, max=300) self.n_passive = widgets.IntSlider(description="# passive ", min=0, max=300) self.max_connection_rate = widgets.IntSlider( description="Max connections (%)", value=100, min=0, max=100) self.churn_rate = widgets.IntSlider(description="Churn Rate (%)", min=0, max=100) self.grid = widgets.GridspecLayout(5, 2, height='300px')
def entry_gui(): style = {'description_width': 'initial'} sm_layout = widgets.Layout(flex='1 1 1%', width='auto') exp_name = widgets.Text(placeholder='pxxxx', description='Exp. Name:', continuous_update=True, disabled=False, style=style) op_name = widgets.Text(placeholder='Name(s)', description='Operator Name(s):', continuous_update=True, disabled=False, style=style) hyd_start = widgets.Text(placeholder='xxx.x', description='Hyd. Start:', continuous_update=True, disabled=False, style=style) hyd_end = widgets.Text(placeholder='xxx.x', description='Hyd. End:', continuous_update=True, disabled=False, style=style) pick_date = widgets.DatePicker(description='Exp. Date:', disabled=False, style=style) names = widgets.VBox(children=[exp_name, op_name], layout=sm_layout) dates = widgets.VBox(children=[pick_date, hyd_start, hyd_end], layout=sm_layout) pre_layout = widgets.Layout(display='flex', flex_flow='row', align_items='stretch', border='2px solid grey', padding='10px', width='75%', grid_gap='60px 60px') preamble = widgets.GridBox(children=[names, dates], layout=pre_layout) area = widgets.Text(placeholder='m^2', description='Contact Area (m^2)', value='', continuous_update=True, disabled=False, style=style) block_thck = widgets.Text(placeholder='mm', description='Sample Block Thickness (no gouge)', continuous_update=True, disabled=False, style=style) layer_thck = widgets.Text(placeholder='mm', description='Layer Thickness', continuous_update=True, disabled=False, style=style) layer_thck_ld = widgets.Text(placeholder='mm', description='Under Load', continuous_update=True, disabled=False, style=style) material = widgets.Text(placeholder='Anhydrite, Westerly Granite', description='Material', continuous_update=True, disabled=False, style=style) part_size = widgets.Text(placeholder='Size Distribution', description='Particle Size, Distribution', continuous_update=True, disabled=False, style=style) mat_layout = widgets.Layout(display='flex', flex_flow='row', align_items='stretch', border='2px solid grey', padding='10px', width='75%', grid_gap='60px 60px') mat_col1 = widgets.VBox(children=[area, block_thck, layer_thck], layout=widgets.Layout(flex='1 1 1%', width='auto')) mat_col2 = widgets.VBox(children=[material, part_size], layout=widgets.Layout(flex='1 1 1%', width='auto')) material_block = widgets.GridBox(children=[mat_col1, mat_col2], layout=mat_layout) h_lc_title = widgets.Label('Horizontal Load Cell') h_lc_picker = widgets.Dropdown( options=['44mm Solid Horiz', '44mm Solid Vert', 'None'], value='44mm Solid Horiz', description='Horiz. Load Cell:', disabled=False, style=style) h_lc_calib = widgets.Text(placeholder='mV/kN', description='Calibration (mV/kN):', continuous_update=True, disabled=False, style=style) h_lc_stress = widgets.Text(placeholder='MPa', description='Target Stress(es) (MPa):', continuous_update=True, disabled=False, style=style) h_lc_ini_V = widgets.Text(placeholder='Volt', description='H. Init. Volt.:', continuous_update=True, disabled=False, style=style) h_load_v = widgets.Label(value='Volt. @ Load = ') def hor_handle_change(change): if str(change.new) == '' or str(change.new) == '--' or str( change.new) == '-': h_load_v.value = 'Volt. @ Load = N/A' else: _, targ_volt = calc_stress(h_lc_calib, area, h_lc_stress, h_lc_ini_V) h_load_v.value = 'Volt. @ Load = ' + targ_volt h_lc_ini_V.observe(hor_handle_change, names='value') # --------------------------------------------------------------------------------------------------------- # --------------------------------------------------------------------------------------------------------- v_lc_title = widgets.Label('Vertical Load Cell') v_lc_picker = widgets.Dropdown( options=['44mm Solid Vert', '44mm Solid Vert', 'None'], value='44mm Solid Vert', description='Vert. Load Cell:', disabled=False, style=style) v_lc_calib = widgets.Text(placeholder='mV/kN', description='Calibration (mV/kN):', continuous_update=True, disabled=False, style=style) v_lc_stress = widgets.Text(placeholder='MPa', description='Target Stress(es) (MPa):', continuous_update=True, disabled=False, style=style) v_lc_ini_V = widgets.Text(placeholder='Volt', description='V. Init. Volt.:', continuous_update=True, disabled=False, style=style) v_load_v = widgets.Label(value='Volt. @ Load = ') def ver_handle_change(change): if str(change.new) == '' or str(change.new) == '--' or str( change.new) == '-': v_load_v.value = 'Volt. @ Load = N/A' else: _, targ_volt = calc_stress(v_lc_calib, area, v_lc_stress, v_lc_ini_V) v_load_v.value = 'Volt. @ Load = ' + targ_volt v_lc_ini_V.observe(ver_handle_change, names='value') # --------------------------------------------------------------------------------------------------------- # VESSEL PRESSURES -- Pc, PpA, PpB # --------------------------------------------------------------------------------------------------------- # ves_grid = widgets.GridspecLayout(6, 3) pore_fluid = widgets.Text(value='DI H2O', placeholder='DI H2O', description='Pore Fluid', continuous_update=True, disabled=False, style=style) vessel_title = widgets.Label('Confining Pressure') pc_gain = widgets.Text(value='0.1456', placeholder='0.1456 V/MPa', description='Pc Gain (V/MPa):', continuous_update=True, disabled=False, style=style) pc_press = widgets.Text(placeholder='MPa', description='Target Stress(es) (MPa):', continuous_update=True, disabled=False, style=style) pc_ini_V = widgets.Text(placeholder='Volt', description='V. Init. Volt.:', continuous_update=True, disabled=False, style=style) pc_load_v = widgets.Label(value='Volt. @ Load = ') def pc_handle_change(change): if str(change.new) == '' or str(change.new) == '--' or str( change.new) == '-': pc_load_v.value = 'Volt. @ Load = N/A' else: targ_volt = calc_press(pc_gain, pc_press, pc_ini_V) pc_load_v.value = 'Volt. @ Load = ' + targ_volt pc_ini_V.observe(pc_handle_change, names='value') pc_items = widgets.VBox( children=[vessel_title, pc_gain, pc_press, pc_ini_V, pc_load_v]) ppa_gain = widgets.Text(placeholder='Ppa Gain (V/MPa)', description='Ppa Gain (V/MPa):', continuous_update=True, disabled=False, style=style) ppa_press = widgets.Text(placeholder='MPa', description='PpA Press. (MPa)', continuous_update=True, disabled=False, style=style) ppa_ini_V = widgets.Text(placeholder='Volt', description='V. Init. Volt.:', continuous_update=True, disabled=False, style=style) ppa_load_v = widgets.Label(value='Volt. @ Load = ') def ppa_handle_change(change): if str(change.new) == '' or str(change.new) == '--' or str( change.new) == '-': ppa_load_v.value = 'Volt. @ Load = N/A' else: targ_volt = calc_press(ppa_gain, ppa_press, ppa_ini_V) ppa_load_v.value = 'Volt. @ Load = ' + targ_volt ppa_ini_V.observe(ppa_handle_change, names='value') ppa_items = widgets.VBox( children=[vessel_title, ppa_gain, ppa_press, ppa_ini_V, ppa_load_v]) ppb_gain = widgets.Text(placeholder='PpB Gain (V/MPa)', description='PpB Gain (V/MPa):', continuous_update=True, disabled=False, style=style) ppb_press = widgets.Text(placeholder='MPa', description='PpB Press. (MPa)', continuous_update=True, disabled=False, style=style) ppb_ini_V = widgets.Text(placeholder='Volt', description='V. Init. Volt.:', continuous_update=True, disabled=False, style=style) ppb_load_v = widgets.Label(value='Volt. @ Load = ') def ppb_handle_change(change): if str(change.new) == '' or str(change.new) == '--' or str( change.new) == '-': ppb_load_v.value = 'Volt. @ Load = N/A' else: targ_volt = calc_press(ppb_gain, ppb_press, ppb_ini_V) ppb_load_v.value = 'Volt. @ Load = ' + targ_volt ppb_ini_V.observe(ppb_handle_change, names='value') ppb_items = widgets.VBox(children=[ pore_fluid, vessel_title, ppb_gain, ppb_press, ppb_ini_V, ppb_load_v ]) layout_args = { 'flex_flow': 'row', 'padding': '10px', 'width': '75%', 'grid_gap': '60px' } layout2 = widgets.Layout(display='flex', **layout_args, border='2px solid royalblue') horizontal = widgets.VBox(children=[ h_lc_title, h_lc_picker, h_lc_calib, h_lc_stress, h_lc_ini_V, h_load_v ], layout=widgets.Layout(flex='1 1 0%', width='auto')) vertical = widgets.VBox(children=[ v_lc_title, v_lc_picker, v_lc_calib, v_lc_stress, v_lc_ini_V, v_load_v ], layout=widgets.Layout(flex='1 1 0%', width='auto')) layout = widgets.Layout(display='flex', flex_flow='row', align_items='stretch', border='2px solid grey', padding='10px', width='75%') hor_vert = widgets.GridBox(children=[horizontal, vertical], layout=layout) use_vessel = widgets.RadioButtons(options=['yes', 'no'], description='Use Vessel?', value='no', disabled=False) def vessel_input(a): pore_press = widgets.Label('') if a == 'yes': pore_press = widgets.GridBox( children=[pc_items, ppa_items, ppb_items], layout=layout2) return display(pore_press) vessel_params = widgets.interactive_output(vessel_input, {'a': use_vessel}) data_logger = widgets.Dropdown(options=['8 channel', '16 channel'], value='8 channel', description='Data Logger Used:', disabled=False, style=style) h_dcdt = widgets.Combobox(options=['short rod', 'long rod', 'None'], placeholder='Horiz. DCDT', ensure_option=True, description='Horiz. DCDT:', disabled=False, style=style) h_dcdt_calib = widgets.Text(placeholder='mm/V', description='Horiz. DCDT calib.:', continuous_update=True, disabled=False, style=style) v_dcdt = widgets.Combobox(options=['Trans-Tek2', 'None'], placeholder='Vert. DCDT', ensure_option=True, description='Vert. DCDT:', disabled=False, style=style) v_dcdt_calib = widgets.Text(placeholder='mm/V', description='Vert. DCDT calib.:', continuous_update=True, disabled=False, style=style) layout = widgets.Layout(display='flex', flex_flow='row', border='2px solid grey', padding='10px', grid_gap='5px 100px', width='75%') hdcdt = widgets.VBox(children=[h_dcdt, h_dcdt_calib], layout=widgets.Layout(flex='1 1 1%', width='auto')) vdcdt = widgets.VBox(children=[v_dcdt, v_dcdt_calib], layout=widgets.Layout(flex='1 1 1%', width='auto')) dcdts = widgets.GridBox(children=[data_logger, hdcdt, vdcdt], layout=layout) style2 = {'width': 'initial'} purpose = widgets.Textarea(placeholder='Purpose/Description', description='Purpose/Description', continuous_update=True, disabled=False, style=style, layout=widgets.Layout(flex='1 1 1%', width='auto')) ac_blocks = widgets.Text(placeholder='', description='Acoustics blocks used', continuous_update=True, disabled=False, style=style, layout=widgets.Layout(flex='1 1 1%', width='auto')) temp = widgets.Text(placeholder='Temperature (C)', description='Temperture', continuous_update=True, disabled=False, style=style, layout=widgets.Layout(flex='1 1 1%', width='auto')) humid = widgets.Text(placeholder='Rel. Humid. (%)', description='Relative Humidity', continuous_update=True, disabled=False, style=style, layout=widgets.Layout(flex='1 1 1%', width='auto')) temp_humid = widgets.HBox([ac_blocks, temp, humid]) notes = widgets.Textarea(placeholder='Experiment Notes', description='Experiment Notes', continuous_update=True, disabled=False, style=style, layout=widgets.Layout(flex='1 1 1%', width='auto')) layout = widgets.Layout(display='flex', flex_flow='column', align_items='stretch', border='2px solid grey', padding='10px', width='75%') exp_info = widgets.GridBox(children=[purpose, temp_humid, notes], layout=layout) # --------------------------------------------------------------------------------------------------------- # PID SETTINGS # --------------------------------------------------------------------------------------------------------- use_pid = widgets.RadioButtons(options=['yes', 'no'], description='Record PID?', value='no', disabled=False) layout = widgets.Layout(display='inline_flex', align_items='center', align_content='center', border='2px solid grey', padding='10px', width='75%') pid_grid = widgets.GridspecLayout(4, 4, layout=layout) pid_grid_args = {'continuous_update': True, 'disabled': False} pid_grid[0, 0:2] = widgets.Label('Hor. Servo Settings') pid_grid[1, 0] = widgets.Text(placeholder='', description='P', layout=widgets.Layout(width='150px'), **pid_grid_args) pid_grid[2, 0] = widgets.Text(placeholder='', description='I', layout=widgets.Layout(width='150px'), **pid_grid_args) pid_grid[3, 0] = widgets.Text(placeholder='', description='D', layout=widgets.Layout(width='150px'), **pid_grid_args) pid_grid[1, 1] = widgets.Text(placeholder='', description='Datten', layout=widgets.Layout(width='150px'), **pid_grid_args) pid_grid[2, 1] = widgets.Text(placeholder='', description='Feedback', layout=widgets.Layout(width='150px'), **pid_grid_args) pid_grid[3, 1] = widgets.Text(placeholder='', description='E-gain', layout=widgets.Layout(width='150px'), **pid_grid_args) pid_grid[0, 2::] = widgets.Label('Vert. Servo Settings') pid_grid[1, 2] = widgets.Text(placeholder='', description='P', layout=widgets.Layout(width='150px'), **pid_grid_args) pid_grid[2, 2] = widgets.Text(placeholder='', description='I', layout=widgets.Layout(width='150px'), **pid_grid_args) pid_grid[3, 2] = widgets.Text(placeholder='', description='D', layout=widgets.Layout(width='150px'), **pid_grid_args) pid_grid[1, 3] = widgets.Text(placeholder='', description='Datten', layout=widgets.Layout(width='150px'), **pid_grid_args) pid_grid[2, 3] = widgets.Text(placeholder='', description='Feedback', layout=widgets.Layout(width='150px'), **pid_grid_args) pid_grid[3, 3] = widgets.Text(placeholder='', description='E-gain', layout=widgets.Layout(width='150px'), **pid_grid_args) def pid_input(a): pid_set = widgets.Label('') if a == 'yes': pid_set = pid_grid return display(pid_set) pid_params = widgets.interactive_output(pid_input, {'a': use_pid}) # --------------------------------------------------------------------------------------------------------- # OUTPUT # --------------------------------------------------------------------------------------------------------- outputs = [ exp_name, op_name, hyd_start, hyd_end, pick_date, area, block_thck, layer_thck, layer_thck_ld, material, part_size, h_lc_picker, h_lc_calib, h_lc_stress, h_lc_ini_V, v_lc_picker, v_lc_calib, v_lc_stress, v_lc_ini_V, pore_fluid, ppa_gain, ppa_press, ppa_ini_V, ppa_load_v, ppb_gain, ppb_press, ppb_ini_V, ppb_load_v, pc_gain, pc_press, pc_ini_V, pc_load_v, use_vessel, vessel_params, data_logger, h_dcdt, h_dcdt_calib, v_dcdt, v_dcdt_calib, layout, purpose, ac_blocks, temp, humid, notes, layout ] gui = display(preamble, material_block, hor_vert, use_vessel, vessel_params, dcdts, exp_info, use_pid, pid_params) return gui, outputs
def __build(self): """ This function is used to build all widgets of the UI. """ # Section: "Dataset Selection" # ============================================================================================================ # label = ipywidgets.Label( value="$\\textbf{•}$ $\\textbf{Dataset Selection}$") self._widget_list.append(label) label = ipywidgets.Label( value= "Please, select a $\\texttt{.csv}$ file from the following list." + " (Only $\\texttt{.csv}$ files stored inside $\\texttt{./data}$ directory are" + " displayed).") self._widget_dataset_file_select = ipywidgets.Select( description="Current Selected Dataset:", style={'description_width': 'initial'}, layout=ipywidgets.Layout(width='90%'), continuous_update=False) self._widget_list.append( ipywidgets.VBox([label, self._widget_dataset_file_select])) # Section: "Plot Options" # ============================================================================================================ # label = ipywidgets.Label( value="$\\textbf{•}$ $\\textbf{Plot Options}$") self._widget_list.append(label) label = ipywidgets.Label( value= "You can customize your $\\textit{Plot}$ using following $\\textit{Widgets}$ " + "(Available $\\textit{Widgets}$ depend on $\\textit{Current Selected Dataset}$)" ) self._widget_list.append(label) self._widget_month_combobox = ipywidgets.Combobox( placeholder="Select/Type 'Month'...", options=calendar.month_name[1:], description='Month:', layout=ipywidgets.Layout(width='350px'), continuous_update=False) self._widget_state_combobox = ipywidgets.Combobox( placeholder="Select/Type 'State'...", description='State:', layout=ipywidgets.Layout(width='350px'), continuous_update=False) self._widget_city_combobox = ipywidgets.Combobox( placeholder="Select/Type 'City'...", description='City:', layout=ipywidgets.Layout(width='350px'), continuous_update=False, ) self._widget_month_checkbox = ipywidgets.Checkbox( description="Enable 'Month Filter'", layout=ipywidgets.Layout(width='350px')) self._widget_display_univariate_regression_line_checkbox = ipywidgets.Checkbox( description="Plot 'Regression Line'", layout=ipywidgets.Layout(width='350px')) grid = ipywidgets.GridspecLayout(3, 2) grid[0, 0] = self._widget_month_combobox grid[1, 0] = self._widget_state_combobox grid[2, 0] = self._widget_city_combobox grid[0, 1] = self._widget_month_checkbox grid[1, 1] = self._widget_display_univariate_regression_line_checkbox self._widget_list.append(grid) self._widget_time_int_range_slider = ipywidgets.IntRangeSlider( step=1, description="Plot's 'Time Range'", disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', style={'description_width': 'initial'}, layout=ipywidgets.Layout(width='90%'), ) self._widget_list.append(self._widget_time_int_range_slider) label = ipywidgets.Label( value= "Using following $\\textit{Widget}$, you can select one or more " + "$\\textit{fields}$ to customize your $\\textit{Plot}$" + " (Hold $\\texttt{CTRL}$ and click to select more $\\textit{fields}$!)" ) self._widget_list.append(label) self._widget_active_columns_select_multiple = ipywidgets.SelectMultiple( rows=10, description='Active Columns:', disabled=False, style={'description_width': 'initial'}, layout=ipywidgets.Layout(width='90%'), ) self._widget_list.append(self._widget_active_columns_select_multiple) # Section 'Dataset Indo' # ============================================================================================================ # label = ipywidgets.Label( value="$\\textbf{•}$ $\\textbf{Dataset Info}$") self._widget_list.append(label) label = ipywidgets.Label( value= "Here are displayed several info about $\\textit{Current Selected Dataset}$ " + "(Displayed data depend on current selected $\\textit{Plot Options}$)" ) self._widget_list.append(label) self._widget_states_summary_label = ipywidgets.Label() self._widget_cities_summary_label = ipywidgets.Label() self._widget_how_many_cities_inside_state_label = ipywidgets.Label() self._widget_state_flag_image_HTML = ipywidgets.HTML() box = ipywidgets.VBox([ self._widget_states_summary_label, self._widget_cities_summary_label, self._widget_how_many_cities_inside_state_label ]) box = ipywidgets.HBox([self._widget_state_flag_image_HTML, box]) self._widget_list.append(box) # Section: "Plot Button" # ============================================================================================================ # label = ipywidgets.Label( value="$\\textbf{•}$ $\\textbf{Plot Section}$") self._widget_list.append(label) self._widget_plot_button = ipywidgets.Button(description='Plot', disabled=False, button_style='success', icon='line-chart') self._widget_list.append(self._widget_plot_button) # Section: "ERROR Label" # ============================================================================================================ # self._widget_error_label = ipywidgets.Label(value="") self._widget_list.append(self._widget_error_label) # Section: "Display Univariate Regression Line" # ============================================================================================================ # self._widget_univariate_regression_line_info_HTMLMath = ipywidgets.HTMLMath( value="", style={'description_width': 'initial'}, ) self._widget_list.append( self._widget_univariate_regression_line_info_HTMLMath)
def conformers( mol: Chem.rdchem.Mol, conf_id: int = -1, n_confs: Union[int, List[int]] = None, align_conf: bool = True, n_cols: int = 3, sync_views: bool = True, remove_hs: bool = True, width: str = "auto", ): """Visualize the conformer(s) of a molecule. Args: mol: a molecule. conf_id: The ID of the conformer to show. -1 shows the first conformer. Only works if `n_confs` is None. n_confs: Can be a number of conformers to shows or a list of conformer indices. When None, only the first conformer is displayed. When -1, show all conformers. align_conf: Whether to align conformers together. n_cols: Number of columns. Defaults to 3. sync_views: Wether to sync the multiple views. remove_hs: Wether to remove the hydrogens of the conformers. width: The width of the returned view. Defaults to "auto". """ widgets = _get_ipywidgets() nv = _get_nglview() if mol.GetNumConformers() == 0: raise ValueError( "The molecule has 0 conformers. You can generate conformers with `dm.conformers.generate(mol)`." ) # Clone the molecule mol = copy.deepcopy(mol) if remove_hs: mol = Chem.RemoveHs(mol) # type: ignore else: mol = Chem.AddHs(mol) # type: ignore if n_confs is None: return nv.show_rdkit(mol, conf_id=conf_id) # If n_confs is int, convert to list of conformer IDs if n_confs == -1: n_confs = [conf.GetId() for conf in mol.GetConformers()] elif isinstance(n_confs, int): if n_confs > mol.GetNumConformers(): n_confs = mol.GetNumConformers() n_confs = list(range(n_confs)) # type: ignore if align_conf: rdMolAlign.AlignMolConformers(mol, confIds=n_confs) # Get number of rows n_rows = len(n_confs) // n_cols n_rows += 1 if (len(n_confs) % n_cols) > 0 else 0 # Create a grid grid = widgets.GridspecLayout(n_rows, n_cols) # type: ignore # Create and add views to the grid. widget_coords = itertools.product(range(n_rows), range(n_cols)) views = [] for i, (conf_id, (x, y)) in enumerate(zip(n_confs, widget_coords)): view = nv.show_rdkit(mol, conf_id=conf_id) view.layout.width = width view.layout.align_self = "stretch" grid[x, y] = view views.append(view) # Sync views if sync_views: for view in views: view._set_sync_camera(views) return grid
def __build(self): """ This function is used to build all widgets of the UI. """ # Section: "Plot Current Selected Dataset" # ============================================================================================================ # label = ipywidgets.Label(value="$\\textbf{•}$ $\\textbf{Current Selected Dataset}$: " + "$\\texttt{GlobalLandTemperaturesByCountry.csv}$ ") self._widget_list.append(label) # Section: "Plot Options" # ============================================================================================================ # label = ipywidgets.Label(value="$\\textbf{•}$ $\\textbf{Comparison Options}$") self._widget_list.append(label) label = ipywidgets.Label( value="You can customize your $\\textit{Comparison}$ using following $\\textit{Widgets}$") self._widget_list.append(label) self._widget_month_combobox = ipywidgets.Combobox( placeholder="Select/Type 'Month'...", options=calendar.month_name[1:], description='Month:', layout=ipywidgets.Layout(width='350px'), continuous_update=False ) self._widget_month_checkbox = ipywidgets.Checkbox( description="Enable 'Month Filter'", layout=ipywidgets.Layout(width='350px') ) grid = ipywidgets.GridspecLayout(1, 2) grid[0, 0] = self._widget_month_combobox grid[0, 1] = self._widget_month_checkbox self._widget_list.append(grid) self._widget_time_int_range_slider = ipywidgets.IntRangeSlider( step=1, description="Plot's 'Time Range'", disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', style={'description_width': 'initial'}, layout=ipywidgets.Layout(width='90%'), ) self._widget_list.append(self._widget_time_int_range_slider) self._widget_active_columns_select = ipywidgets.Select( rows=10, description='Active Column:', disabled=False, style={'description_width': 'initial'}, layout=ipywidgets.Layout(width='90%'), ) self._widget_list.append(self._widget_active_columns_select) # Section: "State Selection" # ============================================================================================================ # label = ipywidgets.Label(value="$\\textbf{•}$ $\\textbf{State Selection}$") self._widget_list.append(label) label = ipywidgets.Label(value="In order to compare regression lines, use the following combobox to select " " a $\\textit{State}$, then click on $\\textit{'Add State'}$ button to insert it " + "into the list below.") self._widget_list.append(label) label = ipywidgets.Label( value="We will compare regression lines of all $\\textit{States}$ that appear in that list!") self._widget_list.append(label) label = ipywidgets.Label( value="You can remove a $\\textit{States}$ selecting it and clicking $\\textit{'Remove State'}$ button!") self._widget_list.append(label) self._widgets_state_for_comparison_combobox = ipywidgets.Combobox( placeholder='Select a state...', layout=ipywidgets.Layout(width='500px'), continuous_update=False, ) self._widgets_state_list_comparison_select = ipywidgets.Select( options=[], disabled=False, layout=ipywidgets.Layout(width='500px'), style={'description_width': 'initial'} ) self._widgets_remove_state_comparison_list_button = ipywidgets.Button( description="Remove 'State'", disabled=False, button_style="danger", icon="minus" ) self._widgets_insert_state_comparison_list_button = ipywidgets.Button( description="Add 'State'", disabled=False, button_style="success", icon="plus" ) items = [self._widgets_insert_state_comparison_list_button, self._widgets_state_for_comparison_combobox, self._widgets_remove_state_comparison_list_button, self._widgets_state_list_comparison_select] self._widget_list.append(ipywidgets.GridBox(items, layout=ipywidgets.Layout(grid_template_columns="repeat(2, 170px)"))) # Section: "Comparison Button" # ============================================================================================================ # label = ipywidgets.Label(value="$\\textbf{•}$ $\\textbf{Comparison Section}$") self._widget_list.append(label) self._widget_compare_button = ipywidgets.Button(description='Compare!', disabled=False, button_style='success', icon='star') self._widget_list.append(self._widget_compare_button) # Section: "ERROR Label" # ============================================================================================================ # self._widget_error_label = ipywidgets.Label(value="") self._widget_list.append(self._widget_error_label)
def gongxianToClass(grid, table, nrows): temp_grid = widgets.GridspecLayout(30, 1, width='auto', height='auto') temp_out = widgets.Output(layout={ 'border': '1px solid black', 'width': '16cm', 'height': '9cm' }) temp_grid[0, 0] = widgets.Dropdown(options=[('1班', 0), ('2班', 1), ('3班', 2), ('4班', 3), ('5班', 4), ('6班', 5), ('7班', 6), ('8班', 7), ('9班', 8), ('10班', 9), ('11班', 10), ('12班', 11), ('13班', 12), ('14班', 13), ('15班', 14), ('16班', 15), ('', 16)], index=16, layout=widgets.Layout(width='5cm'), description='班级') for i in range(1, 25): if i == 1: temp_grid[i, 0] = widgets.Text(value='考次1', layout=widgets.Layout(width='5cm'), disabled=True) elif i == 7: temp_grid[i, 0] = widgets.Text(value='考次2', layout=widgets.Layout(width='5cm'), disabled=True) elif i == 13: temp_grid[i, 0] = widgets.Text(value='考次3', layout=widgets.Layout(width='5cm'), disabled=True) elif i == 19: temp_grid[i, 0] = widgets.Text(value='考次4', layout=widgets.Layout(width='5cm'), disabled=True) else: temp_grid[i, 0] = widgets.Dropdown(options=[ ('第1名', 0), ('第2名', 1), ('第3名', 2), ('第4名', 3), ('第5名', 4), ('第6名', 5), ('第7名', 6), ('第8名', 7), ('第9名', 8), ('第10名', 9), ('第11名', 10), ('第12名', 11), ('第13名', 12), ('第14名', 13), ('第15名', 14), ('第16名', 15), ('', 16) ], index=16, layout=widgets.Layout(width='5cm')) if i in [2, 8, 14, 20]: temp_grid[i, 0].description = '语文' elif i in [3, 9, 15, 21]: temp_grid[i, 0].description = '数学' elif i in [4, 10, 16, 22]: temp_grid[i, 0].description = '英语' elif i in [5, 11, 17, 23]: temp_grid[i, 0].description = '物理' elif i in [6, 12, 18, 24]: temp_grid[i, 0].description = '化学' temp_grid[25, 0] = widgets.Button(description='确定当前数据内容') grid[1:19, 0:30].children[0].children[5].children = [ widgets.HBox([temp_grid, temp_out]) ] with temp_out: print('请先在左侧进行选择!') def button_click(b): chinese_y = [] math_y = [] english_y = [] physical_y = [] chemistry_y = [] x = [] count = 0 if temp_grid[0, 0].value == '' or temp_grid[ 2, 0].value == '' or temp_grid[3, 0].value == '' or temp_grid[ 4, 0].value == '' or temp_grid[ 5, 0].value == '' or temp_grid[6, 0].value == '': temp_out.clear_output() with temp_out: print('班级与第一次考试排名不能为空!') else: for i in [2, 8, 14, 20]: if temp_grid[i, 0].index < 16: count = count + 1 chinese_y = chinese_y + [temp_grid[i, 0].index + 1] for i in [3, 9, 15, 21]: if temp_grid[i, 0].index < 16: math_y = math_y + [temp_grid[i, 0].index + 1] for i in [4, 10, 16, 22]: if temp_grid[i, 0].index < 16: english_y = english_y + [temp_grid[i, 0].index + 1] for i in [5, 11, 17, 23]: if temp_grid[i, 0].index < 16: physical_y = physical_y + [temp_grid[i, 0].index + 1] for i in [6, 12, 18, 24]: if temp_grid[i, 0].index < 16: chemistry_y = chemistry_y + [temp_grid[i, 0].index + 1] print(chinese_y) for i in range(count): x = x + [str(i + 1)] drawing(temp_out, x, chinese_y, math_y, english_y, physical_y, chemistry_y, str(temp_grid[0, 0].index + 1)) temp_grid[25, 0].on_click(button_click) return
def main_toolbar(m): padding = "0px 0px 0px 5px" # upper, right, bottom, left toolbar_button = widgets.ToggleButton( value=False, tooltip="Toolbar", icon="wrench", layout=widgets.Layout(width="28px", height="28px", padding=padding), ) close_button = widgets.ToggleButton( value=False, tooltip="Close the tool", icon="times", button_style="primary", layout=widgets.Layout(height="28px", width="28px", padding=padding), ) toolbar = widgets.HBox([toolbar_button]) def close_click(change): if change["new"]: toolbar_button.close() close_button.close() toolbar.close() close_button.observe(close_click, "value") rows = 2 cols = 3 grid = widgets.GridspecLayout(rows, cols, grid_gap="0px", layout=widgets.Layout(width="96px")) icons = ["folder-open", "map", "gears", "filter", "map-marker", "question"] for i in range(rows): for j in range(cols): grid[i, j] = widgets.Button(description="", button_style="primary", icon=icons[i * rows + j], layout=widgets.Layout(width="28px", padding="0px")) toolbar = widgets.VBox([toolbar_button]) def toolbar_click(change): if change["new"]: toolbar.children = [ widgets.HBox([close_button, toolbar_button]), grid ] else: toolbar.children = [toolbar_button] toolbar_button.observe(toolbar_click, "value") toolbar_ctrl = WidgetControl(widget=toolbar, position="topright") m.add_control(toolbar_ctrl) output = widgets.Output() output_ctrl = WidgetControl(widget=output, position="topright") buttons = widgets.ToggleButtons( value=None, options=["Apply", "Reset", "Close"], tooltips=["Apply", "Reset", "Close"], button_style="primary", ) buttons.style.button_width = "80px" data_dir = os.path.abspath('./data') # File Chooser Widget fc = FileChooser(data_dir) fc.use_dir_icons = True fc.filter_pattern = ['*.shp', '*.geojson', '*.json'] filechooser_widget = widgets.VBox([fc, buttons]) def button_click(change): if change["new"] == "Apply" and fc.selected is not None: if fc.selected.endswith(".shp"): m.add_shapefile(fc.selected, layer_name="Shapefile") elif fc.selected.endswith(".geojson"): m.add_geojson(fc.selected, layer_name="GeoJSON") elif fc.selected.endswith(".json"): m.add_geojson(fc.selected, layer_name="GeoJSON") elif change["new"] == "Reset": fc.reset() elif change["new"] == "Close": fc.reset() m.remove_control(output_ctrl) buttons.observe(button_click, "value") # Basemap Widget from .basemaps import _ee_basemaps dropdown_basemap = widgets.Dropdown( options=list(_ee_basemaps.keys()), value="ROADMAP", layout=widgets.Layout(width="200px"), description="Basemaps", ) close_button_basemap = widgets.Button( icon="times", tooltip="Close the basemap widget", button_style="primary", layout=widgets.Layout(width="32px"), ) basemap_widget = widgets.HBox([dropdown_basemap, close_button_basemap]) def on_click(change): basemap_name = change["new"] if len(m.layers) == 1: old_basemap = m.layers[0] else: old_basemap = m.layers[1] m.substitute_layer(old_basemap, _ee_basemaps[basemap_name]) dropdown_basemap.observe(on_click, "value") def close_click(change): if m.basemap_ctrl is not None and m.basemap_ctrl in m.controls: m.remove_control(m.basemap_ctrl) basemap_widget.close() close_button_basemap.on_click(close_click) basemap_control = WidgetControl(widget=basemap_widget, position="topright") m.basemap_ctrl = basemap_control # Select Layer for Filtering Widget layers = [ layer.name for layer in m.layers if not isinstance(layer, ipyleaflet.TileLayer) ] dropdown_layer = widgets.Dropdown(options=layers, description='Layer:') dropdown_layer_field = widgets.Dropdown(description='Field:') dropdown_layer_field_value = widgets.Dropdown(description='Value:') out_filter_layer = widgets.Output() def on_click_layer(change): with out_filter_layer: out_filter_layer.clear_output() dropdown_layer_field.options = list( m.find_layer( change.new).data['features'][0]['properties'].keys()) dropdown_layer.observe(on_click_layer, names="value") out_filter_layer_field = widgets.Output() def on_click_layer_field(change): with out_filter_layer_field: out_filter_layer_field.clear_output() field_values = set() for record in m.find_layer(dropdown_layer.value).data['features']: field_values.add( record['properties'][dropdown_layer_field.value]) dropdown_layer_field_value.options = sorted(field_values) dropdown_layer_field.observe(on_click_layer_field, names="value") add_filter_layer = widgets.Button( icon="plus", tooltip="Add a layer based on the filter options", button_color="lightgreen", layout=widgets.Layout(width="32px")) out_click_add_filter_layer = widgets.Output() def click_add_filter_layer(change): import itertools import copy data = copy.deepcopy(m.find_layer(dropdown_layer.value).data) filter_data = [ record for record in data['features'] if record['properties'][ dropdown_layer_field.value] == dropdown_layer_field_value.value ] data['features'] = filter_data style = { "stroke": True, "color": "#000000", "weight": 2, "opacity": 1, "fill": True, "fillColor": "#0000ff", "fillOpacity": 0.4, } geojson = ipyleaflet.GeoJSON(data=data, style=style, name="{} - {} - {} Layer".format( dropdown_layer.value, dropdown_layer_field.value, dropdown_layer_field_value.value)) m.add_layer(geojson) add_filter_layer.on_click(click_add_filter_layer) close_dropdown_layer = widgets.Button(icon="times", tooltip="Close the filter widget", button_style="primary", layout=widgets.Layout(width="32px")) box_layout = widgets.Layout(display='flex', flex_flow='row', align_items='stretch', width='70%') filter_buttons_box = widgets.Box([close_dropdown_layer, add_filter_layer]) filter_dropdown_box = widgets.Box( [dropdown_layer, dropdown_layer_field, dropdown_layer_field_value]) filter_widget = widgets.HBox([filter_dropdown_box, filter_buttons_box]) def close_click_dropdown(change): filter_widget.close() close_dropdown_layer.on_click(close_click_dropdown) filter_layer_control = WidgetControl(widget=filter_widget, position="bottomright") m.filter_layer_ctrl = filter_layer_control # Add CSV Widget buttons_csv = widgets.ToggleButtons( value=None, options=["Display", "Close"], tooltips=["Display", "Close"], button_style="primary", ) buttons_csv.style.button_width = "80px" layer_name_csv = widgets.Text(value="Untitled" + random_string(), placeholder="Type the layer name here", description="Layer name:", disabled=False) #observe(layer_name_csv, "value") fc_csv = FileChooser(data_dir) fc_csv.use_dir_icons = True fc_csv.filter_pattern = ['*.csv'] add_csv_widget = widgets.VBox([fc_csv, layer_name_csv, buttons_csv]) def button_click_csv(change): if change["new"] == "Display" and fc_csv.selected is not None: layer_name = "RandomForNow" m.add_points_from_csv(fc_csv.selected, layer_name=layer_name) elif change["new"] == "Close": fc_csv.reset() m.remove_control(output_ctrl) buttons_csv.observe(button_click_csv, "value") def tool_click(b): with output: output.clear_output() if b.icon == "folder-open": display(filechooser_widget) m.add_control(output_ctrl) elif b.icon == "filter": dropdown_layer.options = [ layer.name for layer in m.layers if not isinstance(layer, ipyleaflet.TileLayer) ] # display(layers) display(filter_widget) m.add_control(filter_layer_control) elif b.icon == "map": display(basemap_widget) m.add_control(basemap_control) elif b.icon == "gears": import whiteboxgui.whiteboxgui as wbt if hasattr(m, "whitebox") and m.whitebox is not None: if m.whitebox in m.controls: m.remove_control(m.whitebox) tools_dict = wbt.get_wbt_dict() wbt_toolbox = wbt.build_toolbox(tools_dict, max_width="800px", max_height="500px") wbt_control = WidgetControl(widget=wbt_toolbox, position="bottomright") m.whitebox = wbt_control m.add_control(wbt_control) elif b.icon == "map-marker": display(add_csv_widget) m.add_control(output_ctrl) # elif b.icon == "question": print(f"You clicked the {b.icon} button") for i in range(rows): for j in range(cols): tool = grid[i, j] tool.on_click(tool_click)
def jianyousheng(grid, table, nrows): temp_grid = widgets.GridspecLayout(10, 2, width='auto', height='auto') temp_out = widgets.Output(layout={ 'border': '1px solid black', 'width': '16cm', 'height': '9cm' }) alldata = {} data = [] for i in range(2, 32): data = table.row_values(i) alldata[str(i - 2)] = data temp_grid[0, 0] = widgets.Dropdown(options=[('第一名', 0), ('第二名', 1), ('第三名', 2), ('第四名', 3), ('第五名', 4), ('第六名', 5), ('第七名', 6), ('第八名', 7), ('第九名', 8), ('第十名', 9), ('第十一名', 10), ('第十二名', 11), ('第十三名', 12), ('第十四名', 13), ('第十五名', 14), ('第十六名', 15), ('第十七名', 16), ('第十八名', 17), ('第十九名', 18), ('第二十名', 19), ('第二十一名', 20), ('第二十二名', 21), ('第二十三名', 22), ('第二十四名', 23), ('第二十五名', 24), ('第二十六名', 25), ('第二十七名', 26), ('第二十八名', 27), ('第二十九名', 28), ('第三十名', 29)], index=0, layout=widgets.Layout(width='3cm')) temp_grid[1, 0] = widgets.Button(description=alldata['0'][0], tooltip='班级', layout=widgets.Layout(width='3cm')) temp_grid[2, 0] = widgets.Button(description=alldata['0'][1], tooltip='学号', layout=widgets.Layout(width='3cm')) temp_grid[3, 0] = widgets.Button(description=alldata['0'][2], tooltip='姓名', layout=widgets.Layout(width='3cm')) temp_grid[4, 0] = widgets.Button(description=str( alldata['0'][18]).split('.')[0], tooltip='总分', layout=widgets.Layout(width='3cm')) ave = alldata['0'][18] / 5 subject_list = ['Chinese', 'Math', 'English', 'Physical', 'Chemistry'] drawing(0, temp_out, subject_list, alldata, ave) grid[1:19, 0:30].children[0].children[4].children = [ widgets.HBox([temp_grid, temp_out]) ] def show_info(change): value = change['new'] temp_grid[1, 0].description = alldata[str(value)][0] temp_grid[2, 0].description = alldata[str(value)][1] temp_grid[3, 0].description = alldata[str(value)][2] temp_grid[4, 0].description = str(alldata[str(value)][18]).split('.')[0] drawing(value, temp_out, subject_list, alldata, ave) temp_grid[0, 0].observe(show_info, names='index') return