Convert a value stored in the database for a particular setting
        to its correct type, as determined by ``register_setting()``.
543023
def _to_python(cls, setting, raw_value):
        

        type_fn = cls.TYPE_FUNCTIONS.get(setting["type"], setting["type"])

        try:
            value = type_fn(raw_value)
        except ValueError:
            # Shouldn't occur, but just a safeguard in case
            # the db value somehow ended up as an invalid type.
            warn("The setting %s should be of type %s, but the value "
                 "retrieved from the database (%s) could not be converted. "
                 "Using the default instead: %s"
                 % (setting["name"], setting["type"].__name__,
                    repr(raw_value), repr(setting["default"])))
            value = setting["default"]

        return value
581486
def convert(self, key, value):
        """"""
        if key not in self._dtypes:
            self.read_types()
            if key not in self._dtypes:
                name = utils.name(value)
                serializer = utils.serializer(name)
                deserializer = utils.deserializer(name)
                self._dtypes[key] = (name, serializer, deserializer)
                with self.db:
                    self.db.execute("replace into value_types (key, value_type) values (?, ?)", (key, name))
        return self._dtypes[key][1](value)
1173296
def dbclass(self, value):
        

        if not is_valid_dbclass(value):
            raise AttributeError("'{}' is not a valid database type".format(value))

        self._class = value
        self._connectionXML.set('class', value)
321617
def convert_to_database_compatible_value(value):
    
    if pd.isnull(value):
        return None
    if isinstance(value, pd.Timestamp):
        return value.to_pydatetime()
    try:
        return value.item()
    except AttributeError:
        return value
455608
def _validate_none_or_type(t):
    
    def _validate(setting):
        """
        Check the setting to make sure it's the right type.

        Args:
            setting (object): The setting to check.

        Returns:
            object: The unmodified object if it's the proper type.

        Raises:
            ValueError: If the setting is the wrong type.
        """
        if setting is not None and not isinstance(setting, t):
            raise ValueError('"{}" is not "{}"'.format(setting, t))
        return setting
    return _validate
1158775
def type_to_sql(type, limit = nil, precision = nil, scale = nil) #:nodoc:
      return super unless type == :integer

      native = native_database_types[type.to_s.downcase.to_sym]
      native.is_a?(Hash) ? native[:name] : native
    end
693800
def value_to_db(self, value):
        
        assert isinstance(value, six.integer_types)
        return str(value).encode("utf_8")
389729
def dbStore(self, typ, py_value, context=None):
        
        if py_value is None:
            return None
        return self.valueToString(py_value, context=context)
593045
def _cast_to_type(self, value):
        
        try:
            return float(value)
        except (ValueError, TypeError):
            self.fail('invalid', value=value)
1054898
def convert_field_value(type_, value):
    """"""
    if value == ".":
        return None
    elif type_ in ("Character", "String"):
        if "%" in value:
            for k, v in record.UNESCAPE_MAPPING:
                value = value.replace(k, v)
        return value
    else:
        try:
            return _CONVERTERS[type_](value)
        except ValueError:
            warnings.warn(
                ("{} cannot be converted to {}, keeping as " "string.").format(value, type_),
                CannotConvertValue,
            )
            return value
235013
def normalize(value, default=None, type=None, raise_exception=False):
    
    NUMBER_RE = re.compile('^[-+]?(([0-9]+\.?[0-9]*)|([0-9]*\.?[0-9]+))$')
    if type is None and default is None:
        type = unicode_type
    elif type is None:
        type = type_(default)
    if type in str_types:
        if value is not None:
            if isinstance(value, unicode_type):
                return value
            elif py3 and isinstance(value, bytes_type):
                return value.decode('utf-8')
            return unicode_type(value)
        if default is None:
            if raise_exception:
                raise ValidationError('invalid string')
            else:
                return unicode_type()
    elif type in (bool, 'bool', 'boolean'):
        if value is not None:
            value = value.lower().strip()
            if value in ('1', 'true', 'yes', 'on'):
                return True
            elif value in ('0', 'false', 'no', 'off'):
                return False
        if default is None:
            if raise_exception:
                raise ValidationError('invalid boolean')
            else:
                return False
    elif type in (numbers.Number, 'number'):
        if value is not None:
            if value.isdigit():
                return int(value)
            elif NUMBER_RE.match(value):
                return eval(value)
        if default is None:
            if raise_exception:
                raise ValidationError('invalid number')
            else:
                return 0
    elif type in (int, 'int', 'integer'):
        try:
            return int(value)
        except Exception:
            if isinstance(value, basestring_type) and NUMBER_RE.match(value):
                return int(eval(value))
            if default is None:
                if raise_exception:
                    raise ValidationError('invalid number')
                else:
                    return 0
    elif type in (float, 'float'):
        if value is not None and NUMBER_RE.match(value):
            return float(value)
        if default is None:
            if raise_exception:
                raise ValidationError('invalid number')
            else:
                return 0.0
    return default
1140461
def _python_type(self, key, value):
        """"""
        try:
            field_type = self._sp_cols[key]['type']
            if field_type in ['Number', 'Currency']:
                return float(value)
            elif field_type == 'DateTime':


                # Need to remove the '123;#' from created dates, but we will do it for all dates
                # self.date_format = re.compile('\d+-\d+-\d+ \d+:\d+:\d+')
                value = self.date_format.search(value).group(0)
                
                # NOTE: I used to round this just date (7/28/2018)
                return datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
            elif field_type == 'Boolean':
                if value == '1':
                    return 'Yes'
                elif value == '0':
                    return 'No'
                else:
                    return ''
            elif field_type in ('User', 'UserMulti'):
                # Sometimes the User no longer exists or
                # has a diffrent ID number so we just remove the "123;#"
                # from the beginning of their name
                if value in self.users['sp']:
                    return self.users['sp'][value]
                elif '#' in value:
                    return value.split('#')[1]
                else:
                    return value
            else:
                return value
        except AttributeError:
            return value
1152241
def get_kind(self, value):
        """"""
        if isinstance(value, float):
            return 'f'
        elif isinstance(value, int):
            return 'i'
        else:
            raise ValueError("Only integer or floating point values can be stored.")
59609
function mapFieldTypeToBindType($field_type)
    {
        switch ($field_type) {
        case MYSQLI_TYPE_DECIMAL:
        case MYSQLI_TYPE_NEWDECIMAL:
        case MYSQLI_TYPE_FLOAT:
        case MYSQLI_TYPE_DOUBLE:
        case MYSQLI_TYPE_BIT:
        case MYSQLI_TYPE_TINY:
        case MYSQLI_TYPE_SHORT:
        case MYSQLI_TYPE_LONG:
        case MYSQLI_TYPE_LONGLONG:
        case MYSQLI_TYPE_INT24:
        case MYSQLI_TYPE_YEAR:
        case MYSQLI_TYPE_ENUM:
            return 'number';

        case MYSQLI_TYPE_DATE:
            return 'date';

        case MYSQLI_TYPE_TIME:
            return 'time';
        case MYSQLI_TYPE_TIMESTAMP:
        case MYSQLI_TYPE_DATETIME:
        case MYSQLI_TYPE_NEWDATE:
            return 'datetime';
        
        case MYSQLI_TYPE_VAR_STRING:
        case MYSQLI_TYPE_STRING:
        case MYSQLI_TYPE_CHAR:
        case MYSQLI_TYPE_GEOMETRY:
        case MYSQLI_TYPE_TINY_BLOB:
        case MYSQLI_TYPE_MEDIUM_BLOB:
        case MYSQLI_TYPE_LONG_BLOB:
        case MYSQLI_TYPE_BLOB:
            return 'string';

        default:
            return 'unknown';
        }
    }
939276
def _safe_type(value):
    """"""

    if type(value) is str: dtype = 'string'
    if type(value) is unicode: dtype = 'string'
    if type(value) is int: dtype = 'integer'
    if type(value) is float: dtype = 'real'

    return dtype
164655
def _coerce_type(self, field_type, value):
        
        if value is None:
            return None
        if field_type == 'string':
            return str(value)
        elif field_type == 'text':
            return str(value)
        elif field_type == 'int':
            try:
                v = int(value)
                return str(v)
            except:
                return None
        elif field_type == 'float':
            try:
                v = float(value)
                return str(v)
            except:
                return None
        elif field_type == 'date':
            try:
                v = datetime.datetime(
                    value['year'],
                    value['month'],
                    value['day'],
                    value['hour'],
                    value['minute'],
                    value['second'],
                )
                v = v.strftime('%Y-%m-%dT%H:%M:%S.0Z')
                return v
            except:
                return None
        return str(value)
564537
def PythonTypeFromMetricValueType(value_type):
  """"""
  if value_type == rdf_stats.MetricMetadata.ValueType.INT:
    return int
  elif value_type == rdf_stats.MetricMetadata.ValueType.FLOAT:
    return float
  else:
    raise ValueError("Unknown value type: %s" % value_type)