Retrieve GECOS field info and return it in dictionary form
8737
def _get_gecos(name):
    '''
    
    '''
    try:
        gecos_field = pwd.getpwnam(name).pw_gecos.split(',', 3)
    except KeyError:
        raise CommandExecutionError(
            'User \'{0}\' does not exist'.format(name)
        )
    if not gecos_field:
        return {}
    else:
        # Assign empty strings for any unspecified trailing GECOS fields
        while len(gecos_field) < 4:
            gecos_field.append('')
        return {'fullname': salt.utils.data.decode(gecos_field[0]),
                'roomnumber': salt.utils.data.decode(gecos_field[1]),
                'workphone': salt.utils.data.decode(gecos_field[2]),
                'homephone': salt.utils.data.decode(gecos_field[3])}
593463
def to_serializable_value(self):
        
        return_dict = {}
        for name, field in self.__dict__.items():
            if isinstance(field, fields.Field):
                return_dict[name] = field.to_serializable_value()
        return return_dict
1205434
def _to_dict(self):
        """"""
        _dict = {}
        if hasattr(self, 'document') and self.document is not None:
            _dict['document'] = self.document._to_dict()
        if hasattr(self, 'model_id') and self.model_id is not None:
            _dict['model_id'] = self.model_id
        if hasattr(self, 'model_version') and self.model_version is not None:
            _dict['model_version'] = self.model_version
        if hasattr(self, 'elements') and self.elements is not None:
            _dict['elements'] = [x._to_dict() for x in self.elements]
        if hasattr(self, 'tables') and self.tables is not None:
            _dict['tables'] = [x._to_dict() for x in self.tables]
        if hasattr(
                self,
                'document_structure') and self.document_structure is not None:
            _dict['document_structure'] = self.document_structure._to_dict()
        if hasattr(self, 'parties') and self.parties is not None:
            _dict['parties'] = [x._to_dict() for x in self.parties]
        if hasattr(self,
                   'effective_dates') and self.effective_dates is not None:
            _dict['effective_dates'] = [
                x._to_dict() for x in self.effective_dates
            ]
        if hasattr(self,
                   'contract_amounts') and self.contract_amounts is not None:
            _dict['contract_amounts'] = [
                x._to_dict() for x in self.contract_amounts
            ]
        if hasattr(self,
                   'termination_dates') and self.termination_dates is not None:
            _dict['termination_dates'] = [
                x._to_dict() for x in self.termination_dates
            ]
        if hasattr(self, 'contract_type') and self.contract_type is not None:
            _dict['contract_type'] = [x._to_dict() for x in self.contract_type]
        return _dict
551259
def _django_to_es_field(self, field):
        """"""
        from django.db import models

        prefix = ""
        if field.startswith("-"):
            prefix = "-"
            field = field.lstrip("-")

        if field in ["id", "pk"]:
            return "_id", models.AutoField

        try:
            dj_field, _, _, _ = self.model._meta.get_field_by_name(field)
            if isinstance(dj_field, models.ForeignKey):
                return prefix + field + "_id", models.ForeignKey
            else:
                return prefix + field, dj_field
        except models.FieldDoesNotExist:
            pass

        return prefix + field.replace(FIELD_SEPARATOR, "."), None
715058
def sql_to_dict(self, query, param):
        
        cursor = connection.cursor()
        cursor.execute(query, param)
        fieldnames = [name[0] for name in cursor.description]
        result = []
        for row in cursor.fetchall():
            rowset = []
            for field in zip(fieldnames, row):
                rowset.append(field)
            result.append(dict(rowset))
        return result
840079
def fields(self):
        ''''''
        out = dict()
        for operator in self.ops:
            out.update(**operator.fields)

        return out
828526
def _to_dict(self):
        """"""
        _dict = {}
        if hasattr(self, 'field_name') and self.field_name is not None:
            _dict['field'] = self.field_name
        if hasattr(self, 'field_type') and self.field_type is not None:
            _dict['type'] = self.field_type
        return _dict
372375
def fields_from_dict(d):
        """"""
        class_container = FieldsContainer.class_container
        fields = [field_cls.from_dict(field_dict) 
                  for field_cls, container in class_container.iteritems()
                  for field_dict in d.get(container, [])]
        return fields
877557
def _get_fields(self, table_name, **kwargs):
        """"""
        ret = {}
        query_str = []
        query_args = ['f', table_name]

        # I had to brush up on my join knowledge while writing this query
        # https://en.wikipedia.org/wiki/Join_(SQL)
        #
        # other helpful links
        # https://wiki.postgresql.org/wiki/Retrieve_primary_key_columns
        # https://www.postgresql.org/docs/9.4/static/catalog-pg-attribute.html
        # https://www.postgresql.org/docs/9.3/static/catalog-pg-type.html
        # 
        # another approach
        # http://dba.stackexchange.com/questions/22362/how-do-i-list-all-columns-for-a-specified-table
        # http://gis.stackexchange.com/questions/94049/how-to-get-the-data-type-of-each-column-from-a-postgis-table
        query_str.append('SELECT')
        query_str.append(',  '.join([
            'a.attnum',
            'a.attname',
            'a.attnotnull',
            't.typname',
            'i.indisprimary',
            #'s.conname',
            #'pg_get_constraintdef(s.oid, true) as condef',
            'c.relname AS confrelname',
        ]))
        query_str.append('FROM')
        query_str.append('  pg_attribute a')
        query_str.append('JOIN pg_type t ON a.atttypid = t.oid')
        query_str.append('LEFT JOIN pg_index i ON a.attrelid = i.indrelid')
        query_str.append('  AND a.attnum = any(i.indkey)')
        query_str.append('LEFT JOIN pg_constraint s ON a.attrelid = s.conrelid')
        query_str.append('  AND s.contype = {} AND a.attnum = any(s.conkey)'.format(self.val_placeholder))
        query_str.append('LEFT JOIN pg_class c ON s.confrelid = c.oid')
        query_str.append('WHERE')
        query_str.append('  a.attrelid = {}::regclass'.format(self.val_placeholder))
        query_str.append('  AND a.attisdropped = False')
        query_str.append('  AND a.attnum > 0')
        query_str.append('ORDER BY a.attnum ASC')

        query_str = os.linesep.join(query_str)
        fields = self.query(query_str, *query_args, **kwargs)

        pg_types = {
            "float8": float,
            "timestamp": datetime.datetime,
            "int2": int,
            "int4": int,
            "int8": long,
            "numeric": decimal.Decimal,
            "text": str,
            "bpchar": str,
            "varchar": str,
            "bool": bool,
            "date": datetime.date,
            "blob": bytearray,
        }

        # the rows we can set: field_type, name, field_required, min_size, max_size,
        #   size, unique, pk, <foreign key info>
        # These keys will roughly correspond with schema.Field
        for row in fields:
            field = {
                "name": row["attname"],
                "field_type": pg_types[row["typname"]],
                "field_required": row["attnotnull"],
                "pk": bool(row["indisprimary"]),
            }

            if row["confrelname"]:
                # TODO -- I can't decide which name I like
                field["schema_table_name"] = row["confrelname"]
                field["ref_table_name"] = row["confrelname"]

            ret[field["name"]] = field

        return ret
61146
def field_to_dict(self, field):
        """"""
        value = getattr(self, field)
        if isinstance(value, (list, tuple)):
            return [self.value_to_dict(val) for val in value]
        return self.value_to_dict(value)
906471
def _format_info(data):
    '''
    
    '''
    return {'gid': data.pw_gid,
            'groups': list_groups(data.pw_name),
            'home': data.pw_dir,
            'name': data.pw_name,
            'shell': data.pw_shell,
            'uid': data.pw_uid,
            'fullname': data.pw_gecos}
927197
def query(self):
        
        q = {}
        for field, value in self._pos.items():
            if value is None:
                q.update({field: {'$exists': True}})
            else:
                q.update({field: {'$gt': value}})
        return q
425604
def to_dict(self):
        """"""
        d = {}
        if self.query_params_match is not None:
            d['@query_params_match'] = self.query_params_match
        if self.query_person_match is not None:
            d['@query_person_match'] = self.query_person_match
        if self.valid_since is not None:
            d['@valid_since'] = datetime_to_str(self.valid_since)
        if self.source is not None:
            d['source'] = self.source.to_dict()
        d.update(self.fields_to_dict())
        return d
197404
def _to_dict(self):
        """"""
        _dict = {}
        if hasattr(self, 'fields') and self.fields is not None:
            _dict['fields'] = [x._to_dict() for x in self.fields]
        return _dict
1230539
def as_dict(self):
        ''''''
        pk = self.pk
        id_type = 3
        if pk.type == 'auto':
            id_type = 1
        return {'id_name': pk.name,
                'id_type': id_type,
                'sorted': bool(self.ordering),
                'autoincr': self.ordering and self.ordering.auto,
                'multi_fields': [field.name for field in self.multifields],
                'indices': dict(((idx.attname, idx.unique)
                                 for idx in self.indices))}
85446
def fields_to_dict(self):
        """"""
        d = {}
        for container in FieldsContainer.class_container.values():
            fields = getattr(self, container)
            if fields:
                d[container] = [field.to_dict() for field in fields]
        return d
961951
def row_dict(self, row):
        """"""
        d = {}
        for field_name,index in self.field_map.items():
            d[field_name] = self.field_value(row, field_name)
        return d