Set field internal value from the python representation of field value
960400
def set_python(self, value):
        """"""
        
        # hook exists to stringify before validation

        # set to string if not string or unicode
        if value is not None and not isinstance(value, self.supported_types) or isinstance(value, int):
            value = str(value)
        return super(TextField, self).set_python(value)
1197551
def to_internal_value_single(self, data, serializer):
        """"""
        related_model = serializer.Meta.model
        if isinstance(data, related_model):
            return data
        try:
            instance = related_model.objects.get(pk=data)
        except related_model.DoesNotExist:
            raise ValidationError(
                "Invalid value for '%s': %s object with ID=%s not found" %
                (self.field_name, related_model.__name__, data)
            )
        return instance
635543
def _set_field(self, fieldname, bytestring, transfunc=None):
        """"""
        if getattr(self, fieldname):  # do not overwrite existing data
            return
        value = bytestring if transfunc is None else transfunc(bytestring)
        if DEBUG:
            stderr('Setting field "%s" to "%s"' % (fieldname, value))
        if fieldname == 'genre' and value.isdigit() and int(value) < len(ID3.ID3V1_GENRES):
            # funky: id3v1 genre hidden in a id3v2 field
            value = ID3.ID3V1_GENRES[int(value)]
        if fieldname in ("track", "disc"):
            if type(value).__name__ in ('str', 'unicode') and '/' in value:
                current, total = value.split('/')[:2]
                setattr(self, "%s_total" % fieldname, total)
            else:
                current = value
            setattr(self, fieldname, current)
        else:
            setattr(self, fieldname, value)
794593
def to_python(self, value):
        """"""
        if isinstance(value, FileDescriptor):
            return value
        elif isinstance(value, str):
            return FileDescriptor(value)
        elif isinstance(value, dict):
            try:
                path = value['file']
            except KeyError:
                raise ValidationError("dictionary must contain a 'file' element")

            if not isinstance(path, str):
                raise ValidationError("field's file element must be a string")

            size = value.get('size', None)
            if size is not None and not isinstance(size, int):
                raise ValidationError("field's size element must be an integer")

            total_size = value.get('total_size', None)
            if total_size is not None and not isinstance(total_size, int):
                raise ValidationError("field's total_size element must be an integer")

            is_remote = value.get('is_remote', None)
            if is_remote is not None and not isinstance(is_remote, bool):
                raise ValidationError("field's is_remote element must be a boolean")

            file_temp = value.get('file_temp', None)
            if file_temp is not None and not isinstance(file_temp, str):
                raise ValidationError("field's file_temp element must be a string")

            refs = value.get('refs', None)
            if refs is not None and not isinstance(refs, list):
                # TODO: Validate that all refs are strings.
                raise ValidationError("field's refs element must be a list of strings")

            return FileDescriptor(
                path,
                size=size,
                total_size=total_size,
                is_remote=is_remote,
                file_temp=file_temp,
                refs=refs,
            )
        elif not isinstance(value, None):
            raise ValidationError("field must be a FileDescriptor, string or a dict")
273474
def set_value(self, obj, value):
        """"""
        if value:
            obj.set_field_value(self.name, value)
        else:
            self.delete_value(obj)
311368
def to_internal_value(self, data):
        """"""
        # When setting the contributor, it may be passed as an integer.
        if isinstance(data, dict) and isinstance(data.get('id', None), int):
            data = data['id']
        elif isinstance(data, int):
            pass
        else:
            raise ValidationError("Contributor must be an integer or a dictionary with key 'id'")

        return self.Meta.model.objects.get(pk=data)
1108907
def _set_values(self):
        
        # Iterate all keys and values in data
        for k, v in self._data.items():
            # If it's a dict, process it (it's probably instance data)
            if isinstance(v, dict):
                try:
                    # Get related model from field (follow path)
                    rel_model = self._model
                    for attr in k.split('__'):
                        rel_model = getattr(rel_model, attr).field.related_model

                except AttributeError:
                    # Not a model, maybe it is a dict field (?)
                    pass

                else:
                    # Model, first shorten field name
                    k = k.replace('__', '_')

                    # Now init instance if required (not if we got ID None)
                    if 'id' in v and v['id'] is None:
                        # This means we grouped by ID, if it's none then FK is None
                        v = None

                    else:
                        # Either we have ID or we didn't group by ID, use instance
                        v = rel_model(**v)

            # Set value
            setattr(self, k, v)
421802
void setFieldValue(final Object containingObj, final Object value) {
        try {
            if (value == null) {
                if (primitiveType != PrimitiveType.NON_PRIMITIVE) {
                    throw new IllegalArgumentException("Tried to set primitive-typed field "
                            + field.getDeclaringClass().getName() + "." + field.getName() + " to null value");
                }
                field.set(containingObj, null);
                return;
            }
            switch (primitiveType) {
            case NON_PRIMITIVE:
                field.set(containingObj, value);
                break;
            case INTEGER:
                if (!(value instanceof Integer)) {
                    throw new IllegalArgumentException(
                            "Expected value of type Integer; got " + value.getClass().getName());
                }
                field.setInt(containingObj, (Integer) value);
                break;
            case LONG:
                if (!(value instanceof Long)) {
                    throw new IllegalArgumentException(
                            "Expected value of type Long; got " + value.getClass().getName());
                }
                field.setLong(containingObj, (Long) value);
                break;
            case SHORT:
                if (!(value instanceof Short)) {
                    throw new IllegalArgumentException(
                            "Expected value of type Short; got " + value.getClass().getName());
                }
                field.setShort(containingObj, (Short) value);
                break;
            case DOUBLE:
                if (!(value instanceof Double)) {
                    throw new IllegalArgumentException(
                            "Expected value of type Double; got " + value.getClass().getName());
                }
                field.setDouble(containingObj, (Double) value);
                break;
            case FLOAT:
                if (!(value instanceof Float)) {
                    throw new IllegalArgumentException(
                            "Expected value of type Float; got " + value.getClass().getName());
                }
                field.setFloat(containingObj, (Float) value);
                break;
            case BOOLEAN:
                if (!(value instanceof Boolean)) {
                    throw new IllegalArgumentException(
                            "Expected value of type Boolean; got " + value.getClass().getName());
                }
                field.setBoolean(containingObj, (Boolean) value);
                break;
            case BYTE:
                if (!(value instanceof Byte)) {
                    throw new IllegalArgumentException(
                            "Expected value of type Byte; got " + value.getClass().getName());
                }
                field.setByte(containingObj, (Byte) value);
                break;
            case CHARACTER:
                if (!(value instanceof Character)) {
                    throw new IllegalArgumentException(
                            "Expected value of type Character; got " + value.getClass().getName());
                }
                field.setChar(containingObj, (Character) value);
                break;
            default:
                throw new IllegalArgumentException();
            }
        } catch (IllegalArgumentException | IllegalAccessException e) {
            throw new IllegalArgumentException(
                    "Could not set field " + field.getDeclaringClass().getName() + "." + field.getName(), e);
        }
    }
713718
def to_internal_value(self, data):
        
        converted_data = _convert_template_id_to_dict(data)
        return super(TemplateSerializer, self)\
            .to_internal_value(converted_data)
966336
def set(self, value):
        

        if not isinstance(value, str_cls):
            raise TypeError(unwrap(
                '''
                %s value must be a unicode string, not %s
                ''',
                type_name(self),
                type_name(value)
            ))

        self._unicode = value
        self.contents = value.encode(self._encoding)
        self._header = None
        if self._indefinite:
            self._indefinite = False
            self.method = 0
        if self._trailer != b'':
            self._trailer = b''
317223
def set(self, value):
        

        if not isinstance(value, int_types) and not isinstance(value, str_cls):
            raise TypeError(unwrap(
                '''
                %s value must be an integer or a unicode string, not %s
                ''',
                type_name(self),
                type_name(value)
            ))

        if isinstance(value, str_cls):
            if value not in self._reverse_map:
                raise ValueError(unwrap(
                    '''
                    %s value "%s" is not a valid value
                    ''',
                    type_name(self),
                    value
                ))

            value = self._reverse_map[value]

        elif value not in self._map:
            raise ValueError(unwrap(
                '''
                %s value %s is not a valid value
                ''',
                type_name(self),
                value
            ))

        Integer.set(self, value)
320413
def _convert_to_internal(self, data):
        """'"""
        for _dict in data:
            keys = list(_dict.keys())[:]
            for key in keys:
                if key not in self._disp_cols:
                    raise Exception(key + ' not a column in current List.')
                _dict[self._disp_cols[key]['name']] = self._sp_type(key, _dict.pop(key))
1135071
def from_dict(self, value):
        
        for key in self.keys():
            setattr(self, key, value.get(key, None))
1254117
def _setField(self, value, field, check=1):
        """"""
        try:
            # expand field name using minimum match
            field = _setFieldDict[field]
        except KeyError as e:
            raise SyntaxError("Cannot set field " + field +
                    " for parameter " + self.name + "\n" + str(e))
        if field == "p_prompt":
            self.prompt = irafutils.removeEscapes(irafutils.stripQuotes(value))
        elif field == "p_value":
            self.set(value,check=check)
        elif field == "p_filename":
            # this is only relevant for list parameters (*imcur, *gcur, etc.)
            self.set(value,check=check)
        elif field == "p_scope":
            self.scope = value
        elif field == "p_maximum":
            self.max = self._coerceOneValue(value)
        elif field == "p_minimum":
            if isinstance(value,str) and '|' in value:
                self._setChoice(irafutils.stripQuotes(value))
            else:
                self.min = self._coerceOneValue(value)
        elif field == "p_mode":
            # not doing any type or value checking here -- setting mode is
            # rare, so assume that it is being done correctly
            self.mode = irafutils.stripQuotes(value)
        else:
            raise RuntimeError("Program bug in IrafPar._setField()" +
                    "Requested field " + field + " for parameter " + self.name)
268164
def _set_fields(self, fields):
        """"""
        for f in fields:
            if hasattr(self, f):
                setattr(self, f, fields[f])
            else:
                raise TypeError("'{arg}' is an invalid argument for {instance_type}".format(arg=f, instance_type=self.__class__.__name__))
250136
def _set_field_if_present(cls, block, name, value, attrs):
        """"""
        if name in block.fields:
            value = (block.fields[name]).from_string(value)
            if "none" in attrs and attrs["none"] == "true":
                setattr(block, name, None)
            else:
                setattr(block, name, value)
        else:
            logging.warning("XBlock %s does not contain field %s", type(block), name)
905378
def to_internal_value(self, data):
        
        data = smart_text(data).strip()
        if len(data) > self.MAX_STRING_LENGTH:
            self.fail('max_string_length')

        try:
            value = decimal.Decimal(data)
        except decimal.DecimalException:
            self.fail('invalid')

        # Check for NaN. It is the only value that isn't equal to itself,
        # so we can use this to identify NaN values.
        if value != value:
            self.fail('invalid')

        # Check for infinity and negative infinity.
        if value in (decimal.Decimal('Inf'), decimal.Decimal('-Inf')):
            self.fail('invalid')

        return self.validate_precision(value)