This method Validates, gets the Python value, checks unique indexes, 
        gets the db value, and then returns the prepared doc dict object. 
        Useful for save and backup functions.
        @param doc_obj: 
        @return:
323014
def prep_doc(self, doc_obj):
        
        doc = doc_obj._data.copy()
        for key, prop in list(doc_obj._base_properties.items()):
            prop.validate(doc.get(key), key)
            raw_value = prop.get_python_value(doc.get(key))
            if prop.unique:
                self.check_unique(doc_obj, key, raw_value)
            value = prop.get_db_value(raw_value)
            doc[key] = value

        doc['_doc_type'] = get_doc_type(doc_obj.__class__)
        return doc
957556
def get_obj_doc0(obj, alt="(no doc)"):
    """"""
    ret = obj.__doc__.strip().split("\n")[0] if obj.__doc__ is not None else alt
    return ret
751596
def get_object(objref, data=None, return_fields=None, max_results=None,
               ensure_none_or_one_result=False, **api_opts):
    '''
    
    '''
    if not data:
        data = {}
    infoblox = _get_infoblox(**api_opts)
    return infoblox.get_object(objref, data, return_fields,
                               max_results, ensure_none_or_one_result)
833245
function getDocsToPersist(docId, view, docIdsToChangesAndEmits) {
    var metaDocId = '_local/doc_' + docId;
    var defaultMetaDoc = {_id: metaDocId, keys: []};
    var docData = docIdsToChangesAndEmits.get(docId);
    var indexableKeysToKeyValues = docData[0];
    var changes = docData[1];

    function getMetaDoc() {
      if (isGenOne(changes)) {
        // generation 1, so we can safely assume initial state
        // for performance reasons (avoids unnecessary GETs)
        return Promise.resolve(defaultMetaDoc);
      }
      return view.db.get(metaDocId).catch(defaultsTo(defaultMetaDoc));
    }

    function getKeyValueDocs(metaDoc) {
      if (!metaDoc.keys.length) {
        // no keys, no need for a lookup
        return Promise.resolve({rows: []});
      }
      return view.db.allDocs({
        keys: metaDoc.keys,
        include_docs: true
      });
    }

    function processKeyValueDocs(metaDoc, kvDocsRes) {
      var kvDocs = [];
      var oldKeys = new pouchdbCollections.Set();

      for (var i = 0, len = kvDocsRes.rows.length; i < len; i++) {
        var row = kvDocsRes.rows[i];
        var doc = row.doc;
        if (!doc) { // deleted
          continue;
        }
        kvDocs.push(doc);
        oldKeys.add(doc._id);
        doc._deleted = !indexableKeysToKeyValues.has(doc._id);
        if (!doc._deleted) {
          var keyValue = indexableKeysToKeyValues.get(doc._id);
          if ('value' in keyValue) {
            doc.value = keyValue.value;
          }
        }
      }
      var newKeys = pouchdbMapreduceUtils.mapToKeysArray(indexableKeysToKeyValues);
      newKeys.forEach(function (key) {
        if (!oldKeys.has(key)) {
          // new doc
          var kvDoc = {
            _id: key
          };
          var keyValue = indexableKeysToKeyValues.get(key);
          if ('value' in keyValue) {
            kvDoc.value = keyValue.value;
          }
          kvDocs.push(kvDoc);
        }
      });
      metaDoc.keys = pouchdbMapreduceUtils.uniq(newKeys.concat(metaDoc.keys));
      kvDocs.push(metaDoc);

      return kvDocs;
    }

    return getMetaDoc().then(function (metaDoc) {
      return getKeyValueDocs(metaDoc).then(function (kvDocsRes) {
        return processKeyValueDocs(metaDoc, kvDocsRes);
      });
    });
  }
132443
def gen_otu_dict(nex_obj, nexson_version=None):
    
    if nexson_version is None:
        nexson_version = detect_nexson_version(nex_obj)
    if _is_by_id_hbf(nexson_version):
        otus = nex_obj['nexml']['otusById']
        if len(otus) > 1:
            d = {}
            for v in otus.values():
                d.update(v['otuById'])
            return d
        else:
            return otus.values()[0]['otuById']
    o_dict = {}
    for ob in nex_obj.get('otus', []):
        for o in ob.get('otu', []):
            oid = o['@id']
            o_dict[oid] = o
    return o_dict
748482
def format_doc(*args, **kwargs):
    
    def set_docstring(obj):

        # None means: use the objects __doc__
        doc = obj.__doc__
        # Delete documentation in this case so we don't end up with
        # awkwardly self-inserted docs.
        obj.__doc__ = None

        # If the original has a not-empty docstring append it to the format
        # kwargs.
        kwargs['__doc__'] = obj.__doc__ or ''
        obj.__doc__ = doc.format(*args, **kwargs)
        return obj
    return set_docstring
614543
def get_attr_from_dict(inspected_obj: Any, attr_name: str) -> Any:
    
    if inspect.isclass(inspected_obj):
        obj_list = [inspected_obj] + list(inspected_obj.__mro__)
    else:
        obj_list = [inspected_obj] + list(inspected_obj.__class__.__mro__)
    for obj in obj_list:
        if hasattr(obj, '__dict__') and attr_name in obj.__dict__:
            return obj.__dict__[attr_name]
    # This happens when user-defined __dir__ returns something that's not
    # in any __dict__. See test_override_dir.
    # Returns attr_name so that it's treated as a normal property.
    return attr_name
300332
def baredoc(obj):
    
    doc = getdoc(obj)
    if not doc:
        return ''
    doc = doc.splitlines()[0]
    return doc.rstrip(' .').lstrip()
23293
def validate_document_class(option, value):
    """"""
    if not issubclass(value, (abc.MutableMapping, RawBSONDocument)):
        raise TypeError("%s must be dict, bson.son.SON, "
                        "bson.raw_bson.RawBSONDocument, or a "
                        "sublass of collections.MutableMapping" % (option,))
    return value
1373334
def related_obj_to_dict(obj, **kwargs):
    

    # Explicitly discard formatter kwarg, should not be cascaded down.
    kwargs.pop('formatter', None)

    # If True, remove fields that start with an underscore (e.g. _secret)
    suppress_private_attr = kwargs.get("suppress_private_attr", False)

    # if True, don't store fields with None values into dictionary.
    suppress_empty_values = kwargs.get("suppress_empty_values", False)

    # get list of attrs fields
    attrs = fields(obj.__class__)

    # instantiate return dict, use OrderedDict type by default
    return_dict = kwargs.get("dict_factory", OrderedDict)()

    for a in attrs:

        # skip if private attr and flag tells you to skip
        if suppress_private_attr and a.name.startswith("_"):
            continue

        metadata = a.metadata or {}

        # formatter is a related-specific `attrs` meta field
        #   see fields.DateField
        formatter = metadata.get('formatter')

        # get value and call to_dict on it, passing the kwargs/formatter
        value = getattr(obj, a.name)
        value = to_dict(value, formatter=formatter, **kwargs)

        # check flag, skip None values
        if suppress_empty_values and value is None:
            continue

        # field name can be overridden by the metadata field
        key_name = a.metadata.get('key') or a.name

        # store converted / formatted value into return dictionary
        return_dict[key_name] = value

    return return_dict
139939
def get(self, doc_id):
        """"""
        resp_dict = self._get_query(q='id:{}'.format(doc_id))
        if resp_dict['response']['numFound'] > 0:
            return resp_dict['response']['docs'][0]
1034971
def doc_strings_to_utf8(obj)
      case obj
      when ::Hash then
        {}.tap { |new_hash|
          obj.each do |key, value|
            new_hash[key] = doc_strings_to_utf8(value)
          end
        }
      when Array then
        obj.map { |item| doc_strings_to_utf8(item) }
      when String then
        if obj[0,2].unpack("C*") == [254, 255]
          utf16_to_utf8(obj)
        else
          pdfdoc_to_utf8(obj)
        end
      else
        @objects.deref(obj)
      end
    end
229316
def _docstring_parameter(obj_type, subset=False):   # pylint: disable=no-self-argument
        """"""
        docstring = (
            "Flexibly search the JSS for objects of type {}.\n\n\tArgs:\n\t\t"
            "Data: Allows different types to conduct different types of "
            "searches. Argument of type:\n\t\t\tNone (or Provide no argument) "
            "to search for all objects.\n\t\t\tInt to search for an object by "
            "ID.\n\t\t\tString to search for an object by name.\n\t\t\t"
            "xml.etree.ElementTree.Element to create a new object from the "
            "Element's data.{}\n\n\tReturns:\n\t\tJSSObjectList for empty "
            "data arguments.\n\t\tReturns an object of type {} for searches "
            "and new objects.\n\t\t(FUTURE) Will return None if nothing is "
            "found that match the search criteria.\n\n\tRaises:\n\t\t"
            "JSSGetError for nonexistent objects.")

        if subset:
            subset_string = (
                "\n\t\tsubset: A list of XML subelement tags to request\n"
                "\t\t\t(e.g. ['general', 'purchasing']), OR an '&' \n\t\t\t"
                "delimited string (e.g. 'general&purchasing').")
        else:
            subset_string = ""

        def dec(obj):
            """Dynamically decorate a docstring."""
            class_name = str(obj_type)[:-2].rsplit(".")[-1]
            updated_docstring = docstring.format(class_name, subset_string,
                                                 class_name)
            obj.__doc__ = obj.__doc__.format(
                dynamic_docstring=updated_docstring)
            return obj
        return dec
1101002
def get_object_data(obj, fields, safe):
    

    temp_dict = dict()
    for field in fields:

        try:
            attribute = getattr(obj, str(field))
            if isinstance(attribute, list) and all([isinstance(item, models.Model) for item in attribute]):
                temp_dict[field] = []
                for item in attribute:
                    temp_dict[field].append(get_object_data(item, get_fields(item), safe))  # Recur
            elif isinstance(attribute, models.Model):
                attribute_fields = get_fields(attribute)
                object_data = get_object_data(attribute, attribute_fields, safe)  # Recur
                temp_dict[field] = object_data
            else:
                if not safe:
                    if isinstance(attribute, basestring):
                        attribute = cgi.escape(attribute)
                temp_dict[field] = attribute

        except Exception as e:
            logger.info("Unable to get attribute.")
            logger.error(e)
            continue

    return temp_dict
1149812
def obj_to_dict(cls, obj):
        
        data = {}
        for field_name in cls.get_fields():
            try:
                value = getattr(obj, field_name)
            except AttributeError:
                # If the field doesn't exist on the object, fail gracefully
                # and don't include the field in the data dict at all. Fail
                # loudly if the field exists but produces a different error
                # (edge case: accessing an *existing* field could technically
                # produce an unrelated AttributeError).
                continue

            if callable(value):
                value = value()
            data[field_name] = value

        return data
694038
def _docspec_comments(obj) -> Dict[str, str]:
    
    # Sometimes our docstring is on the class, and sometimes it's on the initializer,
    # so we've got to check both.
    class_docstring = getattr(obj, '__doc__', None)
    init_docstring = getattr(obj.__init__, '__doc__', None) if hasattr(obj, '__init__') else None

    docstring = class_docstring or init_docstring or ''

    doc = NumpyDocString(docstring)
    params = doc["Parameters"]
    comments: Dict[str, str] = {}

    for line in params:
        # It looks like when there's not a space after the parameter name,
        # numpydocstring parses it incorrectly.
        name_bad = line[0]
        name = name_bad.split(":")[0]

        # Sometimes the line has 3 fields, sometimes it has 4 fields.
        comment = "\n".join(line[-1])

        comments[name] = comment

    return comments
1174136
def create_document(doc) #:nodoc:
      http_response = call_server(:method => :post, :uri => "document/#{@database}", \
          :content_type => 'application/json', :data => doc.to_json)
      resp = process_response(http_response) do
        raise DataError, 'validation problem' if http_response.body =~ /OValidationException/
      end

      resp = ::JSON.parse(http_response.body) # workaround: https://groups.google.com/forum/?fromgroups=#!topic/orient-database/UJGAXYpHDmo
      resp.extend Orientdb4r::DocumentMetadata
      resp
    end