Return leaf bus idx, line idx, and the line foreign key

        Returns
        -------
        (list, list, list) or DataFrame
321319
def leaf_bus(self, df=False):
        
        # leafs - leaf bus idx
        # lines - line idx
        # fkey - the foreign key of Line, in 'bus1' or 'bus2', linking the bus

        leafs, lines, fkeys = list(), list(), list()

        # convert to unique, ordered list
        buses = sorted(list(set(self.bus1 + self.bus2)))

        links = self.link_bus(buses)

        for bus, link in zip(buses, links):
            line = link[0]
            fkey = link[1]
            if line is None:
                continue
            if len(line) == 1:
                leafs.append(bus)
                lines.extend(line)
                fkeys.extend(fkey)

        # output formatting
        if df is False:
            return leafs, lines, fkeys
        else:
            _data = {'Bus idx': leafs, 'Line idx': lines, 'fkey': fkeys}
            if globals()['pd'] is None:
                globals()['pd'] = importlib.import_module('pandas')
            return pd.DataFrame(data=_data)
1262189
def to_sql(self):
        
        return self._sql_query_skeleton.format(
            prefix=self.prefix, select=self.select_block,
            relation=self.from_block, conditions=self.where_block)
92869
def _indexed_leafs(parent):
    
    if not parent.get('children'):
        return {parent['nodeid']: parent}
    indexed = {}
    for child in parent['children']:
        child['parent'] = parent
        if 'leaf' in child:
            indexed[child['nodeid']] = child
        else:
            indexed.update(_indexed_leafs(child))
    parent['leaf'] = _parent_value(parent['children'])
    return indexed
595123
def query(self, sql, **kwargs):
        
        if 'format' not in kwargs or kwargs['format'] == 'dataframe':
            resp = self.get('/v1/query', data={'q': sql, 'format': 'table'}).json()
            if len(resp) == 0:
                return pd.DataFrame()
            else:
                return pd.DataFrame.from_records(resp[1:], columns=resp[0],
                                                 index="_rowName")
        kwargs['q'] = sql
        return self.get('/v1/query', **kwargs).json()
1287950
def in_bulk(self, id_list):
        
        if not id_list:
            return {}
        qs = self._clone()
        qs.add_filter(('pk__in', id_list))
        qs._clear_ordering(force_empty=True)
        return dict([(obj._get_pk_val(), obj) for obj in qs])
1182065
def get_nodes_from_ids(id_list: Iterable[str]) -> List[Node]:
    
    node_list = []

    for result in get_scigraph_nodes(id_list):
        if 'lbl' in result:
            label = result['lbl']
        else:
            label = None  # Empty string or None?
        node_list.append(Node(result['id'], label))

    return node_list
1183794
def list_get(l, idx, default=None):
    
    try:
        if l[idx]:
            return l[idx]
        else:
            return default
    except IndexError:
        return default
1290915
def var_to_df(self):
        
        ret = {}
        self._check_pd()

        if self._flags['address'] is False:
            return pd.DataFrame.from_dict(ret)

        ret.update({'name': self.name})
        ret.update({'idx': self.idx})

        for x in self._states:
            idx = self.__dict__[x]
            ret.update({x: self.system.dae.x[idx]})
        for y in self._algebs:
            idx = self.__dict__[y]
            ret.update({y: self.system.dae.y[idx]})

        var_df = pd.DataFrame.from_dict(ret).set_index('idx')

        return var_df
616290
def get_rows(self):
        
        possible_dataframes = ['F', 'FY', 'M', 'S',
                               'D_cba', 'D_pba',  'D_imp', 'D_exp',
                               'D_cba_reg', 'D_pba_reg',
                               'D_imp_reg', 'D_exp_reg',
                               'D_cba_cap', 'D_pba_cap',
                               'D_imp_cap', 'D_exp_cap', ]
        for df in possible_dataframes:
            if (df in self.__dict__) and (getattr(self, df) is not None):
                return getattr(self, df).index.get_values()
        else:
            logging.warn("No attributes available to get row names")
            return None
741813
def get_index_field_declaration_list_sql(self, fields):
        
        ret = []

        for field in fields:
            ret.append(field)

        return ", ".join(ret)
890946
def sql(self):
        
        assert self.in_key and not self.nullable   # primary key attributes are never nullable
        return '`{name}` {type} NOT NULL COMMENT "{comment}"'.format(
            name=self.name, type=self.type, comment=self.comment)
1280727
def link_bus(self, bus_idx):
        
        ret = []

        if not self._config['is_series']:
            self.log(
                'link_bus function is not valid for non-series model <{}>'.
                format(self.name))
            return []

        if isinstance(bus_idx, (int, float, str)):
            bus_idx = [bus_idx]

        fkey = list(self._ac.keys())
        if 'bus' in fkey:
            fkey.remove('bus')

        nfkey = len(fkey)
        fkey_val = [self.__dict__[i] for i in fkey]

        for item in bus_idx:
            idx = []
            key = []
            for i in range(self.n):
                for j in range(nfkey):
                    if fkey_val[j][i] == item:
                        idx.append(self.idx[i])
                        key.append(fkey[j])
                        # <= 1 terminal should connect to the same bus
                        break

            if len(idx) == 0:
                idx = None
            if len(key) == 0:
                key = None

            ret.append((idx, key))

        return ret
986958
def index(self, row, column, parent):
        

        if not self.hasIndex(row, column, parent):
            return QtCore.QModelIndex()

        if not parent.isValid():
            parentItem = self.root
        else:
            # So, here we go from QModelIndex to the actual object .. ?
            parentItem = parent.internalPointer()

        # the only place where a child item is queried
        childItem = parentItem.getChild(row)
        if childItem:
            # return self.createIndex(row, column)
            return self.createIndex(row, column, childItem)
            """
            # .. that one does not work for PySide 5.12+
            TypeError: 'PySide2.QtCore.QAbstractItemModel.createIndex' called with wrong argument types:
            PySide2.QtCore.QAbstractItemModel.createIndex(int, int, ServerListItem)
            Supported signatures:
            PySide2.QtCore.QAbstractItemModel.createIndex(int, int, quintptr = 0)
            PySide2.QtCore.QAbstractItemModel.createIndex(int, int, void = nullptr)
            """
        else:
            return QtCore.QModelIndex()
1224051
def column_cells(self, column_idx):
        
        cells = self._cells
        idxs = range(column_idx, len(cells), self._column_count)
        return [cells[idx] for idx in idxs]
471335
def dataframe(self):
        
        frames = []
        for game in self.__iter__():
            df = game.dataframe
            if df is not None:
                frames.append(df)
        if frames == []:
            return None
        return pd.concat(frames)
1267356
def toList(self):
        
        if self.getNumCols() > 1:
            return [
                tuple(self.getRowByIndex(i))
                for i in range(self.getNumRows())
            ]
        else:
            return [
                self.getRowByIndex(i)[0]
                for i in range(self.getNumRows())
            ]
467694
def from_rdd_of_dataframes(self, rdd, column_idxs=None):
        """"""
        def frame_to_spark_sql(frame):
            """Convert a Panda's DataFrame into Spark SQL Rows"""
            return [r.tolist() for r in frame.to_records()]

        def frame_to_schema_and_idx_names(frames):
            """Returns the schema and index names of the frames. Useful
            if the frame is large and we wish to avoid transfering
            the entire frame. Only bothers to apply once per partiton"""
            try:
                frame = frames.next()
                return [(list(frame.columns), list(frame.index.names))]
            except StopIteration:
                return []

        # Store if the RDD was persisted so we don't uncache an
        # explicitly cached input.
        was_persisted = rdd.is_cached
        # If we haven't been supplied with the schema info cache the RDD
        # since we are going to eveluate the first partition and then eveluate
        # the entire RDD as part of creating a Spark DataFrame.
        (schema, index_names) = ([], [])
        if not column_idxs:
            rdd.cache()
            (schema, index_names) = rdd.mapPartitions(
                frame_to_schema_and_idx_names).first()
        else:
            (schema, index_names) = column_idxs
        # Add the index_names to the schema.
        index_names = _normalize_index_names(index_names)
        schema = index_names + schema
        ddf = DataFrame.from_schema_rdd(
            self.sql_ctx.createDataFrame(rdd.flatMap(frame_to_spark_sql),
                                         schema=schema))
        ddf._index_names = index_names
        if not was_persisted:
            rdd.unpersist()
        return ddf