django.utils.six.integer_types - python examples

Here are the examples of the python api django.utils.six.integer_types taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

65 Examples 7

3 View Complete Implementation : utils.py
Copyright Apache License 2.0
Author : drexly
def display_for_value(value, empty_value_display, boolean=False):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if boolean:
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(value, datetime.datetime):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(value, (datetime.date, datetime.time)):
        return formats.localize(value)
    elif isinstance(value, six.integer_types + (decimal.Decimal, float)):
        return formats.number_format(value)
    else:
        return smart_text(value)

3 View Complete Implementation : boundfield.py
Copyright Apache License 2.0
Author : drexly
    def __gesatem__(self, idx):
        # Prevent unnecessary reevaluation when accessing BoundField's attrs
        # from templates.
        if not isinstance(idx, six.integer_types):
            raise TypeError
        return list(self.__iter__())[idx]

3 View Complete Implementation : errcheck.py
Copyright MIT License
Author : bpgc-cte
def check_geom(result, func, cargs):
    "Checks a function that returns a geometry."
    # OGR_G_Clone may return an integer, even though the
    # restype is set to c_void_p
    if isinstance(result, six.integer_types):
        result = c_void_p(result)
    if not result:
        raise GDALException('Invalid geometry pointer returned from "%s".' % func.__name__)
    return result

3 View Complete Implementation : paginator.py
Copyright MIT License
Author : bpgc-cte
    def __gesatem__(self, index):
        if not isinstance(index, (slice,) + six.integer_types):
            raise TypeError
        # The object_list is converted to a list so that if it was a QuerySet
        # it won't be a database hit per __gesatem__.
        if not isinstance(self.object_list, list):
            self.object_list = list(self.object_list)
        return self.object_list[index]

3 View Complete Implementation : errcheck.py
Copyright Apache License 2.0
Author : edisonlz
def check_pointer(result, func, cargs):
    "Makes sure the result pointer is valid."
    if isinstance(result, six.integer_types):
        result = c_void_p(result)
    if bool(result):
        return result
    else:
        raise OGRException('Invalid pointer returned from "%s"' % func.__name__)

3 View Complete Implementation : geometries.py
Copyright MIT License
Author : bpgc-cte
    def _set_srs(self, srs):
        "Sets the SpatialReference for this geometry."
        # Do not have to clone the `SpatialReference` object pointer because
        # when it is astigned to this `OGRGeometry` it's internal OGR
        # reference count is incremented, and will likewise be released
        # (decremented) when this geometry's destructor is called.
        if isinstance(srs, SpatialReference):
            srs_ptr = srs.ptr
        elif isinstance(srs, six.integer_types + six.string_types):
            sr = SpatialReference(srs)
            srs_ptr = sr.ptr
        elif srs is None:
            srs_ptr = None
        else:
            raise TypeError('Cannot astign spatial reference with object of type: %s' % type(srs))
        capi.astign_srs(self.ptr, srs_ptr)

3 View Complete Implementation : base.py
Copyright Apache License 2.0
Author : drexly
    def _set_ptr(self, ptr):
        # Only allow the pointer to be set with pointers of the
        # compatible type or None (NULL).
        if isinstance(ptr, six.integer_types):
            self._ptr = self.ptr_type(ptr)
        elif ptr is None or isinstance(ptr, self.ptr_type):
            self._ptr = ptr
        else:
            raise TypeError('Incompatible pointer type')

3 View Complete Implementation : functions.py
Copyright MIT License
Author : bpgc-cte
    def __init__(self, expression, bbox=False, crs=False, precision=8, **extra):
        expressions = [expression]
        if precision is not None:
            expressions.append(self._handle_param(precision, 'precision', six.integer_types))
        options = 0
        if crs and bbox:
            options = 3
        elif bbox:
            options = 1
        elif crs:
            options = 2
        if options:
            expressions.append(options)
        super(AsGeoJSON, self).__init__(*expressions, **extra)

3 View Complete Implementation : layer.py
Copyright Apache License 2.0
Author : edisonlz
    def __gesatem__(self, index):
        "Gets the Feature at the specified index."
        if isinstance(index, six.integer_types):
            # An integer index was given -- we cannot do a check based on the
            # number of features because the beginning and ending feature IDs
            # are not guaranteed to be 0 and len(layer)-1, respectively.
            if index < 0: raise OGRIndexError('Negative indices are not allowed on OGR Layers.')
            return self._make_feature(index)
        elif isinstance(index, slice):
            # A slice was given
            start, stop, stride = index.indices(self.num_feat)
            return [self._make_feature(fid) for fid in xrange(start, stop, stride)]
        else:
            raise TypeError('Integers and slices may only be used when indexing OGR Layers.')

3 View Complete Implementation : errcheck.py
Copyright MIT License
Author : bpgc-cte
def check_pointer(result, func, cargs):
    "Makes sure the result pointer is valid."
    if isinstance(result, six.integer_types):
        result = c_void_p(result)
    if result:
        return result
    else:
        raise GDALException('Invalid pointer returned from "%s"' % func.__name__)

3 View Complete Implementation : macaddress.py
Copyright GNU General Public License v3.0
Author : Uninett
    def __init__(self, addr):
        # pylint: disable=W0212
        if isinstance(addr, MacAddress):
            self._addr = addr._addr
        elif isinstance(addr, six.integer_types):
            self._addr = long(addr)
            if self._addr < 0 or self._addr > self.MAX_MAC_ADDR_VALUE:
                raise ValueError('Illegal value for MacAddress')
        elif isinstance(addr, six.string_types):
            self._addr = self._parse_address_string(addr)
        else:
            raise ValueError('Illegal parameter-type')

3 View Complete Implementation : test_mutable_list.py
Copyright Apache License 2.0
Author : edisonlz
    def test07_allowed_types(self):
        'Type-restricted list'
        pl, ul = self.lists_of_len()
        ul._allowed = six.integer_types
        ul[1] = 50
        ul[:2] = [60, 70, 80]
        def setfcn(x, i, v): x[i] = v
        self.astertRaises(TypeError, setfcn, ul, 2, 'hello')
        self.astertRaises(TypeError, setfcn, ul, slice(0,3,2), ('hello','goodbye'))

3 View Complete Implementation : query.py
Copyright MIT License
Author : bpgc-cte
    def transform(self, srid=4326, **kwargs):
        """
        Transforms the given geometry field to the given SRID.  If no SRID is
        provided, the transformation will default to using 4326 (WGS84).
        """
        if not isinstance(srid, six.integer_types):
            raise TypeError('An integer SRID must be provided.')
        field_name = kwargs.get('field_name')
        self._spatial_setup('transform', field_name=field_name)
        self.query.add_context('transformed_srid', srid)
        return self._clone()

3 View Complete Implementation : boundfield.py
Copyright MIT License
Author : bpgc-cte
    def __gesatem__(self, idx):
        # Prevent unnecessary reevaluation when accessing BoundField's attrs
        # from templates.
        if not isinstance(idx, six.integer_types + (slice,)):
            raise TypeError
        return self.subwidgets[idx]

3 View Complete Implementation : functions.py
Copyright MIT License
Author : bpgc-cte
    def __init__(self, expression, relative=False, precision=8, **extra):
        relative = relative if hasattr(relative, 'resolve_expression') else int(relative)
        expressions = [
            expression,
            relative,
            self._handle_param(precision, 'precision', six.integer_types),
        ]
        super(astVG, self).__init__(*expressions, **extra)

3 View Complete Implementation : functions.py
Copyright Apache License 2.0
Author : drexly
    def __init__(self, expression, srid, **extra):
        expressions = [
            expression,
            self._handle_param(srid, 'srid', six.integer_types),
        ]
        super(Transform, self).__init__(*expressions, **extra)

3 View Complete Implementation : layer.py
Copyright MIT License
Author : bpgc-cte
    def __gesatem__(self, index):
        "Gets the Feature at the specified index."
        if isinstance(index, six.integer_types):
            # An integer index was given -- we cannot do a check based on the
            # number of features because the beginning and ending feature IDs
            # are not guaranteed to be 0 and len(layer)-1, respectively.
            if index < 0:
                raise OGRIndexError('Negative indices are not allowed on OGR Layers.')
            return self._make_feature(index)
        elif isinstance(index, slice):
            # A slice was given
            start, stop, stride = index.indices(self.num_feat)
            return [self._make_feature(fid) for fid in range(start, stop, stride)]
        else:
            raise TypeError('Integers and slices may only be used when indexing OGR Layers.')

3 View Complete Implementation : geometries.py
Copyright Apache License 2.0
Author : drexly
    def _set_srs(self, srs):
        "Sets the SpatialReference for this geometry."
        # Do not have to clone the `SpatialReference` object pointer because
        # when it is astigned to this `OGRGeometry` it's internal OGR
        # reference count is incremented, and will likewise be released
        # (decremented) when this geometry's destructor is called.
        if isinstance(srs, SpatialReference):
            srs_ptr = srs.ptr
        elif isinstance(srs, six.integer_types + six.string_types):
            sr = SpatialReference(srs)
            srs_ptr = sr.ptr
        else:
            raise TypeError('Cannot astign spatial reference with object of type: %s' % type(srs))
        capi.astign_srs(self.ptr, srs_ptr)

3 View Complete Implementation : encoding.py
Copyright GNU General Public License v2.0
Author : blackye
def is_protected_type(obj):
    """Determine if the object instance is of a protected type.

    Objects of protected types are preserved as-is when pasted to
    force_text(strings_only=True).
    """
    return isinstance(obj, six.integer_types + (type(None), float, Decimal,
        datetime.datetime, datetime.date, datetime.time))

3 View Complete Implementation : util.py
Copyright Apache License 2.0
Author : edisonlz
def display_for_value(value, boolean=False):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon
    from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE

    if boolean:
        return _boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(value, datetime.datetime):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(value, (datetime.date, datetime.time)):
        return formats.localize(value)
    elif isinstance(value, six.integer_types + (decimal.Decimal, float)):
        return formats.number_format(value)
    else:
        return smart_text(value)

3 View Complete Implementation : errcheck.py
Copyright MIT License
Author : bpgc-cte
def check_srs(result, func, cargs):
    if isinstance(result, six.integer_types):
        result = c_void_p(result)
    if not result:
        raise SRSException('Invalid spatial reference pointer returned from "%s".' % func.__name__)
    return result

3 View Complete Implementation : errcheck.py
Copyright Apache License 2.0
Author : edisonlz
def check_geom(result, func, cargs):
    "Checks a function that returns a geometry."
    # OGR_G_Clone may return an integer, even though the
    # restype is set to c_void_p
    if isinstance(result, six.integer_types):
        result = c_void_p(result)
    if not result:
        raise OGRException('Invalid geometry pointer returned from "%s".' % func.__name__)
    return result

3 View Complete Implementation : paginator.py
Copyright GNU General Public License v2.0
Author : blackye
    def __gesatem__(self, index):
        if not isinstance(index, (slice,) + six.integer_types):
            raise TypeError
        # The object_list is converted to a list so that if it was a QuerySet
        # it won't be a database hit per __gesatem__.
        return list(self.object_list)[index]

3 View Complete Implementation : mutable_list.py
Copyright Apache License 2.0
Author : edisonlz
    def __delitem__(self, index):
        "Delete the item(s) at the specified index/slice."
        if not isinstance(index, six.integer_types + (slice,)):
            raise TypeError("%s is not a legal index" % index)

        # calculate new length and dimensions
        origLen     = len(self)
        if isinstance(index, six.integer_types):
            index = self._checkindex(index)
            indexRange  = [index]
        else:
            indexRange  = range(*index.indices(origLen))

        newLen      = origLen - len(indexRange)
        newItems    = ( self._get_single_internal(i)
                        for i in xrange(origLen)
                        if i not in indexRange )

        self._rebuild(newLen, newItems)

3 View Complete Implementation : source.py
Copyright MIT License
Author : bpgc-cte
    @srs.setter
    def srs(self, value):
        """
        Sets the spatial reference used in this GDALRaster. The input can be
        a SpatialReference or any parameter accepted by the SpatialReference
        constructor.
        """
        if isinstance(value, SpatialReference):
            srs = value
        elif isinstance(value, six.integer_types + six.string_types):
            srs = SpatialReference(value)
        else:
            raise ValueError('Could not create a SpatialReference from input.')
        capi.set_ds_projection_ref(self._ptr, srs.wkt.encode())
        self._flush()

3 View Complete Implementation : logengine.py
Copyright GNU General Public License v3.0
Author : Uninett
def add_type(facility, mnemonic, priorityid, types, database):
    database.execute("SELECT nextval('log_message_type_type_seq')")
    typeid = int(database.fetchone()[0])
    astert isinstance(typeid, six.integer_types)

    database.execute("INSERT INTO log_message_type (type, facility, "
                     "mnemonic, priority) "
                     "VALUES (%s, %s, %s, %s)",
                     (typeid, facility, mnemonic, priorityid))
    if facility not in types:
        types[facility] = {}
    types[facility][mnemonic] = typeid

3 View Complete Implementation : config.py
Copyright GNU General Public License v3.0
Author : Uninett
    def get_timeout_for(self, option):
        """Gets an integer timeout value from option in the timeouts section.

        :param option: An option name in the timeouts section, or an integer.
        :return: An integer number of seconds parsed from option. If the
                 option is not present, None is returned.  If option itself is
                 an int, option is returned unchanged.

        """
        if isinstance(option, six.integer_types):
            return option
        try:
            return parse_interval(self.get('timeouts', option))
        except (NoSectionError, NoOptionError):
            past

3 View Complete Implementation : polygon.py
Copyright MIT License
Author : bpgc-cte
    @clastmethod
    def from_bbox(cls, bbox):
        "Constructs a Polygon from a bounding box (4-tuple)."
        x0, y0, x1, y1 = bbox
        for z in bbox:
            if not isinstance(z, six.integer_types + (float,)):
                return GEOSGeometry('POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))' %
                                    (x0, y0, x0, y1, x1, y1, x1, y0, x0, y0))
        return Polygon(((x0, y0), (x0, y1), (x1, y1), (x1, y0), (x0, y0)))

3 View Complete Implementation : mibretriever.py
Copyright GNU General Public License v3.0
Author : Uninett
    def to_python(self, value):
        """Translate an SNMP value into something python-like.

        If the syntax of this object is an Enumeration, value will be
        translated from and int to a str object.  If it is an
        SNMPv2-TC::TruthValue, it will be translated from int to bool.

        """
        if (self.enum and isinstance(value, six.integer_types)
                and value in self.enum):
            value = self.enum[value]
        return value

3 View Complete Implementation : utils.py
Copyright MIT License
Author : bpgc-cte
def display_for_value(value, empty_value_display, boolean=False):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if boolean:
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(value, datetime.datetime):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(value, (datetime.date, datetime.time)):
        return formats.localize(value)
    elif isinstance(value, six.integer_types + (decimal.Decimal, float)):
        return formats.number_format(value)
    elif isinstance(value, (list, tuple)):
        return ', '.join(force_text(v) for v in value)
    else:
        return force_text(value)

3 View Complete Implementation : formats.py
Copyright GNU General Public License v2.0
Author : blackye
def localize_input(value, default=None):
    """
    Checks if an input value is a localizable type and returns it
    formatted with the appropriate formatting string of the current locale.
    """
    if isinstance(value, (decimal.Decimal, float) + six.integer_types):
        return number_format(value)
    elif isinstance(value, datetime.datetime):
        value = datetime_safe.new_datetime(value)
        format = force_str(default or get_format('DATETIME_INPUT_FORMATS')[0])
        return value.strftime(format)
    elif isinstance(value, datetime.date):
        value = datetime_safe.new_date(value)
        format = force_str(default or get_format('DATE_INPUT_FORMATS')[0])
        return value.strftime(format)
    elif isinstance(value, datetime.time):
        format = force_str(default or get_format('TIME_INPUT_FORMATS')[0])
        return value.strftime(format)
    return value

3 View Complete Implementation : functions.py
Copyright MIT License
Author : bpgc-cte
    def __init__(self, expression, srid, **extra):
        expressions = [
            expression,
            self._handle_param(srid, 'srid', six.integer_types),
        ]
        if 'output_field' not in extra:
            extra['output_field'] = GeometryField(srid=srid)
        super(Transform, self).__init__(*expressions, **extra)

3 View Complete Implementation : mutable_list.py
Copyright MIT License
Author : bpgc-cte
    def __delitem__(self, index):
        "Delete the item(s) at the specified index/slice."
        if not isinstance(index, six.integer_types + (slice,)):
            raise TypeError("%s is not a legal index" % index)

        # calculate new length and dimensions
        origLen = len(self)
        if isinstance(index, six.integer_types):
            index = self._checkindex(index)
            indexRange = [index]
        else:
            indexRange = range(*index.indices(origLen))

        newLen = origLen - len(indexRange)
        newItems = (self._get_single_internal(i)
                    for i in range(origLen)
                    if i not in indexRange)

        self._rebuild(newLen, newItems)

3 View Complete Implementation : logengine.py
Copyright GNU General Public License v3.0
Author : Uninett
def add_origin(origin, category, origins, database):
    database.execute("SELECT nextval('origin_origin_seq')")
    originid = database.fetchone()[0]
    astert isinstance(originid, six.integer_types)
    database.execute("INSERT INTO origin (origin, name, "
                     "category) VALUES (%s, %s, %s)",
                     (originid, origin, category))
    origins[origin] = originid
    return originid

0 View Complete Implementation : introspection.py
Copyright MIT License
Author : bpgc-cte
    def get_geometry_type(self, table_name, geo_col):
        cursor = self.connection.cursor()
        try:
            # Querying the `geometry_columns` table to get additional metadata.
            cursor.execute('SELECT coord_dimension, srid, geometry_type '
                           'FROM geometry_columns '
                           'WHERE f_table_name=%s AND f_geometry_column=%s',
                           (table_name, geo_col))
            row = cursor.fetchone()
            if not row:
                raise Exception('Could not find a geometry column for "%s"."%s"' %
                                (table_name, geo_col))

            # OGRGeomType does not require GDAL and makes it easy to convert
            # from OGC geom type name to Django field.
            ogr_type = row[2]
            if isinstance(ogr_type, six.integer_types) and ogr_type > 1000:
                # SpatiaLite versions >= 4 use the new SFSQL 1.2 offsets
                # 1000 (Z), 2000 (M), and 3000 (ZM) to indicate the presence of
                # higher dimensional coordinates (M not yet supported by Django).
                ogr_type = ogr_type % 1000 + OGRGeomType.wkb25bit
            field_type = OGRGeomType(ogr_type).django

            # Getting any GeometryField keyword arguments that are not the default.
            dim = row[0]
            srid = row[1]
            field_params = {}
            if srid != 4326:
                field_params['srid'] = srid
            if (isinstance(dim, six.string_types) and 'Z' in dim) or dim == 3:
                field_params['dim'] = 3
        finally:
            cursor.close()

        return field_type, field_params

0 View Complete Implementation : functions.py
Copyright MIT License
Author : bpgc-cte
    def __init__(self, expression, version=2, precision=8, **extra):
        expressions = [version, expression]
        if precision is not None:
            expressions.append(self._handle_param(precision, 'precision', six.integer_types))
        super(AsGML, self).__init__(*expressions, **extra)

0 View Complete Implementation : functions.py
Copyright MIT License
Author : bpgc-cte
    def __init__(self, expression, precision=None, **extra):
        expressions = [expression]
        if precision is not None:
            expressions.append(self._handle_param(precision, 'precision', six.integer_types))
        super(GeoHash, self).__init__(*expressions, **extra)

0 View Complete Implementation : query.py
Copyright MIT License
Author : bpgc-cte
    def geojson(self, precision=8, crs=False, bbox=False, **kwargs):
        """
        Returns a GeoJSON representation of the geometry field in a `geojson`
        attribute on each element of the GeoQuerySet.

        The `crs` and `bbox` keywords may be set to True if the user wants
        the coordinate reference system and the bounding box to be included
        in the GeoJSON representation of the geometry.
        """
        backend = connections[self.db].ops
        if not backend.geojson:
            raise NotImplementedError('Only PostGIS and SpatiaLite support GeoJSON serialization.')

        if not isinstance(precision, six.integer_types):
            raise TypeError('Precision keyword must be set with an integer.')

        options = 0
        if crs and bbox:
            options = 3
        elif bbox:
            options = 1
        elif crs:
            options = 2
        s = {'desc': 'GeoJSON',
             'procedure_args': {'precision': precision, 'options': options},
             'procedure_fmt': '%(geo_col)s,%(precision)s,%(options)s',
             }
        return self._spatial_attribute('geojson', s, **kwargs)

0 View Complete Implementation : query.py
Copyright MIT License
Author : bpgc-cte
    def snap_to_grid(self, *args, **kwargs):
        """
        Snap all points of the input geometry to the grid.  How the
        geometry is snapped to the grid depends on how many arguments
        were given:
          - 1 argument : A single size to snap both the X and Y grids to.
          - 2 arguments: X and Y sizes to snap the grid to.
          - 4 arguments: X, Y sizes and the X, Y origins.
        """
        if False in [isinstance(arg, (float,) + six.integer_types) for arg in args]:
            raise TypeError('Size argument(s) for the grid must be a float or integer values.')

        nargs = len(args)
        if nargs == 1:
            size = args[0]
            procedure_fmt = '%(geo_col)s,%(size)s'
            procedure_args = {'size': size}
        elif nargs == 2:
            xsize, ysize = args
            procedure_fmt = '%(geo_col)s,%(xsize)s,%(ysize)s'
            procedure_args = {'xsize': xsize, 'ysize': ysize}
        elif nargs == 4:
            xsize, ysize, xorigin, yorigin = args
            procedure_fmt = '%(geo_col)s,%(xorigin)s,%(yorigin)s,%(xsize)s,%(ysize)s'
            procedure_args = {'xsize': xsize, 'ysize': ysize,
                              'xorigin': xorigin, 'yorigin': yorigin}
        else:
            raise ValueError('Must provide 1, 2, or 4 arguments to `snap_to_grid`.')

        s = {'procedure_fmt': procedure_fmt,
             'procedure_args': procedure_args,
             'select_field': GeomField(),
             }

        return self._spatial_attribute('snap_to_grid', s, **kwargs)

0 View Complete Implementation : query.py
Copyright MIT License
Author : bpgc-cte
    def svg(self, relative=False, precision=8, **kwargs):
        """
        Returns SVG representation of the geographic field in a `svg`
        attribute on each element of this GeoQuerySet.

        Keyword Arguments:
         `relative`  => If set to True, this will evaluate the path in
                        terms of relative moves (rather than absolute).

         `precision` => May be used to set the maximum number of decimal
                        digits used in output (defaults to 8).
        """
        relative = int(bool(relative))
        if not isinstance(precision, six.integer_types):
            raise TypeError('SVG precision keyword argument must be an integer.')
        s = {
            'desc': 'SVG',
            'procedure_fmt': '%(geo_col)s,%(rel)s,%(precision)s',
            'procedure_args': {
                'rel': relative,
                'precision': precision,
            }
        }
        return self._spatial_attribute('svg', s, **kwargs)

0 View Complete Implementation : geometries.py
Copyright MIT License
Author : bpgc-cte
    def _set_srid(self, srid):
        if isinstance(srid, six.integer_types) or srid is None:
            self.srs = srid
        else:
            raise TypeError('SRID must be set with an integer.')

0 View Complete Implementation : geometries.py
Copyright MIT License
Author : bpgc-cte
    def transform(self, coord_trans, clone=False):
        """
        Transforms this geometry to a different spatial reference system.
        May take a CoordTransform object, a SpatialReference object, string
        WKT or PROJ.4, and/or an integer SRID.  By default nothing is returned
        and the geometry is transformed in-place.  However, if the `clone`
        keyword is set, then a transformed clone of this geometry will be
        returned.
        """
        if clone:
            klone = self.clone()
            klone.transform(coord_trans)
            return klone

        # Depending on the input type, use the appropriate OGR routine
        # to perform the transformation.
        if isinstance(coord_trans, CoordTransform):
            capi.geom_transform(self.ptr, coord_trans.ptr)
        elif isinstance(coord_trans, SpatialReference):
            capi.geom_transform_to(self.ptr, coord_trans.ptr)
        elif isinstance(coord_trans, six.integer_types + six.string_types):
            sr = SpatialReference(coord_trans)
            capi.geom_transform_to(self.ptr, sr.ptr)
        else:
            raise TypeError('Transform only accepts CoordTransform, '
                            'SpatialReference, string, and integer objects.')

0 View Complete Implementation : mutable_list.py
Copyright MIT License
Author : bpgc-cte
    def insert(self, index, val):
        "Standard list insert method"
        if not isinstance(index, six.integer_types):
            raise TypeError("%s is not a legal index" % index)
        self[index:index] = [val]

0 View Complete Implementation : point.py
Copyright MIT License
Author : bpgc-cte
    def __init__(self, x=None, y=None, z=None, srid=None):
        """
        The Point object may be initialized with either a tuple, or individual
        parameters.

        For Example:
        >>> p = Point((5, 23)) # 2D point, pasted in as a tuple
        >>> p = Point(5, 23, 8) # 3D point, pasted in with individual parameters
        """
        if x is None:
            coords = []
        elif isinstance(x, (tuple, list)):
            # Here a tuple or list was pasted in under the `x` parameter.
            coords = x
        elif isinstance(x, six.integer_types + (float,)) and isinstance(y, six.integer_types + (float,)):
            # Here X, Y, and (optionally) Z were pasted in individually, as parameters.
            if isinstance(z, six.integer_types + (float,)):
                coords = [x, y, z]
            else:
                coords = [x, y]
        else:
            raise TypeError('Invalid parameters given for Point initialization.')

        point = self._create_point(len(coords), coords)

        # Initializing using the address returned from the GEOS
        #  createPoint factory.
        super(Point, self).__init__(point, srid=srid)

0 View Complete Implementation : base.py
Copyright MIT License
Author : bpgc-cte
def _sqlite_format_dtdelta(conn, lhs, rhs):
    """
    LHS and RHS can be either:
        - An integer number of microseconds
        - A string representing a timedelta object
        - A string representing a datetime
    """
    try:
        if isinstance(lhs, six.integer_types):
            lhs = str(decimal.Decimal(lhs) / decimal.Decimal(1000000))
        real_lhs = parse_duration(lhs)
        if real_lhs is None:
            real_lhs = backend_utils.typecast_timestamp(lhs)
        if isinstance(rhs, six.integer_types):
            rhs = str(decimal.Decimal(rhs) / decimal.Decimal(1000000))
        real_rhs = parse_duration(rhs)
        if real_rhs is None:
            real_rhs = backend_utils.typecast_timestamp(rhs)
        if conn.strip() == '+':
            out = real_lhs + real_rhs
        else:
            out = real_lhs - real_rhs
    except (ValueError, TypeError):
        return None
    # typecast_timestamp returns a date or a datetime without timezone.
    # It will be formatted as "%Y-%m-%d" or "%Y-%m-%d %H:%M:%S[.%f]"
    return str(out)

0 View Complete Implementation : schema.py
Copyright MIT License
Author : bpgc-cte
    def quote_value(self, value):
        # The backend "mostly works" without this function and there are use
        # cases for compiling Python without the sqlite3 libraries (e.g.
        # security hardening).
        try:
            import sqlite3
            value = sqlite3.adapt(value)
        except ImportError:
            past
        except sqlite3.ProgrammingError:
            past
        # Manual emulation of SQLite parameter quoting
        if isinstance(value, type(True)):
            return str(int(value))
        elif isinstance(value, (Decimal, float)):
            return str(value)
        elif isinstance(value, six.integer_types):
            return str(value)
        elif isinstance(value, six.string_types):
            return "'%s'" % six.text_type(value).replace("\'", "\'\'")
        elif value is None:
            return "NULL"
        elif isinstance(value, (bytes, bytearray, six.memoryview)):
            # Bytes are only allowed for BLOB fields, encoded as string
            # literals containing hexadecimal data and preceded by a single "X"
            # character:
            # value = b'\x01\x02' => value_hex = b'0102' => return X'0102'
            value = bytes(value)
            hex_encoder = codecs.getencoder('hex_codec')
            value_hex, _length = hex_encoder(value)
            # Use 'ascii' encoding for b'01' => '01', no need to use force_text here.
            return "X'%s'" % value_hex.decode('ascii')
        else:
            raise ValueError("Cannot quote parameter value %r of type %s" % (value, type(value)))

0 View Complete Implementation : serializer.py
Copyright MIT License
Author : bpgc-cte
def serializer_factory(value):
    from django.db.migrations.writer import SettingsReference
    if isinstance(value, Promise):
        value = force_text(value)
    elif isinstance(value, LazyObject):
        # The unwrapped value is returned as the first item of the arguments
        # tuple.
        value = value.__reduce__()[1][0]

    if isinstance(value, models.Field):
        return ModelFieldSerializer(value)
    if isinstance(value, models.manager.BaseManager):
        return ModelManagerSerializer(value)
    if isinstance(value, Operation):
        return OperationSerializer(value)
    if isinstance(value, type):
        return TypeSerializer(value)
    # Anything that knows how to deconstruct itself.
    if hasattr(value, 'deconstruct'):
        return DeconstructableSerializer(value)

    # Unfortunately some of these are order-dependent.
    if isinstance(value, frozenset):
        return FrozensetSerializer(value)
    if isinstance(value, list):
        return SequenceSerializer(value)
    if isinstance(value, set):
        return SetSerializer(value)
    if isinstance(value, tuple):
        return TupleSerializer(value)
    if isinstance(value, dict):
        return DictionarySerializer(value)
    if enum and isinstance(value, enum.Enum):
        return EnumSerializer(value)
    if isinstance(value, datetime.datetime):
        return DatetimeSerializer(value)
    if isinstance(value, datetime.date):
        return DateSerializer(value)
    if isinstance(value, datetime.time):
        return TimeSerializer(value)
    if isinstance(value, datetime.timedelta):
        return TimedeltaSerializer(value)
    if isinstance(value, SettingsReference):
        return SettingsReferenceSerializer(value)
    if isinstance(value, float):
        return FloatSerializer(value)
    if isinstance(value, six.integer_types + (bool, type(None))):
        return BaseSimpleSerializer(value)
    if isinstance(value, six.binary_type):
        return ByteTypeSerializer(value)
    if isinstance(value, six.text_type):
        return TextTypeSerializer(value)
    if isinstance(value, decimal.Decimal):
        return DecimalSerializer(value)
    if isinstance(value, functools.partial):
        return FunctoolsPartialSerializer(value)
    if isinstance(value, (types.FunctionType, types.BuiltinFunctionType, types.MethodType)):
        return FunctionTypeSerializer(value)
    if isinstance(value, collections.Iterable):
        return IterableSerializer(value)
    if isinstance(value, (COMPILED_REGEX_TYPE, RegexObject)):
        return RegexSerializer(value)
    if isinstance(value, uuid.UUID):
        return UUIDSerializer(value)
    raise ValueError(
        "Cannot serialize: %r\nThere are some values Django cannot serialize into "
        "migration files.\nFor more, see https://docs.djangoproject.com/en/%s/"
        "topics/migrations/#migration-serializing" % (value, get_docs_version())
    )

0 View Complete Implementation : __init__.py
Copyright MIT License
Author : bpgc-cte
def lazy_number(func, resultclast, number=None, **kwargs):
    if isinstance(number, six.integer_types):
        kwargs['number'] = number
        proxy = lazy(func, resultclast)(**kwargs)
    else:
        original_kwargs = kwargs.copy()

        clast NumberAwareString(resultclast):
            def __bool__(self):
                return bool(kwargs['singular'])

            def __nonzero__(self):  # Python 2 compatibility
                return type(self).__bool__(self)

            def __mod__(self, rhs):
                if isinstance(rhs, dict) and number:
                    try:
                        number_value = rhs[number]
                    except KeyError:
                        raise KeyError(
                            "Your dictionary lacks key '%s\'. Please provide "
                            "it, because it is required to determine whether "
                            "string is singular or plural." % number
                        )
                else:
                    number_value = rhs
                kwargs['number'] = number_value
                translated = func(**kwargs)
                try:
                    translated = translated % rhs
                except TypeError:
                    # String doesn't contain a placeholder for the number
                    past
                return translated

        proxy = lazy(lambda **kwargs: NumberAwareString(), NumberAwareString)(**kwargs)
        proxy.__reduce__ = lambda: (_lazy_number_unpickle, (func, resultclast, number, original_kwargs))
    return proxy

0 View Complete Implementation : introspection.py
Copyright Apache License 2.0
Author : drexly
    def get_geometry_type(self, table_name, geo_col):
        cursor = self.connection.cursor()
        try:
            # Querying the `geometry_columns` table to get additional metadata.
            type_col = 'type' if self.connection.ops.spatial_version < (4, 0, 0) else 'geometry_type'
            cursor.execute('SELECT coord_dimension, srid, %s '
                           'FROM geometry_columns '
                           'WHERE f_table_name=%%s AND f_geometry_column=%%s' % type_col,
                           (table_name, geo_col))
            row = cursor.fetchone()
            if not row:
                raise Exception('Could not find a geometry column for "%s"."%s"' %
                                (table_name, geo_col))

            # OGRGeomType does not require GDAL and makes it easy to convert
            # from OGC geom type name to Django field.
            ogr_type = row[2]
            if isinstance(ogr_type, six.integer_types) and ogr_type > 1000:
                # Spatialite versions >= 4 use the new SFSQL 1.2 offsets
                # 1000 (Z), 2000 (M), and 3000 (ZM) to indicate the presence of
                # higher dimensional coordinates (M not yet supported by Django).
                ogr_type = ogr_type % 1000 + OGRGeomType.wkb25bit
            field_type = OGRGeomType(ogr_type).django

            # Getting any GeometryField keyword arguments that are not the default.
            dim = row[0]
            srid = row[1]
            field_params = {}
            if srid != 4326:
                field_params['srid'] = srid
            if (isinstance(dim, six.string_types) and 'Z' in dim) or dim == 3:
                field_params['dim'] = 3
        finally:
            cursor.close()

        return field_type, field_params

0 View Complete Implementation : query.py
Copyright Apache License 2.0
Author : drexly
    def geojson(self, precision=8, crs=False, bbox=False, **kwargs):
        """
        Returns a GeoJSON representation of the geometry field in a `geojson`
        attribute on each element of the GeoQuerySet.

        The `crs` and `bbox` keywords may be set to True if the user wants
        the coordinate reference system and the bounding box to be included
        in the GeoJSON representation of the geometry.
        """
        backend = connections[self.db].ops
        if not backend.geojson:
            raise NotImplementedError('Only PostGIS 1.3.4+ and SpatiaLite 3.0+ '
                                      'support GeoJSON serialization.')

        if not isinstance(precision, six.integer_types):
            raise TypeError('Precision keyword must be set with an integer.')

        options = 0
        if crs and bbox:
            options = 3
        elif bbox:
            options = 1
        elif crs:
            options = 2
        s = {'desc': 'GeoJSON',
             'procedure_args': {'precision': precision, 'options': options},
             'procedure_fmt': '%(geo_col)s,%(precision)s,%(options)s',
             }
        return self._spatial_attribute('geojson', s, **kwargs)