Extract subelement from obj, according to tokens.

        :param obj: the object source
        :param bypass_ref: disable JSON Reference errors
4156
def extract(self, obj, bypass_ref=False):
        
        for token in self.tokens:
            obj = token.extract(obj, bypass_ref)
        return obj
849815
def get_object_comment_reference(instance, title=None):
    
    span = '<span data-object-type="%s.%s" data-object-pk="%s">%s</span>' % (
        instance.__module__,
        instance.__class__.__name__,
        instance.pk,
        instance if title is None else title
    )
    try:
        return '<a href="%s">%s</a>' % (
            instance.get_absolute_url(),
            span
        )
    except AttributeError:
        return span
824904
def parse_object_ref(ref)
      prefix = ref[1]
      ref = ref[0]
      # Let's make sure the value isn't nil. If it is, return the default Hash.
      return {} if ref.nil?
      class_name =
        if ref.respond_to?(:haml_object_ref)
          ref.haml_object_ref
        else
          underscore(ref.class)
        end
      ref_id =
        if ref.respond_to?(:to_key)
          key = ref.to_key
          key.join('_') unless key.nil?
        else
          ref.id
        end
      id = "#{class_name}_#{ref_id || 'new'}"
      if prefix
        class_name = "#{ prefix }_#{ class_name}"
        id = "#{ prefix }_#{ id }"
      end

      { 'id'.freeze => id, 'class'.freeze => class_name }
    end
55670
def extract_tags(cls, obj):
        
        return dict(uuid=obj.uuid, entrypoint=obj.__class__.path)
944414
def obj_ref(obj):
    """"""
    from indico_livesync.models.queue import EntryType
    if isinstance(obj, Category):
        ref = {'type': EntryType.category, 'category_id': obj.id}
    elif isinstance(obj, Event):
        ref = {'type': EntryType.event, 'event_id': obj.id}
    elif isinstance(obj, Session):
        ref = {'type': EntryType.session, 'session_id': obj.id}
    elif isinstance(obj, Contribution):
        ref = {'type': EntryType.contribution, 'contrib_id': obj.id}
    elif isinstance(obj, SubContribution):
        ref = {'type': EntryType.subcontribution, 'subcontrib_id': obj.id}
    else:
        raise ValueError('Unexpected object: {}'.format(obj.__class__.__name__))
    return ImmutableDict(ref)
1046205
def extract(self, obj, bypass_ref=False):
        
        for i in range(0, self.stages):
            try:
                obj = obj.parent_obj
            except AttributeError:
                raise UnstagedError(obj, '{!r} must be staged before '
                                         'exploring its parents'.format(obj))
        if self.member:
            return obj.parent_member
        return obj
616344
def extract(obj, pointer, bypass_ref=False):
    

    return Pointer(pointer).extract(obj, bypass_ref)
137076
def _refs(obj, named, *ats, **kwds):
    '''
    '''
    if named:
        for a in ats:  # cf. inspect.getmembers()
            if hasattr(obj, a):
                yield _NamedRef(a, getattr(obj, a))
        if kwds:  # kwds are _dir2() args
            for a, o in _dir2(obj, **kwds):
                yield _NamedRef(a, o)
    else:
        for a in ats:  # cf. inspect.getmembers()
            if hasattr(obj, a):
                yield getattr(obj, a)
        if kwds:  # kwds are _dir2() args
            for _, o in _dir2(obj, **kwds):
                yield o
1118914
private Object refObj(Object obj, XmlParser.Node node) throws NoSuchMethodException,
            ClassNotFoundException, InvocationTargetException, IllegalAccessException
    {
        String id = node.getAttribute("id");
        obj = _idMap.get(id);
        if (obj == null) throw new IllegalStateException("No object for id=" + id);
        configure(obj, node, 0);
        return obj;
    }
830147
def extract_objects_from_source(self, text, type_filter=None):
    '''
    '''
    objects = parse_verilog(text)

    if type_filter:
      objects = [o for o in objects if isinstance(o, type_filter)]

    return objects
472056
def _decode(obj):  # type: (bytes or str or unicode or object) -> unicode # noqa ignore=F821
    
    if obj is None:
        return u''
    if six.PY3 and isinstance(obj, six.binary_type):
        # transforms a byte string (b'') in unicode
        return obj.decode('latin1')
    elif six.PY3:
        # PY3 strings are unicode.
        return str(obj)
    elif isinstance(obj, six.text_type):
        # returns itself if it is unicode
        return obj
    else:
        # decodes pY2 string to unicode
        return str(obj).decode('utf-8')
728581
def dump(obj, attributes = True, _refset = None):
    ""
    if _refset is None:
        _refset = set()
    if obj is None:
        return None
    elif isinstance(obj, DataObject):        
        if id(obj) in _refset:
            attributes = False
        else:
            _refset.add(id(obj))
        cls = type(obj)
        clsname = getattr(cls, '__module__', '<unknown>') + '.' + getattr(cls, '__name__', '<unknown>')
        baseresult = {'_type': clsname, '_key': obj.getkey()}
        if not attributes:
            return baseresult
        else:
            baseresult.update((k,dump(v, attributes, _refset)) for k,v in vars(obj).items() if k[:1] != '_')
            _refset.remove(id(obj))
        return baseresult
    elif isinstance(obj, ReferenceObject):
        if obj._ref is not None:
            return dump(obj._ref, attributes, _refset)
        else:
            return {'_ref':obj.getkey()}
    elif isinstance(obj, WeakReferenceObject):
        return {'_weakref':obj.getkey()}
    elif isinstance(obj, DataObjectSet):
        return dump(list(obj.dataset()))
    elif isinstance(obj, dict):
        return dict((k, dump(v, attributes, _refset)) for k,v in obj.items())
    elif isinstance(obj, list) or isinstance(obj, tuple) or isinstance(obj, set):
        return [dump(v, attributes, _refset) for v in obj]
    else:
        return obj
497318
def extract_tags(cls, obj):
        
        return dict(
            [("request.{}".format(attr), obj.get(attr, None)) for attr in
             cls.TAGS]
        )
1212594
def convert(self, obj):
        
        if self.pristine_if_invalid:
            raise NotImplementedError('pristine_if_invalid option is not supported yet')

        nex = get_nexml_el(obj)
        assert nex
        # Create the new objects as locals. This section should not
        #   mutate obj, so that if there is an exception the object
        #   is unchanged on the error exit
        otus = _index_list_of_values(nex, 'otus')
        o_t = self.convert_otus(otus)
        otusById, otusElementOrder = o_t
        trees = _get_index_list_of_values(nex, 'trees')
        treesById = dict((i['@id'], i) for i in trees)
        treesElementOrder = [i['@id'] for i in trees]
        if len(treesById) != len(treesElementOrder):
            trees_id_set = set()
            for tgid in treesElementOrder:
                if tgid in trees_id_set:
                    raise NexsonError('Repeated trees element id "{}"'.format(tgid))
                trees_id_set.add(tgid)
        tree_id_set = set()
        treeContainingObjByTreesId = {}
        for tree_group in trees:
            # _LOG.debug('converting tree group {} to by_id'.format(tree_group['@id']))
            treeById = {}
            treeElementOrder = []
            tree_array = _get_index_list_of_values(tree_group, 'tree')
            for tree in tree_array:
                # _LOG.debug('# pre-convert keys = {}'.format(tree.keys()))
                t_t = self.convert_tree(tree)
                if t_t is None:
                    continue
                tid, tree_alias = t_t  # pylint: disable=W0633
                if tid in tree_id_set:
                    raise NexsonError('Repeated tree element id "{}"'.format(tid))
                tree_id_set.add(tid)

                # _LOG.debug('converting tree {} to by_id'.format(tid))
                # _LOG.debug('# post-convert keys = {}'.format(tree.keys()))
                assert tree_alias is tree
                treeById[tid] = tree
                treeElementOrder.append(tid)
            treeContainingObjByTreesId[tree_group['@id']] = treeById
            tree_group['^ot:treeElementOrder'] = treeElementOrder

        # If all that succeeds, add the new object to the dict, creating a fat structure
        nex['otusById'] = otusById
        nex['^ot:otusElementOrder'] = otusElementOrder
        nex['treesById'] = treesById
        nex['^ot:treesElementOrder'] = treesElementOrder
        for k, v in treeContainingObjByTreesId.items():
            treesById[k]['treeById'] = v
        nex['@nexml2json'] = str(BY_ID_HONEY_BADGERFISH)
        # Make the struct leaner
        if self.remove_old_structs:
            del nex['otus']
            del nex['trees']
            for k, v in treesById.items():
                if 'tree' in v:
                    del v['tree']
                del v['@id']
        return obj
261007
def getreferingobjs(referedobj, iddgroups=None, fields=None):
    """"""
    # pseudocode for code below
    # referringobjs = []
    # referedobj has: -> Name
    #                 -> reference
    # for each obj in idf:
    # [optional filter -> objects in iddgroup]
    #     each field of obj:
    #     [optional filter -> field in fields]
    #         has object-list [refname]:
    #             if refname in reference:
    #                 if Name = field value:
    #                     referringobjs.append()
    referringobjs = []
    idf = referedobj.theidf
    referedidd = referedobj.getfieldidd("Name")
    try:
        references = referedidd['reference']
    except KeyError as e:
        return referringobjs
    idfobjs = idf.idfobjects.values()
    idfobjs = list(itertools.chain.from_iterable(idfobjs))  # flatten list
    if iddgroups:  # optional filter
        idfobjs = [anobj for anobj in idfobjs
            if anobj.getfieldidd('key')['group'] in iddgroups]
    for anobj in idfobjs:
        if not fields:
            thefields = anobj.objls
        else:
            thefields = fields
        for field in thefields:
            try:
                itsidd = anobj.getfieldidd(field)
            except ValueError as e:
                continue
            if 'object-list' in itsidd:
                refname = itsidd['object-list'][0]
                if refname in references:
                    if referedobj.isequal('Name', anobj[field]):
                        referringobjs.append(anobj)
    return referringobjs
567350
def full_subgraph(self, objects):
        
        vertices = ElementTransformSet(transform=id)
        out_edges = KeyTransformDict(transform=id)
        in_edges = KeyTransformDict(transform=id)
        for obj in objects:
            vertices.add(obj)
            out_edges[obj] = []
            in_edges[obj] = []

        edges = set()
        head = {}
        tail = {}

        for referrer in vertices:
            for edge in self._out_edges[referrer]:
                referent = self._head[edge]
                if referent not in vertices:
                    continue
                edges.add(edge)
                tail[edge] = referrer
                head[edge] = referent
                out_edges[referrer].append(edge)
                in_edges[referent].append(edge)

        return ObjectGraph._raw(
            vertices=vertices,
            edges=edges,
            out_edges=out_edges,
            in_edges=in_edges,
            head=head,
            tail=tail,
        )
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