Register relation endpoint(s) between two resources.
551634
def configure_relation(graph, ns, mappings):
    
    convention = RelationConvention(graph)
    convention.configure(ns, mappings)
1256670
function relationship(factory, type, r, options) {
  var engine = factory.engine || resourceful.engine || {},
      rfactory,     // Resource factory/constructor
      rstring,      // Resource string
      rstringp,     // Resource pluralized string
      rstringc;     // Resource capitalized string

  if (typeof(r) === 'string') {
    rstringc = resourceful.capitalize(r);
    rfactory = resourceful.resources[rstringc];

    // We're dealing with .child('name-of-this-resource')
    if (!rfactory && rstringc === factory.resource) {
      rfactory = factory;
    }
  } else if (typeof(r) === 'function') {
    rstringc = r.resource;
    rfactory = r;
  } else {
    throw new(TypeError)("argument must be a string or constructor");
  }

  if (typeof rfactory === 'undefined') {
    //
    // If the Parent resource is not yet defined,
    // then store the relationship as defferred, where it could be called later
    //
    if (typeof resourceful.deferredRelationships[r] === 'undefined') {
      resourceful.deferredRelationships[r] = [factory.resource]
    } else {
      resourceful.deferredRelationships[r].push(factory.resource)
    }
    //
    // Return nothing, do not attempt to relate unknown resource.
    // If the missing resource is later defined...this relationship
    // will then be mapped at define-time for the missing resource
    //
    return;
  }

  rstring  = rfactory.lowerResource;
  rstringp = resourceful.pluralize(rstring);

  if (type == 'child') {
    if (factory._children.indexOf(rstringc) !== -1) return;

    factory._children.push(rstringc);
    factory.property(rstring + '_ids', Array, { 'default': [], required: true });
    //
    // Parent.children(id, callback)
    //
    if (engine._children) {
      engine._children.call(this, factory, rstringp, rfactory);
    } else {
      factory[rstringp] = function (id, callback) {
        return rfactory['by' + factory.resource](id, callback)
      };
    }
    //
    // parent.children(callback)
    //
    factory.prototype[rstringp] = function (callback) {
      return this.constructor[rstringp](this.key, callback);
    };

    //
    // Parent.getChild(parent, child_id, callback)
    //
    factory['get' + rstringc] = function (parent, child_id, callback) {
      var id  = parent.key || parent,
          cid = child_id;

      id_path = factory.lowerResource + '/' + id + '/' + cid

      rfactory.get(id_path, function(err, child){
        if(err) {
          if(callback) return callback(err);
        }
        return callback(null, child);
      });
    }
    //
    // parent.getChild(child_id, callback)
    //
    factory.prototype['get' + rstringc] = function (child_id, callback) {
      return this.constructor['get' + rstringc](this.key, child_id, callback);
    };

    //
    // Parent.createChild(id, child, callback)
    //
    factory['create' + rstringc] = function (parent, child, callback) {
      var key = factory.lowerResource + '_id',
          id  = parent.key || parent,
          cid = child[rfactory.key] || resourceful.uuid.v4();

      function notifyParent(c, callback) {
        factory.get(id, function(err, p) {
          if(err) {
            if(callback) return callback(err);
          }

          var rstringi = rstring + '_ids';

          if (p[rstringi] && !Array.isArray(p[rstringi])) {
            p[rstringi] = [p[rstringi]];
          }
          p[rstringi] = p[rstringi] || [];

          if (p[rstringi].indexOf(cid) < 0) {
            p[rstringi].push(cid);
          }

          p.save(function(err, result){
            callback(err, c);
          });
        });
      }

      child[rfactory.key] = factory.lowerResource + '/' + id + '/' + cid;

      if (child instanceof rfactory) {
        child[key] = id;
        child.save(function(err) {
          if(err) {
            if(callback) return callback(err);
          }
          notifyParent(child, callback);
        });
      } else {
        var inheritance = {};
        inheritance[key] = id;
        child = resourceful.mixin({}, child, inheritance);
        rfactory.create(child, function(err, c) {
          if(err) {
            if(callback) return callback(err);
          }
          notifyParent(c, function(e, r) {
            if(e) {
              if(callback) return callback(e);
            } else {
              if(callback) callback(err, r);
            }
          });
        });
      }
    }

    //
    // parent.createChild(child, callback)
    //
    factory.prototype['create' + rstringc] = function (child, callback) {
      factory['create' + rstringc](this, child, callback);
    };

    factory.before('destroy', function (obj, next) {
      obj = obj[rfactory.key] || obj;
      obj = obj.split('/').slice(1).join('/');

      factory.get(obj, function (e, p) {
        if (e) { return next(e); }

        p[rstringp](function (e, c) {
          if (e) { return next(e); }

          resourceful.async.forEachSeries(c, function (i, cb) {
            i.destroy(cb);
          }, function (e) {
            next(e);
          });
        });
      });
    });

    // Notify child about new parent
    rfactory.parent(factory);
  } else {
    if (factory._parents.indexOf(rstringc) !== -1) return;

    factory._parents.push(rstringc);

    //
    // Child.byParent(id, callback)
    //
    if (engine._byParent) {
      engine._byParent.call(factory._connection, factory, rfactory);
    } else {
      factory['by' + rstringc] = function (id, callback) {
        var filter = {};
        filter[rstring + '_id'] = id;
        factory.find(filter, callback);
      };
    }

    //
    // child.parent(callback)
    //
    factory.prototype[rstring] = function (callback) {
      if (this[rstring + '_id']) {
        return rfactory.get(this[rstring + '_id'], callback);
      }
      callback(null, null);
    };
    factory.property(rstring + '_id', [String, null], {
      'default': null,
      required: true
    });

    factory.before('destroy', function(obj, next) {
      obj = obj[rfactory.key] || obj;
      obj = obj.split('/').slice(1).join('/');

      factory.get(obj, function(e, c) {
        if(e) { return next(e); }

        c[rstring](function(err, p) {
          if(err || !p) { return next(err); }
          var key = factory.lowerResource + '_ids';
          obj = obj.replace(rfactory.lowerResource + '/' + p.key + '/', '');

          if(p[key].indexOf(obj) > -1) {
            p[key].splice(p[key].indexOf(obj), 1);
            p.save(function(err) {
              if(err) { return next(err); }
              next();
            });
          } else {
            next();
          }
        });
      });
    });

    // Notify parent about new child
    rfactory.child(factory);
  }
}
155017
def connect(self, index):
        """"""
        # Determine which model is the target model as either side of the relation
        # may be passed as `field`.
        if index.object_type == self.field.rel.model:
            self.model = self.field.rel.related_model
            self.accessor = self.field.rel.field.attname
        else:
            self.model = self.field.rel.model
            if self.field.rel.symmetrical:
                # Symmetrical m2m relation on self has no reverse accessor.
                raise NotImplementedError(
                    'Dependencies on symmetrical M2M relations are not supported due '
                    'to strange handling of the m2m_changed signal which only makes '
                    'half of the relation visible during signal execution. For now you '
                    'need to use symmetrical=False on the M2M field definition.'
                )
            else:
                self.accessor = self.field.rel.get_accessor_name()

        # Connect signals.
        signals = super().connect(index)

        m2m_signal = ElasticSignal(self, 'process_m2m', pass_kwargs=True)
        m2m_signal.connect(m2m_changed, sender=self.field.through)
        signals.append(m2m_signal)

        # If the relation has a custom through model, we need to subscribe to it.
        if not self.field.rel.through._meta.auto_created:  # pylint: disable=protected-access
            signal = ElasticSignal(self, 'process_m2m_through_save', pass_kwargs=True)
            signal.connect(post_save, sender=self.field.rel.through)
            signals.append(signal)

            signal = ElasticSignal(self, 'process_m2m_through_pre_delete', pass_kwargs=True)
            signal.connect(pre_delete, sender=self.field.rel.through)
            signals.append(signal)

            signal = ElasticSignal(self, 'process_m2m_through_post_delete', pass_kwargs=True)
            signal.connect(post_delete, sender=self.field.rel.through)
            signals.append(signal)

        return signals
154057
public function registerConnectionSingleton()
    {
        $this->app->singleton(Client::class, function () {

            $defaultConfig = [
                'logPath'   => storage_path().'/logs/elasticsearch-'.php_sapi_name().'.log',
            ];

            $config = array_merge($defaultConfig, config('elasticsearch'));

            $connection = array_get($config, 'connections.'.$config['defaultConnection']);

            $client = ClientBuilder::create()->setHosts($connection['hosts']);

            if ($connection['logging']) {
                $logger = ClientBuilder::defaultLogger($connection['logPath']);
                $client->setLogger($logger);
            }

            return $client->build();
        });
    }
258066
protected static function registerRelations()
    {
        if (!static::$relations) {
            $supported = [
                HasOne::class => HasOneWrapper::class,
                BelongsTo::class => BelongsToWrapper::class,
                BelongsToMany::class => BelongsToManyWrapper::class,
                HasMany::class => HasManyWrapper::class,
            ];

            static::$relations = Collection::make([]);

            foreach ($supported as $rel => $wrapperName) {
                static::$relations[$rel] = [
                    'className' => $wrapperName,
                ];
            }
        }
    }
873976
def register(self, resource=None, **meta):
        
        if resource is None:
            def wrapper(resource):
                return self.register(resource, **meta)
            return wrapper

        # Must be instance of ResourceView
        if not issubclass(resource, ResourceView):
            raise AssertionError("%s not subclass of ResourceView" % resource)

        # Cannot be abstract
        if resource._meta.abstract:
            raise AssertionError("Attempt register of abstract resource: %s."
                                 % resource)

        # Fabric of resources
        meta = dict(self.meta, **meta)
        meta['name'] = meta.get('name', resource._meta.name)
        options = type('Meta', tuple(), meta)

        params = dict(api=self, Meta=options, **meta)

        params['__module__'] = '%s.%s' % (
            self.prefix, self.str_version.replace('.', '_'))

        params['__doc__'] = resource.__doc__

        new_resource = type(
            '%s%s' % (resource.__name__, len(self.resources)),
            (resource,), params)

        if self.resources.get(new_resource._meta.url_name):
            logger.warning(
                "A resource '%r' is replacing the existing record for '%s'",
                new_resource, self.resources.get(new_resource._meta.url_name))

        self.resources[new_resource._meta.url_name] = new_resource

        return resource
1007416
private void setupRelationshipRepositories(Class<?> resourceClass, boolean mapped) {
		MetaLookup metaLookup = mapped ? resourceMetaLookup : jpaMetaLookup;

		Class<? extends MetaDataObject> metaClass = mapped ? MetaJsonObject.class : MetaJpaDataObject.class;
		MetaDataObject meta = metaLookup.getMeta(resourceClass, metaClass);

		for (MetaAttribute attr : meta.getAttributes()) {
			if (!attr.isAssociation()) {
				continue;
			}
			MetaType attrType = attr.getType().getElementType();

			if (attrType instanceof MetaEntity) {
				// normal entity association
				Class<?> attrImplClass = attrType.getImplementationClass();
				JpaRepositoryConfig<?> attrConfig = getRepositoryConfig(attrImplClass);

				// only include relations that are exposed as repositories
				if (attrConfig != null) {
					RelationshipRepositoryV2<?, ?, ?, ?> relationshipRepository = filterRelationshipCreation(attrImplClass, repositoryFactory.createRelationshipRepository(this, resourceClass, attrConfig));
					context.addRepository(relationshipRepository);
				}
			} else if (attrType instanceof MetaResource) {
				Class<?> attrImplClass = attrType.getImplementationClass();
				JpaRepositoryConfig<?> attrConfig = getRepositoryConfig(attrImplClass);
				if (attrConfig == null || attrConfig.getMapper() == null) {
					throw new IllegalStateException("no mapped entity for " + attrType.getName() + " reference by " + attr.getId() + " registered");
				}
				JpaRepositoryConfig<?> targetConfig = getRepositoryConfig(attrImplClass);
				Class<?> targetResourceClass = targetConfig.getResourceClass();

				RelationshipRepositoryV2<?, ?, ?, ?> relationshipRepository = filterRelationshipCreation(targetResourceClass, repositoryFactory.createRelationshipRepository(this, resourceClass, attrConfig));
				context.addRepository(relationshipRepository);
			} else {
				throw new IllegalStateException("unable to process relation: " + attr.getId() + ", neither a entity nor a mapped entity is referenced");
			}
		}
	}
497901
public void importRelation(String resourceName, String targetPath, String relationType) throws CmsException {

        createRelation(resourceName, targetPath, relationType, true);
    }
267346
static public void register (EndPoint endPoint) {
		Kryo kryo = endPoint.getKryo();
		kryo.register(RegisterName.class);
		kryo.register(String[].class);
		kryo.register(UpdateNames.class);
		kryo.register(ChatMessage.class);
	}
497342
protected function registerConnectionServices()
    {
        // The connection factory is used to create the actual connection instances on
        // the database. We will inject the factory into the manager so that it may
        // make the connections while they are actually needed and not of before.
        $this->container['db.factory'] = function ($container) {
            return new ConnectionFactory($container);
        };

        // The database manager is used to resolve various connections, since multiple
        // connections might be managed. It also implements the connection resolver
        // interface which may be used by other components requiring connections.
        $this->container['db'] = function ($container) {
            return new DatabaseManager($container, $container['db.factory']);
        };

        $this->container['db.connection'] = function ($container) {
            return $container['db']->connection();
        };
    }
1064031
def register_endpoints(self, backend_names):
        
        url_map = [("^{}".format(self.name), self.ping_endpoint)]

        return url_map
920321
function resolveRelations(attrNode, context) {
    if (attrNode.dataSources || attrNode.resource) {
        const parentResource = context.parentResource;
        let childResource = attrNode;

        context.errorContext = getErrorContext(!parentResource ? 'resource' : 'sub-resource', context);

        if (attrNode.resource) {
            if (!context.resourceConfigs[attrNode.resource]) {
                throw new ImplementationError('Unknown resource "' + attrNode.resource + '"' + context.errorContext);
            }
            childResource = context.resourceConfigs[attrNode.resource].config;
        }

        if (parentResource) {
            if (!('parentKey' in attrNode)) throw new ImplementationError('Missing parentKey' + context.errorContext);
            if (!('childKey' in attrNode)) throw new ImplementationError('Missing childKey' + context.errorContext);

            if (attrNode.parentKey === null) {
                attrNode.parentKey = _.cloneDeep(parentResource.primaryKey);
            }
            if (attrNode.childKey === null) {
                attrNode.childKey = _.cloneDeep(childResource.primaryKey);
            }

            if (attrNode.joinVia) {
                const joinViaDataSource = attrNode.dataSources[attrNode.joinVia];
                if (attrNode.parentKey.length !== joinViaDataSource.joinParentKey.length) {
                    throw new ImplementationError(
                        'Composite key length of parentKey (' +
                            attrNode.parentKey.length +
                            ') does not match joinParentKey length (' +
                            joinViaDataSource.joinParentKey.length +
                            ') ' +
                            'of DataSource "' +
                            attrNode.joinVia +
                            '"' +
                            context.errorContext
                    );
                }
                if (attrNode.childKey.length !== joinViaDataSource.joinChildKey.length) {
                    throw new ImplementationError(
                        'Composite key length of childKey (' +
                            attrNode.childKey.length +
                            ') does not match joinChildKey length (' +
                            joinViaDataSource.joinChildKey.length +
                            ') ' +
                            'of DataSource "' +
                            attrNode.joinVia +
                            '"' +
                            context.errorContext
                    );
                }
            } else if (attrNode.parentKey.length !== attrNode.childKey.length) {
                throw new ImplementationError(
                    'Composite key length of parentKey (' +
                        attrNode.parentKey.length +
                        ') does not match childKey length (' +
                        attrNode.childKey.length +
                        ')' +
                        context.errorContext
                );
            }

            const errorContext = context.errorContext;
            context.errorContext = ' in parentKey' + errorContext;
            attrNode.resolvedParentKey = resolveKey(
                attrNode.parentKey,
                parentResource,
                {
                    allowMultiValued: true
                },
                context
            );

            context.errorContext = ' in childKey' + errorContext;
            attrNode.resolvedChildKey = resolveKey(
                attrNode.childKey,
                childResource,
                {
                    neededDataSources: ['primary'],
                    allowMultiValued: false
                },
                context
            );
            context.errorContext = errorContext;
        }

        context.parentResource = attrNode;
    }

    if (attrNode.attributes) {
        Object.keys(attrNode.attributes).forEach(subAttrName => {
            const subAttrNode = attrNode.attributes[subAttrName];
            const subContext = Object.assign({}, context);
            subContext.attrPath = context.attrPath.concat([subAttrName]);

            resolveRelations(subAttrNode, subContext);
        });
    }
}
220142
def match_relations(self, el, relation):
        """"""

        found = False

        if relation[0].rel_type.startswith(':'):
            found = self.match_future_relations(el, relation)
        else:
            found = self.match_past_relations(el, relation)

        return found
422366
protected function registerConnectionServices()
    {
        // The connection factory is used to create the actual connection instances on
        // the database. We will inject the factory into the manager so that it may
        // make the connections while they are actually needed and not of before.
        $this->getContainer()->share('db.factory', ConnectionFactory::class);

        // The database manager is used to resolve various connections, since multiple
        // connections might be managed. It also implements the connection resolver
        // interface which may be used by other components requiring connections.
        $this->getContainer()->share('db', DatabaseManager::class)
            ->withArgument(Application::class)
            ->withArgument(ConnectionFactory::class);

        $this->getContainer()->share('db.connection', function () {
            return app('db')->connection();
        });
    }
64730
def RegisterResources(self, client_resources):
    """"""
    self.user_cpu_stats.RegisterValue(client_resources.cpu_usage.user_cpu_time)
    self.system_cpu_stats.RegisterValue(
        client_resources.cpu_usage.system_cpu_time)
    self.network_bytes_sent_stats.RegisterValue(
        client_resources.network_bytes_sent)

    self.worst_performers.Append(client_resources)
    new_worst_performers = sorted(
        self.worst_performers,
        key=lambda s: s.cpu_usage.user_cpu_time + s.cpu_usage.system_cpu_time,
        reverse=True)[:self.NUM_WORST_PERFORMERS]
    self.worst_performers = new_worst_performers
464491
protected function loadRelations(ResourceInterface $resource, array $relationshipKeys)
    {
        if ($this->relationLoader !== null && !empty($relationshipKeys)) {
            $this->relationLoader->load($resource, $relationshipKeys);
        }
    }
209108
protected function registerDependencies()
    {
        Yii::$container->setDefinitions([
            EmailTemplatesRepositoryInterface::class => $this->repository,
            LanguageProviderInterface::class => $this->languageProvider,
        ]);
    }