inverse of getParam function
        :param kwargs_lens: keyword arguments depending on model options
        :param kwargs_source: keyword arguments depending on model options
        :return: tuple of parameters
428590
def kwargs2args(self, kwargs_lens=None, kwargs_source=None, kwargs_lens_light=None, kwargs_ps=None, kwargs_cosmo=None):
        

        args = self.lensParams.setParams(kwargs_lens)
        args += self.souceParams.setParams(kwargs_source)
        args += self.lensLightParams.setParams(kwargs_lens_light)
        args += self.pointSourceParams.setParams(kwargs_ps)
        args += self.cosmoParams.setParams(kwargs_cosmo)
        return args
326223
def get_by_natural_key(self, *args):
        

        kwargs = self.natural_key_kwargs(*args)

        # Since kwargs already has __ lookups in it, we could just do this:
        # return self.get(**kwargs)

        # But, we should call each related model's get_by_natural_key in case
        # it's been overridden
        for name, rel_to in self.model.get_natural_key_info():
            if not rel_to:
                continue

            # Extract natural key for related object
            nested_key = extract_nested_key(kwargs, rel_to, name)
            if nested_key:
                # Update kwargs with related object
                try:
                    kwargs[name] = rel_to.objects.get_by_natural_key(
                        *nested_key
                    )
                except rel_to.DoesNotExist:
                    # If related object doesn't exist, assume this one doesn't
                    raise self.model.DoesNotExist()
            else:
                kwargs[name] = None

        return self.get(**kwargs)
151563
def view_getattr():
    

    def view_getattr(_value, context, **_params):
        value = getattr(context["view"], context["key"])
        return _attr(value)

    return view_getattr
112087
def parameters_from_model(parameters_model):
        
        parameters = {}
        for p in parameters_model:
            if p.is_function:
                code, defaults, closure = pickle.loads(p.value)
                parameters[p.key] = func_load(code, defaults, closure, globs=globals())
            elif p.is_set:
                parameters[p.key] = set(p.value)
            else:
                parameters[p.key] = p.value
        return parameters
52384
def get_or_create(self, **kwargs):
        
        assert kwargs, \
                'get_or_create() must be passed at least one keyword argument'
        defaults = kwargs.pop('defaults', {})
        lookup = kwargs.copy()
        #TODO: check fields
        try:
            return self.get(**lookup), False
        except self.model.DoesNotExist:
            params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
            params.update(defaults)
            obj = self.model(**params)
            meta = obj.get_meta()
            meta.connection = get_es_connection(self.es_url, self.es_kwargs)
            meta.index=self.index
            meta.type=self.type
            obj.save(force=True)
            return obj, True
1301510
def _extract_array(self, kwargs_list):
        
        if self._solver_type == 'PROFILE_SHEAR':
            e1 = kwargs_list[1]['e1']
            e2 = kwargs_list[1]['e2']
            phi_ext, gamma_ext = param_util.ellipticity2phi_gamma(e1, e2)
        else:
            phi_ext = 0
        lens_model = self._lens_mode_list[0]
        if lens_model in ['SPEP', 'SPEMD', 'SIE', 'NIE']:
            e1 = kwargs_list[0]['e1']
            e2 = kwargs_list[0]['e2']
            center_x = kwargs_list[0]['center_x']
            center_y = kwargs_list[0]['center_y']
            theta_E = kwargs_list[0]['theta_E']
            x = [theta_E, e1, e2, center_x, center_y, phi_ext]
        elif lens_model in ['NFW_ELLIPSE']:
            e1 = kwargs_list[0]['e1']
            e2 = kwargs_list[0]['e2']
            center_x = kwargs_list[0]['center_x']
            center_y = kwargs_list[0]['center_y']
            theta_Rs = kwargs_list[0]['theta_Rs']
            x = [theta_Rs, e1, e2, center_x, center_y, phi_ext]
        elif lens_model in ['SHAPELETS_CART']:
            coeffs = list(kwargs_list[0]['coeffs'])
            [c10, c01, c20, c11, c02] = coeffs[1: 6]
            x = [c10, c01, c20, c11, c02, phi_ext]
        else:
            raise ValueError("Lens model %s not supported for 4-point solver!" % lens_model)
        return x
1186199
def _lens_light_internal(self, x_grid, y_grid, kwargs_lens_light, model_bool_list=None):
        
        if model_bool_list is None:
            model_bool_list = [True] * len(kwargs_lens_light)
        lens_light = np.zeros_like(x_grid)
        for i, bool in enumerate(model_bool_list):
            if bool is True:
                lens_light_i = self.LensLightModel.surface_brightness(x_grid, y_grid, kwargs_lens_light, k=i)
                lens_light += lens_light_i
        return lens_light
1254137
def value_getattr():
    

    def value_getattr(value, context, **_params):
        value = getattr(value, context["key"])
        return _attr(value)

    return source_getattr
648206
def _getattr (self, fieldname, raw=False, index=None):
        
        self._assertField(fieldname)
        value = None

        if fieldname == 'raw':
            value = createRawPacket(self)
        elif fieldname == 'history':
            value = self._defn.history
        else:
            if fieldname in self._defn.derivationmap:
                defn = self._defn.derivationmap[fieldname]
            else:
                defn = self._defn.fieldmap[fieldname]

            if isinstance(defn.type, dtype.ArrayType) and index is None:
                return createFieldList(self, defn, raw)

            if defn.when is None or defn.when.eval(self):
                if isinstance(defn, DerivationDefinition):
                    value = defn.equation.eval(self)
                elif raw or (defn.dntoeu is None and defn.expr is None):
                    value = defn.decode(self._data, raw, index)
                elif defn.dntoeu is not None:
                    value = defn.dntoeu.eval(self)
                elif defn.expr is not None:
                    value = defn.expr.eval(self)

        return value
1312174
def effectiv_num_data_points(self, kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps):
        
        num_linear = 0
        if self._image_likelihood is True:
            num_linear = self.image_likelihood.num_param_linear(kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps)
        num_param, _ = self.param.num_param()
        return self.num_data - num_param - num_linear
325926
def get_field_kwargs(self, field_name, model_field):
        
        kwargs = {}
        validator_kwarg = list(model_field.validators)

        # The following will only be used by ModelField classes.
        # Gets removed for everything else.
        kwargs['model_field'] = model_field

        if model_field.verbose_name and needs_label(model_field, field_name):
            kwargs['label'] = capfirst(model_field.verbose_name)

        if model_field.help_text:
            kwargs['help_text'] = model_field.help_text

        max_digits = getattr(model_field, 'max_digits', None)
        if max_digits is not None:
            kwargs['max_digits'] = max_digits

        decimal_places = getattr(model_field, 'decimal_places', None)
        if decimal_places is not None:
            kwargs['decimal_places'] = decimal_places

        if isinstance(model_field, models.TextField):
            kwargs['style'] = {'base_template': 'textarea.html'}

        if isinstance(model_field, models.AutoField) \
                or not model_field.editable:
            # If this field is read-only, then return early.
            # Further keyword arguments are not valid.
            kwargs['read_only'] = True
            return kwargs

        if model_field.has_default or model_field.blank or model_field.null:
            kwargs['required'] = False

        if model_field.null and not isinstance(model_field,
                                               models.NullBooleanField):
            kwargs['allow_null'] = True

        if model_field.blank and (
            isinstance(model_field, models.CharField) or
            isinstance(model_field, models.TextField) or
            isinstance(model_field, columns.Text)
        ):
            kwargs['allow_blank'] = True

        if isinstance(model_field, models.FilePathField):
            kwargs['path'] = model_field.path

            if model_field.match is not None:
                kwargs['match'] = model_field.match

            if model_field.recursive is not False:
                kwargs['recursive'] = model_field.recursive

            if model_field.allow_files is not True:
                kwargs['allow_files'] = model_field.allow_files

            if model_field.allow_folders is not False:
                kwargs['allow_folders'] = model_field.allow_folders

        if model_field.choices:
            # If this model field contains choices, then return early.
            # Further keyword arguments are not valid.
            kwargs['choices'] = model_field.choices
            return kwargs

        # Our decimal validation is handled in the field code,
        # not validator code.
        # (In Django 1.9+ this differs from previous style)
        if isinstance(model_field, models.DecimalField) and DecimalValidator:
            validator_kwarg = [
                validator for validator in validator_kwarg
                if not isinstance(validator, DecimalValidator)
            ]

        # Ensure that max_length is passed explicitly as a keyword arg,
        # rather than as a validator.
        max_length = getattr(model_field, 'max_length', None)
        if max_length is not None and (
                    isinstance(model_field, models.CharField) or
                    isinstance(model_field, models.TextField)):
            kwargs['max_length'] = max_length
            validator_kwarg = [
                validator for validator in validator_kwarg
                if not isinstance(validator, validators.MaxLengthValidator)
            ]

        # Ensure that min_length is passed explicitly as a keyword arg,
        # rather than as a validator.
        min_length = next((
            validator.limit_value for validator in validator_kwarg
            if isinstance(validator, validators.MinLengthValidator)
        ), None)
        if min_length is not None and isinstance(model_field,
                                                 models.CharField):
            kwargs['min_length'] = min_length
            validator_kwarg = [
                validator for validator in validator_kwarg
                if not isinstance(validator, validators.MinLengthValidator)
            ]

        # Ensure that max_value is passed explicitly as a keyword arg,
        # rather than as a validator.
        max_value = next((
            validator.limit_value for validator in validator_kwarg
            if isinstance(validator, validators.MaxValueValidator)
        ), None)
        if max_value is not None and isinstance(model_field,
                                                NUMERIC_FIELD_TYPES):
            kwargs['max_value'] = max_value
            validator_kwarg = [
                validator for validator in validator_kwarg
                if not isinstance(validator, validators.MaxValueValidator)
            ]

        # Ensure that max_value is passed explicitly as a keyword arg,
        # rather than as a validator.
        min_value = next((
            validator.limit_value for validator in validator_kwarg
            if isinstance(validator, validators.MinValueValidator)
        ), None)
        if min_value is not None and isinstance(model_field,
                                                NUMERIC_FIELD_TYPES):
            kwargs['min_value'] = min_value
            validator_kwarg = [
                validator for validator in validator_kwarg
                if not isinstance(validator, validators.MinValueValidator)
            ]

        # URLField does not need to include the URLValidator argument,
        # as it is explicitly added in.
        if isinstance(model_field, models.URLField):
            validator_kwarg = [
                validator for validator in validator_kwarg
                if not isinstance(validator, validators.URLValidator)
            ]

        # EmailField does not need to include the validate_email argument,
        # as it is explicitly added in.
        if isinstance(model_field, models.EmailField):
            validator_kwarg = [
                validator for validator in validator_kwarg
                if validator is not validators.validate_email
            ]

        # SlugField do not need to include the 'validate_slug' argument,
        if isinstance(model_field, models.SlugField):
            validator_kwarg = [
                validator for validator in validator_kwarg
                if validator is not validators.validate_slug
            ]

        # IPAddressField do not need to include the 'validate_ipv46_address'
        # argument,
        if isinstance(model_field, models.GenericIPAddressField):
            validator_kwarg = [
                validator for validator in validator_kwarg
                if validator is not validators.validate_ipv46_address
            ]

        if getattr(model_field, 'unique', False):
            warnings.warn(
                'UniqueValidator is currently not supported '
                'in DjangoCassandraSerializer'
            )

        if validator_kwarg:
            kwargs['validators'] = validator_kwarg

        return kwargs
266443
def params(**kwargs):
    

    # Types that we'll all for as 'tuple' params
    TUPLE_TYPES = tuple, set, frozenset, list
    if (sys.version_info > (3, 0)):
        VALID_TYPES = int, float, str, bool
    else:
        VALID_TYPES = int, float, str, unicode, bool

    class ParamValidator(object):
        # name
        param_name = None  # the name of the param in the request, e.g. 'user_id' (even if we pass 'user' to the Fn)

        # type
        param_type = None

        # method - explicitly allow a certain method. If both are false we'll use defaults
        allow_GET = False
        allow_POST = False

        # value validators
        gt = None
        gte = None
        lt = None
        lte = None
        eq = None

        # optional
        optional = False
        default = None

        # multiple vals
        many = False

        # django models only
        deferred = True
        field = 'id'

        def __init__(self, arg_name, **kwargs):
            self.param_name = arg_name
            for k, v in kwargs.items():
                setattr(self, k, v)

        def check_type(self, param):
            """ Check that the type of param is valid, or raise an Exception. This doesn't take self.many into account. """
            valid_type = True
            if isinstance(self.param_type, TUPLE_TYPES):
                if not param in self.param_type:
                    raise Exception('invalid option "%s": Must be one of: %s' % (param, self.param_type))
            else:
                if self.param_type == int:
                    param = int(param)
                elif self.param_type == float:
                    param = float(param)
                elif self.param_type == str:
                    assert(isinstance(param, (str, unicode)))
                    param = unicode(param)
                elif self.param_type == bool:
                    param = str(param).lower()  # bool isn't case sensitive
                    if param in TRUE_VALUES:
                        param = True
                    elif param in FALSE_VALUES:
                        param = False
                    else:
                        raise Exception('%s is not a valid bool: must be one of: %s', param, TRUE_VALUES + FALSE_VALUES)
                elif hasattr(self.param_type, '_default_manager'):  # isinstance(django.models.Model) doesn't seem to work, but this is a good tell
                    query_set = self.param_type.objects
                    if self.deferred:
                        query_set = query_set.only('id')
                    param = query_set.get(**{self.field: param})
                else:
                    valid_type = False
            if not valid_type:
                raise Exception("Invalid param type: %s" % self.param_type.____name__)
            return param

        def check_value(self, param):
            """ Check that a single value is lt/gt/etc. Doesn't take self.many into account. """
            val = None
            if self.param_type == int or self.param_type == float:
                val = param
            elif self.param_type == str:
                val = len(param)
            if val:
                try:
                    if self.eq and val != self.eq:
                        raise Exception("must be less than %s!" % self.eq)
                    else:
                        if self.lt and val >= self.lt:
                            raise Exception("must be less than %s!" % self.lt)
                        if self.lte and val > self.lte:
                            raise Exception("must be less than or equal to %s!" % self.lte)
                        if self.gt and val <= self.gt:
                            raise Exception("must be greater than %s!" % self.gt)
                        if self.gte and val < self.gte:
                            raise Exception("must be greater than or equal to %s!" % self.gte)
                except Exception as e:
                    msg = str(e)
                    msg = ("Length " if self.param_type == str else 'Value ') + msg
                    raise Exception(msg)

    validators = {}

    for k, v in kwargs.items():
        parts = k.split('__')
        param_key = parts[0]

        if not param_key in validators:
            validators[param_key] = ParamValidator(param_key)
        obj = validators[param_key]

        if (len(parts) == 1):
            # set type
            if not hasattr(v, '_default_manager'):  # django model
                if not isinstance(v, TUPLE_TYPES) and not v in VALID_TYPES:
                    raise Exception("Invalid type for %s: %s is not a valid type" % (k, v))
            obj.param_type = v
        else:
            # we only are interested in the last part, since the only thing that can be multipart is __length__eq (etc) and 'length' is not important
            last_part = parts[-1]

            if last_part == 'method':
                if isinstance(v, TUPLE_TYPES):
                    for method in v:
                        if method == 'GET':
                            obj.allow_GET = True
                        elif method == 'POST':
                            obj.allow_POST = True
                        else:
                            raise Exception('Invalid value for __method: "%s"' % method)
                else:
                    if v == 'GET':
                        obj.allow_GET = True
                    elif v == 'POST':
                        obj.allow_POST = True
                    else:
                        raise Exception('Invalid value for __method: "%s"' % v)
                continue

            if last_part == 'name':
                obj.param_name = v
                continue

            BOOL_PARTS = 'deferred', 'optional', 'many'
            if last_part in BOOL_PARTS:
                assert(isinstance(v, bool))
                setattr(obj, last_part, v)
                continue

            NUM_PARTS = 'gt', 'gte', 'lt', 'lte', 'eq'
            if last_part in NUM_PARTS:
                assert(isinstance(v, int) or isinstance(v, float))
                setattr(obj, last_part, v)
                continue

            if last_part == 'default':
                obj.optional = True
                obj.default = v
                continue

            if last_part == 'field':
                assert(isinstance(last_part, str))
                obj.field = v
                continue

            raise Exception("Invalid option: '__%s' in param '%s'" % (last_part, k))

    def _params(fn):

        @wraps(fn)
        def wrapped_request_fn(first_arg, *args, **kwargs):

            if len(args) == 0:
                request = first_arg  # request function is a top-level function
            else:
                request = args[0]  # request fn is a method, first_arg is 'self'

            request_method = request.META['REQUEST_METHOD']
            default_param_method = 'POST' if request_method == 'POST' or request_method == 'PUT' else 'GET'
            # Validate the params
            for arg_name, validator in validators.items():
                param_name = validator.param_name

                # what methods are allowed?
                use_default_methods = not validator.allow_GET and not validator.allow_POST
                allow_GET = (default_param_method == 'GET') if use_default_methods else validator.allow_GET
                allow_POST = (default_param_method == 'POST') if use_default_methods else validator.allow_POST

                # find the param
                param = None
                if allow_POST:
                    param = request.DATA.get(param_name, None)
                    param_type = 'POST'
                if not param and allow_GET:
                    param = request.GET.get(param_name, None)
                    param_type = 'GET'

                try:
                    # optional/default
                    if param is None:  # but not False, because that's a valid boolean param
                        if not validator.optional:
                            raise Exception('Param is missing')
                        else:
                            kwargs[arg_name] = validator.default
                            continue

                    # check type, value
                    if validator.many:
                        if param_type == 'GET':
                            params = str(param).split(',')
                        else:
                            params = param if isinstance(param, list) else (param,)
                        params = [validator.check_type(p) for p in params]
                        [validator.check_value(p) for p in params]
                    else:
                        param = validator.check_type(param)
                        validator.check_value(param)

                except Exception as e:
                    return Response({'error': 'Invalid param "%s": %s' % (param_name, str(e))}, status=status.HTTP_400_BAD_REQUEST)

                kwargs[arg_name] = params if validator.many else param

            return fn(first_arg, *args, **kwargs)
        return wrapped_request_fn
    return _params
1348538
def _get_model_fields(self, field_names, declared_fields, extra_kwargs):
        
        model = getattr(self.Meta, 'model')
        model_fields = {}

        for field_name in field_names:
            if field_name in declared_fields:
                # If the field is declared on the serializer
                field = declared_fields[field_name]
                source = field.source or field_name
            else:
                try:
                    source = extra_kwargs[field_name]['source']
                except KeyError:
                    source = field_name

            if '.' in source or source == '*':
                # Model fields will always have a simple source mapping,
                # they can't be nested attribute lookups.
                continue

            try:
                field = model._meta.get_field(source)
                if isinstance(field, DjangoModelField):
                    model_fields[source] = field
            except FieldDoesNotExist:
                pass

        return model_fields
543235
def get_object(self, view_name, view_args, view_kwargs):
        
        lookup_value = view_kwargs.get(self.lookup_url_kwarg)
        parent_lookup_value = view_kwargs.get(self.parent_lookup_field)
        lookup_kwargs = {
            self.lookup_field: lookup_value,
        }
        # Try to lookup parent attr
        if parent_lookup_value:
            lookup_kwargs.update({self.parent_lookup_field: parent_lookup_value})
        return self.get_queryset().get(**lookup_kwargs)
85171
def get_object(self, **kwargs) ->Model:
        
        queryset = self.filter_queryset(
            queryset=self.get_queryset(**kwargs),
            **kwargs
        )

        # Perform the lookup filtering.
        lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field

        assert lookup_url_kwarg in kwargs, (
                'Expected view %s to be called with a URL keyword argument '
                'named "%s". Fix your URL conf, or set the `.lookup_field` '
                'attribute on the view correctly.' %
                (self.__class__.__name__, lookup_url_kwarg)
        )

        filter_kwargs = {self.lookup_field: kwargs[lookup_url_kwarg]}

        obj = get_object_or_404(queryset, **filter_kwargs)
        # TODO check_object_permissions

        return obj
543123
def parameter(self):
        """"""
        D = {}
        for source in PARAM_SOURCE_ORDER:
            D.update(self.params[source])
        return D
1331178
def source_filter(method_name, *args, **kwargs):
    

    def source_filter(value, context, **_params):
        method = getattr(context["model"].source, method_name)
        return _filter(method, value, args, kwargs)

    return source_filter