returns a list of possible comparison images for the current cutout.  Will query CADC to create the list when
        first called.
        @rtype: Table
967118
def comparison_image_list(self):
        

        if self._comparison_image_list is not None:
            return self._comparison_image_list

        ref_ra = self.reading.ra * units.degree
        ref_dec = self.reading.dec * units.degree
        radius = self.radius is not None and self.radius or config.read('CUTOUTS.SINGLETS.RADIUS') * units.arcminute
        print("Querying CADC for list of possible comparison images at RA: {}, DEC: {}, raidus: {}".format(ref_ra,
                                                                                                           ref_dec,
                                                                                                           radius))
        query_result = storage.cone_search(ref_ra, ref_dec, radius, radius)  # returns an astropy.table.table.Table
        print("Got {} possible images".format(len(query_result)))
        ans = raw_input("Do you want to lookup IQ? (y/n)")
        print("Building table for presentation and selection")
        if ans == "y":
            print("Including getting fwhm which is a bit slow.")
        comparison_image_list = []
        if len(query_result['collectionID']) > 0:  # are there any comparison images even available on that sky?
            index = -1
            for row in query_result:
                expnum = row['collectionID']
                if expnum in self._bad_comparison_images:
                    continue
                date = Time(row['mjdate'], format='mjd').mpc
                if Time(row['mjdate'], format='mjd') < Time('2013-01-01 00:00:00', format='iso'):
                    continue
                exptime = row['exptime']
                if float(exptime) < 250:
                    continue
                filter_name = row['filter']
                if 'U' in filter_name:
                    continue
                if filter_name.lower() in self.hdulist[-1].header['FILTER'].lower():
                    filter_name = "* {:8s}".format(filter_name)
                fwhm = -1.0
                if ans == 'y':
                    try:
                        fwhm = "{:5.2f}".format(float(storage.get_fwhm_tag(expnum, 22)))
                    except:
                        pass
                index += 1
                comparison_image_list.append([index, expnum, date, exptime, filter_name, fwhm, None])
        self._comparison_image_list = Table(data=numpy.array(comparison_image_list),
                                            names=["ID", "EXPNUM", "DATE-OBS", "EXPTIME", "FILTER", "FWHM", "REFERENCE"])
        return self._comparison_image_list
263367
def _involvedTables(self):
        
        # SQL and arguments
        if self.comparison is not None:
            tables = self.comparison.getInvolvedTables()
            self.args = self.comparison.getArgs(self.store)
        else:
            tables = list(self.tableClass)
            self.args = []

        for tableClass in self.tableClass:
            if tableClass not in tables:
                raise ValueError(
                    "Comparison omits required reference to result type %s"
                    % tableClass.typeName)

        return tables
98227
def _process_table_cells(self, table):
        

        rows = []

        for i, tr in enumerate(table.find_all('tr')):
            row = []

            for c in tr.contents:
                cell_type = getattr(c, 'name', None)

                if cell_type not in ('td', 'th'):
                    continue

                rowspan = int(c.attrs.get('rowspan', 1))
                colspan = int(c.attrs.get('colspan', 1))
                contents = self._process_children(c).strip()

                if cell_type == 'th' and i > 0:
                    contents = self._inline('**', contents)

                row.append(Cell(cell_type, rowspan, colspan, contents))

            rows.append(row)

        return rows
8988
def chop_list( blocks, src, start, end ):
    
    new_blocks = []
    for block in blocks: 
        ref = block.get_component_by_src( src )
        # If the reference component is on the '-' strand we should complement the interval
        if ref.strand == '-':
            slice_start = max( ref.src_size - end, ref.start )
            slice_end = max( ref.src_size - start, ref.end )
        else:
            slice_start = max( start, ref.start )
            slice_end = min( end, ref.end )
        sliced = block.slice_by_component( ref, slice_start, slice_end ) 
        good = True
        for c in sliced.components: 
            if c.size < 1: 
                good = False
        if good:
            new_blocks.append( sliced )
    return new_blocks
784573
def _list_checkers(self):
        
        classes = set()
        for checker_group in checkers.checkers.itervalues():
            for checker in checker_group:
                classes.add(checker)

        max_width = 0
        for clazz in classes:
            max_width = max(max_width, len(clazz.tool), len(clazz.__name__))

        for clazz in sorted(classes):
            status, _ = commands.getstatusoutput('which %s' % clazz.tool)
            result = 'missing' if status else 'installed'
            version = '' if status else clazz.get_version()
            print '%s%s%s%s' % (
                clazz.__name__.ljust(max_width + 1),
                clazz.tool.ljust(max_width + 1),
                result.ljust(max_width + 1),
                version,
            )
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)
1277838
def clean(image, mask=None, iterations = 1):
    '''
    '''
    global clean_table
    if mask is None:
        masked_image = image
    else:
        masked_image = image.astype(bool).copy()
        masked_image[~mask] = False
    result = table_lookup(masked_image, clean_table, False, iterations)
    if not mask is None:
        result[~mask] = image[~mask]
    return result
977770
def tables(self):
        
        select = ("SELECT name FROM sqlite_master",)
        query = self.execute(*select)
        result = query.fetchall()

        # Filter first column from rows.
        return [row[0] for row in result]
199991
def values(self):
        
        return [getattr(self, c.name, None) for c in self.__table__._columns]
865915
def tables(self):
        
        from .table import Table
        return [Table(tbl, self) for tbl in self._element.tbl_lst]
555474
def get_column_listing(self, table):
        
        table = self._connection.get_table_prefix() + table

        results = self._connection.select(self._grammar.compile_column_exists(table))

        return self._connection.get_post_processor().process_column_listing(results)
499355
def get_comparison_methods():
    
    method_list = []
    def _register(func):
        method_list.append(func)
        return func

    # Comparison operators for sorting and uniqueness
    @_register
    def __lt__(self, other):
        return compare_instance(op.lt, self, other)

    @_register
    def __le__(self, other):
        return compare_instance(op.le, self, other)

    @_register
    def __eq__(self, other):
        return compare_instance(op.eq, self, other)

    @_register
    def __ne__(self, other):
        return compare_instance(op.ne, self, other)

    @_register
    def __gt__(self, other):
        return compare_instance(op.gt, self, other)

    @_register
    def __ge__(self, other):
        return compare_instance(op.ge, self, other)

    return method_list
507362
private List<Table> findAllUsedTablesInFrom() {
        List<Table> allTables = new ArrayList<Table>();
        Map<Table, List<JoinCriteria>> sourceMap = new HashMap<Table, List<JoinCriteria>>();
        Map<Table, List<JoinCriteria>> destMap = new HashMap<Table, List<JoinCriteria>>();
        
        // see what tables are used in outer joins        
        for (Object criteria : criterias) {
            try {
                JoinCriteria joinCriteria = (JoinCriteria) criteria;
                Table sourceTable = joinCriteria.getSource().getTable();
                Table destTable = joinCriteria.getDestination().getTable();
                List<JoinCriteria> sourceList = sourceMap.get(sourceTable);
                List<JoinCriteria> destList = sourceMap.get(destTable);
                if (sourceList == null) {
                	sourceList = new ArrayList<JoinCriteria>();
                	sourceMap.put(sourceTable, sourceList);
                }
                sourceList.add(joinCriteria);        
                if (destList == null) {
                	destList = new ArrayList<JoinCriteria>();
                	destMap.put(destTable, destList);
                }
                destList.add(joinCriteria);        
            } catch (ClassCastException ex) {
                // not a JoinCriteria
            }
        }    
        
        // add tables from column selection
        for (Column column : columns) {
            Table table = column.getTable();
            if (table != null) {
                table.setDialect(dialect);
            }
            if (canAddTableToFromClause(table, destMap, allTables)) {
            	table.setJoins(sourceMap.get(table));
        		allTables.add(table);
        	}    
        }        
        
        // add tables from criterias 
        // it is possible that a table is used only in joins without any column selection from it
        for (Object criteria : criterias) {
            try {            	
                JoinCriteria joinCriteria = (JoinCriteria) criteria;
                Table sourceTable = joinCriteria.getSource().getTable();
                Table destTable = joinCriteria.getDestination().getTable();
                if (canAddTableToFromClause(sourceTable, destMap, allTables)) {
                	sourceTable.setJoins(sourceMap.get(sourceTable));
            		allTables.add(sourceTable);
            	}                
                if (canAddTableToFromClause(destTable, destMap, allTables)) {
                	destTable.setJoins(destMap.get(destTable));
                    allTables.add(destTable);
                }                                 
            } catch (ClassCastException ex) {
                // not a JoinCriteria
            }
        }

        // add tables used by order columns
        for (Order order : orders) {
            Table table = order.getColumn().getTable();
            if (table != null) {
                table.setDialect(dialect);
            }
            if (canAddTableToFromClause(table, destMap, allTables)) {
                allTables.add(table);
            }
        }

        return allTables;
    }
659552
def _build_color_table():
        
        FG = FOREGROUND_COLOR
        BG = BACKROUND_COLOR

        return [
            (0x00, 0x00, 0x00, FG.BLACK, BG.BLACK),
            (0x00, 0x00, 0xaa, FG.BLUE, BG.BLUE),
            (0x00, 0xaa, 0x00, FG.GREEN, BG.GREEN),
            (0x00, 0xaa, 0xaa, FG.CYAN, BG.CYAN),
            (0xaa, 0x00, 0x00, FG.RED, BG.RED),
            (0xaa, 0x00, 0xaa, FG.MAGENTA, BG.MAGENTA),
            (0xaa, 0xaa, 0x00, FG.YELLOW, BG.YELLOW),
            (0x88, 0x88, 0x88, FG.GRAY, BG.GRAY),

            (0x44, 0x44, 0xff, FG.BLUE | FG.INTENSITY, BG.BLUE | BG.INTENSITY),
            (0x44, 0xff, 0x44, FG.GREEN | FG.INTENSITY, BG.GREEN | BG.INTENSITY),
            (0x44, 0xff, 0xff, FG.CYAN | FG.INTENSITY, BG.CYAN | BG.INTENSITY),
            (0xff, 0x44, 0x44, FG.RED | FG.INTENSITY, BG.RED | BG.INTENSITY),
            (0xff, 0x44, 0xff, FG.MAGENTA | FG.INTENSITY, BG.MAGENTA | BG.INTENSITY),
            (0xff, 0xff, 0x44, FG.YELLOW | FG.INTENSITY, BG.YELLOW | BG.INTENSITY),

            (0x44, 0x44, 0x44, FG.BLACK | FG.INTENSITY, BG.BLACK | BG.INTENSITY),
            (0xff, 0xff, 0xff, FG.GRAY | FG.INTENSITY, BG.GRAY | BG.INTENSITY),
        ]
544136
def list(self,table, **kparams):
        
        records = self.api.list(table, **kparams)
        return records
519980
def print_table(table):
    
    table = [[str(cell) for cell in row] for row in table]
    column_widths = [len(cell) for cell in table[0]]
    for row in table:
        for x, cell in enumerate(row):
            column_widths[x] = max(column_widths[x], len(cell))

    formatters = []
    for width in column_widths:
        formatters.append('{:>' + str(width) + '}')
    formatter = '  '.join(formatters)
    for row in table:
        print(formatter.format(*row))
831249
def segmentation_images(self,*args,**kwargs):
        
        if not self.db: raise ValueError("Need to set db")
        segs = SegmentationImages.read_cellframe(self,*args,**kwargs)
        segs.microns_per_pixel = segs.microns_per_pixel
        return segs