Get relations from includes section or create a remote proxy
552031
@Override
    protected Result<Object> fetchRelated(RegistryEntry entry, Serializable relationId, QueryAdapter queryAdapter) {

        ResultFactory resultFactory = context.getResultFactory();

        String uid = getUID(entry, relationId);
        Object relatedResource = resourceMap.get(uid);
        if (relatedResource != null) {
            return resultFactory.just(relatedResource);
        }
        ResourceInformation resourceInformation = entry.getResourceInformation();
        Class<?> resourceClass = resourceInformation.getResourceClass();
        return resultFactory.just(proxyFactory.createResourceProxy(resourceClass, relationId));
    }
775992
def relation_get(attribute=None, unit=None, rid=None):
    """"""
    _args = ['relation-get', '--format=json']
    if rid:
        _args.append('-r')
        _args.append(rid)
    _args.append(attribute or '-')
    if unit:
        _args.append(unit)
    try:
        return json.loads(subprocess.check_output(_args).decode('UTF-8'))
    except ValueError:
        return None
    except CalledProcessError as e:
        if e.returncode == 2:
            return None
        raise
247191
def relation_call(method, relation_name=None, flag=None, state=None, *args):
    """"""
    if relation_name:
        relation = relation_from_name(relation_name)
        if relation is None:
            raise ValueError('Relation not found: %s' % relation_name)
    elif flag or state:
        relation = relation_from_flag(flag or state)
        if relation is None:
            raise ValueError('Relation not found: %s' % (flag or state))
    else:
        raise ValueError('Must specify either relation_name or flag')
    result = getattr(relation, method)(*args)
    if isinstance(relation, RelationBase) and method == 'conversations':
        # special case for conversations to make them work from CLI
        result = [c.scope for c in result]
    return result
137171
def relations_to(self, target, include_object=False):
        '''  '''
        relations = self._get_item_node(target).incoming
        if include_object:
            for k in relations:
                for v in relations[k]:
                    if hasattr(v, 'obj'): # filter dead links
                        yield v.obj, k
        else:
            yield from relations
999383
def _fetch(self):
        '''
        
        '''
        origin = self.repo.remotes[0]
        refs_pre = self.repo.listall_references()
        fetch_kwargs = {}
        # pygit2 radically changed fetchiing in 0.23.2
        if self.remotecallbacks is not None:
            fetch_kwargs['callbacks'] = self.remotecallbacks
        else:
            if self.credentials is not None:
                origin.credentials = self.credentials
        try:
            fetch_kwargs['prune'] = pygit2.GIT_FETCH_PRUNE
        except AttributeError:
            # pruning only available in pygit2 >= 0.26.2
            pass
        try:
            fetch_results = origin.fetch(**fetch_kwargs)
        except GitError as exc:
            exc_str = get_error_message(exc).lower()
            if 'unsupported url protocol' in exc_str \
                    and isinstance(self.credentials, pygit2.Keypair):
                log.error(
                    'Unable to fetch SSH-based %s remote \'%s\'. '
                    'You may need to add ssh:// to the repo string or '
                    'libgit2 must be compiled with libssh2 to support '
                    'SSH authentication.', self.role, self.id,
                    exc_info=True
                )
            elif 'authentication required but no callback set' in exc_str:
                log.error(
                    '%s remote \'%s\' requires authentication, but no '
                    'authentication configured', self.role, self.id,
                    exc_info=True
                )
            else:
                log.error(
                    'Error occurred fetching %s remote \'%s\': %s',
                    self.role, self.id, exc,
                    exc_info=True
                )
            return False
        try:
            # pygit2.Remote.fetch() returns a dict in pygit2 < 0.21.0
            received_objects = fetch_results['received_objects']
        except (AttributeError, TypeError):
            # pygit2.Remote.fetch() returns a class instance in
            # pygit2 >= 0.21.0
            received_objects = fetch_results.received_objects
        if received_objects != 0:
            log.debug(
                '%s received %s objects for remote \'%s\'',
                self.role, received_objects, self.id
            )
        else:
            log.debug('%s remote \'%s\' is up-to-date', self.role, self.id)
        refs_post = self.repo.listall_references()
        cleaned = self.clean_stale_refs(local_refs=refs_post)
        return True \
            if (received_objects or refs_pre != refs_post or cleaned) \
            else None
93395
private static function loadRemoteComplements()
    {
        $currentID = App::getCurrentID();
        $complement = self::getType();
        $remote = self::$config['remote'];

        $complements = array_keys(self::$instances[$currentID][$complement]);

        foreach ($remote as $complement => $url) {
            if (! in_array($complement, $complements, true)) {
                self::load($url);
            }

            self::$complement()->setOption('config-url', $url);
        }
    }
167605
def check_relations(self, relations):
        """"""
        for rel in relations:
            if not rel:
                continue
            fields = rel.split('.', 1)

            local_field = fields[0]
            if local_field not in self.fields:
                raise ValueError('Unknown field "{}"'.format(local_field))

            field = self.fields[local_field]
            if not isinstance(field, BaseRelationship):
                raise ValueError('Can only include relationships. "{}" is a "{}"'
                                 .format(field.name, field.__class__.__name__))

            field.include_data = True
            if len(fields) > 1:
                field.schema.check_relations(fields[1:])
1141825
def copy(self, contents=True):
        ''''''
        cp = connection(self._baseiri, self._attr_cls, self._logger)
        if contents: cp.add_many(self._relationships)

        return cp
739398
def get_iter_content(self, uri, disable_proxy=False):
        """"""
        return self.get(uri=uri, disable_proxy=disable_proxy, stream=True)
811845
def do_get_block(req, proxy, conn, &block)
    @request_filter.each do |filter|
      filter.filter_request(req)
    end
    if str = @test_loopback_response.shift
      dump_dummy_request_response(req.body.dump, str) if @debug_dev
      conn.push(HTTP::Message.new_response(str))
      return
    end
    content = ''
    res = HTTP::Message.new_response(content)
    @debug_dev << "= Request\n\n" if @debug_dev
    sess = @session_manager.query(req, proxy)
    res.peer_cert = sess.ssl_peer_cert
    @debug_dev << "\n\n= Response\n\n" if @debug_dev
    do_get_header(req, res, sess)
    conn.push(res)
    sess.get_data() do |str|
      block.call(str) if block
      content << str
    end
    @session_manager.keep(sess) unless sess.closed?
    commands = @request_filter.collect { |filter|
      filter.filter_response(req, res)
    }
    if commands.find { |command| command == :retry }
      raise Client::RetryableResponse.new
    end
  end
1121399
def list_relations(self):
        '''  '''
        _ = self._execute('select * from relations').fetchall()
        for i in _:
            #print(i)
            src, name, dst = i
            src = self.deserialize(
                next(self._execute('select code from objects where id=?',(src,)))[0]
            )
            dst = self.deserialize(
                next(self._execute('select code from objects where id=?',(dst,)))[0]
            )
            yield src, name, dst
370452
def get_collection(self, session, query, api_key):
        
        model = self._fetch_model(api_key)
        include = self._parse_include(query.get('include', '').split(','))
        fields = self._parse_fields(query)
        included = {}
        sorts = query.get('sort', '').split(',')
        order_by = []

        collection = session.query(model)

        for attr in sorts:
            if attr == '':
                break

            attr_name, is_asc = [attr[1:], False]\
                if attr[0] == '-'\
                else [attr, True]

            if attr_name not in model.__mapper__.all_orm_descriptors.keys()\
                    or not hasattr(model, attr_name)\
                    or attr_name in model.__mapper__.relationships.keys():
                return NotSortableError(model, attr_name)

            attr = getattr(model, attr_name)
            if not hasattr(attr, 'asc'):
                # pragma: no cover
                return NotSortableError(model, attr_name)

            check_permission(model, attr_name, Permissions.VIEW)

            order_by.append(attr.asc() if is_asc else attr.desc())

        if len(order_by) > 0:
            collection = collection.order_by(*order_by)

        pos = -1
        start, end = self._parse_page(query)

        response = JSONAPIResponse()
        response.data['data'] = []

        for instance in collection:
            try:
                check_permission(instance, None, Permissions.VIEW)
            except PermissionDeniedError:
                continue

            pos += 1
            if end is not None and (pos < start or pos > end):
                continue

            built = self._render_full_resource(instance, include, fields)
            included.update(built.pop('included'))
            response.data['data'].append(built)

        response.data['included'] = list(included.values())
        return response
762302
function findProxyObject(uri, proxyName, callback) {
    var proxyObject = {},
        folderUri = path.join(uri, proxyName)

    iterateFiles(folderUri, function (fileName) {
        var relativePropertyName = path.relative(folderUri, fileName),
            relativeValue = path.relative(uri, fileName)

        relativePropertyName = relativePropertyName.replace(isFile, "")
        var props = relativePropertyName.split("/")

        props.reduce(function (memo, value, index) {
            if (index === props.length - 1) {
                memo[value] = relativeValue
            } else {
                return (memo[value] = memo[value] || {})
            }
        }, proxyObject)

    }, function (err) {
        callback(err, proxyObject)
    })

    //fs.readdir(folderUri, mapIntoProxyObject)

    function mapIntoProxyObject(err, files) {
        if (err) {
            return callback(err)
        }
        files.filter(isFileFunction).forEach(addToProxyObject)
        callback(null, proxyObject)
    }

    function addToProxyObject(fileName) {
        var propertyName = fileName.replace(isFile, "")

        proxyObject[propertyName] = 
            path.join(proxyName, fileName)
    }
}
459305
def prefetch_related(self, *args: str) -> "QuerySet":
        
        queryset = self._clone()
        queryset._prefetch_map = {}

        for relation in args:
            if isinstance(relation, Prefetch):
                relation.resolve_for_queryset(queryset)
                continue
            relation_split = relation.split("__")
            first_level_field = relation_split[0]
            if first_level_field not in self.model._meta.fetch_fields:
                raise FieldError(
                    "relation {} for {} not found".format(first_level_field, self.model._meta.table)
                )
            if first_level_field not in queryset._prefetch_map.keys():
                queryset._prefetch_map[first_level_field] = set()
            forwarded_prefetch = "__".join(relation_split[1:])
            if forwarded_prefetch:
                queryset._prefetch_map[first_level_field].add(forwarded_prefetch)
        return queryset
688672
def get_parent(self, update=False):
        """"""
        if self._meta.proxy_for_model:
            # the current node is a proxy model; the returned parent
            # should be the same proxy model, so we need to explicitly
            # fetch it as an instance of that model rather than simply
            # following the 'parent' relation
            if self.parent_id is None:
                return None
            else:
                return self.__class__.objects.get(pk=self.parent_id)
        else:
            return self.parent
116419
def get_relative_to_remote(self):
        
        s = self.git("status", "--short", "-b")[0]
        r = re.compile("\[([^\]]+)\]")
        toks = r.findall(s)
        if toks:
            try:
                s2 = toks[-1]
                adj, n = s2.split()
                assert(adj in ("ahead", "behind"))
                n = int(n)
                return -n if adj == "behind" else n
            except Exception as e:
                raise ReleaseVCSError(
                    ("Problem parsing first line of result of 'git status "
                     "--short -b' (%s):\n%s") % (s, str(e)))
        else:
            return 0
773611
function getIncludesArray (query) {
  var relationships = query.include.split(',')

  return relationships.map(function (val) {
    return val.trim()
  })
}