Ejemplo n.º 1
0
 def restore_from_xml(self, root):
     from ast import literal_eval
     try:
         cw = literal_eval(unescape(root.find('COLWIDTH').text))
         self.colwidth = cw
     except Exception as e:
         basic.ignore_exception(e)
     self.model().restore_from_xml(root)
Ejemplo n.º 2
0
 def restore_from_xml(self, nd):
     try:
         self.use = bool(int(nd.find("USE").text))
         self.absolute_limits = bool(int(nd.find("ABSLIMITS").text))
         self.color_by = int(nd.find("COLUMN").text)
         cc = int(nd.find("COLORSCHEME/CLASS").text)
         self.color_scheme = ColorScheme.scheme_by_order(cc)()
         self.color_scheme.restore_from_xml(nd.find("COLORSCHEME"))
     except Exception as e:
         basic.ignore_exception(e)
Ejemplo n.º 3
0
    def __init__(self, flow, proj, opts):
        'proj - prog.projroot.ProjectDB'
        super().__init__()
        # init position (will be changed by opts data)
        self.resize(800, 600)
        self.setWindowIcon(QtGui.QIcon(":/biostata"))
        self.setGeometry(
            QtWidgets.QStyle.alignedRect(
                QtCore.Qt.LeftToRight, QtCore.Qt.AlignCenter, self.size(),
                QtWidgets.qApp.desktop().availableGeometry()))
        self.__subwindows = []

        # data
        self.proj = proj
        self.flow = flow
        self.opts = opts

        self.models = []
        self.tabframes = []
        self.active_model = None
        self.reload_options()

        # assemble actions
        self._build_acts()

        # interface
        self._ui()

        # restore
        try:
            state, geom = self.opts.mainwindow_state()
            self.restoreState(state)
            self.restoreGeometry(geom)
        except Exception as e:
            basic.ignore_exception(e)

        # signals to slots
        self.flow.command_done.add_subscriber(self._update_menu_status)
        self.active_model_changed.connect(self._update_menu_status)
        self.database_saved.connect(self._update_menu_status)
        self.wtab.currentChanged.connect(self._tab_changed)
        self.proj.xml_saved.add_subscriber(self.to_xml)
        self.proj.xml_loaded.add_subscriber(self.restore_from_xml)
        self.proj.monitor_recent_db(self.opts)
        QtWidgets.qApp.aboutToQuit.connect(self._on_quit)

        # Load data
        self.reset_title()
        filename = self.opts.default_project_filename()
        if filename is not None:
            try:
                self.acts['Open database'].load(filename)
            except Exception as e:
                qtcommon.message_exc(self, "Load error", e=e)
                self._close_database()
Ejemplo n.º 4
0
 def func(*args):
     try:
         ret = []
         for c, x in zip(columns, args):
             if x is not None:
                 ret.append(str(c.repr(x)))
             else:
                 ret.append('##')
         return delimiter.join(ret)
     except Exception as e:
         basic.ignore_exception(e, "collapse error. " + str(args))
Ejemplo n.º 5
0
 def _read_field(path, frmt, attr, islist=False):
     ndval = lambda x: (frmt(x) if x is not None else ''
                        if frmt == str else None)
     try:
         if not islist:
             self.__dict__[attr] = ndval(root.find(path).text)
         else:
             self.__dict__[attr].clear()
             for nd in root.findall(path):
                 self.__dict__[attr].append(ndval(nd.text))
     except Exception as e:
         basic.ignore_exception(e, "xmlnode {} failed".format(path))
Ejemplo n.º 6
0
 def restore_from_xml(self, nd):
     from ast import literal_eval
     try:
         c1 = bool(int(nd.find('CONT').text))
         c2 = int(nd.find('DCOUNT').text)
         c3 = bool(int(nd.find('REV').text))
         c4 = literal_eval(nd.find('DEFAULT').text)
         self.set_discrete(not c1, c2)
         self.set_reversed(c3)
         self._default_color = c4
     except Exception as e:
         basic.ignore_exception(e)
Ejemplo n.º 7
0
 def restore_from_xml(self, root):
     from ast import literal_eval
     # folds
     try:
         self._unfolded_groups = literal_eval(root.find('UNFOLDED').text)
         if isinstance(self._unfolded_groups, int):
             self._unfolded_groups = bool(self._unfolded_groups)
     except Exception as e:
         basic.ignore_exception(e)
     # coloring
     self.coloring.restore_from_xml(root.find('COLORING'))
     # init coloring
     self.view_update()
Ejemplo n.º 8
0
    def save(self):
        from bgui import qtcommon
        from prog import basic
        import prog
        try:
            root = ET.Element('BiostataOptions')
            root.attrib['version'] = prog.version

            # representation
            orepr = ET.SubElement(root, "TABLE")
            ET.SubElement(ET.SubElement(orepr, 'FONT'),
                          'SIZE').text = str(self.basic_font_size)
            ET.SubElement(orepr, 'BOOL_AS').text = self.show_bool_as
            ET.SubElement(orepr,
                          'REAL_PREC').text = str(self.real_numbers_prec)

            # external programs
            exrepr = ET.SubElement(root, "EXTERNAL")
            ET.SubElement(exrepr, "XLSX").text = self.external_xlsx_editor
            ET.SubElement(exrepr, "TXT").text = self.external_txt_editor

            # behaviour
            brepr = ET.SubElement(root, "BEHAVIOUR")
            ET.SubElement(brepr, "OPEN_RECENT").text = str(
                self.open_recent_db_on_start)

            # recent databases
            rdb = ET.SubElement(root, "RECENT_DB")
            for r in self.recent_db:
                ET.SubElement(rdb, "PATH_DB").text = r

            # forms positions
            wnd = ET.SubElement(root, "WINDOWS")
            qtcommon.save_window_positions(wnd)
            # mainwindow state
            mainstate = ET.SubElement(wnd, "MAIN")
            ET.SubElement(mainstate, "GEOMETRY").text = self.mw_geom
            ET.SubElement(mainstate, "STATE").text = self.mw_state

            # save to file
            basic.xmlindent(root)
            tree = ET.ElementTree(root)
            tree.write(self.rcfile(), xml_declaration=True, encoding='utf-8')
        except Exception as e:
            basic.ignore_exception(e)
Ejemplo n.º 9
0
 def restore_from_xml(self, nd):
     self._close_database()
     self._init_project()
     root = nd.find('PROGVIEW')
     if root is None:
         return
     for f in root.findall('TAB'):
         nm = f.find('NAME').text
         for t in self.tabframes:
             if t.table_name() == nm:
                 t.restore_from_xml(f)
                 break
         else:
             assert False, '{}'.format(nm)
     try:
         ct = int(root.find('CURRENT_TAB').text)
         self.wtab.setCurrentIndex(ct)
     except Exception as e:
         basic.ignore_exception(e)
Ejemplo n.º 10
0
    def load(self):
        from bgui import qtcommon

        def _read_field(path, frmt, attr, islist=False):
            ndval = lambda x: (frmt(x) if x is not None else ''
                               if frmt == str else None)
            try:
                if not islist:
                    self.__dict__[attr] = ndval(root.find(path).text)
                else:
                    self.__dict__[attr].clear()
                    for nd in root.findall(path):
                        self.__dict__[attr].append(ndval(nd.text))
            except Exception as e:
                basic.ignore_exception(e, "xmlnode {} failed".format(path))

        try:
            root = ET.parse(self.rcfile())
        except Exception as e:
            basic.ignore_exception(e, "Loading options file failed")
            return

        _read_field('TABLE/FONT/SIZE', int, 'basic_font_size')
        _read_field('TABLE/BOOL_AS', str, 'show_bool_as')
        _read_field('TABLE/REAL_PREC', int, 'real_numbers_prec')
        _read_field('EXTERNAL/XLSX', str, 'external_xlsx_editor')
        _read_field('EXTERNAL/TXT', str, 'external_txt_editor')
        _read_field('BEHAVIOUR/OPEN_RECENT', int, 'open_recent_db_on_start')
        _read_field('RECENT_DB/PATH_DB', str, 'recent_db', True)

        # set window sizes
        posnode = root.find('WINDOWS')
        if posnode is not None:
            qtcommon.set_window_positions(posnode)

        _read_field('WINDOWS/MAIN/GEOMETRY', str, 'mw_geom')
        _read_field('WINDOWS/MAIN/STATE', str, 'mw_state')
Ejemplo n.º 11
0
            # on windows try to read config.txt file which should be located
            # in main executable directory
            cfgpath = os.path.join(os.path.dirname(__file__), '..',
                                   'config.txt')
            if os.path.exists(cfgpath):
                out = None
                with open(cfgpath, 'r') as fid:
                    lines = fid.readlines()
                    for ln in lines:
                        if ln.strip().startswith('datadir:'):
                            out = ln[8:].strip()
                            break
                if out is not None and os.path.exists(out):
                    _progoutpath = os.path.abspath(out)
        except Exception as e:
            basic.ignore_exception(e)
            _progoutpath = '.'
    if _progoutpath == '.':
        # otherwise get user local folder
        _progoutpath = os.path.expanduser('~')


class BiostataOptions:
    def __init__(self):
        # representation
        self.basic_font_size = 10
        self.show_bool_as = 'icons'  # [icons, codes, 0/1, Yes/No]
        self.real_numbers_prec = 6

        # external programs
        self.external_xlsx_editor = ''
Ejemplo n.º 12
0
def split_plain_text(fname, options):
    """ used options attributes:
            firstline, lastline, comment_sign, ignore_blank, row_sep, col_sep
            colcount.
        returns equal column size 2d array of stripped text entries
    """
    lines = None
    for e in ['utf8', 'unicode', 'windows-1250', 'windows-1252']:
        try:
            with open(fname, 'r', encoding=e) as f:
                lines = f.readlines()
        except Exception as e:
            basic.ignore_exception(e=e)
        else:
            break
    if lines is None:
        # try without encoding to raise Exception
        with open(fname, 'r') as f:
            lines = f.readlines()

    # firstline-lastline
    firstline = max(0, options.firstline - 1)
    lastline = options.lastline if options.lastline > 0 else len(lines) - 1
    lines = lines[firstline:lastline + 1]
    # remove text after comments
    if options.comment_sign:
        for i, line in enumerate(lines):
            pos = line.find(options.comment_sign)
            if pos >= 0:
                lines[i] = line[:pos]
    # remove blank lines
    if options.ignore_blank:
        lines = list(filter(lambda x: len(x.strip()) > 0, lines))

    # reassemble lines if row separator is not a new line
    if options.row_sep != "newline":
        lines = " ".join(lines)
        if options.row_sep != "no (use column count)":
            lines = lines.split(options.row_sep)
        else:
            lines = [lines]

    # assemble columns
    if options.col_sep == 'whitespaces':
        for i, line in enumerate(lines):
            lines[i] = line.split()
    elif options.col_sep == 'tabular':
        for i, line in enumerate(lines):
            lines[i] = line.split('\t')
    elif options.col_sep == 'in double quotes':
        for i, line in enumerate(lines):
            lines[i] = line.split('"')[1::2]
    else:
        for i, line in enumerate(lines):
            lines[i] = line.split(options.col_sep)

    if len(lines) == 0:
        raise Exception("No data were loaded")

    # row split by column count
    if options.row_sep == "no (use column count)":
        lines2 = [
            lines[0][x:x + options.colcount]
            for x in range(0, len(lines[0]), options.colcount)
        ]
        lines = lines2

    # equal column count
    if options.colcount <= 0:
        cc = max([len(x) for x in lines])
    else:
        cc = options.colcount
    for i, line in enumerate(lines):
        if len(line) > cc:
            lines[i] = line[:cc]
        elif len(line) < cc:
            lines[i] = line + [""] * (cc - len(line))

    # final strip
    for line in lines:
        for j, x in enumerate(line):
            line[j] = x.strip()
    return lines
Ejemplo n.º 13
0
 def func(i):
     try:
         return dt[i-1]
     except Exception as e:
         basic.ignore_exception(e, 'explicit column error')