Exports the inputed tree object to the given excel file.
        
        :param      tree     | <QTreeWidget>
                    filename | <str>
        
        :return     <bool>
4634
def exportTree(self, tree, filename):
        
        book = xlwt.Workbook()
        
        # determine the title for the sheet to export
        title = nativestring(tree.windowTitle())
        if not title:
            title = nativestring(tree.objectName())
        if not title:
            title = 'Sheet 1'
        
        sheet = book.add_sheet(title)
        
        # determine visible columns to export
        cols = [c for c in range(tree.columnCount()) \
                if not tree.isColumnHidden(c)]
        
        # export the column headers
        hitem = tree.headerItem()
        for c, col in enumerate(cols):
            sheet.write(0, c, nativestring(hitem.text(col)))
        
        self._currrow = 1
        for i in range(tree.topLevelItemCount()):
            self.exportTreeItem(sheet, cols, tree.topLevelItem(i))
        
        book.save(filename)
        return True
1228130
def write_tree_newick(self, filename, hide_rooted_prefix=False):
        '''
        '''
        if not isinstance(filename, str):
            raise TypeError("filename must be a str")
        treestr = self.newick()
        if hide_rooted_prefix:
            if treestr.startswith('[&R]'):
                treestr = treestr[4:].strip()
            else:
                warn("Specified hide_rooted_prefix, but tree was not rooted")
        if filename.lower().endswith('.gz'): # gzipped file
            f = gopen(expanduser(filename),'wb',9); f.write(treestr.encode()); f.close()
        else: # plain-text file
            f = open(expanduser(filename),'w'); f.write(treestr); f.close()
1058742
def convert_tree(self, tree):
        
        nodeById = {}
        root_node = None
        node_list = _index_list_of_values(tree, 'node')
        for node in node_list:
            nodeById[node['@id']] = node
            r = node.get('@root')
            # _LOG.debug(' node {} @root={}'.format(node['@id'], r))
            if r in [True, 'true']:  # @TEMP accepting true or "true"
                assert root_node is None
                root_node = node
        assert root_node is not None
        edgeBySourceId = {}
        edge_list = _get_index_list_of_values(tree, 'edge')
        for edge in edge_list:
            sourceId = edge['@source']
            eid = edge['@id']
            del edge['@id']
            byso = edgeBySourceId.setdefault(sourceId, {})
            byso[eid] = edge
        # If all that succeeds, add the new object to the dict, creating a fat structure
        tree['nodeById'] = nodeById
        tree['edgeBySourceId'] = edgeBySourceId
        tree['^ot:rootNodeId'] = root_node['@id']
        # Make the struct leaner
        tid = tree['@id']
        if self.remove_old_structs:
            del tree['@id']
            del tree['node']
            try:
                del tree['edge']
            except:
                # Tree Tr75035 in http://treebase.org/treebase-web/search/study/summary.html?id=14763
                #   is empty. in NeXML that shows up as a tree with a node but no edges.
                #   See https://github.com/OpenTreeOfLife/opentree/issues/641
                # TODO: returning None seems safest, but could cull trees with just metadata.
                #       but creating a fake tree for metadata is ugly. So, I'm fine with not
                #       supporting this.
                _LOG.warn('Tree with ID "{}" is being dropped because it has no edges'.format(tid))
                assert not edge_list
                return None
            for node in node_list:
                if '^ot:isLeaf' in node:
                    del node['^ot:isLeaf']
                del node['@id']
        return tid, tree
59213
def itemData(self, treeItem, column, role=Qt.DisplayRole):
        
        if role == Qt.DisplayRole:
            if column == self.COL_NODE_NAME:
                return treeItem.nodeName
            elif column == self.COL_NODE_PATH:
                return treeItem.nodePath
            elif column == self.COL_SHAPE:
                if treeItem.isSliceable:
                    return " x ".join(str(elem) for elem in treeItem.arrayShape)
                else:
                    return ""
            elif column == self.COL_IS_OPEN:
                # Only show for RTIs that actually open resources.
                # TODO: this must be clearer. Use CanFetchChildren? Set is Open to None by default?
                if treeItem.hasChildren():
                    return str(treeItem.isOpen)
                else:
                    return ""
            elif column == self.COL_ELEM_TYPE:
                return treeItem.elementTypeName
            elif column == self.COL_FILE_NAME:
                return treeItem.fileName if hasattr(treeItem, 'fileName') else ''
            elif column == self.COL_UNIT:
                return treeItem.unit
            elif column == self.COL_MISSING_DATA:
                return to_string(treeItem.missingDataValue, noneFormat='') # empty str for Nones
            elif column == self.COL_RTI_TYPE:
                return type_name(treeItem)
            elif column == self.COL_EXCEPTION:
                return str(treeItem.exception) if treeItem.exception else ''
            else:
                raise ValueError("Invalid column: {}".format(column))

        elif role == Qt.ToolTipRole:
            if treeItem.exception:
                return str(treeItem.exception)
            if column == self.COL_NODE_NAME:
                return treeItem.nodePath # Also path when hovering over the name
            elif column == self.COL_NODE_PATH:
                return treeItem.nodePath
            elif column == self.COL_SHAPE:
                if treeItem.isSliceable:
                    return " x ".join(str(elem) for elem in treeItem.arrayShape)
                else:
                    return ""
            elif column == self.COL_UNIT:
                return treeItem.unit
            elif column == self.COL_MISSING_DATA:
                return to_string(treeItem.missingDataValue, noneFormat='') # empty str for Nones
            elif column == self.COL_RTI_TYPE:
                return type_name(treeItem)
            elif column == self.COL_ELEM_TYPE:
                return treeItem.elementTypeName
            elif column == self.COL_FILE_NAME:
                return treeItem.fileName if hasattr(treeItem, 'fileName') else ''
            else:
                return None
        else:
            return super(RepoTreeModel, self).itemData(treeItem, column, role=role)
405508
def tree_load(**kwargs):
            
            str_pathDiskRoot    = ''
            b_loadJSON          = True
            b_loadPickle        = False
            for key, val in kwargs.items():
                if key == 'pathDiskRoot':   str_pathDiskRoot    = val
                if key == 'loadJSON':       b_loadJSON          = val
                if key == 'loadPickle':     b_loadPickle        = val

            l_dir   = []
            l_file  = []
            for str_root, l_directories, l_filenames in os.walk(str_pathDiskRoot):
                for str_dir in l_directories:
                    l_dir.append(os.path.join(str_root, str_dir))
                for str_file in l_filenames:
                    l_file.append(os.path.join(str_root, str_file))
            stree_dirs  = [d.replace(str_pathDiskRoot, '') for d in l_dir]
            stree_files = [f.replace(str_pathDiskRoot, '') for f in l_file]

            # Create the tree
            rtree       = C_stree()
            # Build the directory structures
            for d in stree_dirs:
                # print(d)
                rtree.mkdir(d)
            # Now read any files
            for f in stree_files:
                dirname     = os.path.dirname(f)
                filename    = os.path.basename(f)
                # print(f)
                if b_loadJSON:
                    with open(str_pathDiskRoot + '/' + f, 'r') as fp:
                        contents = json.load(fp)
                        fp.close()
                if b_loadPickle:
                    with open(str_pathDiskRoot + '/' + f, 'rb') as fp:
                        contents = pickle.load(fp)
                        fp.close()

                if rtree.cd(dirname)['status']:
                    rtree.touch(filename, contents)

            return rtree
939904
def save(self):
        
        fpath = self.get_fpath()
        if fpath in ['', None]:
            if self._tree.parent is not None:
                if VERBOSE_PREF:
                    print('[pref.save] Can my parent save me?')  # ...to disk
                return self._tree.parent.save()
            if VERBOSE_PREF:
                print('[pref.save] I cannot be saved. I have no parents.')
            return False
        with open(fpath, 'wb') as f:
            print('[pref] Saving to ' + fpath)
            pref_dict = self.to_dict()
            pickle.dump(pref_dict, f, protocol=2)  # Use protocol 2 to support python2 and 3
        return True
516849
def set_tree(self, tree):
        
        self.tree = tree
        self.__record_progress(Status.DOWNLOAD_FILES)
422884
def save_as(self, new_filename):
        
        xfile._save_file(
            self._filename, self._workbookTree, new_filename)
193173
def export(self, filename, fmt="DER"):
        
        f = open(filename, "wb")
        if fmt == "DER":
            f.write(self.der)
        elif fmt == "PEM":
            f.write(self.pem)
        f.close()
901859
def fill_treeview(self, tree, input_dict):
        

        tree.model().removeRows(0, tree.model().rowCount())

        def add_element(item, key, value):
            child_name = QtWidgets.QStandardItem(key)

            if isinstance(value, dict):
                for key_child, value_child in value.items():
                    add_element(child_name, key_child, value_child)
                item.appendRow(child_name)
            else:
                child_value = QtWidgets.QStandardItem(str(value))

                item.appendRow([child_name, child_value])

        for index, (key, value) in enumerate(input_dict.items()):

            if isinstance(value, dict):
                item = QtWidgets.QStandardItem(key)
                for sub_key, sub_value in value.items():
                    add_element(item, sub_key, sub_value)
                tree.model().appendRow(item)
            elif isinstance(value, str):
                item = QtGui.QStandardItem(key)
                item_value = QtGui.QStandardItem(value)
                item_value.setEditable(True)
                item_value.setSelectable(True)
                tree.model().appendRow([item, item_value])
321451
def filetree(collector, *paths):
    '''
    
    '''
    _paths = []
    # Unglob
    for path in paths:
        _paths += glob.glob(path)
    for path in set(_paths):
        if not path:
            out.error('Path not defined', ident=2)
        elif not os.path.exists(path):
            out.warning('Path {} does not exists'.format(path))
        else:
            # The filehandler needs to be explicitly passed here, so PyLint needs to accept that.
            # pylint: disable=W8470
            if os.path.isfile(path):
                filename = os.path.basename(path)
                try:
                    file_ref = salt.utils.files.fopen(path)  # pylint: disable=W
                    out.put('Add {}'.format(filename), indent=2)
                    collector.add(filename)
                    collector.link(title=path, path=file_ref)
                except Exception as err:
                    out.error(err, ident=4)
            # pylint: enable=W8470
            else:
                try:
                    for fname in os.listdir(path):
                        fname = os.path.join(path, fname)
                        filetree(collector, [fname])
                except Exception as err:
                    out.error(err, ident=4)
697770
def make_tree(self):
        
        self.tree['is_ready'] = False
        leaf_count = len(self.tree['leaves'])
        if leaf_count > 0:
            # skip this whole process if there are no leaves added to the tree
            self._unshift(self.tree['levels'], self.tree['leaves'])
            while len(self.tree['levels'][0]) > 1:
                self._unshift(self.tree['levels'], self._calculate_next_level())
        self.tree['is_ready'] = True
800700
def _tree_to_string(cls, root_element, xml_declaration=True, pretty_print=True):
        
        from lxml import etree
        return gf.safe_unicode(etree.tostring(
            root_element,
            encoding="UTF-8",
            method="xml",
            xml_declaration=xml_declaration,
            pretty_print=pretty_print
        ))
663851
def _tree_filename(self):
        
        if self.Parameters['--out']:
            aln_filename = self._absolute(self.Parameters['--out'].Value)
        else:
            raise ValueError, "No tree output file specified."
        return aln_filename
459199
def print_tree(self, filename, tree=None):
        
        old_stream = self.stream
        self.stream = open(filename, 'w')
        try:
            super(FileBrowser, self).print_tree(tree=tree)
        finally:
            self.stream.close()
            self.stream = old_stream
1249260
def _load(self, tree):
        
        filename = tree.load_file[0]
        if filename[0] in ['"', "'"]:
            filename = unwrap(filename)
        if not os.path.exists(filename):
            raise Exception("No such file %r" % filename)
        batch = self.connection.batch_write(tree.table)
        count = 0
        with batch:
            remainder, ext = os.path.splitext(filename)
            if ext.lower() in [".gz", ".gzip"]:
                ext = os.path.splitext(remainder)[1]
                opened = gzip.open(filename, "rb")
            else:
                opened = open(filename, "r")
            with opened as ifile:
                if ext.lower() == ".csv":
                    reader = csv.DictReader(ifile)
                    for row in reader:
                        batch.put(row)
                        count += 1
                elif ext.lower() == ".json":
                    for row in ifile:
                        batch.put(json.loads(row))
                        count += 1
                else:
                    try:
                        while True:
                            batch.put(pickle.load(ifile))
                            count += 1
                    except EOFError:
                        pass
        return count
640690
function (from, to) {
            var toFile = xpfile(to);
            return xpfile(from).moveTo(toFile.parent, toFile.leafName);
        }