make an interactive grid in which users can edit specimen names
        as well as which sample a specimen belongs to
189462
def InitSpecCheck(self):
        
        #wait = wx.BusyInfo("Please wait, working...")
        #wx.SafeYield()
        self.contribution.propagate_lithology_cols()
        spec_df = self.contribution.tables['specimens'].df
        self.panel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        self.grid_frame = grid_frame3.GridFrame(self.contribution, self.WD,
                                                'specimens', 'specimens', self.panel,
                                                 main_frame=self.main_frame)
        # redefine default 'save & exit grid' button to go to next dialog instead
        self.grid_frame.exitButton.SetLabel('Save and continue')
        grid = self.grid_frame.grid
        self.grid_frame.Bind(wx.EVT_BUTTON,
                             lambda event: self.onContinue(event, grid, self.InitSampCheck),
                             self.grid_frame.exitButton)

            # add back button
        self.backButton = wx.Button(self.grid_frame.panel, id=-1, label='Back',
                                      name='back_btn')
        self.backButton.Disable()
        self.grid_frame.main_btn_vbox.Add(self.backButton, flag=wx.ALL, border=5)
        # re-do fit
        self.grid_frame.do_fit(None, self.min_size)
        # center
        self.grid_frame.Centre()
        return
907588
def InitSpecCheck(self):
        """"""

        self.panel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        #import wx.lib.scrolledpanel as libpanel # does not work well
        #self.panel = libpanel.ScrolledPanel(self, style=wx.SIMPLE_BORDER)

        text = """Step 1:
Check that all specimens belong to the correct sample
(if sample name is simply wrong, that will be fixed in step 2)"""
        label = wx.StaticText(self.panel, label=text)
        self.grid_builder = grid_frame2.GridBuilder(self.er_magic_data, 'specimen',
                                                   self.er_magic_data.headers, self.panel,
                                                   'sample')
        self.spec_grid = self.grid_builder.make_grid(incl_pmag=False)
        self.grid = self.spec_grid

        self.spec_grid.InitUI()

        self.grid_builder.add_data_to_grid(self.spec_grid, 'specimen', incl_pmag=False)

        samples = self.er_magic_data.make_name_list(self.er_magic_data.samples)
        self.drop_down_menu = drop_down_menus.Menus("specimen", self, self.spec_grid, samples)


        #### Create Buttons ####
        hbox_one = wx.BoxSizer(wx.HORIZONTAL)
        self.addSampleButton = wx.Button(self.panel, label="Add a new sample")
        self.samples = [name for name in self.er_magic_data.samples]
        self.Bind(wx.EVT_BUTTON, self.on_addSampleButton, self.addSampleButton)
        self.helpButton = wx.Button(self.panel, label="Help")
        self.Bind(wx.EVT_BUTTON, lambda event: self.on_helpButton(event, "ErMagicSpecimenHelp.html"), self.helpButton)
        hbox_one.Add(self.addSampleButton, flag=wx.ALIGN_LEFT|wx.RIGHT, border=10)
        hbox_one.Add(self.helpButton)

        #
        hboxok = wx.BoxSizer(wx.HORIZONTAL)
        self.saveButton = wx.Button(self.panel, id=-1, label='Save')
        self.Bind(wx.EVT_BUTTON, lambda event: self.on_saveButton(event, self.spec_grid), self.saveButton)
        self.cancelButton = wx.Button(self.panel, wx.ID_CANCEL, '&Cancel')
        self.Bind(wx.EVT_BUTTON, self.on_cancelButton, self.cancelButton)
        self.continueButton = wx.Button(self.panel, id=-1, label='Save and continue')
        self.Bind(wx.EVT_BUTTON, lambda event: self.on_continueButton(event, self.spec_grid, next_dia=self.InitSampCheck), self.continueButton)

        hboxok.Add(self.saveButton, flag=wx.ALIGN_LEFT|wx.RIGHT, border=10)
        hboxok.Add(self.cancelButton, flag=wx.ALIGN_LEFT|wx.RIGHT, border=10)
        hboxok.Add(self.continueButton, flag=wx.ALIGN_LEFT)

        #
        hboxgrid = pw.hbox_grid(self.panel, self.onDeleteRow, 'specimen', self.grid)
        self.deleteRowButton = hboxgrid.deleteRowButton

        self.panel.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.onLeftClickLabel, self.grid)

        ### Create Containers ###
        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.AddSpacer(10)
        vbox.Add(label, flag=wx.ALIGN_CENTER|wx.TOP|wx.BOTTOM, border=10)

        vbox.Add(hbox_one, flag=wx.TOP|wx.LEFT|wx.BOTTOM, border=10)
        vbox.Add(hboxok, flag=wx.BOTTOM|wx.LEFT, border=10)
        vbox.Add(hboxgrid, flag=wx.BOTTOM|wx.LEFT, border=10)
        vbox.Add(self.spec_grid, flag=wx.ALL, border=10)#|wx.EXPAND, border=30)
        vbox.AddSpacer(20)

        self.hbox_all = wx.BoxSizer(wx.HORIZONTAL)
        self.hbox_all.AddSpacer(20)
        self.hbox_all.Add(vbox)
        self.hbox_all.AddSpacer(20)

        self.panel.SetSizer(self.hbox_all)
        #self.panel.SetScrollbars(20, 20, 50, 50)
        self.hbox_all.Fit(self)
        self.Centre()
        self.Show()
        self.Hide()
        self.Show()
266125
def samples(self):
        """"""
        names = self.series.dimensions
        for values in zip(*(getattr(self.series, name) for name in names)):
            yield dict(zip(names, values))
498885
def tableMaker(inputLabel, outputLabels, port, _E=elementMaker):
    
    colspan = {}
    if outputLabels:
        colspan['colspan'] = str(len(outputLabels))

    inputLabelCell = _E("td",
                        _E("font",
                           inputLabel,
                           face="menlo-italic"),
                        color="purple",
                        port=port,
                        **colspan)

    pointSize = {"point-size": "9"}
    outputLabelCells = [_E("td",
                           _E("font",
                              outputLabel,
                              **pointSize),
                           color="pink")
                        for outputLabel in outputLabels]

    rows = [_E("tr", inputLabelCell)]

    if outputLabels:
        rows.append(_E("tr", *outputLabelCells))

    return _E("table", *rows)
1312809
def interact_gridsearch_result_images(show_result_func, cfgdict_list,
                                      cfglbl_list, cfgresult_list,
                                      score_list=None, fnum=None, figtitle='',
                                      unpack=False, max_plots=25, verbose=True,
                                      precision=3, scorelbl='score',
                                      onclick_func=None):
    
    assert callable(show_result_func), 'NEED FUNCTION GOT: %r' % (show_result_func,)

    import utool as ut
    import plottool as pt
    from plottool import plot_helpers as ph
    from plottool import interact_helpers as ih
    if verbose:
        print('Plotting gridsearch results figtitle=%r' % (figtitle,))
    if score_list is None:
        score_list = [None] * len(cfgdict_list)
    else:
        # sort by score if available
        sortx_list = ut.list_argsort(score_list, reverse=True)
        score_list = ut.take(score_list, sortx_list)
        cfgdict_list = ut.take(cfgdict_list, sortx_list)
        cfglbl_list = ut.take(cfglbl_list, sortx_list)
        cfgresult_list = ut.take(cfgresult_list, sortx_list)
    # Dont show too many results only the top few
    score_list = ut.listclip(score_list, max_plots)

    # Show the config results
    fig = pt.figure(fnum=fnum)
    # Get plots for each of the resutls
    nRows, nCols = pt.get_square_row_cols(len(score_list), fix=True)
    next_pnum = pt.make_pnum_nextgen(nRows, nCols)
    for cfgdict, cfglbl, cfgresult, score in zip(cfgdict_list, cfglbl_list,
                                                  cfgresult_list,
                                                  score_list):
        if score is not None:
            cfglbl += '\n' + scorelbl + '=' + ut.repr2(score, precision=precision)
        pnum = next_pnum()
        try:
            if unpack:
                show_result_func(*cfgresult, fnum=fnum, pnum=pnum)
            else:
                show_result_func(cfgresult, fnum=fnum, pnum=pnum)
        except Exception as ex:
            if isinstance(cfgresult, tuple):
                #print(ut.repr4(cfgresult))
                print(ut.depth_profile(cfgresult))
                print(ut.list_type_profile(cfgresult))
            ut.printex(ex, 'error showing', keys=['cfgresult', 'fnum', 'pnum'])
            raise
        #pt.imshow(255 * cfgresult, fnum=fnum, pnum=next_pnum(), title=cfglbl)
        ax = pt.gca()
        pt.set_title(cfglbl, ax=ax)  # , size)
        ph.set_plotdat(ax, 'cfgdict', cfgdict)
        ph.set_plotdat(ax, 'cfglbl', cfglbl)
        ph.set_plotdat(ax, 'cfgresult', cfgresult)
    # Define clicked callback
    def on_clicked(event):
        print('\n[pt] clicked gridsearch axes')
        if event is None or event.xdata is None or event.inaxes is None:
            print('out of axes')
            pass
        else:
            ax = event.inaxes
            plotdat_dict = ph.get_plotdat_dict(ax)
            print(ut.repr4(plotdat_dict))
            cfglbl = ph.get_plotdat(ax, 'cfglbl', None)
            cfgdict = ph.get_plotdat(ax, 'cfgdict', {})
            cfgresult = ph.get_plotdat(ax, 'cfgresult', {})
            infostr_list = [
                ('cfglbl = %s' % (cfglbl,)),
                '',
                ('cfgdict = ' + ut.repr4(cfgdict, sorted_=True)),
            ]
            # Call a user defined function if given
            if onclick_func is not None:
                if unpack:
                    onclick_func(*cfgresult)
                else:
                    onclick_func(cfgresult)
            infostr = ut.msgblock('CLICKED', '\n'.join(infostr_list))
            print(infostr)
    # Connect callbacks
    ih.connect_callback(fig, 'button_press_event', on_clicked)
    pt.set_figtitle(figtitle)
4897
def samples(self):
        """"""
        names = self.series.dimensions
        for n, offset in enumerate(self.series.offsets):
            dt = datetime.timedelta(microseconds=offset * 1000)
            d = {"ts": self.ts + dt}
            for name in names:
                d[name] = getattr(self.series, name)[n]
            yield d
1004399
def editCell(self, vcolidx=None, rowidx=None, **kwargs):
        ''

        if vcolidx is None:
            vcolidx = self.cursorVisibleColIndex
        x, w = self.visibleColLayout.get(vcolidx, (0, 0))

        col = self.visibleCols[vcolidx]
        if rowidx is None:
            rowidx = self.cursorRowIndex
        if rowidx < 0:  # header
            y = 0
            currentValue = col.name
        else:
            y = self.rowLayout.get(rowidx, 0)
            currentValue = col.getDisplayValue(self.rows[self.cursorRowIndex])

        editargs = dict(value=currentValue,
                        fillchar=options.disp_edit_fill,
                        truncchar=options.disp_truncator)
        editargs.update(kwargs)  # update with user-specified args
        r = self.vd.editText(y, x, w, **editargs)
        if rowidx >= 0:  # if not header
            r = col.type(r)  # convert input to column type, let exceptions be raised

        return r
1231470
def cli(ctx, organism_id, common_name, directory, blatdb="", species="", genus="", public=False):
    
    return ctx.gi.organisms.update_organism(organism_id, common_name, directory, blatdb=blatdb, species=species, genus=genus, public=public)
263849
function () {
            if (!this.options.grid) {
                return;
            }

            var o = this.options,
                i, z,

                total = o.max - o.min,
                big_num = o.grid_num,
                big_p = 0,
                big_w = 0,

                small_max = 4,
                local_small_max,
                small_p,
                small_w = 0,

                result,
                html = '';



            this.calcGridMargin();

            if (o.grid_snap) {
                big_num = total / o.step;
            }

            if (big_num > 50) big_num = 50;
            big_p = this.toFixed(100 / big_num);

            if (big_num > 4) {
                small_max = 3;
            }
            if (big_num > 7) {
                small_max = 2;
            }
            if (big_num > 14) {
                small_max = 1;
            }
            if (big_num > 28) {
                small_max = 0;
            }

            for (i = 0; i < big_num + 1; i++) {
                local_small_max = small_max;

                big_w = this.toFixed(big_p * i);

                if (big_w > 100) {
                    big_w = 100;
                }
                this.coords.big[i] = big_w;

                small_p = (big_w - (big_p * (i - 1))) / (local_small_max + 1);

                for (z = 1; z <= local_small_max; z++) {
                    if (big_w === 0) {
                        break;
                    }

                    small_w = this.toFixed(big_w - (small_p * z));

                    html += '<span class="irs-grid-pol small" style="left: ' + small_w + '%"></span>';
                }

                html += '<span class="irs-grid-pol" style="left: ' + big_w + '%"></span>';

                result = this.convertToValue(big_w);
                if (o.values.length) {
                    result = o.p_values[result];
                } else {
                    result = this._prettify(result);
                }

                html += '<span class="irs-grid-text js-grid-text-' + i + '" style="left: ' + big_w + '%">' + result + '</span>';
            }
            this.coords.big_num = Math.ceil(big_num + 1);



            this.$cache.cont.addClass("irs-with-grid");
            this.$cache.grid.html(html);
            this.cacheGridLabels();
        }
333425
def names(self):
        """"""
        ret = set()
        for arr in self:
            if isinstance(arr, InteractiveList):
                ret.update(arr.names)
            else:
                ret.add(arr.name)
        return ret
1363427
def tab_name_editor(self):
        """"""
        index = self.tabwidget.currentIndex()
        self.tabwidget.tabBar().tab_name_editor.edit_tab(index)
1303220
def onDeleteRow(self, event, data_type):
        
        ancestry = self.er_magic_data.ancestry
        child_type = ancestry[ancestry.index(data_type) - 1]
        names = [self.grid.GetCellValue(row, 0) for row in self.selected_rows]
        if data_type == 'site':
            how_to_fix = 'Make sure to select a new site for each orphaned sample in the next step'
        else:
            how_to_fix = 'Go back a step and select a new {} for each orphaned {}'.format(data_type, child_type)

        orphans = []
        for name in names:
            row = self.grid.row_labels.index(name)
            orphan = self.er_magic_data.delete_methods[data_type](name)
            if orphan:
                orphans.extend(orphan)
            self.grid.remove_row(row)
        if orphans:
            orphan_names = self.er_magic_data.make_name_list(orphans)
            pw.simple_warning('You have deleted:\n\n  {}\n\nthe parent(s) of {}(s):\n\n  {}\n\n{}'.format(', '.join(names), child_type, ', '.join(orphan_names), how_to_fix))

        self.selected_rows = set()

        # update grid and data model
        self.update_grid(self.grid)#, grids[grid_name])

        self.grid.Refresh()
655542
def onSelect_specimen(self, event):
        
        new_s = self.specimens_box.GetValue()
        if self.select_specimen(new_s):
            self.update_selection()
        else:
            self.specimens_box.SetValue(self.s)
            self.user_warning(
                "no specimen %s reverting to old specimen %s" % (new_s, self.s))
344807
def make_sample():
    
    if md_sample:
        # user has set another:
        return md_sample
    _md = []
    for hl in range(1, 7): _md.append('#' * hl + ' ' + 'Header %s' % hl)
    this = open(__file__).read().split('"""', 3)[2].splitlines()[:10]
    _md.append('```python\n""" Test """\n%s\n```' % '\n'.join(this).strip())
    _md.append("""
| Tables        | Fmt |
| -- | -- |
| !!! hint: wrapped | 0.1 **strong** |
    """)
    for ad in admons.keys()[:1]:
        _md.append('!!! %s: title\n    this is a %s\n' % (ad, ad.capitalize()))
    # 'this theme' replaced in the roller (but not at mdv w/o args):
    globals()['md_sample'] = \
            '\n'.join(_md) + '\n----\n!!! question: %s' % you_like
662411
def replace_cells(self, key, sorted_row_idxs):
        """"""

        row, col, tab = key

        new_keys = {}
        del_keys = []

        selection = self.grid.actions.get_selection()

        for __row, __col, __tab in self.grid.code_array:
            if __tab == tab and \
               (not selection or (__row, __col) in selection):
                new_row = sorted_row_idxs.index(__row)
                if __row != new_row:
                    new_keys[(new_row, __col, __tab)] = \
                        self.grid.code_array((__row, __col, __tab))
                    del_keys.append((__row, __col, __tab))

        for key in del_keys:
            self.grid.code_array.pop(key)

        for key in new_keys:
            CellActions.set_code(self, key, new_keys[key])
1358147
def add_new_grid_headers(self, new_headers):
        
        already_present = []
        for name in new_headers:
            if name:
                if name not in self.grid.col_labels:
                    col_number = self.grid.add_col(name)
                    # add to appropriate headers list
                    # add drop down menus for user-added column
                    if name in self.contribution.vocab.vocabularies:
                        self.drop_down_menu.add_drop_down(col_number, name)
                    elif name in self.contribution.vocab.suggested:
                        self.drop_down_menu.add_drop_down(col_number, name)
                    elif name in ['specimen', 'sample', 'site',
                                  'specimens', 'samples', 'sites']:
                        self.drop_down_menu.add_drop_down(col_number, name)
                    elif name == 'experiments':
                        self.drop_down_menu.add_drop_down(col_number, name)
                    if name == "method_codes":
                        self.drop_down_menu.add_method_drop_down(col_number, name)
                else:
                    already_present.append(name)
                    #pw.simple_warning('You are already using column header: {}'.format(name))
        return already_present
674481
def create_sheet(self):
        '''
        
        '''
        #--------------------------------
        # orient.txt supports many other headers
        # but we will only initialize with
        # the essential headers for
        # sample orientation and headers present
        # in existing demag_orient.txt file
        #--------------------------------


        #--------------------------------
        # create the grid
        #--------------------------------

        samples_list = list(self.orient_data.keys())
        samples_list.sort()
        self.samples_list = [ sample for sample in samples_list if sample is not "" ]
        #self.headers.extend(self.add_extra_headers(samples_list))
        display_headers = [header[1] for header in self.headers]
        self.grid = magic_grid.MagicGrid(self.panel, 'orient grid',
                                         self.samples_list, display_headers)
        self.grid.InitUI()

        #--------------------------------
        # color the columns by groups
        #--------------------------------

        for i in range(len(self.samples_list)):
            self.grid.SetCellBackgroundColour(i, 0, "LIGHT GREY")
            self.grid.SetCellBackgroundColour(i, 1, "LIGHT STEEL BLUE")
            self.grid.SetCellBackgroundColour(i, 2, "YELLOW")
            self.grid.SetCellBackgroundColour(i, 3, "YELLOW")
            self.grid.SetCellBackgroundColour(i, 4, "PALE GREEN")
            self.grid.SetCellBackgroundColour(i, 5, "PALE GREEN")
            self.grid.SetCellBackgroundColour(i, 6, "KHAKI")
            self.grid.SetCellBackgroundColour(i, 7, "KHAKI")
            self.grid.SetCellBackgroundColour(i, 8, "KHAKI")
            self.grid.SetCellBackgroundColour(i, 9, "KHAKI")
            self.grid.SetCellBackgroundColour(i, 10, "KHAKI")
            self.grid.SetCellBackgroundColour(i, 11, "LIGHT MAGENTA")
            self.grid.SetCellBackgroundColour(i, 12, "LIGHT MAGENTA")


        #--------------------------------
        # fill data from self.orient_data
        #--------------------------------

        headers = [header[0] for header in self.headers]
        for sample in self.samples_list:
            for key in list(self.orient_data[sample].keys()):
                if key in headers:
                    sample_index = self.samples_list.index(sample)
                    i = headers.index(key)
                    val = str(self.orient_data[sample][key])
                    # if it's a pmag_object, use its name
                    try:
                        val = val.name
                    except AttributeError:
                        pass
                    if val and val != "None":
                        self.grid.SetCellValue(sample_index, i, val)

        #--------------------------------

        #--------------------------------
        # fill in some default values
        #--------------------------------
        for row in range(self.grid.GetNumberRows()):
            col = 1
            if not self.grid.GetCellValue(row, col):
                self.grid.SetCellValue(row, col, 'g')

        #--------------------------------

        # temporary trick to get drop-down-menus to work
        self.grid.changes = {'a'}

        self.grid.AutoSize()
        #self.drop_down_menu = drop_down_menus.Menus("orient", self, self.grid, '')
        self.drop_down_menu = drop_down_menus3.Menus("orient", self.contribution, self.grid)
        self.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.onLeftClickLabel, self.grid)