Convert dict fields into objects, where appropriate
421972
def _update_fields_with_objects(self):
        
        # Update the photo target with photo objects
        if self.target is not None:
            if self.target_type == "photo":
                self.target = Photo(self._client, self.target)
            else:
                raise NotImplementedError("Actions can only be assigned to "
                                          "Photos")
1235291
def _user_object_converter(cls):
    # type: (Type[Any]) -> _AggregateConverter
    """"""
    def _from_dict(dict_value):
        try:
            object_value = cls(**dict_value)
        except TypeError:
            # Constructor does not support keyword arguments, try setting each
            # field individually.
            object_value = cls()
            for field_name, field_value in dict_value.items():
                setattr(object_value, field_name, field_value)

        return object_value

    def _to_dict(value):
        if value:
            return value.__dict__

        return {}

    return _AggregateConverter(from_dict=_from_dict, to_dict=_to_dict)
516744
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'document_id' in _dict:
            args['document_id'] = _dict.get('document_id')
        if 'field' in _dict:
            args['field'] = _dict.get('field')
        if 'start_offset' in _dict:
            args['start_offset'] = _dict.get('start_offset')
        if 'end_offset' in _dict:
            args['end_offset'] = _dict.get('end_offset')
        if 'entities' in _dict:
            args['entities'] = [
                QueryEvidenceEntity._from_dict(x)
                for x in (_dict.get('entities'))
            ]
        return cls(**args)
356212
def fromDict(cls, _dict):
        
        obj = cls()
        obj.__dict__.update(_dict)
        return obj
373989
function(fields, data) {
    if (!_.isString(fields)) {
      return data;
    }

    // If a field is specified as `foo.bar` or `foo.bar.baz`,
    // Convert it to just `foo`
    var map = {};
    _.forEach(fields.split(','), function(field) {
      map[field.split('.')[0]] = 1;
    });

    var keys = _.keys(map);
    if (_.isArray(data)) {
      data = _.map(data, function(object) {
        return _.pick(object, keys);
      });
    } else if (_.isObject(data)) {
      data = _.pick(data, keys);
    }

    return data;
  }
1255585
def __objecthasfields(bunchdt, data, commdct, idfobject, places=7, **kwargs):
    """"""
    for key, value in list(kwargs.items()):
        if not isfieldvalue(
                bunchdt, data, commdct,
                idfobject, key, value, places=places):
            return False
    return True
395523
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'location' in _dict:
            args['location'] = Location._from_dict(_dict.get('location'))
        if 'text' in _dict:
            args['text'] = _dict.get('text')
        if 'types' in _dict:
            args['types'] = [
                TypeLabel._from_dict(x) for x in (_dict.get('types'))
            ]
        if 'categories' in _dict:
            args['categories'] = [
                Category._from_dict(x) for x in (_dict.get('categories'))
            ]
        if 'attributes' in _dict:
            args['attributes'] = [
                Attribute._from_dict(x) for x in (_dict.get('attributes'))
            ]
        return cls(**args)
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)
306956
def to_object(item):
        
        def convert(item): 
            if isinstance(item, dict):
                return IterableObject({k: convert(v) for k, v in item.items()})
            if isinstance(item, list):
                def yield_convert(item):
                    for index, value in enumerate(item):
                        yield convert(value)
                return list(yield_convert(item))
            else:
                return item

        return convert(item)
1178435
def asdict(self):
        
        result = {}
        for key in self._fields:
            value = getattr(self, key)
            if isinstance(value, list):
                value = [i.asdict() if isinstance(i, Resource) else i for i in value]
            if isinstance(value, Resource):
                value = value.asdict()
            result[key] = value
        return result
21210
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'matching_results' in _dict:
            args['matching_results'] = _dict.get('matching_results')
        if 'results' in _dict:
            args['results'] = [
                QueryResult._from_dict(x) for x in (_dict.get('results'))
            ]
        if 'aggregations' in _dict:
            args['aggregations'] = [
                QueryAggregation._from_dict(x)
                for x in (_dict.get('aggregations'))
            ]
        if 'passages' in _dict:
            args['passages'] = [
                QueryPassages._from_dict(x) for x in (_dict.get('passages'))
            ]
        if 'duplicates_removed' in _dict:
            args['duplicates_removed'] = _dict.get('duplicates_removed')
        if 'session_token' in _dict:
            args['session_token'] = _dict.get('session_token')
        if 'retrieval_details' in _dict:
            args['retrieval_details'] = RetrievalDetails._from_dict(
                _dict.get('retrieval_details'))
        return cls(**args)
914279
def clean_field_dict(field_dict, cleaner=str.strip, time_zone=None):
    
    """
    d = {}
    if time_zone is None:
        tz = DEFAULT_TZ
    for k, v in viewitems(field_dict):
        if k == '_state':
            continue
        if isinstance(v, basestring):
            d[k] = cleaner(str(v))
        elif isinstance(v, (datetime.datetime, datetime.date)):
            d[k] = tz.localize(v)
        else:
            d[k] = v
    return d
831377
def _basic_field_data(field, obj):
    """"""
    value = field.value_from_object(obj)
    return {Field.TYPE: FieldType.VAL, Field.VALUE: value}
1241977
def iter_field_objects(fields):
    
    if isinstance(fields, dict):
        i = six.iteritems(fields)
    else:
        i = iter(fields)

    for field in i:
        if isinstance(field, RequestField):
            yield field
        else:
            yield RequestField.from_tuples(*field)
1230723
def _normalize_coerce_to_field_dict(self, v):
        

        def tokenize(s):
            """ Tokenize a string by splitting it by + and -

            >>> tokenize('this + that')
            ['this', '+', 'that']

            >>> tokenize('this+that')
            ['this', '+', 'that']

            >>> tokenize('this+that-other')
            ['this', '+', 'that', '-', 'other]
            """

            # Crude tokenization
            s = s.replace('+', ' + ').replace('-', ' - ') \
                .replace('/', ' / ').replace('*', ' * ')
            words = [w for w in s.split(' ') if w]
            return words

        if isinstance(v, _str_type):
            field_parts = tokenize(v)
            field = field_parts[0]
            d = {'value': field}
            if len(field_parts) > 1:
                # if we need to add and subtract from the field join the field
                # parts into pairs, for instance if field parts is
                #     [MyTable.first, '-', MyTable.second, '+', MyTable.third]
                # we will get two pairs here
                #     [('-', MyTable.second), ('+', MyTable.third)]
                d['operators'] = []
                for operator, other_field in zip(
                    field_parts[1::2], field_parts[2::2]
                ):
                    d['operators'].append({
                        'operator': operator,
                        'field': {
                            'value': other_field
                        }
                    })
            return d
        else:
            return v
331296
def object_as_dict(obj):
    
    return {c.key: getattr(obj, c.key)
            for c in inspect(obj).mapper.column_attrs}
1221817
def field_to_dict(field, instance):
    
    # avoid a circular import
    from django.db.models.fields.related import ManyToManyField

    return (many_to_many_field_to_dict(field, instance) if isinstance(field, ManyToManyField)
            else field.value_from_object(instance))