Python django.utils.six 模块,integer_types() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.six.integer_types()

项目:django-actions-logger    作者:shtalinberg    | 项目源码 | 文件源码
def get_for_objects(self, queryset):
        """
        Get log entries for the objects in the specified queryset.
        :param queryset: The queryset to get the log entries for.
        :type queryset: QuerySet
        :return: The LogAction objects for the objects in the given queryset.
        :rtype: QuerySet
        """
        if not isinstance(queryset, QuerySet) or queryset.count() == 0:
            return self.none()

        content_type = ContentType.objects.get_for_model(queryset.model)
        primary_keys = queryset.values_list(queryset.model._meta.pk.name, flat=True)

        if isinstance(primary_keys[0], integer_types):
            return self.filter(content_type=content_type).filter(Q(object_id__in=primary_keys)).distinct()
        else:
            return self.filter(content_type=content_type).filter(Q(object_pk__in=primary_keys)).distinct()
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def _check_max_length_attribute(self, **kwargs):
        if self.max_length is None:
            return [
                checks.Error(
                    "CharFields must define a 'max_length' attribute.",
                    hint=None,
                    obj=self,
                    id='fields.E120',
                )
            ]
        elif not isinstance(self.max_length, six.integer_types) or self.max_length <= 0:
            return [
                checks.Error(
                    "'max_length' must be a positive integer.",
                    hint=None,
                    obj=self,
                    id='fields.E121',
                )
            ]
        else:
            return []
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def localize(value, use_l10n=None):
    """
    Checks if value is a localizable type (date, number...) and returns it
    formatted as a string using current locale format.

    If use_l10n is provided and is not None, that will force the value to
    be localized (or not), overriding the value of settings.USE_L10N.
    """
    if isinstance(value, bool):
        return mark_safe(six.text_type(value))
    elif isinstance(value, (decimal.Decimal, float) + six.integer_types):
        return number_format(value, use_l10n=use_l10n)
    elif isinstance(value, datetime.datetime):
        return date_format(value, 'DATETIME_FORMAT', use_l10n=use_l10n)
    elif isinstance(value, datetime.date):
        return date_format(value, use_l10n=use_l10n)
    elif isinstance(value, datetime.time):
        return time_format(value, 'TIME_FORMAT', use_l10n=use_l10n)
    else:
        return value
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def int_to_base36(i):
    """
    Converts an integer to a base36 string
    """
    char_set = '0123456789abcdefghijklmnopqrstuvwxyz'
    if i < 0:
        raise ValueError("Negative base36 conversion input.")
    if six.PY2:
        if not isinstance(i, six.integer_types):
            raise TypeError("Non-integer base36 conversion input.")
        if i > sys.maxint:
            raise ValueError("Base36 conversion input too large.")
    if i < 36:
        return char_set[i]
    b36 = ''
    while i != 0:
        i, n = divmod(i, 36)
        b36 = char_set[n] + b36
    return b36
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def _set_srs(self, srs):
        "Sets the SpatialReference for this geometry."
        # Do not have to clone the `SpatialReference` object pointer because
        # when it is assigned 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 assign spatial reference with object of type: %s' % type(srs))
        capi.assign_srs(self.ptr, srs_ptr)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
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)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
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 smart_text(value)
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def _set_srs(self, srs):
        "Sets the SpatialReference for this geometry."
        # Do not have to clone the `SpatialReference` object pointer because
        # when it is assigned 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 assign spatial reference with object of type: %s' % type(srs))
        capi.assign_srs(self.ptr, srs_ptr)
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
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)
项目:dream_blog    作者:fanlion    | 项目源码 | 文件源码
def _from_python(self, value):
        """
        Converts Python values to a string for Whoosh.

        Code courtesy of pysolr.
        """
        if hasattr(value, 'strftime'):
            if not hasattr(value, 'hour'):
                value = datetime(value.year, value.month, value.day, 0, 0, 0)
        elif isinstance(value, bool):
            if value:
                value = 'true'
            else:
                value = 'false'
        elif isinstance(value, (list, tuple)):
            value = u','.join([force_text(v) for v in value])
        elif isinstance(value, (six.integer_types, float)):
            # Leave it alone.
            pass
        else:
            value = force_text(value)
        return value
项目:django    作者:alexsukhrin    | 项目源码 | 文件源码
def _set_srs(self, srs):
        "Sets the SpatialReference for this geometry."
        # Do not have to clone the `SpatialReference` object pointer because
        # when it is assigned 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 assign spatial reference with object of type: %s' % type(srs))
        capi.assign_srs(self.ptr, srs_ptr)
项目:Gypsy    作者:benticarlos    | 项目源码 | 文件源码
def _set_srs(self, srs):
        "Sets the SpatialReference for this geometry."
        # Do not have to clone the `SpatialReference` object pointer because
        # when it is assigned 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 assign spatial reference with object of type: %s' % type(srs))
        capi.assign_srs(self.ptr, srs_ptr)
项目:Gypsy    作者:benticarlos    | 项目源码 | 文件源码
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)
项目:Gypsy    作者:benticarlos    | 项目源码 | 文件源码
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 smart_text(value)
项目:DjangoBlog    作者:0daybug    | 项目源码 | 文件源码
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)
项目:DjangoBlog    作者:0daybug    | 项目源码 | 文件源码
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)
项目:wanblog    作者:wanzifa    | 项目源码 | 文件源码
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)
项目:tabmaster    作者:NicolasMinghetti    | 项目源码 | 文件源码
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)
项目:trydjango18    作者:lucifer-yqh    | 项目源码 | 文件源码
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)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def __getitem__(self, idx):
        # Prevent unnecessary reevaluation when accessing BoundField's attrs
        # from templates.
        if not isinstance(idx, six.integer_types + (slice,)):
            raise TypeError
        return list(self.__iter__())[idx]
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def __getitem__(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 __getitem__.
        if not isinstance(self.object_list, list):
            self.object_list = list(self.object_list)
        return self.object_list[index]
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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()
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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(AsSVG, self).__init__(*expressions, **extra)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def __getitem__(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.')
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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


# ### Other error-checking routines ###
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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__)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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()
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def _set_srs(self, srs):
        "Sets the SpatialReference for this geometry."
        # Do not have to clone the `SpatialReference` object pointer because
        # when it is assigned 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 assign spatial reference with object of type: %s' % type(srs))
        capi.assign_srs(self.ptr, srs_ptr)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def _set_srid(self, srid):
        if isinstance(srid, six.integer_types):
            self.srs = srid
        else:
            raise TypeError('SRID must be set with an integer.')
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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.')
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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')
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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)))

    # ### These routines are needed for list-like operation w/ListMixin ###
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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]
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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).
        import sqlite3
        try:
            value = sqlite3.adapt(value)
        except sqlite3.ProgrammingError:
            pass
        # 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)))
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def lazy_number(func, resultclass, number=None, **kwargs):
    if isinstance(number, six.integer_types):
        kwargs['number'] = number
        proxy = lazy(func, resultclass)(**kwargs)
    else:
        original_kwargs = kwargs.copy()

        class NumberAwareString(resultclass):
            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
                    pass
                return translated

        proxy = lazy(lambda **kwargs: NumberAwareString(), NumberAwareString)(**kwargs)
        proxy.__reduce__ = lambda: (_lazy_number_unpickle, (func, resultclass, number, original_kwargs))
    return proxy
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def __getitem__(self, idx):
        # Prevent unnecessary reevaluation when accessing BoundField's attrs
        # from templates.
        if not isinstance(idx, six.integer_types + (slice,)):
            raise TypeError
        return list(self.__iter__())[idx]
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def __getitem__(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 __getitem__.
        if not isinstance(self.object_list, list):
            self.object_list = list(self.object_list)
        return self.object_list[index]
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
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
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
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)