Return a preference registry using a model instance
423985
def get_by_instance(self, instance):
        """"""
        # we iterate throught registered preference models in order to get the instance class
        # and check if instance is and instance of this class
        for model, registry in self.items():
            try:
                instance_class = model._meta.get_field('instance').remote_field.model
                if isinstance(instance, instance_class):
                    return registry

            except FieldDoesNotExist:  # global preferences
                pass
        return None
918883
def get_model(sender, model_name, model_inst, model_info, model_config):
    
    MC = get_mc()
    if MC:
        model = MC.get((MC.c.model_name==model_name) & (MC.c.uuid!=''))
        if model:
            cached_inst = __cache__.get(model_name)
            if not cached_inst or (cached_inst and cached_inst[1]!=model.uuid):
                model_inst = model.get_instance()
                M = orm.create_model(model_name, fields=eval(model_inst.fields or '[]'),
                                     indexes=eval(model_inst.indexes or '[]'),
                                     basemodel=model_inst.basemodel,
                                     __replace__=True)
                __cache__[model_name] = (M, model.uuid)

                #process extension model
                if model_inst.has_extension:
                    ext_model_name = model_name + '_extension'
                    fields = eval(model_inst.extension_fields or '[]')
                    fields.insert(0, {'name':'_parent', 'type':'OneToOne', 'reference_class':model_name, 'collection_name':'ext'})
                    ME = orm.create_model(ext_model_name, fields=fields,
                                          indexes=eval(model_inst.extension_indexes or '[]'),
                                          basemodel=model_inst.extension_model,
                                          __replace__=True)

            else:
                M = cached_inst[0]

            return M
804284
def registry(attr, base=type):
    """"""
    class Registry(base):
        def __init__(cls, name, bases, attrs):
            super(Registry, cls).__init__(name, bases, attrs)
            if not hasattr(cls, '__registry__'):
                cls.__registry__ = {}
            key = getattr(cls, attr)
            if key is not NotImplemented:
                assert key not in cls.__registry__
                cls.__registry__[key] = cls
        def __dispatch__(cls, key):
            try:
                return cls.__registry__[key]
            except KeyError:
                raise ValueError('Unknown %s: %s' % (attr, key))
    return Registry
526027
def all(self):
        
        if not preferences_settings.ENABLE_CACHE:
            return self.load_from_db()

        preferences = self.registry.preferences()

        # first we hit the cache once for all existing preferences
        a = self.many_from_cache(preferences)
        if len(a) == len(preferences):
            return a  # avoid database hit if not necessary

        # then we fill those that miss, but exist in the database
        # (just hit the database for all of them, filtering is complicated, and
        # in most cases you'd need to grab the majority of them anyway)
        a.update(self.load_from_db(cache=True))
        return a
1085557
def register(name=''):
    ""
    def reg(widget):
        """A decorator registering a widget class in the widget registry."""
        w = widget.class_traits()
        Widget.widget_types.register(w['_model_module'].default_value,
                                    w['_model_module_version'].default_value,
                                    w['_model_name'].default_value,
                                    w['_view_module'].default_value,
                                    w['_view_module_version'].default_value,
                                    w['_view_name'].default_value,
                                    widget)
        return widget
    if isinstance(name, string_types):
        import warnings
        warnings.warn("Widget registration using a string name has been deprecated. Widget registration now uses a plain `@register` decorator.", DeprecationWarning)
        return reg
    else:
        return reg(name)
700524
def _get_metadata_model(name=None):
    """"""
    if name is not None:
        try:
            return registry[name]
        except KeyError:
            if len(registry) == 1:
                valid_names = 'Try using the name "%s" or simply leaving it '\
                              'out altogether.' % list(registry)[0]
            else:
                valid_names = "Valid names are " + ", ".join(
                    '"%s"' % k for k in list(registry))
            raise Exception(
                "Metadata definition with name \"%s\" does not exist.\n%s" % (
                    name, valid_names))
    else:
        assert len(registry) == 1, \
            "You must have exactly one Metadata class, if using " \
            "get_metadata() without a 'name' parameter."
        return list(registry.values())[0]
830098
def _find_adapter(registry, ob):
    """"""
    types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob))))
    for t in types:
        if t in registry:
            return registry[t]
460299
def _get_model_objs_to_sync(model_ids_to_sync, model_objs_map, sync_all):
    
    model_objs_to_sync = {}
    for ctype, model_ids_to_sync_for_ctype in model_ids_to_sync.items():
        model_qset = entity_registry.entity_registry.get(ctype.model_class()).queryset

        if not sync_all:
            model_objs_to_sync[ctype] = model_qset.filter(id__in=model_ids_to_sync_for_ctype)
        else:
            model_objs_to_sync[ctype] = [
                model_objs_map[ctype, model_id] for model_id in model_ids_to_sync_for_ctype
            ]

    return model_objs_to_sync
712308
def get(self, *args, **kwargs):
        """"""
        assert not args
        assert list(kwargs.keys()) == ['pk']
        pk = kwargs['pk']
        model_name = self.model.__name__
        object_spec = (model_name, pk, None)
        instances = self.cache.get_instances((object_spec,))
        try:
            model_data = instances[(model_name, pk)][0]
        except KeyError:
            raise self.model.DoesNotExist(
                "No match for %r with args %r, kwargs %r" %
                (self.model, args, kwargs))
        else:
            return CachedModel(self.model, model_data)
817580
def safe_get_user_model():
    
    user_app, user_model = settings.AUTH_USER_MODEL.split('.')
    return apps.get_registered_model(user_app, user_model)
192937
def choice_default_loader(self, pk):
        """"""
        try:
            obj = Choice.objects.get(pk=pk)
        except Choice.DoesNotExist:
            return None
        else:
            self.choice_default_add_related_pks(obj)
            return obj
1127497
function(options) {
  var r = null;
  if (options.readPreference) {
    r = options.readPreference;
  } else {
    return options;
  }

  if (typeof r === 'string') {
    options.readPreference = new ReadPreference(r);
  } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') {
    const mode = r.mode || r.preference;
    if (mode && typeof mode === 'string') {
      options.readPreference = new ReadPreference(mode, r.tags, {
        maxStalenessSeconds: r.maxStalenessSeconds
      });
    }
  } else if (!(r instanceof ReadPreference)) {
    throw new TypeError('Invalid read preference: ' + r);
  }

  return options;
}
359640
def user_preference_form_builder(instance, preferences=[], **kwargs):
    
    return preference_form_builder(
        UserPreferenceForm,
        preferences,
        model={'instance': instance},
        **kwargs)
893188
def register(self, preference_class):
        
        preference = preference_class(registry=self)
        self.section_objects[preference.section.name] = preference.section

        try:
            self[preference.section.name][preference.name] = preference

        except KeyError:
            self[preference.section.name] = collections.OrderedDict()
            self[preference.section.name][preference.name] = preference

        return preference_class
1299031
def update_settings(instance_id, settings)
      params = {
        :instance_id => instance_id
      }

      instance = Models::RegistryInstance[params] || Models::RegistryInstance.new(params)
      instance.settings = settings
      instance.save
    end
928841
def get_services(cls, request=None):
        
        return {service['name']: reverse(service['list_view'], request=request)
                for service in cls._registry.values()}
1085391
def preferences_class_prepared(sender, *args, **kwargs):
    
    cls = sender
    if issubclass(cls, Preferences):
        # Add singleton manager to subclasses.
        cls.add_to_class('singleton', SingletonManager())
        # Add property for preferences object to preferences.preferences.
        setattr(preferences.Preferences, cls._meta.object_name, property(lambda x: cls.singleton.get()))